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
|
---|---|---|---|---|---|---|---|---|---|
155d0a96afd494f2ca8cc33547a6710f2cf6a6ac
|
DragonBonesDesignPanelLib/src/core/utils/TextureUtil.as
|
DragonBonesDesignPanelLib/src/core/utils/TextureUtil.as
|
package core.utils
{
import flash.geom.Rectangle;
/**
* For place texture
*/
public final class TextureUtil
{
private static const HIGHEST:uint = 0xFFFFFFFF;
/**
* Place textures by textureAtlasXML data
*/
public static function packTextures(widthDefault:uint, padding:uint, rectMap:Object, verticalSide:Boolean = false, isNearest2N:Boolean = true):Rectangle
{
for each(var rect:Rectangle in rectMap)
{
break;
}
if(!rect)
{
return null;
}
var dimensions:uint = 0;
var maxWidth:Number = 0;
var rectList:Vector.<Rectangle> = new Vector.<Rectangle>;
for each(rect in rectMap)
{
dimensions += rect.width * rect.height;
rectList.push(rect);
maxWidth = Math.max(rect.width, maxWidth);
}
//sort texture by size
rectList.sort(sortRectList);
if(widthDefault == 0)
{
//calculate width for Auto size
widthDefault = Math.sqrt(dimensions);
}
widthDefault = Math.max(maxWidth + padding, widthDefault);
if (isNearest2N)
{
widthDefault = getNearest2N(widthDefault);
}
var heightMax:uint = HIGHEST;
var remainAreaList:Vector.<Rectangle> = new Vector.<Rectangle>;
remainAreaList.push(new Rectangle(0, 0, widthDefault, heightMax));
var isFit:Boolean;
var width:int;
var height:int;
var area:Rectangle;
var areaPrev:Rectangle;
var areaNext:Rectangle;
var areaID:int;
var rectID:int;
do
{
//Find highest blank area
area = getHighestArea(remainAreaList);
areaID = remainAreaList.indexOf(area);
isFit = false;
rectID = 0;
for each(rect in rectList)
{
//check if the area is fit
width = int(rect.width) + padding;
height = int(rect.height) + padding;
if (area.width >= width && area.height >= height)
{
//place portrait texture
if(
verticalSide?
(
height > width * 4?
(
areaID > 0?
(area.height - height >= remainAreaList[areaID - 1].height):
true
):
true
):
true
)
{
isFit = true;
break;
}
}
rectID ++;
}
if(isFit)
{
//place texture if size is fit
rect.x = area.x;
rect.y = area.y;
rectList.splice(rectID, 1);
remainAreaList.splice(
areaID + 1,
0,
new Rectangle(area.x + width, area.y, area.width - width, area.height)
);
area.y += height;
area.width = width;
area.height -= height;
}
else
{
//not fit, don't place it, merge blank area to others toghther
if(areaID == 0)
{
areaNext = remainAreaList[areaID + 1];
}
else if(areaID == remainAreaList.length - 1)
{
areaNext = remainAreaList[areaID - 1];
}
else
{
areaPrev = remainAreaList[areaID - 1];
areaNext = remainAreaList[areaID + 1];
areaNext = areaPrev.height <= areaNext.height?areaNext:areaPrev;
}
if(area.x < areaNext.x)
{
areaNext.x = area.x;
}
areaNext.width = area.width + areaNext.width;
remainAreaList.splice(areaID, 1);
}
}
while (rectList.length > 0);
heightMax = heightMax - (getLowestArea(remainAreaList).height + padding);
if (isNearest2N)
{
getNearest2N(heightMax);
}
return new Rectangle(0, 0, widthDefault, heightMax);
}
private static function sortRectList(rect1:Rectangle, rect2:Rectangle):int
{
var v1:uint = rect1.width + rect1.height;
var v2:uint = rect2.width + rect2.height;
if (v1 == v2)
{
return rect1.width > rect2.width?-1:1;
}
return v1 > v2?-1:1;
}
private static function getNearest2N(_n:uint):uint
{
return _n & _n - 1?1 << _n.toString(2).length:_n;
}
private static function getHighestArea(areaList:Vector.<Rectangle>):Rectangle
{
var height:uint = 0;
var areaHighest:Rectangle;
for each(var area:Rectangle in areaList)
{
if (area.height > height)
{
height = area.height;
areaHighest = area;
}
}
return areaHighest;
}
private static function getLowestArea(areaList:Vector.<Rectangle>):Rectangle
{
var height:uint = HIGHEST;
var areaLowest:Rectangle;
for each(var area:Rectangle in areaList)
{
if (area.height < height)
{
height = area.height;
areaLowest = area;
}
}
return areaLowest;
}
}
}
|
package core.utils
{
import flash.geom.Rectangle;
/**
* For place texture
*/
public final class TextureUtil
{
private static const HIGHEST:uint = 0xFFFFFFFF;
/**
* Place textures by textureAtlasXML data
*/
public static function packTextures(widthDefault:uint, padding:uint, rectMap:Object, verticalSide:Boolean = false, isNearest2N:Boolean = true):Rectangle
{
for each(var rect:Rectangle in rectMap)
{
break;
}
if(!rect)
{
return null;
}
var dimensions:uint = 0;
var maxWidth:Number = 0;
var rectList:Vector.<Rectangle> = new Vector.<Rectangle>;
for each(rect in rectMap)
{
dimensions += rect.width * rect.height;
rectList.push(rect);
maxWidth = Math.max(rect.width, maxWidth);
}
//sort texture by size
rectList.sort(sortRectList);
if(widthDefault == 0)
{
//calculate width for Auto size
widthDefault = Math.sqrt(dimensions);
}
widthDefault = Math.max(maxWidth + padding, widthDefault);
if (isNearest2N)
{
widthDefault = getNearest2N(widthDefault);
}
var heightMax:uint = HIGHEST;
var remainAreaList:Vector.<Rectangle> = new Vector.<Rectangle>;
remainAreaList.push(new Rectangle(0, 0, widthDefault, heightMax));
var isFit:Boolean;
var width:int;
var height:int;
var area:Rectangle;
var areaPrev:Rectangle;
var areaNext:Rectangle;
var areaID:int;
var rectID:int;
do
{
//Find highest blank area
area = getHighestArea(remainAreaList);
areaID = remainAreaList.indexOf(area);
isFit = false;
rectID = 0;
for each(rect in rectList)
{
//check if the area is fit
width = int(rect.width) + padding;
height = int(rect.height) + padding;
if (area.width >= width && area.height >= height)
{
//place portrait texture
if(
verticalSide?
(
height > width * 4?
(
areaID > 0?
(area.height - height >= remainAreaList[areaID - 1].height):
true
):
true
):
true
)
{
isFit = true;
break;
}
}
rectID ++;
}
if(isFit)
{
//place texture if size is fit
rect.x = area.x;
rect.y = area.y;
rectList.splice(rectID, 1);
remainAreaList.splice(
areaID + 1,
0,
new Rectangle(area.x + width, area.y, area.width - width, area.height)
);
area.y += height;
area.width = width;
area.height -= height;
}
else
{
//not fit, don't place it, merge blank area to others toghther
if(areaID == 0)
{
areaNext = remainAreaList[areaID + 1];
}
else if(areaID == remainAreaList.length - 1)
{
areaNext = remainAreaList[areaID - 1];
}
else
{
areaPrev = remainAreaList[areaID - 1];
areaNext = remainAreaList[areaID + 1];
areaNext = areaPrev.height <= areaNext.height?areaNext:areaPrev;
}
if(area.x < areaNext.x)
{
areaNext.x = area.x;
}
areaNext.width = area.width + areaNext.width;
remainAreaList.splice(areaID, 1);
}
}
while (rectList.length > 0);
heightMax = heightMax - (getLowestArea(remainAreaList).height + padding);
if (isNearest2N)
{
heightMax = getNearest2N(heightMax);
}
return new Rectangle(0, 0, widthDefault, heightMax);
}
private static function sortRectList(rect1:Rectangle, rect2:Rectangle):int
{
var v1:uint = rect1.width + rect1.height;
var v2:uint = rect2.width + rect2.height;
if (v1 == v2)
{
return rect1.width > rect2.width?-1:1;
}
return v1 > v2?-1:1;
}
private static function getNearest2N(_n:uint):uint
{
return _n & _n - 1?1 << _n.toString(2).length:_n;
}
private static function getHighestArea(areaList:Vector.<Rectangle>):Rectangle
{
var height:uint = 0;
var areaHighest:Rectangle;
for each(var area:Rectangle in areaList)
{
if (area.height > height)
{
height = area.height;
areaHighest = area;
}
}
return areaHighest;
}
private static function getLowestArea(areaList:Vector.<Rectangle>):Rectangle
{
var height:uint = HIGHEST;
var areaLowest:Rectangle;
for each(var area:Rectangle in areaList)
{
if (area.height < height)
{
height = area.height;
areaLowest = area;
}
}
return areaLowest;
}
}
}
|
fix export bug change Export Scale makes not power of 2 image bug
|
fix export bug
change Export Scale makes not power of 2 image bug
|
ActionScript
|
mit
|
DragonBones/DesignPanel
|
7ffccb0b3c427a1bb6f3996cedb4ae2ee73f2686
|
FlexUnit4/src/org/flexunit/runners/Suite.as
|
FlexUnit4/src/org/flexunit/runners/Suite.as
|
/**
* Copyright (c) 2009 Digital Primates IT Consulting Group
*
* 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.
*
* @author Michael Labriola
* @version
**/
package org.flexunit.runners {
import flex.lang.reflect.Klass;
import org.flexunit.internals.dependency.IExternalRunnerDependencyWatcher;
import org.flexunit.internals.runners.InitializationError;
import org.flexunit.runner.Description;
import org.flexunit.runner.IDescription;
import org.flexunit.runner.IRunner;
import org.flexunit.runner.external.IExternalDependencyRunner;
import org.flexunit.runner.manipulation.IFilterable;
import org.flexunit.runner.notification.IRunListener;
import org.flexunit.runner.notification.IRunNotifier;
import org.flexunit.runner.notification.StoppedByUserException;
import org.flexunit.runners.model.IRunnerBuilder;
import org.flexunit.token.AsyncTestToken;
/**
* A <code>Suite</code> is an <code>IRunner</code> that contains test cases and other
* <code>Suites</code> to be run during the course of a test run. The <code>Suite</code> is
* responsible for locating all non-static classes that it contains and obtaining an array of
* <code>IRunner</code>s for each child that was found in this manner. The
* <code>IRunnerBuilder</code> to be used to determine the runner for the child classes is
* provided to the <code>Suite</code> during its instantiation.<br/>
*
* When a <code>Suite</code> goes to run a child, it is telling another <code>IRunner</code> to
* begin running, supplying the <code>IRunner</code> with an <code>IRunNotifier</code> in
* order to keep track of the test run. An <code>AsyncTestToken</code> is also provided to
* the child <code>IRunner</code> in order to notify the <code>Suite</code> when the child has
* finished.<br/>
*
* In order to declare a class as a suite class, the class must include a <code>[Suite]</code>
* and <code>[RunWith("org.flexunit.runners.Suite")]</code> metadata tag. The
* <code>[RunWith]</code> tag will instruct an <code>IRunnerBuilder</code> to use the
* <code>Suite</code> <code>IRunner</code> for the class.<br/>
*
* <pre><code>
* [Suite]
* [RunWith("org.flexunit.runners.Suite")]
* public class SuiteToRun
* {
* public var oneTest:OneTest; //A Test
* public var anotherTest:AnotherTest; //Another Test
* public var differentSuite:DifferentSuite; //A Suite
* }
* </code></pre>
*/
public class Suite extends ParentRunner implements IFilterable, IExternalDependencyRunner {
/**
* @private
*/
private var _runners:Array;
/**
* @private
*/
private var _dependencyWatcher:IExternalRunnerDependencyWatcher;
/**
* @inheritDoc
*/
override public function pleaseStop():void {
super.pleaseStop();
if ( _runners ) {
for ( var i:int=0; i<_runners.length; i++ ) {
( _runners[ i ] as IRunner ).pleaseStop();
}
}
}
/**
* @private
*/
private var descriptionIsCached:Boolean = false;
/**
* @inheritDoc
*/
override public function get description():IDescription {
var desc:IDescription;
if ( descriptionIsCached ) {
desc = super.description;
} else {
if ( _dependencyWatcher && _dependencyWatcher.allDependenciesResolved ) {
//We are good to go, so let it cache this time and from now on we will defer to the super class' copy
descriptionIsCached = true;
desc = super.description;
} else {
//For some reason we still have unresolved dependencies.. most likey, we have external dependencies
//but we are being filtered, so, just keep generating new descriptions when asked as we could change
desc = generateDescription();
}
}
return desc;
}
/**
* @inheritDoc
*/
override protected function get children():Array {
return _runners;
}
/**
* @inheritDoc
*/
override protected function describeChild( child:* ):IDescription {
return IRunner( child ).description;
}
/**
* @inheritDoc
*/
override protected function runChild( child:*, notifier:IRunNotifier, childRunnerToken:AsyncTestToken ):void {
if ( stopRequested ) {
childRunnerToken.sendResult( new StoppedByUserException() );
return;
}
IRunner( child ).run( notifier, childRunnerToken );
}
/**
* Setter for a dependency watcher. This is a class that implements IExternalRunnerDependencyWatcher
* and watches for any external dependencies (such as loading data) are finalized before execution of
* tests is allowed to commence.
*
* @param value An implementation of IExternalRunnerDependencyWatcher
*/
public function set dependencyWatcher( value:IExternalRunnerDependencyWatcher ):void {
var runner:IRunner;
_dependencyWatcher = value;
if ( children ) {
for ( var i:int=0; i<children.length; i++ ) {
runner = children[ i ] as IRunner;
if ( runner is IExternalDependencyRunner ) {
( runner as IExternalDependencyRunner ).dependencyWatcher = value;
}
}
}
}
/**
*
* Setter to indicate an error occured while attempting to load exteranl dependencies
* for this test. It accepts a string to allow the creator of the external dependency
* loader to pass a viable error string back to the user.
*
* @param value The error message
*
*/
public function set externalDependencyError( value:String ):void {
//do nothing... suites don't actually have externalDependencies..
//they just need to pass this along
}
/**
* Returns an array of non-static class feilds in the provided <code>suite</code> class.
*
* @param suite The class to check for non-static class fields.
*
* @return an array of non-static class feilds in the provided <code>suite</code> class.
*/
private static function getSuiteClasses( suite:Class ):Array {
var klassInfo:Klass = new Klass( suite );
var classRef:Class;
var classArray:Array = new Array();
var fields:Array = klassInfo.fields;
for ( var i:int=0; i<fields.length; i++ ) {
if ( !fields[ i ].isStatic ) {
try {
classRef = fields[i].type;
classArray.push( classRef );
} catch ( e:Error ) {
//Not sure who we should inform here yet. We will need someway of capturing the idea that this
//is a missing class, but not sure where or how to promote that up the chain....if it is even possible
//that we could have a missing class, given the way we are linking it
}
}
}
/***
<variable name="two" type="suite.cases::TestTwo"/>
<variable name="one" type="suite.cases::TestOne"/>
SuiteClasses annotation= klass.getAnnotation(SuiteClasses.class);
if (annotation == null)
throw new InitializationError(String.format("class '%s' must have a SuiteClasses annotation", klass.getName()));
return annotation.value();
**/
//this needs to return the suiteclasses
return classArray;
}
/**
* This will either be passed a builder, followed by an array of classes... (when there is not root class)
* Or it will be passed a root class and a builder.
*
* So, the two signatures we are supporting are:
*
* Suite( builder:IRunnerBuilder, classes:Array )
* Suite( testClass:Class, builder:IRunnerBuilder )
***/
public function Suite( arg1:*, arg2:* ) {
var builder:IRunnerBuilder;
var testClass:Class;
var classArray:Array;
var runnners:Array;
var error:Boolean = false;
if ( arg1 is IRunnerBuilder && arg2 is Array ) {
builder = arg1 as IRunnerBuilder;
classArray = arg2 as Array;
} else if ( arg1 is Class && arg2 is IRunnerBuilder ) {
testClass = arg1 as Class;
builder = arg2 as IRunnerBuilder;
classArray = getSuiteClasses(testClass);
} else {
error = true;
}
super( testClass );
//Fix for FXU-51
//Tests to see if suite actually has viable children. If it does not, it is considered an
//initialization error
if ( !error && classArray.length > 0) { //a class is specified as a Suite, and has children
_runners = builder.runners( testClass, classArray );
} else if ( !error && classArray.length == 0 ) {
throw new InitializationError("Empty test Suite!");
} else {
throw new Error("Incorrectly formed arguments passed to suite class");
}
}
}
}
|
/**
* Copyright (c) 2009 Digital Primates IT Consulting Group
*
* 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.
*
* @author Michael Labriola
* @version
**/
package org.flexunit.runners {
import flex.lang.reflect.Klass;
import flexunit.framework.TestSuite;
import org.flexunit.internals.dependency.IExternalRunnerDependencyWatcher;
import org.flexunit.internals.runners.InitializationError;
import org.flexunit.runner.Description;
import org.flexunit.runner.IDescription;
import org.flexunit.runner.IRunner;
import org.flexunit.runner.external.IExternalDependencyRunner;
import org.flexunit.runner.manipulation.IFilterable;
import org.flexunit.runner.notification.IRunListener;
import org.flexunit.runner.notification.IRunNotifier;
import org.flexunit.runner.notification.StoppedByUserException;
import org.flexunit.runners.model.IRunnerBuilder;
import org.flexunit.token.AsyncTestToken;
/**
* A <code>Suite</code> is an <code>IRunner</code> that contains test cases and other
* <code>Suites</code> to be run during the course of a test run. The <code>Suite</code> is
* responsible for locating all non-static classes that it contains and obtaining an array of
* <code>IRunner</code>s for each child that was found in this manner. The
* <code>IRunnerBuilder</code> to be used to determine the runner for the child classes is
* provided to the <code>Suite</code> during its instantiation.<br/>
*
* When a <code>Suite</code> goes to run a child, it is telling another <code>IRunner</code> to
* begin running, supplying the <code>IRunner</code> with an <code>IRunNotifier</code> in
* order to keep track of the test run. An <code>AsyncTestToken</code> is also provided to
* the child <code>IRunner</code> in order to notify the <code>Suite</code> when the child has
* finished.<br/>
*
* In order to declare a class as a suite class, the class must include a <code>[Suite]</code>
* and <code>[RunWith("org.flexunit.runners.Suite")]</code> metadata tag. The
* <code>[RunWith]</code> tag will instruct an <code>IRunnerBuilder</code> to use the
* <code>Suite</code> <code>IRunner</code> for the class.<br/>
*
* <pre><code>
* [Suite]
* [RunWith("org.flexunit.runners.Suite")]
* public class SuiteToRun
* {
* public var oneTest:OneTest; //A Test
* public var anotherTest:AnotherTest; //Another Test
* public var differentSuite:DifferentSuite; //A Suite
* }
* </code></pre>
*/
public class Suite extends ParentRunner implements IFilterable, IExternalDependencyRunner {
/**
* @private
*/
private var _runners:Array;
/**
* @private
*/
private var _dependencyWatcher:IExternalRunnerDependencyWatcher;
/**
* @inheritDoc
*/
override public function pleaseStop():void {
super.pleaseStop();
if ( _runners ) {
for ( var i:int=0; i<_runners.length; i++ ) {
( _runners[ i ] as IRunner ).pleaseStop();
}
}
}
/**
* @private
*/
private var descriptionIsCached:Boolean = false;
/**
* @inheritDoc
*/
override public function get description():IDescription {
var desc:IDescription;
if ( descriptionIsCached ) {
desc = super.description;
} else {
if ( _dependencyWatcher && _dependencyWatcher.allDependenciesResolved ) {
//We are good to go, so let it cache this time and from now on we will defer to the super class' copy
descriptionIsCached = true;
desc = super.description;
} else {
//For some reason we still have unresolved dependencies.. most likey, we have external dependencies
//but we are being filtered, so, just keep generating new descriptions when asked as we could change
desc = generateDescription();
}
}
return desc;
}
/**
* @inheritDoc
*/
override protected function get children():Array {
return _runners;
}
/**
* @inheritDoc
*/
override protected function describeChild( child:* ):IDescription {
return IRunner( child ).description;
}
/**
* @inheritDoc
*/
override protected function runChild( child:*, notifier:IRunNotifier, childRunnerToken:AsyncTestToken ):void {
if ( stopRequested ) {
childRunnerToken.sendResult( new StoppedByUserException() );
return;
}
IRunner( child ).run( notifier, childRunnerToken );
}
/**
* Setter for a dependency watcher. This is a class that implements IExternalRunnerDependencyWatcher
* and watches for any external dependencies (such as loading data) are finalized before execution of
* tests is allowed to commence.
*
* @param value An implementation of IExternalRunnerDependencyWatcher
*/
public function set dependencyWatcher( value:IExternalRunnerDependencyWatcher ):void {
var runner:IRunner;
_dependencyWatcher = value;
if ( children ) {
for ( var i:int=0; i<children.length; i++ ) {
runner = children[ i ] as IRunner;
if ( runner is IExternalDependencyRunner ) {
( runner as IExternalDependencyRunner ).dependencyWatcher = value;
}
}
}
}
/**
*
* Setter to indicate an error occured while attempting to load exteranl dependencies
* for this test. It accepts a string to allow the creator of the external dependency
* loader to pass a viable error string back to the user.
*
* @param value The error message
*
*/
public function set externalDependencyError( value:String ):void {
//do nothing... suites don't actually have externalDependencies..
//they just need to pass this along
}
/**
* Returns an array of non-static class feilds in the provided <code>suite</code> class.
*
* @param suite The class to check for non-static class fields.
*
* @return an array of non-static class feilds in the provided <code>suite</code> class.
*/
private static function getSuiteClasses( suite:Class ):Array {
var klassInfo:Klass = new Klass( suite );
var classRef:Class;
var classArray:Array = new Array();
var fields:Array = klassInfo.fields;
//ADD CHECK FOR TESTRUNNER EXTENSION... this will cause an issue where the super class is introspected and attempts to test String and Collection
if ( klassInfo.descendsFrom( TestSuite ) ) {
throw new TypeError("This suite both extends from the FlexUnit 1 TestSuite class and has the FlexUnit 4 metada. Please do not extend from TestSuite.");
}
for ( var i:int=0; i<fields.length; i++ ) {
if ( !fields[ i ].isStatic ) {
try {
classRef = fields[i].type;
classArray.push( classRef );
} catch ( e:Error ) {
//Not sure who we should inform here yet. We will need someway of capturing the idea that this
//is a missing class, but not sure where or how to promote that up the chain....if it is even possible
//that we could have a missing class, given the way we are linking it
}
}
}
/***
<variable name="two" type="suite.cases::TestTwo"/>
<variable name="one" type="suite.cases::TestOne"/>
SuiteClasses annotation= klass.getAnnotation(SuiteClasses.class);
if (annotation == null)
throw new InitializationError(String.format("class '%s' must have a SuiteClasses annotation", klass.getName()));
return annotation.value();
**/
//this needs to return the suiteclasses
return classArray;
}
/**
* This will either be passed a builder, followed by an array of classes... (when there is not root class)
* Or it will be passed a root class and a builder.
*
* So, the two signatures we are supporting are:
*
* Suite( builder:IRunnerBuilder, classes:Array )
* Suite( testClass:Class, builder:IRunnerBuilder )
***/
public function Suite( arg1:*, arg2:* ) {
var builder:IRunnerBuilder;
var testClass:Class;
var classArray:Array;
var runnners:Array;
var error:Boolean = false;
if ( arg1 is IRunnerBuilder && arg2 is Array ) {
builder = arg1 as IRunnerBuilder;
classArray = arg2 as Array;
} else if ( arg1 is Class && arg2 is IRunnerBuilder ) {
testClass = arg1 as Class;
builder = arg2 as IRunnerBuilder;
classArray = getSuiteClasses(testClass);
} else {
error = true;
}
super( testClass );
//Fix for FXU-51
//Tests to see if suite actually has viable children. If it does not, it is considered an
//initialization error
if ( !error && classArray.length > 0) { //a class is specified as a Suite, and has children
_runners = builder.runners( testClass, classArray );
} else if ( !error && classArray.length == 0 ) {
throw new InitializationError("Empty test Suite!");
} else {
throw new Error("Incorrectly formed arguments passed to suite class");
}
}
}
}
|
Fix per Jesse Warden's twitter issue. When using both the RunWith and specifying the Suite runner and descending from the old FlexUnit.9 Suite class, you receive initialization errors as the Suite code finds both a public String and Collection instance in the TestSuite class and attempts to treat them as TestCases
|
Fix per Jesse Warden's twitter issue. When using both the RunWith and specifying the Suite runner and descending from the old FlexUnit.9 Suite class, you receive initialization errors as the Suite code finds both a public String and Collection instance in the TestSuite class and attempts to treat them as TestCases
|
ActionScript
|
apache-2.0
|
SlavaRa/flex-flexunit,apache/flex-flexunit,SlavaRa/flex-flexunit,SlavaRa/flex-flexunit,apache/flex-flexunit,SlavaRa/flex-flexunit,apache/flex-flexunit,apache/flex-flexunit
|
895dfcdb3a8df9083c1a8acfe095b1ac73a8f188
|
bin/Data/Scripts/Editor/EditorGizmo.as
|
bin/Data/Scripts/Editor/EditorGizmo.as
|
// Urho3D editor node transform gizmo handling
Node@ gizmoNode;
StaticModel@ gizmo;
const float axisMaxD = 0.1;
const float axisMaxT = 1.0;
const float rotSensitivity = 50.0;
EditMode lastGizmoMode;
// For undo
bool previousGizmoDrag;
bool needGizmoUndo;
Array<Transform> oldGizmoTransforms;
class GizmoAxis
{
Ray axisRay;
bool selected;
bool lastSelected;
float t;
float d;
float lastT;
float lastD;
GizmoAxis()
{
selected = false;
lastSelected = false;
t = 0.0;
d = 0.0;
lastT = 0.0;
lastD = 0.0;
}
void Update(Ray cameraRay, float scale, bool drag)
{
// Do not select when UI has modal element
if (ui.HasModalElement())
{
selected = false;
return;
}
Vector3 closest = cameraRay.ClosestPoint(axisRay);
Vector3 projected = axisRay.Project(closest);
d = axisRay.Distance(closest);
t = (projected - axisRay.origin).DotProduct(axisRay.direction);
// Determine the sign of d from a plane that goes through the camera position to the axis
Plane axisPlane(cameraNode.position, axisRay.origin, axisRay.origin + axisRay.direction);
if (axisPlane.Distance(closest) < 0.0)
d = -d;
// Update selected status only when not dragging
if (!drag)
{
selected = Abs(d) < axisMaxD * scale && t >= -axisMaxD * scale && t <= axisMaxT * scale;
lastT = t;
lastD = d;
}
}
void Moved()
{
lastT = t;
lastD = d;
}
}
GizmoAxis gizmoAxisX;
GizmoAxis gizmoAxisY;
GizmoAxis gizmoAxisZ;
void CreateGizmo()
{
gizmoNode = Node();
gizmo = gizmoNode.CreateComponent("StaticModel");
gizmo.model = cache.GetResource("Model", "Models/Editor/Axes.mdl");
gizmo.materials[0] = cache.GetResource("Material", "Materials/Editor/RedUnlit.xml");
gizmo.materials[1] = cache.GetResource("Material", "Materials/Editor/GreenUnlit.xml");
gizmo.materials[2] = cache.GetResource("Material", "Materials/Editor/BlueUnlit.xml");
gizmo.enabled = false;
gizmo.viewMask = 0x80000000; // Editor raycasts use viewmask 0x7fffffff
gizmo.occludee = false;
gizmoAxisX.lastSelected = false;
gizmoAxisY.lastSelected = false;
gizmoAxisZ.lastSelected = false;
lastGizmoMode = EDIT_MOVE;
}
void HideGizmo()
{
if (gizmo !is null)
gizmo.enabled = false;
}
void ShowGizmo()
{
if (gizmo !is null)
{
gizmo.enabled = true;
// Because setting enabled = false detaches the gizmo from octree,
// and it is a manually added drawable, must readd to octree when showing
if (editorScene.octree !is null)
editorScene.octree.AddManualDrawable(gizmo);
}
}
void UpdateGizmo()
{
UseGizmo();
PositionGizmo();
ResizeGizmo();
}
void PositionGizmo()
{
if (gizmo is null)
return;
Vector3 center(0, 0, 0);
bool containsScene = false;
for (uint i = 0; i < editNodes.length; ++i)
{
// Scene's transform should not be edited, so hide gizmo if it is included
if (editNodes[i] is editorScene)
{
containsScene = true;
break;
}
center += editNodes[i].worldPosition;
}
if (editNodes.empty || containsScene)
{
HideGizmo();
return;
}
center /= editNodes.length;
gizmoNode.position = center;
if (axisMode == AXIS_WORLD || editNodes.length > 1)
gizmoNode.rotation = Quaternion();
else
gizmoNode.rotation = editNodes[0].worldRotation;
if (editMode != lastGizmoMode)
{
switch (editMode)
{
case EDIT_MOVE:
gizmo.model = cache.GetResource("Model", "Models/Editor/Axes.mdl");
break;
case EDIT_ROTATE:
gizmo.model = cache.GetResource("Model", "Models/Editor/RotateAxes.mdl");
break;
case EDIT_SCALE:
gizmo.model = cache.GetResource("Model", "Models/Editor/ScaleAxes.mdl");
break;
}
lastGizmoMode = editMode;
}
if ((editMode != EDIT_SELECT && !orbiting) && !gizmo.enabled)
ShowGizmo();
else if ((editMode == EDIT_SELECT || orbiting) && gizmo.enabled)
HideGizmo();
}
void ResizeGizmo()
{
if (gizmo is null || !gizmo.enabled)
return;
float c = 0.1;
if (camera.orthographic)
gizmoNode.scale = Vector3(c, c, c);
else
{
/// \todo if matrix classes were exposed to script could simply use the camera's inverse world transform
float z = (cameraNode.worldRotation.Inverse() * (gizmoNode.worldPosition - cameraNode.worldPosition)).z;
gizmoNode.scale = Vector3(c * z, c * z, c * z);
}
}
void CalculateGizmoAxes()
{
gizmoAxisX.axisRay = Ray(gizmoNode.position, gizmoNode.rotation * Vector3(1, 0, 0));
gizmoAxisY.axisRay = Ray(gizmoNode.position, gizmoNode.rotation * Vector3(0, 1, 0));
gizmoAxisZ.axisRay = Ray(gizmoNode.position, gizmoNode.rotation * Vector3(0, 0, 1));
}
void GizmoMoved()
{
gizmoAxisX.Moved();
gizmoAxisY.Moved();
gizmoAxisZ.Moved();
}
void UseGizmo()
{
if (gizmo is null || !gizmo.enabled || editMode == EDIT_SELECT)
{
StoreGizmoEditActions();
previousGizmoDrag = false;
return;
}
IntVector2 pos = ui.cursorPosition;
if (ui.GetElementAt(pos) !is null)
return;
Ray cameraRay = GetActiveViewportCameraRay();
float scale = gizmoNode.scale.x;
// Recalculate axes only when not left-dragging
bool drag = input.mouseButtonDown[MOUSEB_LEFT];
if (!drag)
CalculateGizmoAxes();
gizmoAxisX.Update(cameraRay, scale, drag);
gizmoAxisY.Update(cameraRay, scale, drag);
gizmoAxisZ.Update(cameraRay, scale, drag);
if (gizmoAxisX.selected != gizmoAxisX.lastSelected)
{
gizmo.materials[0] = cache.GetResource("Material", gizmoAxisX.selected ? "Materials/Editor/BrightRedUnlit.xml" :
"Materials/Editor/RedUnlit.xml");
gizmoAxisX.lastSelected = gizmoAxisX.selected;
}
if (gizmoAxisY.selected != gizmoAxisY.lastSelected)
{
gizmo.materials[1] = cache.GetResource("Material", gizmoAxisY.selected ? "Materials/Editor/BrightGreenUnlit.xml" :
"Materials/Editor/GreenUnlit.xml");
gizmoAxisY.lastSelected = gizmoAxisY.selected;
}
if (gizmoAxisZ.selected != gizmoAxisZ.lastSelected)
{
gizmo.materials[2] = cache.GetResource("Material", gizmoAxisZ.selected ? "Materials/Editor/BrightBlueUnlit.xml" :
"Materials/Editor/BlueUnlit.xml");
gizmoAxisZ.lastSelected = gizmoAxisZ.selected;
};
if (drag)
{
// Store initial transforms for undo when gizmo drag started
if (!previousGizmoDrag)
{
oldGizmoTransforms.Resize(editNodes.length);
for (uint i = 0; i < editNodes.length; ++i)
oldGizmoTransforms[i].Define(editNodes[i]);
}
bool moved = false;
if (editMode == EDIT_MOVE)
{
Vector3 adjust(0, 0, 0);
if (gizmoAxisX.selected)
adjust += Vector3(1, 0, 0) * (gizmoAxisX.t - gizmoAxisX.lastT);
if (gizmoAxisY.selected)
adjust += Vector3(0, 1, 0) * (gizmoAxisY.t - gizmoAxisY.lastT);
if (gizmoAxisZ.selected)
adjust += Vector3(0, 0, 1) * (gizmoAxisZ.t - gizmoAxisZ.lastT);
moved = MoveNodes(adjust);
}
else if (editMode == EDIT_ROTATE)
{
Vector3 adjust(0, 0, 0);
if (gizmoAxisX.selected)
adjust.x = (gizmoAxisX.d - gizmoAxisX.lastD) * rotSensitivity / scale;
if (gizmoAxisY.selected)
adjust.y = -(gizmoAxisY.d - gizmoAxisY.lastD) * rotSensitivity / scale;
if (gizmoAxisZ.selected)
adjust.z = (gizmoAxisZ.d - gizmoAxisZ.lastD) * rotSensitivity / scale;
moved = RotateNodes(adjust);
}
else if (editMode == EDIT_SCALE)
{
Vector3 adjust(0, 0, 0);
if (gizmoAxisX.selected)
adjust += Vector3(1, 0, 0) * (gizmoAxisX.t - gizmoAxisX.lastT);
if (gizmoAxisY.selected)
adjust += Vector3(0, 1, 0) * (gizmoAxisY.t - gizmoAxisY.lastT);
if (gizmoAxisZ.selected)
adjust += Vector3(0, 0, 1) * (gizmoAxisZ.t - gizmoAxisZ.lastT);
// Special handling for uniform scale: use the unmodified X-axis movement only
if (editMode == EDIT_SCALE && gizmoAxisX.selected && gizmoAxisY.selected && gizmoAxisZ.selected)
{
float x = gizmoAxisX.t - gizmoAxisX.lastT;
adjust = Vector3(x, x, x);
}
moved = ScaleNodes(adjust);
}
if (moved)
{
GizmoMoved();
UpdateNodeAttributes();
needGizmoUndo = true;
}
}
else
{
if (previousGizmoDrag)
StoreGizmoEditActions();
}
previousGizmoDrag = drag;
}
bool IsGizmoSelected()
{
return gizmo !is null && gizmo.enabled && (gizmoAxisX.selected || gizmoAxisY.selected || gizmoAxisZ.selected);
}
bool MoveNodes(Vector3 adjust)
{
bool moved = false;
if (adjust.length > M_EPSILON)
{
for (uint i = 0; i < editNodes.length; ++i)
{
if (moveSnap)
{
float moveStepScaled = moveStep * snapScale;
adjust.x = Floor(adjust.x / moveStepScaled + 0.5) * moveStepScaled;
adjust.y = Floor(adjust.y / moveStepScaled + 0.5) * moveStepScaled;
adjust.z = Floor(adjust.z / moveStepScaled + 0.5) * moveStepScaled;
}
Node@ node = editNodes[i];
Vector3 nodeAdjust = adjust;
if (axisMode == AXIS_LOCAL && editNodes.length == 1)
nodeAdjust = node.worldRotation * nodeAdjust;
Vector3 worldPos = node.worldPosition;
Vector3 oldPos = node.position;
worldPos += nodeAdjust;
if (node.parent is null)
node.position = worldPos;
else
node.position = node.parent.WorldToLocal(worldPos);
if (node.position != oldPos)
moved = true;
}
}
return moved;
}
bool RotateNodes(Vector3 adjust)
{
bool moved = false;
if (rotateSnap)
{
float rotateStepScaled = rotateStep * snapScale;
adjust.x = Floor(adjust.x / rotateStepScaled + 0.5) * rotateStepScaled;
adjust.y = Floor(adjust.y / rotateStepScaled + 0.5) * rotateStepScaled;
adjust.z = Floor(adjust.z / rotateStepScaled + 0.5) * rotateStepScaled;
}
if (adjust.length > M_EPSILON)
{
moved = true;
for (uint i = 0; i < editNodes.length; ++i)
{
Node@ node = editNodes[i];
Quaternion rotQuat(adjust);
if (axisMode == AXIS_LOCAL && editNodes.length == 1)
node.rotation = node.rotation * rotQuat;
else
{
Vector3 offset = node.worldPosition - gizmoAxisX.axisRay.origin;
if (node.parent !is null && node.parent.worldRotation != Quaternion(1, 0, 0, 0))
rotQuat = node.parent.worldRotation.Inverse() * rotQuat * node.parent.worldRotation;
node.rotation = rotQuat * node.rotation;
Vector3 newPosition = gizmoAxisX.axisRay.origin + rotQuat * offset;
if (node.parent !is null)
newPosition = node.parent.WorldToLocal(newPosition);
node.position = newPosition;
}
}
}
return moved;
}
bool ScaleNodes(Vector3 adjust)
{
bool moved = false;
if (adjust.length > M_EPSILON)
{
for (uint i = 0; i < editNodes.length; ++i)
{
Node@ node = editNodes[i];
Vector3 scale = node.scale;
Vector3 oldScale = scale;
if (!scaleSnap)
scale += adjust;
else
{
float scaleStepScaled = scaleStep * snapScale;
if (adjust.x != 0)
{
scale.x += adjust.x * scaleStepScaled;
scale.x = Floor(scale.x / scaleStepScaled + 0.5) * scaleStepScaled;
}
if (adjust.y != 0)
{
scale.y += adjust.y * scaleStepScaled;
scale.y = Floor(scale.y / scaleStepScaled + 0.5) * scaleStepScaled;
}
if (adjust.z != 0)
{
scale.z += adjust.z * scaleStepScaled;
scale.z = Floor(scale.z / scaleStepScaled + 0.5) * scaleStepScaled;
}
}
if (scale != oldScale)
moved = true;
node.scale = scale;
}
}
return moved;
}
void StoreGizmoEditActions()
{
if (needGizmoUndo && editNodes.length > 0 && oldGizmoTransforms.length == editNodes.length)
{
EditActionGroup group;
for (uint i = 0; i < editNodes.length; ++i)
{
EditNodeTransformAction action;
action.Define(editNodes[i], oldGizmoTransforms[i]);
group.actions.Push(action);
}
SaveEditActionGroup(group);
SetSceneModified();
}
needGizmoUndo = false;
}
|
// Urho3D editor node transform gizmo handling
Node@ gizmoNode;
StaticModel@ gizmo;
const float axisMaxD = 0.1;
const float axisMaxT = 1.0;
const float rotSensitivity = 50.0;
EditMode lastGizmoMode;
// For undo
bool previousGizmoDrag;
bool needGizmoUndo;
Array<Transform> oldGizmoTransforms;
class GizmoAxis
{
Ray axisRay;
bool selected;
bool lastSelected;
float t;
float d;
float lastT;
float lastD;
GizmoAxis()
{
selected = false;
lastSelected = false;
t = 0.0;
d = 0.0;
lastT = 0.0;
lastD = 0.0;
}
void Update(Ray cameraRay, float scale, bool drag)
{
// Do not select when UI has modal element
if (ui.HasModalElement())
{
selected = false;
return;
}
Vector3 closest = cameraRay.ClosestPoint(axisRay);
Vector3 projected = axisRay.Project(closest);
d = axisRay.Distance(closest);
t = (projected - axisRay.origin).DotProduct(axisRay.direction);
// Determine the sign of d from a plane that goes through the camera position to the axis
Plane axisPlane(cameraNode.position, axisRay.origin, axisRay.origin + axisRay.direction);
if (axisPlane.Distance(closest) < 0.0)
d = -d;
// Update selected status only when not dragging
if (!drag)
{
selected = Abs(d) < axisMaxD * scale && t >= -axisMaxD * scale && t <= axisMaxT * scale;
lastT = t;
lastD = d;
}
}
void Moved()
{
lastT = t;
lastD = d;
}
}
GizmoAxis gizmoAxisX;
GizmoAxis gizmoAxisY;
GizmoAxis gizmoAxisZ;
void CreateGizmo()
{
gizmoNode = Node();
gizmo = gizmoNode.CreateComponent("StaticModel");
gizmo.model = cache.GetResource("Model", "Models/Editor/Axes.mdl");
gizmo.materials[0] = cache.GetResource("Material", "Materials/Editor/RedUnlit.xml");
gizmo.materials[1] = cache.GetResource("Material", "Materials/Editor/GreenUnlit.xml");
gizmo.materials[2] = cache.GetResource("Material", "Materials/Editor/BlueUnlit.xml");
gizmo.enabled = false;
gizmo.viewMask = 0x80000000; // Editor raycasts use viewmask 0x7fffffff
gizmo.occludee = false;
gizmoAxisX.lastSelected = false;
gizmoAxisY.lastSelected = false;
gizmoAxisZ.lastSelected = false;
lastGizmoMode = EDIT_MOVE;
}
void HideGizmo()
{
if (gizmo !is null)
gizmo.enabled = false;
}
void ShowGizmo()
{
if (gizmo !is null)
{
gizmo.enabled = true;
// Because setting enabled = false detaches the gizmo from octree,
// and it is a manually added drawable, must readd to octree when showing
if (editorScene.octree !is null)
editorScene.octree.AddManualDrawable(gizmo);
}
}
void UpdateGizmo()
{
UseGizmo();
PositionGizmo();
ResizeGizmo();
}
void PositionGizmo()
{
if (gizmo is null)
return;
Vector3 center(0, 0, 0);
bool containsScene = false;
for (uint i = 0; i < editNodes.length; ++i)
{
// Scene's transform should not be edited, so hide gizmo if it is included
if (editNodes[i] is editorScene)
{
containsScene = true;
break;
}
center += editNodes[i].worldPosition;
}
if (editNodes.empty || containsScene)
{
HideGizmo();
return;
}
center /= editNodes.length;
gizmoNode.position = center;
if (axisMode == AXIS_WORLD || editNodes.length > 1)
gizmoNode.rotation = Quaternion();
else
gizmoNode.rotation = editNodes[0].worldRotation;
if (editMode != lastGizmoMode)
{
switch (editMode)
{
case EDIT_MOVE:
gizmo.model = cache.GetResource("Model", "Models/Editor/Axes.mdl");
break;
case EDIT_ROTATE:
gizmo.model = cache.GetResource("Model", "Models/Editor/RotateAxes.mdl");
break;
case EDIT_SCALE:
gizmo.model = cache.GetResource("Model", "Models/Editor/ScaleAxes.mdl");
break;
}
lastGizmoMode = editMode;
}
if ((editMode != EDIT_SELECT && !orbiting) && !gizmo.enabled)
ShowGizmo();
else if ((editMode == EDIT_SELECT || orbiting) && gizmo.enabled)
HideGizmo();
}
void ResizeGizmo()
{
if (gizmo is null || !gizmo.enabled)
return;
float scale = 0.1;
if (camera.orthographic)
scale *= camera.orthoSize;
else
scale *= (camera.view.Inverse() * gizmoNode.position).z;
gizmoNode.scale = Vector3(scale, scale, scale);
}
void CalculateGizmoAxes()
{
gizmoAxisX.axisRay = Ray(gizmoNode.position, gizmoNode.rotation * Vector3(1, 0, 0));
gizmoAxisY.axisRay = Ray(gizmoNode.position, gizmoNode.rotation * Vector3(0, 1, 0));
gizmoAxisZ.axisRay = Ray(gizmoNode.position, gizmoNode.rotation * Vector3(0, 0, 1));
}
void GizmoMoved()
{
gizmoAxisX.Moved();
gizmoAxisY.Moved();
gizmoAxisZ.Moved();
}
void UseGizmo()
{
if (gizmo is null || !gizmo.enabled || editMode == EDIT_SELECT)
{
StoreGizmoEditActions();
previousGizmoDrag = false;
return;
}
IntVector2 pos = ui.cursorPosition;
if (ui.GetElementAt(pos) !is null)
return;
Ray cameraRay = GetActiveViewportCameraRay();
float scale = gizmoNode.scale.x;
// Recalculate axes only when not left-dragging
bool drag = input.mouseButtonDown[MOUSEB_LEFT];
if (!drag)
CalculateGizmoAxes();
gizmoAxisX.Update(cameraRay, scale, drag);
gizmoAxisY.Update(cameraRay, scale, drag);
gizmoAxisZ.Update(cameraRay, scale, drag);
if (gizmoAxisX.selected != gizmoAxisX.lastSelected)
{
gizmo.materials[0] = cache.GetResource("Material", gizmoAxisX.selected ? "Materials/Editor/BrightRedUnlit.xml" :
"Materials/Editor/RedUnlit.xml");
gizmoAxisX.lastSelected = gizmoAxisX.selected;
}
if (gizmoAxisY.selected != gizmoAxisY.lastSelected)
{
gizmo.materials[1] = cache.GetResource("Material", gizmoAxisY.selected ? "Materials/Editor/BrightGreenUnlit.xml" :
"Materials/Editor/GreenUnlit.xml");
gizmoAxisY.lastSelected = gizmoAxisY.selected;
}
if (gizmoAxisZ.selected != gizmoAxisZ.lastSelected)
{
gizmo.materials[2] = cache.GetResource("Material", gizmoAxisZ.selected ? "Materials/Editor/BrightBlueUnlit.xml" :
"Materials/Editor/BlueUnlit.xml");
gizmoAxisZ.lastSelected = gizmoAxisZ.selected;
};
if (drag)
{
// Store initial transforms for undo when gizmo drag started
if (!previousGizmoDrag)
{
oldGizmoTransforms.Resize(editNodes.length);
for (uint i = 0; i < editNodes.length; ++i)
oldGizmoTransforms[i].Define(editNodes[i]);
}
bool moved = false;
if (editMode == EDIT_MOVE)
{
Vector3 adjust(0, 0, 0);
if (gizmoAxisX.selected)
adjust += Vector3(1, 0, 0) * (gizmoAxisX.t - gizmoAxisX.lastT);
if (gizmoAxisY.selected)
adjust += Vector3(0, 1, 0) * (gizmoAxisY.t - gizmoAxisY.lastT);
if (gizmoAxisZ.selected)
adjust += Vector3(0, 0, 1) * (gizmoAxisZ.t - gizmoAxisZ.lastT);
moved = MoveNodes(adjust);
}
else if (editMode == EDIT_ROTATE)
{
Vector3 adjust(0, 0, 0);
if (gizmoAxisX.selected)
adjust.x = (gizmoAxisX.d - gizmoAxisX.lastD) * rotSensitivity / scale;
if (gizmoAxisY.selected)
adjust.y = -(gizmoAxisY.d - gizmoAxisY.lastD) * rotSensitivity / scale;
if (gizmoAxisZ.selected)
adjust.z = (gizmoAxisZ.d - gizmoAxisZ.lastD) * rotSensitivity / scale;
moved = RotateNodes(adjust);
}
else if (editMode == EDIT_SCALE)
{
Vector3 adjust(0, 0, 0);
if (gizmoAxisX.selected)
adjust += Vector3(1, 0, 0) * (gizmoAxisX.t - gizmoAxisX.lastT);
if (gizmoAxisY.selected)
adjust += Vector3(0, 1, 0) * (gizmoAxisY.t - gizmoAxisY.lastT);
if (gizmoAxisZ.selected)
adjust += Vector3(0, 0, 1) * (gizmoAxisZ.t - gizmoAxisZ.lastT);
// Special handling for uniform scale: use the unmodified X-axis movement only
if (editMode == EDIT_SCALE && gizmoAxisX.selected && gizmoAxisY.selected && gizmoAxisZ.selected)
{
float x = gizmoAxisX.t - gizmoAxisX.lastT;
adjust = Vector3(x, x, x);
}
moved = ScaleNodes(adjust);
}
if (moved)
{
GizmoMoved();
UpdateNodeAttributes();
needGizmoUndo = true;
}
}
else
{
if (previousGizmoDrag)
StoreGizmoEditActions();
}
previousGizmoDrag = drag;
}
bool IsGizmoSelected()
{
return gizmo !is null && gizmo.enabled && (gizmoAxisX.selected || gizmoAxisY.selected || gizmoAxisZ.selected);
}
bool MoveNodes(Vector3 adjust)
{
bool moved = false;
if (adjust.length > M_EPSILON)
{
for (uint i = 0; i < editNodes.length; ++i)
{
if (moveSnap)
{
float moveStepScaled = moveStep * snapScale;
adjust.x = Floor(adjust.x / moveStepScaled + 0.5) * moveStepScaled;
adjust.y = Floor(adjust.y / moveStepScaled + 0.5) * moveStepScaled;
adjust.z = Floor(adjust.z / moveStepScaled + 0.5) * moveStepScaled;
}
Node@ node = editNodes[i];
Vector3 nodeAdjust = adjust;
if (axisMode == AXIS_LOCAL && editNodes.length == 1)
nodeAdjust = node.worldRotation * nodeAdjust;
Vector3 worldPos = node.worldPosition;
Vector3 oldPos = node.position;
worldPos += nodeAdjust;
if (node.parent is null)
node.position = worldPos;
else
node.position = node.parent.WorldToLocal(worldPos);
if (node.position != oldPos)
moved = true;
}
}
return moved;
}
bool RotateNodes(Vector3 adjust)
{
bool moved = false;
if (rotateSnap)
{
float rotateStepScaled = rotateStep * snapScale;
adjust.x = Floor(adjust.x / rotateStepScaled + 0.5) * rotateStepScaled;
adjust.y = Floor(adjust.y / rotateStepScaled + 0.5) * rotateStepScaled;
adjust.z = Floor(adjust.z / rotateStepScaled + 0.5) * rotateStepScaled;
}
if (adjust.length > M_EPSILON)
{
moved = true;
for (uint i = 0; i < editNodes.length; ++i)
{
Node@ node = editNodes[i];
Quaternion rotQuat(adjust);
if (axisMode == AXIS_LOCAL && editNodes.length == 1)
node.rotation = node.rotation * rotQuat;
else
{
Vector3 offset = node.worldPosition - gizmoAxisX.axisRay.origin;
if (node.parent !is null && node.parent.worldRotation != Quaternion(1, 0, 0, 0))
rotQuat = node.parent.worldRotation.Inverse() * rotQuat * node.parent.worldRotation;
node.rotation = rotQuat * node.rotation;
Vector3 newPosition = gizmoAxisX.axisRay.origin + rotQuat * offset;
if (node.parent !is null)
newPosition = node.parent.WorldToLocal(newPosition);
node.position = newPosition;
}
}
}
return moved;
}
bool ScaleNodes(Vector3 adjust)
{
bool moved = false;
if (adjust.length > M_EPSILON)
{
for (uint i = 0; i < editNodes.length; ++i)
{
Node@ node = editNodes[i];
Vector3 scale = node.scale;
Vector3 oldScale = scale;
if (!scaleSnap)
scale += adjust;
else
{
float scaleStepScaled = scaleStep * snapScale;
if (adjust.x != 0)
{
scale.x += adjust.x * scaleStepScaled;
scale.x = Floor(scale.x / scaleStepScaled + 0.5) * scaleStepScaled;
}
if (adjust.y != 0)
{
scale.y += adjust.y * scaleStepScaled;
scale.y = Floor(scale.y / scaleStepScaled + 0.5) * scaleStepScaled;
}
if (adjust.z != 0)
{
scale.z += adjust.z * scaleStepScaled;
scale.z = Floor(scale.z / scaleStepScaled + 0.5) * scaleStepScaled;
}
}
if (scale != oldScale)
moved = true;
node.scale = scale;
}
}
return moved;
}
void StoreGizmoEditActions()
{
if (needGizmoUndo && editNodes.length > 0 && oldGizmoTransforms.length == editNodes.length)
{
EditActionGroup group;
for (uint i = 0; i < editNodes.length; ++i)
{
EditNodeTransformAction action;
action.Define(editNodes[i], oldGizmoTransforms[i]);
group.actions.Push(action);
}
SaveEditActionGroup(group);
SetSceneModified();
}
needGizmoUndo = false;
}
|
Fix gizmo scale in orthographic mode (ortho size not taken into account). Cleaned up gizmo scaling code to use camera view matrix. Closes #626.
|
Fix gizmo scale in orthographic mode (ortho size not taken into account). Cleaned up gizmo scaling code to use camera view matrix. Closes #626.
|
ActionScript
|
mit
|
carnalis/Urho3D,urho3d/Urho3D,bacsmar/Urho3D,MeshGeometry/Urho3D,luveti/Urho3D,SuperWangKai/Urho3D,xiliu98/Urho3D,cosmy1/Urho3D,MonkeyFirst/Urho3D,orefkov/Urho3D,tommy3/Urho3D,rokups/Urho3D,helingping/Urho3D,c4augustus/Urho3D,fire/Urho3D-1,codedash64/Urho3D,SirNate0/Urho3D,xiliu98/Urho3D,kostik1337/Urho3D,299299/Urho3D,SirNate0/Urho3D,tommy3/Urho3D,bacsmar/Urho3D,orefkov/Urho3D,abdllhbyrktr/Urho3D,bacsmar/Urho3D,abdllhbyrktr/Urho3D,weitjong/Urho3D,henu/Urho3D,orefkov/Urho3D,c4augustus/Urho3D,kostik1337/Urho3D,tommy3/Urho3D,MonkeyFirst/Urho3D,urho3d/Urho3D,weitjong/Urho3D,luveti/Urho3D,tommy3/Urho3D,xiliu98/Urho3D,SuperWangKai/Urho3D,MonkeyFirst/Urho3D,SuperWangKai/Urho3D,MeshGeometry/Urho3D,fire/Urho3D-1,codedash64/Urho3D,codemon66/Urho3D,codemon66/Urho3D,luveti/Urho3D,urho3d/Urho3D,299299/Urho3D,codemon66/Urho3D,kostik1337/Urho3D,weitjong/Urho3D,carnalis/Urho3D,victorholt/Urho3D,kostik1337/Urho3D,henu/Urho3D,abdllhbyrktr/Urho3D,cosmy1/Urho3D,iainmerrick/Urho3D,eugeneko/Urho3D,codemon66/Urho3D,eugeneko/Urho3D,PredatorMF/Urho3D,carnalis/Urho3D,codemon66/Urho3D,299299/Urho3D,c4augustus/Urho3D,orefkov/Urho3D,carnalis/Urho3D,henu/Urho3D,helingping/Urho3D,luveti/Urho3D,SuperWangKai/Urho3D,iainmerrick/Urho3D,henu/Urho3D,kostik1337/Urho3D,xiliu98/Urho3D,luveti/Urho3D,299299/Urho3D,weitjong/Urho3D,PredatorMF/Urho3D,codedash64/Urho3D,PredatorMF/Urho3D,victorholt/Urho3D,fire/Urho3D-1,eugeneko/Urho3D,MeshGeometry/Urho3D,helingping/Urho3D,henu/Urho3D,rokups/Urho3D,rokups/Urho3D,fire/Urho3D-1,SirNate0/Urho3D,c4augustus/Urho3D,xiliu98/Urho3D,tommy3/Urho3D,SirNate0/Urho3D,abdllhbyrktr/Urho3D,rokups/Urho3D,299299/Urho3D,bacsmar/Urho3D,urho3d/Urho3D,eugeneko/Urho3D,helingping/Urho3D,299299/Urho3D,rokups/Urho3D,cosmy1/Urho3D,victorholt/Urho3D,codedash64/Urho3D,weitjong/Urho3D,c4augustus/Urho3D,MonkeyFirst/Urho3D,cosmy1/Urho3D,fire/Urho3D-1,PredatorMF/Urho3D,MeshGeometry/Urho3D,cosmy1/Urho3D,MonkeyFirst/Urho3D,iainmerrick/Urho3D,iainmerrick/Urho3D,victorholt/Urho3D,abdllhbyrktr/Urho3D,MeshGeometry/Urho3D,helingping/Urho3D,carnalis/Urho3D,rokups/Urho3D,codedash64/Urho3D,iainmerrick/Urho3D,SuperWangKai/Urho3D,SirNate0/Urho3D,victorholt/Urho3D
|
cd2c0dc0191a35c3d72c6185a75e82e55d4a404b
|
krew-framework/krewfw/starling_utility/TileMapHelper.as
|
krew-framework/krewfw/starling_utility/TileMapHelper.as
|
package krewfw.starling_utility {
import flash.geom.Point;
import starling.display.Image;
import starling.textures.Texture;
/**
* Tiled Map Editor (http://www.mapeditor.org/) $B$N(B tmx $B%U%!%$%k$+$i(B
* $B=PNO$7$?(B json $B$r$b$H$K3F%^%9$N(B Image $B$rJV$9%f!<%F%#%j%F%#(B
*/
//------------------------------------------------------------
public class TileMapHelper {
// avoid instantiation cost
private static var _point:Point = new Point(0, 0);
/**
* Tiled Map Editor $B$G$O6u%?%$%k$O(B 0 $B$HI=8=$5$l$k!#(B
* $B%=!<%9$N%?%$%k2hA|$N0lHV:8>e$O(B 1 $B$+$i;O$^$k!#(B
* $B;XDj$7$?%^%9$,(B 0 $B$N>l9g$O(B null $B$rJV$9(B.
*
* [Note] $B0J2<$N%?%$%k2hA|$N%U%)!<%^%C%H$G%F%9%H!'(B
* <pre>
* - Canvas size: 512 x 512
* - Tile size: 32 x 32
* - spacing: 2
* </pre>
*/
public static function getTileImage(tileMapInfo:Object, tileLayer:Object, tileSet:Object,
tilesTexture:Texture, col:uint, row:uint):Image
{
// calculate UV coord
var numMapCol:uint = tileLayer.width;
var tileIndex:int = tileLayer.data[(row * numMapCol) + col] - 1;
if (tileIndex < 0) { return null; }
// * consider spacing
var tileWidth :Number = (tileSet.tilewidth + tileSet.spacing);
var tileHeight:Number = (tileSet.tileheight + tileSet.spacing);
var numTileImageCol:uint = tileSet.imagewidth / tileWidth;
var numTileImageRow:uint = tileSet.imageheight / tileHeight;
var tileImageCol:uint = tileIndex % numTileImageCol;
var tileImageRow:uint = tileIndex / numTileImageCol;
var uvLeft:Number = (tileWidth * tileImageCol) / tileSet.imagewidth;
var uvTop :Number = (tileHeight * tileImageRow) / tileSet.imageheight;
var uvSize:Number = tileSet.tilewidth / tileSet.imagewidth;
// make Image with UV
var image:Image = new Image(tilesTexture);
image.width = tileMapInfo.tilewidth;
image.height = tileMapInfo.tileheight;
_point.setTo(uvLeft, uvTop ); image.setTexCoords(0, _point);
_point.setTo(uvLeft + uvSize, uvTop ); image.setTexCoords(1, _point);
_point.setTo(uvLeft, uvTop + uvSize); image.setTexCoords(2, _point);
_point.setTo(uvLeft + uvSize, uvTop + uvSize); image.setTexCoords(3, _point);
var padding:Number = 0.0005; // $B$=$N$^$^(B UV $B;XDj$9$k$H%?%$%k4V$K$o$:$+$J7d4V$,8+$($F$7$^$C$?$N$G(B
_setUv(image, 0, uvLeft , uvTop , padding, padding);
_setUv(image, 1, uvLeft + uvSize, uvTop , -padding, padding);
_setUv(image, 2, uvLeft , uvTop + uvSize, padding, -padding);
_setUv(image, 3, uvLeft + uvSize, uvTop + uvSize, -padding, -padding);
return image;
}
/**
* vertices index:
* 0 - 1
* | / |
* 2 - 3
*/
private static function _setUv(image:Image, vertexId:int, x:Number, y:Number,
paddingX:Number=0, paddingY:Number=0):void
{
_point.setTo(x + paddingX, y + paddingY);
image.setTexCoords(vertexId, _point);
}
}
}
|
package krewfw.starling_utility {
import flash.geom.Point;
import starling.display.Image;
import starling.textures.Texture;
import krewfw.utility.KrewUtil;
/**
* Tiled Map Editor (http://www.mapeditor.org/) の tmx ファイルから
* 出力した json をもとに各マスの Image を返すユーティリティ
*/
//------------------------------------------------------------
public class TileMapHelper {
// avoid instantiation cost
private static var _point:Point = new Point(0, 0);
/**
* Tiled Map Editor で出力した json の Object から、
* 名前でレイヤーのデータを取得する。名前がヒットしなかった場合は null を返す
*/
public static function getLayerByName(tileMapInfo:Object, layerName:String):Object {
for each (var layerData:Object in tileMapInfo.layers) {
if (layerData.name == layerName) {
return layerData;
}
}
KrewUtil.fwlog("[TileMapHelpr] Layer not found: " + layerName);
return null;
}
/**
* Tiled Map Editor では空タイルは 0 と表現される。
* ソースのタイル画像の一番左上は 1 から始まる。
* 指定したマスが 0 の場合は null を返す.
*
* [Note] 以下のタイル画像のフォーマットでテスト:
* <pre>
* - Canvas size: 512 x 512
* - Tile size: 32 x 32
* - spacing: 2
* </pre>
*/
public static function getTileImage(tileMapInfo:Object, tileLayer:Object, tileSet:Object,
tilesTexture:Texture, col:uint, row:uint):Image
{
// calculate UV coord
var numMapCol:uint = tileLayer.width;
var tileIndex:int = tileLayer.data[(row * numMapCol) + col] - 1;
if (tileIndex < 0) { return null; }
// * consider spacing
var tileWidth :Number = (tileSet.tilewidth + tileSet.spacing);
var tileHeight:Number = (tileSet.tileheight + tileSet.spacing);
var numTileImageCol:uint = tileSet.imagewidth / tileWidth;
var numTileImageRow:uint = tileSet.imageheight / tileHeight;
var tileImageCol:uint = tileIndex % numTileImageCol;
var tileImageRow:uint = tileIndex / numTileImageCol;
var uvLeft:Number = (tileWidth * tileImageCol) / tileSet.imagewidth;
var uvTop :Number = (tileHeight * tileImageRow) / tileSet.imageheight;
var uvSize:Number = tileSet.tilewidth / tileSet.imagewidth;
// make Image with UV
var image:Image = new Image(tilesTexture);
image.width = tileMapInfo.tilewidth;
image.height = tileMapInfo.tileheight;
_point.setTo(uvLeft, uvTop ); image.setTexCoords(0, _point);
_point.setTo(uvLeft + uvSize, uvTop ); image.setTexCoords(1, _point);
_point.setTo(uvLeft, uvTop + uvSize); image.setTexCoords(2, _point);
_point.setTo(uvLeft + uvSize, uvTop + uvSize); image.setTexCoords(3, _point);
var padding:Number = 0.0005; // そのまま UV 指定するとタイル間にわずかな隙間が見えてしまったので
_setUv(image, 0, uvLeft , uvTop , padding, padding);
_setUv(image, 1, uvLeft + uvSize, uvTop , -padding, padding);
_setUv(image, 2, uvLeft , uvTop + uvSize, padding, -padding);
_setUv(image, 3, uvLeft + uvSize, uvTop + uvSize, -padding, -padding);
return image;
}
/**
* vertices index:
* 0 - 1
* | / |
* 2 - 3
*/
private static function _setUv(image:Image, vertexId:int, x:Number, y:Number,
paddingX:Number=0, paddingY:Number=0):void
{
_point.setTo(x + paddingX, y + paddingY);
image.setTexCoords(vertexId, _point);
}
}
}
|
Update TileMapHelper
|
Update TileMapHelper
|
ActionScript
|
mit
|
tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework
|
49097481d0c9683a6baebc5e20577cc93c2e8233
|
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 : uint;
/** Level Name. **/
public var name : String;
/** level index (sorted by bitrate) **/
public var index : int = 0;
/** level index (manifest order) **/
public var manifest_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). (it is a vector so that we can store redundant streams in same level) **/
public var urls : Vector.<String>;
// index of used url (non 0 if we switch to a redundant stream)
private var _redundantStreamId : int = 0;
/** 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>();
};
public function get url() : String {
return urls[_redundantStreamId];
}
public function get redundantStreamsNb() : int {
if(urls && urls.length) {
return urls.length-1;
} else {
return 0;
}
}
public function get redundantStreamId() : int {
return _redundantStreamId;
}
// when switching to a redundant stream, reset fragments. they will be retrieved from new playlist
public function set redundantStreamId(id) : void {
if(id < urls.length && id != _redundantStreamId) {
_redundantStreamId = id;
fragments = new Vector.<Fragment>();
start_seqnum = end_seqnum = NaN;
}
}
/** 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!");
}
}
}
}
}
|
/* 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 : uint;
/** Level Name. **/
public var name : String;
/** level index (sorted by bitrate) **/
public var index : int = 0;
/** level index (manifest order) **/
public var manifest_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). (it is a vector so that we can store redundant streams in same level) **/
public var urls : Vector.<String>;
// index of used url (non 0 if we switch to a redundant stream)
private var _redundantStreamId : int = 0;
/** 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>();
};
public function get url() : String {
return urls[_redundantStreamId];
}
public function get redundantStreamsNb() : int {
if(urls && urls.length) {
return urls.length-1;
} else {
return 0;
}
}
public function get redundantStreamId() : int {
return _redundantStreamId;
}
// when switching to a redundant stream, reset fragments. they will be retrieved from new playlist
public function set redundantStreamId(id : int) : void {
if(id < urls.length && id != _redundantStreamId) {
_redundantStreamId = id;
fragments = new Vector.<Fragment>();
start_seqnum = end_seqnum = NaN;
}
}
/** 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!");
}
}
}
}
}
|
Set redundantStreamId() setter argument as an int
|
Set redundantStreamId() setter argument as an int
It fixes compilation warnings when Flashls is imported with sources.
Occurs when using mxmlc strict mode (-strict).
|
ActionScript
|
mpl-2.0
|
neilrackett/flashls,codex-corp/flashls,mangui/flashls,vidible/vdb-flashls,loungelogic/flashls,fixedmachine/flashls,clappr/flashls,thdtjsdn/flashls,Corey600/flashls,codex-corp/flashls,clappr/flashls,hola/flashls,vidible/vdb-flashls,fixedmachine/flashls,loungelogic/flashls,thdtjsdn/flashls,tedconf/flashls,tedconf/flashls,mangui/flashls,Corey600/flashls,hola/flashls,neilrackett/flashls,jlacivita/flashls,NicolasSiver/flashls,jlacivita/flashls,NicolasSiver/flashls
|
8b966a4fda804b09fc015b962efbbdc8ca3c137b
|
src/aerys/minko/scene/controller/EnterFrameController.as
|
src/aerys/minko/scene/controller/EnterFrameController.as
|
package aerys.minko.scene.controller
{
import aerys.minko.render.Viewport;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import flash.display.BitmapData;
import flash.utils.Dictionary;
/**
* EnterFrameController are controllers triggered whenever the Scene.enterFrame
* signal is executed.
*
* The best way to
*
* @author Jean-Marc Le Roux
*
*/
public class EnterFrameController extends AbstractController
{
private var _numTargetsInScene : Dictionary;
protected function getNumTargetsInScene(scene : Scene) : uint
{
return _numTargetsInScene[scene];
}
public function EnterFrameController(targetType : Class = null)
{
super(targetType);
initialize();
}
private function initialize() : void
{
_numTargetsInScene = new Dictionary(true);
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
protected function targetAddedHandler(ctrl : EnterFrameController,
target : ISceneNode) : void
{
if (target.scene)
targetAddedToScene(target, target.scene);
target.added.add(addedHandler);
target.removed.add(removedHandler);
}
protected function targetRemovedHandler(ctrl : EnterFrameController,
target : ISceneNode) : void
{
if (target.scene)
targetRemovedFromScene(target, target.scene);
target.added.remove(addedHandler);
target.removed.remove(removedHandler);
}
private function addedHandler(target : ISceneNode,
ancestor : Group) : void
{
var scene : Scene = target.scene;
if (!scene)
return ;
targetAddedToScene(target, scene);
}
protected function targetAddedToScene(target : ISceneNode, scene : Scene) : void
{
if (!_numTargetsInScene[scene])
{
_numTargetsInScene[scene] = 1;
scene.enterFrame.add(sceneEnterFrameHandler);
}
else
_numTargetsInScene[scene]++;
}
private function removedHandler(target : ISceneNode,
ancestor : Group) : void
{
var scene : Scene = ancestor.scene;
if (!scene)
return ;
targetRemovedFromScene(target, scene);
}
protected function targetRemovedFromScene(target : ISceneNode, scene : Scene) : void
{
_numTargetsInScene[scene]--;
if (_numTargetsInScene[scene] == 0)
{
delete _numTargetsInScene[scene];
scene.enterFrame.remove(sceneEnterFrameHandler);
}
}
protected function sceneEnterFrameHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : Number) : void
{
throw new Error(
'The method EnterFrameController.sceneEnterFrameHandler must be overriden.'
);
}
}
}
|
package aerys.minko.scene.controller
{
import aerys.minko.render.Viewport;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import flash.display.BitmapData;
import flash.utils.Dictionary;
/**
* EnterFrameController are controllers triggered whenever the Scene.enterFrame
* signal is executed.
*
* @author Jean-Marc Le Roux
*
*/
public class EnterFrameController extends AbstractController
{
private var _numTargetsInScene : Dictionary;
protected function getNumTargetsInScene(scene : Scene) : uint
{
return _numTargetsInScene[scene];
}
public function EnterFrameController(targetType : Class = null)
{
super(targetType);
initialize();
}
private function initialize() : void
{
_numTargetsInScene = new Dictionary(true);
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
protected function targetAddedHandler(ctrl : EnterFrameController,
target : ISceneNode) : void
{
if (target.scene)
targetAddedToScene(target, target.scene);
target.added.add(addedHandler);
target.removed.add(removedHandler);
}
protected function targetRemovedHandler(ctrl : EnterFrameController,
target : ISceneNode) : void
{
if (target.scene)
targetRemovedFromScene(target, target.scene);
target.added.remove(addedHandler);
target.removed.remove(removedHandler);
}
private function addedHandler(target : ISceneNode,
ancestor : Group) : void
{
var scene : Scene = target.scene;
if (!scene)
return ;
targetAddedToScene(target, scene);
}
protected function targetAddedToScene(target : ISceneNode, scene : Scene) : void
{
if (!_numTargetsInScene[scene])
{
_numTargetsInScene[scene] = 1;
scene.enterFrame.add(sceneEnterFrameHandler);
}
else
_numTargetsInScene[scene]++;
}
private function removedHandler(target : ISceneNode,
ancestor : Group) : void
{
var scene : Scene = ancestor.scene;
if (!scene)
return ;
targetRemovedFromScene(target, scene);
}
protected function targetRemovedFromScene(target : ISceneNode, scene : Scene) : void
{
_numTargetsInScene[scene]--;
if (_numTargetsInScene[scene] == 0)
{
delete _numTargetsInScene[scene];
scene.enterFrame.remove(sceneEnterFrameHandler);
}
}
protected function sceneEnterFrameHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : Number) : void
{
throw new Error(
'The method EnterFrameController.sceneEnterFrameHandler must be overriden.'
);
}
}
}
|
fix typo
|
fix typo
|
ActionScript
|
mit
|
aerys/minko-as3
|
5e7f8d93c94178117a3b8d970bfe4367f48212f3
|
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 avmplus.getQualifiedClassName;
import flash.utils.Dictionary;
import flash.utils.Proxy;
import flash.utils.describeType;
import flash.utils.flash_proxy;
import flash.utils.getQualifiedClassName;
import mx.messaging.channels.StreamingAMFChannel;
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())
{
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();
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 avmplus.getQualifiedClassName;
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())
{
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();
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 + '\'.'
);
}
}
}
|
Update src/aerys/minko/scene/SceneIterator.as
|
Update src/aerys/minko/scene/SceneIterator.as
Fixes issue #52
|
ActionScript
|
mit
|
aerys/minko-as3
|
174ce396034ccc173ed804817ed3d234a62acd6e
|
src/widgets/Geoprocessing/parameters/DataFileParameter.as
|
src/widgets/Geoprocessing/parameters/DataFileParameter.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 widgets.Geoprocessing.parameters
{
import com.esri.ags.tasks.supportClasses.DataFile;
public class DataFileParameter extends BaseParameter
{
//--------------------------------------------------------------------------
//
// Constants
//
//--------------------------------------------------------------------------
private static const URL_DELIMITER:String = "url:";
private static const VALID_URL_REGEX:RegExp = /^(ht|f)tps?:\/\/[^\s\.]+(\.[^\s\.]+)*((\/|\.)[^\s\.]+)+\/?$/;
//--------------------------------------------------------------------------
//
// Overridden properties
//
//--------------------------------------------------------------------------
//----------------------------------
// defaultValue
//----------------------------------
private var _defaultValue:DataFile;
override public function get defaultValue():Object
{
return _defaultValue;
}
override public function set defaultValue(value:Object):void
{
_defaultValue = new DataFile(value.url);
}
//----------------------------------
// type
//----------------------------------
override public function get type():String
{
return GPParameterTypes.DATA_FILE;
}
//--------------------------------------------------------------------------
//
// Overridden methods
//
//--------------------------------------------------------------------------
override public function defaultValueFromString(description:String):void
{
var url:String = description.substr(URL_DELIMITER.length, description.length);
_defaultValue = new DataFile(url);
}
override public function hasValidValue():Boolean
{
if (_defaultValue.url)
{
var validURLIndex:int = _defaultValue.url.search(VALID_URL_REGEX);
return validURLIndex == 0;
}
else
{
return false;
}
}
}
}
|
///////////////////////////////////////////////////////////////////////////
// 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 widgets.Geoprocessing.parameters
{
import com.esri.ags.tasks.supportClasses.DataFile;
public class DataFileParameter extends BaseParameter
{
//--------------------------------------------------------------------------
//
// Constants
//
//--------------------------------------------------------------------------
private static const URL_DELIMITER:String = "url:";
private static const ITEM_ID_DELIMITER:String = "itemID:";
private static const VALID_URL_REGEX:RegExp = /^(ht|f)tps?:\/\/[^\s\.]+(\.[^\s\.]+)*((\/|\.)[^\s\.]+)+\/?$/;
//--------------------------------------------------------------------------
//
// Overridden properties
//
//--------------------------------------------------------------------------
//----------------------------------
// defaultValue
//----------------------------------
private var _defaultValue:DataFile;
override public function get defaultValue():Object
{
return _defaultValue;
}
override public function set defaultValue(value:Object):void
{
_defaultValue = new DataFile(value.url, value.itemID);
}
//----------------------------------
// type
//----------------------------------
override public function get type():String
{
return GPParameterTypes.DATA_FILE;
}
//--------------------------------------------------------------------------
//
// Overridden methods
//
//--------------------------------------------------------------------------
override public function defaultValueFromString(description:String):void
{
var dataFile:DataFile = new DataFile();
if (description.indexOf(URL_DELIMITER) == 0)
{
dataFile.url = description.substr(URL_DELIMITER.length);
}
else if (description.indexOf(ITEM_ID_DELIMITER) == 0)
{
dataFile.itemID = description.substr(ITEM_ID_DELIMITER.length);
}
_defaultValue = dataFile;
}
override public function hasValidValue():Boolean
{
if (_defaultValue.itemID)
{
return true;
}
else if (_defaultValue.url)
{
var validURLIndex:int = _defaultValue.url.search(VALID_URL_REGEX);
return validURLIndex == 0;
}
else
{
return false;
}
}
}
}
|
Update DataFileParameter to handle item ID.
|
Update DataFileParameter to handle item ID.
|
ActionScript
|
apache-2.0
|
Esri/arcgis-viewer-flex,CanterburyRegionalCouncil/arcgis-viewer-flex,Esri/arcgis-viewer-flex,CanterburyRegionalCouncil/arcgis-viewer-flex,CanterburyRegionalCouncil/arcgis-viewer-flex
|
48fd9eb095f499c6408e6458552d1ba3bf167cc3
|
src/aerys/minko/render/material/basic/BasicMaterial.as
|
src/aerys/minko/render/material/basic/BasicMaterial.as
|
package aerys.minko.render.material.basic
{
import aerys.minko.render.Effect;
import aerys.minko.render.material.Material;
import aerys.minko.render.resource.texture.TextureResource;
import aerys.minko.type.binding.IDataProvider;
import aerys.minko.type.math.Matrix4x4;
public class BasicMaterial extends Material
{
public static const DEFAULT_NAME : String = 'BasicMaterial';
public static const DEFAULT_BASIC_SHADER : BasicShader = new BasicShader();
public static const DEFAULT_EFFECT : Effect = new Effect(DEFAULT_BASIC_SHADER);
public function get blending() : uint
{
return getProperty(BasicProperties.BLENDING);
}
public function set blending(value : uint) : void
{
setProperty(BasicProperties.BLENDING, value);
}
public function get triangleCulling() : uint
{
return getProperty(BasicProperties.TRIANGLE_CULLING);
}
public function set triangleCulling(value : uint) : void
{
setProperty(BasicProperties.TRIANGLE_CULLING, value);
}
public function get diffuseColor() : uint
{
return getProperty(BasicProperties.DIFFUSE_COLOR);
}
public function set diffuseColor(value : uint) : void
{
setProperty(BasicProperties.DIFFUSE_COLOR, value);
}
public function get diffuseMap() : TextureResource
{
return getProperty(BasicProperties.DIFFUSE_MAP);
}
public function set diffuseMap(value : TextureResource) : void
{
setProperty(BasicProperties.DIFFUSE_MAP, value);
}
public function get alphaThreshold() : Number
{
return getProperty(BasicProperties.ALPHA_THRESHOLD);
}
public function set alphaThreshold(value : Number) : void
{
setProperty(BasicProperties.ALPHA_THRESHOLD, value);
}
public function get depthTest() : uint
{
return getProperty(BasicProperties.DEPTH_TEST);
}
public function set depthTest(value : uint) : void
{
setProperty(BasicProperties.DEPTH_TEST, value);
}
public function get depthWriteEnabled() : Boolean
{
return getProperty(BasicProperties.DEPTH_WRITE_ENABLED);
}
public function set depthWriteEnabled(value : Boolean) : void
{
setProperty(BasicProperties.DEPTH_WRITE_ENABLED, value);
}
public function get stencilTriangleFace() : uint
{
return getProperty(BasicProperties.STENCIL_TRIANGLE_FACE);
}
public function set stencilTriangleFace(value : uint) : void
{
setProperty(BasicProperties.STENCIL_TRIANGLE_FACE, value);
}
public function get stencilCompareMode() : uint
{
return getProperty(BasicProperties.STENCIL_COMPARE_MODE);
}
public function set stencilCompareMode(value : uint) : void
{
setProperty(BasicProperties.STENCIL_COMPARE_MODE, value);
}
public function get stencilActionBothPass() : uint
{
return getProperty(BasicProperties.STENCIL_ACTION_BOTH_PASS);
}
public function set stencilActionBothPass(value : uint) : void
{
setProperty(BasicProperties.STENCIL_ACTION_BOTH_PASS, value);
}
public function get stencilActionDepthFail() : uint
{
return getProperty(BasicProperties.STENCIL_ACTION_DEPTH_FAIL);
}
public function set stencilActionDepthFail(value : uint) : void
{
setProperty(BasicProperties.STENCIL_ACTION_DEPTH_FAIL, value);
}
public function get stencilActionDepthPassStencilFail() : uint
{
return getProperty(BasicProperties.STENCIL_ACTION_DEPTH_PASS_STENCIL_FAIL);
}
public function set stencilActionDepthPassStencilFail(value : uint) : void
{
setProperty(BasicProperties.STENCIL_ACTION_DEPTH_PASS_STENCIL_FAIL, value);
}
public function get stencilReferenceValue() : Number
{
return getProperty(BasicProperties.STENCIL_REFERENCE_VALUE);
}
public function set stencilReferenceValue(value : Number) : void
{
setProperty(BasicProperties.STENCIL_REFERENCE_VALUE, value);
}
public function get stencilReadMask() : uint
{
return getProperty(BasicProperties.STENCIL_READ_MASK);
}
public function set stencilReadMask(value : uint) : void
{
setProperty(BasicProperties.STENCIL_READ_MASK, value);
}
public function get stencilWriteMask() : uint
{
return getProperty(BasicProperties.STENCIL_WRITE_MASK);
}
public function set stencilWriteMask(value : uint) : void
{
setProperty(BasicProperties.STENCIL_WRITE_MASK, value);
}
public function get diffuseTransform() : Matrix4x4
{
return getProperty(BasicProperties.DIFFUSE_TRANSFORM);
}
public function set diffuseTransform(value : Matrix4x4) : void
{
setProperty(BasicProperties.DIFFUSE_TRANSFORM, value);
}
public function BasicMaterial(properties : Object = null, effect : Effect = null, name : String = DEFAULT_NAME)
{
super(effect || DEFAULT_EFFECT, properties, name);
}
override public function clone() : IDataProvider
{
var mat : BasicMaterial = new BasicMaterial(this, effect, name);
return mat;
}
}
}
|
package aerys.minko.render.material.basic
{
import aerys.minko.render.Effect;
import aerys.minko.render.material.Material;
import aerys.minko.render.resource.texture.TextureResource;
import aerys.minko.type.binding.IDataProvider;
import aerys.minko.type.math.Matrix4x4;
public class BasicMaterial extends Material
{
public static const DEFAULT_NAME : String = 'BasicMaterial';
public static const DEFAULT_BASIC_SHADER : BasicShader = new BasicShader();
public static const DEFAULT_EFFECT : Effect = new Effect(DEFAULT_BASIC_SHADER);
public function get blending() : uint
{
return getProperty(BasicProperties.BLENDING);
}
public function set blending(value : uint) : void
{
setProperty(BasicProperties.BLENDING, value);
}
public function get triangleCulling() : uint
{
return getProperty(BasicProperties.TRIANGLE_CULLING);
}
public function set triangleCulling(value : uint) : void
{
setProperty(BasicProperties.TRIANGLE_CULLING, value);
}
public function get diffuseColor() : uint
{
return getProperty(BasicProperties.DIFFUSE_COLOR);
}
public function set diffuseColor(value : uint) : void
{
setProperty(BasicProperties.DIFFUSE_COLOR, value);
}
public function get diffuseMap() : TextureResource
{
return getProperty(BasicProperties.DIFFUSE_MAP);
}
public function set diffuseMap(value : TextureResource) : void
{
setProperty(BasicProperties.DIFFUSE_MAP, value);
}
public function get alphaMap() : TextureResource
{
return getProperty(BasicProperties.ALPHA_MAP) as TextureResource;
}
public function set alphaMap(value : TextureResource) : void
{
setProperty(BasicProperties.ALPHA_MAP, value);
}
public function get alphaThreshold() : Number
{
return getProperty(BasicProperties.ALPHA_THRESHOLD);
}
public function set alphaThreshold(value : Number) : void
{
setProperty(BasicProperties.ALPHA_THRESHOLD, value);
}
public function get depthTest() : uint
{
return getProperty(BasicProperties.DEPTH_TEST);
}
public function set depthTest(value : uint) : void
{
setProperty(BasicProperties.DEPTH_TEST, value);
}
public function get depthWriteEnabled() : Boolean
{
return getProperty(BasicProperties.DEPTH_WRITE_ENABLED);
}
public function set depthWriteEnabled(value : Boolean) : void
{
setProperty(BasicProperties.DEPTH_WRITE_ENABLED, value);
}
public function get stencilTriangleFace() : uint
{
return getProperty(BasicProperties.STENCIL_TRIANGLE_FACE);
}
public function set stencilTriangleFace(value : uint) : void
{
setProperty(BasicProperties.STENCIL_TRIANGLE_FACE, value);
}
public function get stencilCompareMode() : uint
{
return getProperty(BasicProperties.STENCIL_COMPARE_MODE);
}
public function set stencilCompareMode(value : uint) : void
{
setProperty(BasicProperties.STENCIL_COMPARE_MODE, value);
}
public function get stencilActionBothPass() : uint
{
return getProperty(BasicProperties.STENCIL_ACTION_BOTH_PASS);
}
public function set stencilActionBothPass(value : uint) : void
{
setProperty(BasicProperties.STENCIL_ACTION_BOTH_PASS, value);
}
public function get stencilActionDepthFail() : uint
{
return getProperty(BasicProperties.STENCIL_ACTION_DEPTH_FAIL);
}
public function set stencilActionDepthFail(value : uint) : void
{
setProperty(BasicProperties.STENCIL_ACTION_DEPTH_FAIL, value);
}
public function get stencilActionDepthPassStencilFail() : uint
{
return getProperty(BasicProperties.STENCIL_ACTION_DEPTH_PASS_STENCIL_FAIL);
}
public function set stencilActionDepthPassStencilFail(value : uint) : void
{
setProperty(BasicProperties.STENCIL_ACTION_DEPTH_PASS_STENCIL_FAIL, value);
}
public function get stencilReferenceValue() : Number
{
return getProperty(BasicProperties.STENCIL_REFERENCE_VALUE);
}
public function set stencilReferenceValue(value : Number) : void
{
setProperty(BasicProperties.STENCIL_REFERENCE_VALUE, value);
}
public function get stencilReadMask() : uint
{
return getProperty(BasicProperties.STENCIL_READ_MASK);
}
public function set stencilReadMask(value : uint) : void
{
setProperty(BasicProperties.STENCIL_READ_MASK, value);
}
public function get stencilWriteMask() : uint
{
return getProperty(BasicProperties.STENCIL_WRITE_MASK);
}
public function set stencilWriteMask(value : uint) : void
{
setProperty(BasicProperties.STENCIL_WRITE_MASK, value);
}
public function get diffuseTransform() : Matrix4x4
{
return getProperty(BasicProperties.DIFFUSE_TRANSFORM);
}
public function set diffuseTransform(value : Matrix4x4) : void
{
setProperty(BasicProperties.DIFFUSE_TRANSFORM, value);
}
public function BasicMaterial(properties : Object = null, effect : Effect = null, name : String = DEFAULT_NAME)
{
super(effect || DEFAULT_EFFECT, properties, name);
}
override public function clone() : IDataProvider
{
var mat : BasicMaterial = new BasicMaterial(this, effect, name);
return mat;
}
}
}
|
add the BasicMaterial.alphaMap property
|
add the BasicMaterial.alphaMap property
|
ActionScript
|
mit
|
aerys/minko-as3
|
f4ec08f3a999ed6ef783b5c7edc7743e15faa691
|
src/aerys/minko/scene/controller/TransformController.as
|
src/aerys/minko/scene/controller/TransformController.as
|
package aerys.minko.scene.controller
{
import aerys.minko.scene.data.TransformDataProvider;
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.type.math.Matrix4x4;
public final class TransformController extends AbstractController
{
private var _node : ISceneNode;
private var _data : TransformDataProvider;
public function TransformController()
{
super();
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function targetAddedHandler(ctrl : TransformController,
node : ISceneNode) : void
{
if (_node)
throw new Error();
_node = node;
_node.transform.changed.add(transformChangedHandler);
_node.added.add(addedHandler);
_node.removed.add(removedHandler);
if (_node is Mesh)
{
_node.addedToScene.add(meshAddedToSceneHandler);
_node.removedFromScene.add(meshRemovedFromSceneHandler);
}
transformChangedHandler(_node.transform);
}
private function targetRemovedHandler(ctrl : TransformController,
node : ISceneNode) : void
{
if (_node is Mesh)
{
_node.addedToScene.remove(meshAddedToSceneHandler);
_node.removedFromScene.remove(meshRemovedFromSceneHandler);
}
_node.removed.remove(removedHandler);
_node.added.remove(addedHandler);
_node.transform.changed.remove(transformChangedHandler);
_node = null;
}
private function meshAddedToSceneHandler(mesh : Mesh, scene : Scene) : void
{
_data = new TransformDataProvider(mesh.localToWorld, mesh.worldToLocal);
mesh.bindings.addProvider(_data);
}
private function meshRemovedFromSceneHandler(mesh : Mesh, scene : Scene) : void
{
mesh.bindings.removeProvider(_data);
_data = null;
}
private function transformChangedHandler(transform : Matrix4x4) : void
{
var parent : ISceneNode = _node.parent;
if (_node.parent)
{
_node.localToWorld.lock()
.copyFrom(_node.transform)
.append(parent.localToWorld)
.unlock();
}
else
_node.localToWorld.copyFrom(_node.transform);
_node.worldToLocal.lock()
.copyFrom(_node.localToWorld)
.invert()
.unlock();
}
private function addedHandler(node : ISceneNode, parent : Group) : void
{
if (node === _node)
{
parent.localToWorld.changed.add(transformChangedHandler);
transformChangedHandler(_node.transform);
}
}
private function removedHandler(node : ISceneNode, parent : Group) : void
{
if (node === _node)
{
parent.localToWorld.changed.remove(transformChangedHandler);
transformChangedHandler(_node.transform);
}
}
}
}
|
package aerys.minko.scene.controller
{
import aerys.minko.scene.data.TransformDataProvider;
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.type.math.Matrix4x4;
public final class TransformController extends AbstractController
{
private var _node : ISceneNode;
private var _data : TransformDataProvider;
public function TransformController()
{
super();
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function targetAddedHandler(ctrl : TransformController,
node : ISceneNode) : void
{
if (_node)
throw new Error();
_node = node;
_node.transform.changed.add(transformChangedHandler);
_node.added.add(addedHandler);
_node.removed.add(removedHandler);
if (_node is Mesh)
{
_node.addedToScene.add(meshAddedToSceneHandler);
_node.removedFromScene.add(meshRemovedFromSceneHandler);
}
transformChangedHandler(_node.transform);
}
private function targetRemovedHandler(ctrl : TransformController,
node : ISceneNode) : void
{
if (_node is Mesh)
{
_node.addedToScene.remove(meshAddedToSceneHandler);
_node.removedFromScene.remove(meshRemovedFromSceneHandler);
}
_node.removed.remove(removedHandler);
_node.added.remove(addedHandler);
_node.transform.changed.remove(transformChangedHandler);
_node = null;
}
private function meshAddedToSceneHandler(mesh : Mesh, scene : Scene) : void
{
_data = new TransformDataProvider(mesh.localToWorld, mesh.worldToLocal);
mesh.bindings.addProvider(_data);
}
private function meshRemovedFromSceneHandler(mesh : Mesh, scene : Scene) : void
{
mesh.bindings.removeProvider(_data);
_data = null;
}
private function transformChangedHandler(transform : Matrix4x4) : void
{
var parent : ISceneNode = _node.parent;
_node.worldToLocal.lock();
_node.localToWorld.lock();
if (_node.parent)
{
_node.localToWorld.lock()
.copyFrom(_node.transform)
.append(parent.localToWorld)
}
else
_node.localToWorld.copyFrom(_node.transform);
_node.worldToLocal.lock()
.copyFrom(_node.localToWorld)
.invert();
_node.worldToLocal.unlock();
_node.localToWorld.unlock();
}
private function addedHandler(node : ISceneNode, parent : Group) : void
{
if (node === _node)
{
parent.localToWorld.changed.add(transformChangedHandler);
transformChangedHandler(_node.transform);
}
}
private function removedHandler(node : ISceneNode, parent : Group) : void
{
if (node === _node)
{
parent.localToWorld.changed.remove(transformChangedHandler);
transformChangedHandler(_node.transform);
}
}
}
}
|
fix TransformController.transformChangedHandler() to lock() and unlock() worldToLocal and localToWorld at the same time
|
fix TransformController.transformChangedHandler() to lock() and unlock() worldToLocal and localToWorld at the same time
|
ActionScript
|
mit
|
aerys/minko-as3
|
2e1202a4cfa174b55d7f43cc5c6626132a828da8
|
com/segonquart/idiomesAnimation.as
|
com/segonquart/idiomesAnimation.as
|
import mx.transitions.easing.*;
import com.mosesSupposes.fuse.*;
class idiomesAnimation extends Movieclip
{
private var arrayLang_arr:Array = new Array ("cat", "es", "en", "fr");
function idiomesAnimation():Void
{
this.stop();
this.onEnterFrame = this.enterSlide;
}
private function enterSlide()
{
arrayLang_arr[0].slideTo('0', '-40', 0.6, 'easeInOutBack', 1);
arrayLang_arr[1].slideTo('0', '-40', 0.8, 'easeInOutBack', 1.1);
arrayLang_arr[2].slideTo('0', '-40', 0.9, 'easeInOutBack', 1.2);
arrayLang_arr[3].slideTo('0', '-40', 1, 'easeInOutBack', 1.3);
}
public function IdiomesColour()
{
this.onRelease = this arrayColour;
target = this.arrayLang_arr[i];
target._tint = 0x8DC60D;
return this;
}
private function arrayColour()
{
for ( var:i ; arrayLang_arr[i] <4; i++)
{
this.colorTo("#628D22", 0.3, "easeOutCirc");
_parent.colorTo('#4b4b4b', 1, 'linear', .2);
}
}
}
|
import mx.transitions.easing.*;
import com.mosesSupposes.fuse.*;
class idiomesAnimation extends Movieclip
{
private var arrayLang_arr:Array = new Array ("cat", "es", "en", "fr");
function idiomesAnimation():Void
{
this.stop();
this.onEnterFrame = this.enterSlide;
}
private function enterSlide()
{
arrayLang_arr[0].slideTo('0', '-40', 0.6, 'easeInOutBack', 1);
arrayLang_arr[1].slideTo('0', '-40', 0.8, 'easeInOutBack', 1.1);
arrayLang_arr[2].slideTo('0', '-40', 0.9, 'easeInOutBack', 1.2);
arrayLang_arr[3].slideTo('0', '-40', 1, 'easeInOutBack', 1.3);
}
public function IdiomesColour()
{
this.onRelease = this arrayColour;
target = this.arrayLang_arr[i];
target._tint = 0x8DC60D;
return this;
}
private function arrayColour()
{
for ( var:i:Number=0 ; arrayLang_arr[i] <4; i++)
{
this.colorTo("#628D22", 0.3, "easeOutCirc");
_parent.colorTo('#4b4b4b', 1, 'linear', .2);
}
}
}
|
Update idiomesAnimation.as
|
Update idiomesAnimation.as
|
ActionScript
|
bsd-3-clause
|
delfiramirez/web-talking-wear,delfiramirez/web-talking-wear,delfiramirez/web-talking-wear
|
f0e063240a4c3d673256d82f42fbecd4e35ba1e5
|
swfcat.as
|
swfcat.as
|
package
{
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.net.Socket;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.net.URLVariables;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.utils.setTimeout;
public class swfcat extends Sprite
{
/* Adobe's Cirrus server for RTMFP connections.
The Cirrus key is defined at compile time by
reading from the CIRRUS_KEY environment var. */
private const CIRRUS_URL:String = "rtmfp://p2p.rtmfp.net";
private const CIRRUS_KEY:String = RTMFP::CIRRUS_KEY;
private const DEFAULT_FACILITATOR_ADDR:Object = {
host: "tor-facilitator.bamsoftware.com",
port: 9002
};
/* Local Tor client to use in case of RTMFP connection. */
private const LOCAL_TOR_CLIENT_ADDR:Object = {
host: "127.0.0.1",
port: 9002
};
private const MAX_NUM_PROXY_PAIRS:uint = 1;
// Milliseconds.
private const FACILITATOR_POLL_INTERVAL:int = 10000;
// Bytes per second. Set to undefined to disable limit.
public const RATE_LIMIT:Number = undefined;
// Seconds.
private const RATE_LIMIT_HISTORY:Number = 5.0;
/* TextField for debug output. */
private var output_text:TextField;
/* UI shown when debug is off. */
private var badge:Badge;
/* Number of proxy pairs currently connected (up to
MAX_NUM_PROXY_PAIRS). */
private var num_proxy_pairs:int = 0;
private var fac_addr:Object;
public var rate_limit:RateLimit;
public function puts(s:String):void
{
output_text.appendText(s + "\n");
output_text.scrollV = output_text.maxScrollV;
}
public function swfcat()
{
// Absolute positioning.
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
output_text = new TextField();
output_text.width = stage.stageWidth;
output_text.height = stage.stageHeight;
output_text.background = true;
output_text.backgroundColor = 0x001f0f;
output_text.textColor = 0x44cc44;
badge = new Badge();
if (RATE_LIMIT)
rate_limit = new BucketRateLimit(RATE_LIMIT * RATE_LIMIT_HISTORY, RATE_LIMIT_HISTORY);
else
rate_limit = new RateUnlimit();
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;
puts("Parameters loaded.");
if (this.loaderInfo.parameters["debug"])
addChild(output_text);
else
addChild(badge);
fac_addr = get_param_addr("facilitator", DEFAULT_FACILITATOR_ADDR);
if (!fac_addr) {
puts("Error: Facilitator spec must be in the form \"host:port\".");
return;
}
if (this.loaderInfo.parameter["proxy"])
proxy_main();
else
client_main();
}
/* Get an address structure from the given movie parameter, or the given
default. Returns null on error. */
private function get_param_addr(param:String, default_addr:Object):Object
{
var spec:String, addr:Object;
spec = this.loaderInfo.parameters[param];
if (spec)
return parse_addr_spec(spec);
else
return default_addr;
}
/* The main logic begins here, after start-up issues are taken care of. */
private function proxy_main():void
{
var fac_url:String;
var loader:URLLoader;
if (num_proxy_pairs >= MAX_NUM_PROXY_PAIRS) {
setTimeout(proxy_main, FACILITATOR_POLL_INTERVAL);
return;
}
loader = new URLLoader();
/* Get the x-www-form-urlencoded values. */
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE, fac_complete);
loader.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("Facilitator: I/O error: " + e.text + ".");
});
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Facilitator: security error: " + e.text + ".");
});
fac_url = "http://" + encodeURIComponent(fac_addr.host)
+ ":" + encodeURIComponent(fac_addr.port) + "/";
puts("Facilitator: connecting to " + fac_url + ".");
loader.load(new URLRequest(fac_url));
}
private function fac_complete(e:Event):void
{
var loader:URLLoader;
var client_spec:String;
var relay_spec:String;
var proxy_pair:Object;
setTimeout(proxy_main, FACILITATOR_POLL_INTERVAL);
loader = e.target as URLLoader;
client_spec = loader.data.client;
if (client_spec == "") {
puts("No clients.");
return;
} else if (!client_spec) {
puts("Error: missing \"client\" in response.");
return;
}
relay_spec = loader.data.relay;
if (!relay_spec) {
puts("Error: missing \"relay\" in response.");
return;
}
puts("Facilitator: got client:\"" + client_spec + "\" "
+ "relay:\"" + relay_spec + "\".");
try {
proxy_pair = make_proxy_pair(client_spec, relay_spec);
} catch (e:ArgumentError) {
puts("Error: " + e);
return;
}
proxy_pair.addEventListener(Event.COMPLETE, function(e:Event):void {
proxy_pair.log("Complete.");
num_proxy_pairs--;
badge.proxy_end();
});
proxy_pair.connect();
num_proxy_pairs++;
badge.proxy_begin();
}
private function client_main():void
{
var rs:RTMFPSocket;
rs = new RTMFPSocket(CIRRUS_URL, CIRRUS_KEY);
rs.addEventListener(Event.COMPLETE, function (e:Event):void {
puts("Got RTMFP id " + rs.id);
register(rs);
});
rs.addEventListener(RTMFPSocket.ACCEPT_EVENT, client_accept);
rs.listen();
}
private function client_accept(e:Event):void {
var rs:RTMFPSocket;
var s_t:Socket;
var proxy_pair:ProxyPair;
rs = e.target as RTMFPSocket;
s_t = new Socket();
puts("Got RTMFP connection from " + rs.peer_id);
proxy_pair = new ProxyPair(this, rs, function ():void {
/* Do nothing; already connected. */
}, s_t, function ():void {
s_t.connect(LOCAL_TOR_CLIENT_ADDR.host, LOCAL_TOR_CLIENT_ADDR.port);
});
proxy_pair.connect();
}
private function register(rs:RTMFPSocket):void {
var fac_url:String;
var loader:URLLoader;
var request:URLRequest;
var variables:URLVariables;
loader = new URLLoader();
loader.addEventListener(Event.COMPLETE, function (e:Event):void {
puts("Facilitator: registered.");
});
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Facilitator: security error: " + e.text + ".");
rs.close();
});
loader.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("Facilitator: I/O error: " + e.text + ".");
rs.close();
});
fac_url = "http://" + encodeURIComponent(fac_addr.host)
+ ":" + encodeURIComponent(fac_addr.port) + "/";
request = new URLRequest(fac_url);
request.method = URLRequestMethod.POST;
request.data = new URLVariables;
request.data["client"] = rs.id;
puts("Facilitator: connecting to " + fac_url + ".");
loader.load(request);
}
private function make_proxy_pair(client_spec:String, relay_spec:String):ProxyPair
{
var proxy_pair:ProxyPair;
var addr_c:Object;
var addr_r:Object;
var s_c:*;
var s_r:Socket;
addr_r = swfcat.parse_addr_spec(relay_spec);
if (!addr_r)
throw new ArgumentError("Relay spec must be in the form \"host:port\".");
addr_c = swfcat.parse_addr_spec(client_spec);
if (addr_c) {
s_c = new Socket();
s_r = new Socket();
proxy_pair = new ProxyPair(this, s_c, function ():void {
s_c.connect(addr_c.host, addr_c.port);
}, s_r, function ():void {
s_r.connect(addr_r.host, addr_r.port);
});
proxy_pair.set_name("<" + addr_c.host + ":" + addr_c.port + ","
+ addr_r.host + ":" + addr_r.port + ">");
return proxy_pair;
}
if (client_spec.match(/^[0-9A-Fa-f]{64}$/)) {
s_c = new RTMFPSocket(CIRRUS_URL, CIRRUS_KEY);
s_r = new Socket();
proxy_pair = new ProxyPair(this, s_c, function ():void {
s_c.connect(client_spec);
}, s_r, function ():void {
s_r.connect(addr_r.host, addr_r.port);
});
proxy_pair.set_name("<" + client_spec.substr(0, 4) + "...,"
+ addr_r.host + ":" + addr_r.port + ">");
return proxy_pair;
}
throw new ArgumentError("Can't parse client spec \"" + client_spec + "\".");
}
/* 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.text.TextFormat;
import flash.text.TextField;
import flash.utils.getTimer;
class Badge extends flash.display.Sprite
{
/* Number of proxy pairs currently connected. */
private var num_proxy_pairs:int = 0;
/* Number of proxy pairs ever connected. */
private var total_proxy_pairs:int = 0;
[Embed(source="badge.png")]
private var BadgeImage:Class;
private var tot_client_count_tf:TextField;
private var tot_client_count_fmt:TextFormat;
private var cur_client_count_tf:TextField;
private var cur_client_count_fmt:TextFormat;
public function Badge()
{
/* Setup client counter for badge. */
tot_client_count_fmt = new TextFormat();
tot_client_count_fmt.color = 0xFFFFFF;
tot_client_count_fmt.align = "center";
tot_client_count_fmt.font = "courier-new";
tot_client_count_fmt.bold = true;
tot_client_count_fmt.size = 10;
tot_client_count_tf = new TextField();
tot_client_count_tf.width = 20;
tot_client_count_tf.height = 17;
tot_client_count_tf.background = false;
tot_client_count_tf.defaultTextFormat = tot_client_count_fmt;
tot_client_count_tf.x=47;
tot_client_count_tf.y=0;
cur_client_count_fmt = new TextFormat();
cur_client_count_fmt.color = 0xFFFFFF;
cur_client_count_fmt.align = "center";
cur_client_count_fmt.font = "courier-new";
cur_client_count_fmt.bold = true;
cur_client_count_fmt.size = 10;
cur_client_count_tf = new TextField();
cur_client_count_tf.width = 20;
cur_client_count_tf.height = 17;
cur_client_count_tf.background = false;
cur_client_count_tf.defaultTextFormat = cur_client_count_fmt;
cur_client_count_tf.x=47;
cur_client_count_tf.y=6;
addChild(new BadgeImage());
addChild(tot_client_count_tf);
addChild(cur_client_count_tf);
/* Update the client counter on badge. */
update_client_count();
}
public function proxy_begin():void
{
num_proxy_pairs++;
total_proxy_pairs++;
update_client_count();
}
public function proxy_end():void
{
num_proxy_pairs--;
update_client_count();
}
private function update_client_count():void
{
/* Update total client count. */
if (String(total_proxy_pairs).length == 1)
tot_client_count_tf.text = "0" + String(total_proxy_pairs);
else
tot_client_count_tf.text = String(total_proxy_pairs);
/* Update current client count. */
cur_client_count_tf.text = "";
for(var i:Number = 0; i < num_proxy_pairs; i++)
cur_client_count_tf.appendText(".");
}
}
class RateLimit
{
public function RateLimit()
{
}
public function update(n:Number):Boolean
{
return true;
}
public function when():Number
{
return 0.0;
}
public function is_limited():Boolean
{
return false;
}
}
class RateUnlimit extends RateLimit
{
public function RateUnlimit()
{
}
public override function update(n:Number):Boolean
{
return true;
}
public override function when():Number
{
return 0.0;
}
public override function is_limited():Boolean
{
return false;
}
}
class BucketRateLimit extends RateLimit
{
private var amount:Number;
private var capacity:Number;
private var time:Number;
private var last_update:uint;
public function BucketRateLimit(capacity:Number, time:Number)
{
this.amount = 0.0;
/* capacity / time is the rate we are aiming for. */
this.capacity = capacity;
this.time = time;
this.last_update = getTimer();
}
private function age():void
{
var now:uint;
var delta:Number;
now = getTimer();
delta = (now - last_update) / 1000.0;
last_update = now;
amount -= delta * capacity / time;
if (amount < 0.0)
amount = 0.0;
}
public override function update(n:Number):Boolean
{
age();
amount += n;
return amount <= capacity;
}
public override function when():Number
{
age();
return (amount - capacity) / (capacity / time);
}
public override function is_limited():Boolean
{
age();
return amount > capacity;
}
}
|
package
{
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.net.Socket;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.net.URLVariables;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.utils.setTimeout;
public class swfcat extends Sprite
{
/* Adobe's Cirrus server for RTMFP connections.
The Cirrus key is defined at compile time by
reading from the CIRRUS_KEY environment var. */
private const CIRRUS_URL:String = "rtmfp://p2p.rtmfp.net";
private const CIRRUS_KEY:String = RTMFP::CIRRUS_KEY;
private const DEFAULT_FACILITATOR_ADDR:Object = {
host: "tor-facilitator.bamsoftware.com",
port: 9002
};
/* Local Tor client to use in case of RTMFP connection. */
private const LOCAL_TOR_CLIENT_ADDR:Object = {
host: "127.0.0.1",
port: 9002
};
private const MAX_NUM_PROXY_PAIRS:uint = 1;
// Milliseconds.
private const FACILITATOR_POLL_INTERVAL:int = 10000;
// Bytes per second. Set to undefined to disable limit.
public const RATE_LIMIT:Number = undefined;
// Seconds.
private const RATE_LIMIT_HISTORY:Number = 5.0;
/* TextField for debug output. */
private var output_text:TextField;
/* UI shown when debug is off. */
private var badge:Badge;
/* Number of proxy pairs currently connected (up to
MAX_NUM_PROXY_PAIRS). */
private var num_proxy_pairs:int = 0;
private var fac_addr:Object;
public var rate_limit:RateLimit;
public function puts(s:String):void
{
output_text.appendText(s + "\n");
output_text.scrollV = output_text.maxScrollV;
}
public function swfcat()
{
// Absolute positioning.
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
output_text = new TextField();
output_text.width = stage.stageWidth;
output_text.height = stage.stageHeight;
output_text.background = true;
output_text.backgroundColor = 0x001f0f;
output_text.textColor = 0x44cc44;
badge = new Badge();
if (RATE_LIMIT)
rate_limit = new BucketRateLimit(RATE_LIMIT * RATE_LIMIT_HISTORY, RATE_LIMIT_HISTORY);
else
rate_limit = new RateUnlimit();
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;
puts("Parameters loaded.");
if (this.loaderInfo.parameters["debug"])
addChild(output_text);
else
addChild(badge);
fac_addr = get_param_addr("facilitator", DEFAULT_FACILITATOR_ADDR);
if (!fac_addr) {
puts("Error: Facilitator spec must be in the form \"host:port\".");
return;
}
if (this.loaderInfo.parameters["client"])
client_main();
else
proxy_main();
}
/* Get an address structure from the given movie parameter, or the given
default. Returns null on error. */
private function get_param_addr(param:String, default_addr:Object):Object
{
var spec:String, addr:Object;
spec = this.loaderInfo.parameters[param];
if (spec)
return parse_addr_spec(spec);
else
return default_addr;
}
/* The main logic begins here, after start-up issues are taken care of. */
private function proxy_main():void
{
var fac_url:String;
var loader:URLLoader;
if (num_proxy_pairs >= MAX_NUM_PROXY_PAIRS) {
setTimeout(proxy_main, FACILITATOR_POLL_INTERVAL);
return;
}
loader = new URLLoader();
/* Get the x-www-form-urlencoded values. */
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE, fac_complete);
loader.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("Facilitator: I/O error: " + e.text + ".");
});
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Facilitator: security error: " + e.text + ".");
});
fac_url = "http://" + encodeURIComponent(fac_addr.host)
+ ":" + encodeURIComponent(fac_addr.port) + "/";
puts("Facilitator: connecting to " + fac_url + ".");
loader.load(new URLRequest(fac_url));
}
private function fac_complete(e:Event):void
{
var loader:URLLoader;
var client_spec:String;
var relay_spec:String;
var proxy_pair:Object;
setTimeout(proxy_main, FACILITATOR_POLL_INTERVAL);
loader = e.target as URLLoader;
client_spec = loader.data.client;
if (client_spec == "") {
puts("No clients.");
return;
} else if (!client_spec) {
puts("Error: missing \"client\" in response.");
return;
}
relay_spec = loader.data.relay;
if (!relay_spec) {
puts("Error: missing \"relay\" in response.");
return;
}
puts("Facilitator: got client:\"" + client_spec + "\" "
+ "relay:\"" + relay_spec + "\".");
try {
proxy_pair = make_proxy_pair(client_spec, relay_spec);
} catch (e:ArgumentError) {
puts("Error: " + e);
return;
}
proxy_pair.addEventListener(Event.COMPLETE, function(e:Event):void {
proxy_pair.log("Complete.");
num_proxy_pairs--;
badge.proxy_end();
});
proxy_pair.connect();
num_proxy_pairs++;
badge.proxy_begin();
}
private function client_main():void
{
var rs:RTMFPSocket;
rs = new RTMFPSocket(CIRRUS_URL, CIRRUS_KEY);
rs.addEventListener(Event.COMPLETE, function (e:Event):void {
puts("Got RTMFP id " + rs.id);
register(rs);
});
rs.addEventListener(RTMFPSocket.ACCEPT_EVENT, client_accept);
rs.listen();
}
private function client_accept(e:Event):void {
var rs:RTMFPSocket;
var s_t:Socket;
var proxy_pair:ProxyPair;
rs = e.target as RTMFPSocket;
s_t = new Socket();
puts("Got RTMFP connection from " + rs.peer_id);
proxy_pair = new ProxyPair(this, rs, function ():void {
/* Do nothing; already connected. */
}, s_t, function ():void {
s_t.connect(LOCAL_TOR_CLIENT_ADDR.host, LOCAL_TOR_CLIENT_ADDR.port);
});
proxy_pair.connect();
}
private function register(rs:RTMFPSocket):void {
var fac_url:String;
var loader:URLLoader;
var request:URLRequest;
var variables:URLVariables;
loader = new URLLoader();
loader.addEventListener(Event.COMPLETE, function (e:Event):void {
puts("Facilitator: registered.");
});
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Facilitator: security error: " + e.text + ".");
rs.close();
});
loader.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("Facilitator: I/O error: " + e.text + ".");
rs.close();
});
fac_url = "http://" + encodeURIComponent(fac_addr.host)
+ ":" + encodeURIComponent(fac_addr.port) + "/";
request = new URLRequest(fac_url);
request.method = URLRequestMethod.POST;
request.data = new URLVariables;
request.data["client"] = rs.id;
puts("Facilitator: connecting to " + fac_url + ".");
loader.load(request);
}
private function make_proxy_pair(client_spec:String, relay_spec:String):ProxyPair
{
var proxy_pair:ProxyPair;
var addr_c:Object;
var addr_r:Object;
var s_c:*;
var s_r:Socket;
addr_r = swfcat.parse_addr_spec(relay_spec);
if (!addr_r)
throw new ArgumentError("Relay spec must be in the form \"host:port\".");
addr_c = swfcat.parse_addr_spec(client_spec);
if (addr_c) {
s_c = new Socket();
s_r = new Socket();
proxy_pair = new ProxyPair(this, s_c, function ():void {
s_c.connect(addr_c.host, addr_c.port);
}, s_r, function ():void {
s_r.connect(addr_r.host, addr_r.port);
});
proxy_pair.set_name("<" + addr_c.host + ":" + addr_c.port + ","
+ addr_r.host + ":" + addr_r.port + ">");
return proxy_pair;
}
if (client_spec.match(/^[0-9A-Fa-f]{64}$/)) {
s_c = new RTMFPSocket(CIRRUS_URL, CIRRUS_KEY);
s_r = new Socket();
proxy_pair = new ProxyPair(this, s_c, function ():void {
s_c.connect(client_spec);
}, s_r, function ():void {
s_r.connect(addr_r.host, addr_r.port);
});
proxy_pair.set_name("<" + client_spec.substr(0, 4) + "...,"
+ addr_r.host + ":" + addr_r.port + ">");
return proxy_pair;
}
throw new ArgumentError("Can't parse client spec \"" + client_spec + "\".");
}
/* 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.text.TextFormat;
import flash.text.TextField;
import flash.utils.getTimer;
class Badge extends flash.display.Sprite
{
/* Number of proxy pairs currently connected. */
private var num_proxy_pairs:int = 0;
/* Number of proxy pairs ever connected. */
private var total_proxy_pairs:int = 0;
[Embed(source="badge.png")]
private var BadgeImage:Class;
private var tot_client_count_tf:TextField;
private var tot_client_count_fmt:TextFormat;
private var cur_client_count_tf:TextField;
private var cur_client_count_fmt:TextFormat;
public function Badge()
{
/* Setup client counter for badge. */
tot_client_count_fmt = new TextFormat();
tot_client_count_fmt.color = 0xFFFFFF;
tot_client_count_fmt.align = "center";
tot_client_count_fmt.font = "courier-new";
tot_client_count_fmt.bold = true;
tot_client_count_fmt.size = 10;
tot_client_count_tf = new TextField();
tot_client_count_tf.width = 20;
tot_client_count_tf.height = 17;
tot_client_count_tf.background = false;
tot_client_count_tf.defaultTextFormat = tot_client_count_fmt;
tot_client_count_tf.x=47;
tot_client_count_tf.y=0;
cur_client_count_fmt = new TextFormat();
cur_client_count_fmt.color = 0xFFFFFF;
cur_client_count_fmt.align = "center";
cur_client_count_fmt.font = "courier-new";
cur_client_count_fmt.bold = true;
cur_client_count_fmt.size = 10;
cur_client_count_tf = new TextField();
cur_client_count_tf.width = 20;
cur_client_count_tf.height = 17;
cur_client_count_tf.background = false;
cur_client_count_tf.defaultTextFormat = cur_client_count_fmt;
cur_client_count_tf.x=47;
cur_client_count_tf.y=6;
addChild(new BadgeImage());
addChild(tot_client_count_tf);
addChild(cur_client_count_tf);
/* Update the client counter on badge. */
update_client_count();
}
public function proxy_begin():void
{
num_proxy_pairs++;
total_proxy_pairs++;
update_client_count();
}
public function proxy_end():void
{
num_proxy_pairs--;
update_client_count();
}
private function update_client_count():void
{
/* Update total client count. */
if (String(total_proxy_pairs).length == 1)
tot_client_count_tf.text = "0" + String(total_proxy_pairs);
else
tot_client_count_tf.text = String(total_proxy_pairs);
/* Update current client count. */
cur_client_count_tf.text = "";
for(var i:Number = 0; i < num_proxy_pairs; i++)
cur_client_count_tf.appendText(".");
}
}
class RateLimit
{
public function RateLimit()
{
}
public function update(n:Number):Boolean
{
return true;
}
public function when():Number
{
return 0.0;
}
public function is_limited():Boolean
{
return false;
}
}
class RateUnlimit extends RateLimit
{
public function RateUnlimit()
{
}
public override function update(n:Number):Boolean
{
return true;
}
public override function when():Number
{
return 0.0;
}
public override function is_limited():Boolean
{
return false;
}
}
class BucketRateLimit extends RateLimit
{
private var amount:Number;
private var capacity:Number;
private var time:Number;
private var last_update:uint;
public function BucketRateLimit(capacity:Number, time:Number)
{
this.amount = 0.0;
/* capacity / time is the rate we are aiming for. */
this.capacity = capacity;
this.time = time;
this.last_update = getTimer();
}
private function age():void
{
var now:uint;
var delta:Number;
now = getTimer();
delta = (now - last_update) / 1000.0;
last_update = now;
amount -= delta * capacity / time;
if (amount < 0.0)
amount = 0.0;
}
public override function update(n:Number):Boolean
{
age();
amount += n;
return amount <= capacity;
}
public override function when():Number
{
age();
return (amount - capacity) / (capacity / time);
}
public override function is_limited():Boolean
{
age();
return amount > capacity;
}
}
|
Make proxy mode the default in swfcat.
|
Make proxy mode the default in swfcat.
In other words, use client=true instead of nothing for client mode, and
nothing instead of proxy=true for proxy mode. This makes it a drop-in
replacement for master swfcat.
|
ActionScript
|
mit
|
infinity0/flashproxy,infinity0/flashproxy,glamrock/flashproxy,glamrock/flashproxy,arlolra/flashproxy,infinity0/flashproxy,arlolra/flashproxy,infinity0/flashproxy,glamrock/flashproxy,glamrock/flashproxy,infinity0/flashproxy,glamrock/flashproxy,glamrock/flashproxy,arlolra/flashproxy,arlolra/flashproxy,infinity0/flashproxy,arlolra/flashproxy,arlolra/flashproxy,arlolra/flashproxy
|
345895c32c3c00b48dc55096d16cb8ad4910184c
|
src/as/com/threerings/flash/FrameSprite.as
|
src/as/com/threerings/flash/FrameSprite.as
|
//
// $Id$
package com.threerings.flash {
import flash.display.Sprite;
import flash.events.Event;
/**
* Convenience superclass to use for sprites that need to update every frame.
* (One must be very careful to remove all ENTER_FRAME listeners when not needed, as they
* will prevent an object from being garbage collected!)
*/
public class FrameSprite extends Sprite
{
public function FrameSprite ()
{
addEventListener(Event.ADDED_TO_STAGE, handleAdded);
addEventListener(Event.REMOVED_FROM_STAGE, handleRemoved);
}
/**
* Called when we're added to the stage.
*/
protected function handleAdded (... ignored) :void
{
addEventListener(Event.ENTER_FRAME, handleFrame);
handleFrame(); // update immediately
}
/**
* Called when we're added to the stage.
*/
protected function handleRemoved (... ignored) :void
{
removeEventListener(Event.ENTER_FRAME, handleFrame);
}
/**
* Called to update our visual appearance prior to the flash player each frame.
*/
protected function handleFrame (... ignored) :void
{
// nothing here. Override in yor subclass.
}
}
}
|
//
// $Id$
package com.threerings.flash {
import flash.display.Sprite;
import flash.events.Event;
/**
* Convenience superclass to use for sprites that need to update every frame.
* (One must be very careful to remove all ENTER_FRAME listeners when not needed, as they
* will prevent an object from being garbage collected!)
*/
public class FrameSprite extends Sprite
{
public function FrameSprite ()
{
addEventListener(Event.ADDED_TO_STAGE, handleAdded);
addEventListener(Event.REMOVED_FROM_STAGE, handleRemoved);
}
/**
* Called when we're added to the stage.
*/
protected function handleAdded (... ignored) :void
{
addEventListener(Event.ENTER_FRAME, handleFrame);
handleFrame(); // update immediately
}
/**
* Called when we're added to the stage.
*/
protected function handleRemoved (... ignored) :void
{
removeEventListener(Event.ENTER_FRAME, handleFrame);
}
/**
* Called to update our visual appearance prior to each frame.
*/
protected function handleFrame (... ignored) :void
{
// nothing here. Override in yor subclass.
}
}
}
|
Comment fixup.
|
Comment fixup.
git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@240 ed5b42cb-e716-0410-a449-f6a68f950b19
|
ActionScript
|
lgpl-2.1
|
threerings/nenya,threerings/nenya
|
2bf2fe41c1dd5acaf38a7db4b9fd8da87a9b46c9
|
exporter/src/main/as/flump/export/Exporter.as
|
exporter/src/main/as/flump/export/Exporter.as
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.export {
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.MouseEvent;
import flash.filesystem.File;
import flash.net.SharedObject;
import flash.utils.IDataOutput;
import flump.executor.Executor;
import flump.executor.Future;
import flump.export.Ternary;
import flump.xfl.ParseError;
import flump.xfl.XflLibrary;
import mx.collections.ArrayList;
import mx.events.CollectionEvent;
import mx.events.PropertyChangeEvent;
import spark.components.DataGrid;
import spark.components.DropDownList;
import spark.components.List;
import spark.components.Window;
import spark.events.GridSelectionEvent;
import starling.display.Sprite;
import com.threerings.util.F;
import com.threerings.util.Log;
import com.threerings.util.StringUtil;
public class Exporter
{
public static const NA :NativeApplication = NativeApplication.nativeApplication;
public function Exporter (win :ExporterWindow) {
Log.setLevel("", Log.INFO);
_win = win;
_errors = _win.errors;
_libraries = _win.libraries;
function updatePreviewAndExport (..._) :void {
_win.export.enabled = _exportChooser.dir != null && _libraries.selectionLength > 0 &&
_libraries.selectedItems.some(function (status :DocStatus, ..._) :Boolean {
return status.isValid;
});
var status :DocStatus = _libraries.selectedItem as DocStatus;
_win.preview.enabled = status != null && status.isValid;
if (_exportChooser.dir == null) return;
_conf.exportDir = _confFile.parent.getRelativePath(_exportChooser.dir, /*useDotDot=*/true);
}
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"), 0);
newMenuItem.keyEquivalent = "n";
newMenuItem.addEventListener(Event.SELECT, function (..._) :void {
_confFile = null;
_conf = new FlumpConf();
updatePublisher();
});
var openMenuItem :NativeMenuItem =
fileMenuItem.submenu.addItemAt(new NativeMenuItem("Open..."), 1);
openMenuItem.keyEquivalent = "o";
openMenuItem.addEventListener(Event.SELECT, function (..._) :void {
var file :File = new File();
file.addEventListener(Event.SELECT, function (..._) :void {
_confFile = file;
openConf();
updatePublisher();
});
file.browseForOpen("Open Flump Configuration");
});
fileMenuItem.submenu.addItemAt(new NativeMenuItem("Sep", /*separator=*/true), 2);
const saveMenuItem :NativeMenuItem =
fileMenuItem.submenu.addItemAt(new NativeMenuItem("Save"), 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));
});
};
function saveAs (..._) :void {
var file :File = new File();
file.addEventListener(Event.SELECT, function (..._) :void {
_confFile = file;
trace("Conf file is now " + _confFile.nativePath);
_settings.data["CONF_FILE"] = _confFile.nativePath;
_settings.flush();
saveConf();
});
file.browseForSave("Save Flump Configuration");
};
saveMenuItem.addEventListener(Event.SELECT, function (..._) :void {
if (_confFile == null) saveAs();
else saveConf();
});
function openConf () :void {
try {
_conf = FlumpConf.fromJSON(JSONFormat.readJSON(_confFile));
_win.title = _confFile.name;
} catch (e :Error) {
log.warning("Unable to parse conf", e);
_errors.dataProvider.addItem(new ParseError(_confFile.nativePath,
ParseError.CRIT, "Unable to read configuration"));
_confFile = null;
}
};
const saveAsMenuItem :NativeMenuItem =
fileMenuItem.submenu.addItemAt(new NativeMenuItem("Save As..."), 4);
saveAsMenuItem.keyEquivalent = "S";
saveAsMenuItem.addEventListener(Event.SELECT, saveAs);
if (_settings.data.hasOwnProperty("CONF_FILE")) {
_confFile = new File(_settings.data["CONF_FILE"]);
openConf();
}
var curSelection :DocStatus = null;
_libraries.addEventListener(GridSelectionEvent.SELECTION_CHANGE, function (..._) :void {
log.info("Changed", "selected", _libraries.selectedIndices);
updatePreviewAndExport();
if (curSelection != null) {
curSelection.removeEventListener(PropertyChangeEvent.PROPERTY_CHANGE, updatePreviewAndExport);
}
var newSelection :DocStatus = _libraries.selectedItem as DocStatus;
if (newSelection != null) {
newSelection.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, updatePreviewAndExport);
}
curSelection = newSelection;
});
_win.reload.addEventListener(MouseEvent.CLICK, function (..._) :void {
setImport(_importChooser.dir);
updatePreviewAndExport();
});
_win.export.addEventListener(MouseEvent.CLICK, function (..._) :void {
for each (var status :DocStatus in _libraries.selectedItems) {
exportFlashDocument(status);
}
});
_win.preview.addEventListener(MouseEvent.CLICK, function (..._) :void {
showPreviewWindow(_libraries.selectedItem.lib);
});
_importChooser = new DirChooser(null, _win.importRoot, _win.browseImport);
_importChooser.changed.add(setImport);
setImport(_importChooser.dir);
_exportChooser = new DirChooser(null, _win.exportRoot, _win.browseExport);
_exportChooser.changed.add(updatePreviewAndExport);
function updatePublisher (..._) :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;
}
if (_exportChooser.dir == null || _conf.exports.length == 0) _publisher = null;
else _publisher = new Publisher(_exportChooser.dir, Vector.<ExportConf>(_conf.exports));
var formatNames :Array = [];
for each (var export :ExportConf in _conf.exports) formatNames.push(export.name);
_win.formatOverview.text = formatNames.join(", ");
};
_exportChooser.changed.add(updatePublisher);
var editFormats :EditFormatsWindow;
_win.editFormats.addEventListener(MouseEvent.CLICK, function (..._) :void {
if (editFormats == null || editFormats.closed) {
editFormats = new EditFormatsWindow();
editFormats.open();
} else editFormats.orderToFront();
var dataProvider :ArrayList = new ArrayList(_conf.exports);
dataProvider.addEventListener(CollectionEvent.COLLECTION_CHANGE, updatePublisher);
editFormats.exports.dataProvider = dataProvider;
editFormats.buttonAdd.addEventListener(MouseEvent.CLICK, function (..._) :void {
var export :ExportConf = new ExportConf();
export.name = "format" + (_conf.exports.length+1);
if (_conf.exports.length > 0) {
export.format = _conf.exports[0].format;
}
dataProvider.addItem(export);
});
editFormats.exports.addEventListener(GridSelectionEvent.SELECTION_CHANGE, function (..._) :void {
editFormats.buttonRemove.enabled = (editFormats.exports.selectedItem != null);
});
editFormats.buttonRemove.addEventListener(MouseEvent.CLICK, function (..._) :void {
for each (var export :ExportConf in editFormats.exports.selectedItems) {
dataProvider.removeItem(export);
}
});
});
updatePublisher();
_win.addEventListener(Event.CLOSE, function (..._) :void { NA.exit(0); });
}
protected function setImport (root :File) :void {
_libraries.dataProvider.removeAll();
_errors.dataProvider.removeAll();
if (root == null) return;
_rootLen = root.nativePath.length + 1;
if (_docFinder != null) _docFinder.shutdownNow();
_docFinder = new Executor();
findFlashDocuments(root, _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 var _previewController :PreviewController;
protected var _previewWindow :PreviewWindow;
protected var _previewControls :PreviewControlsWindow;
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) {
_errors.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;
_publisher.publish(status.lib);
stage.quality = prevQuality;
status.updateModified(Ternary.FALSE);
}
protected function addFlashDocument (file :File) :void {
var name :String = file.nativePath.substring(_rootLen).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, _rootLen, Ternary.UNKNOWN, Ternary.UNKNOWN, null);
_libraries.dataProvider.addItem(status);
load.succeeded.add(function (lib :XflLibrary) :void {
status.lib = lib;
status.updateModified(Ternary.of(_publisher == null || _publisher.modified(lib)));
for each (var err :ParseError in lib.getErrors()) _errors.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 _rootLen :int;
protected var _publisher :Publisher;
protected var _docFinder :Executor;
protected var _win :ExporterWindow;
protected var _libraries :DataGrid;
protected var _errors :DataGrid;
protected var _exportChooser :DirChooser;
protected var _importChooser :DirChooser;
protected var _authoredResolution :DropDownList;
protected var _conf :FlumpConf = new FlumpConf();
protected var _confFile :File;
protected const _settings :SharedObject = SharedObject.getLocal("flump/Exporter");
private static const log :Log = Log.getLog(Exporter);
}
}
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 = QUESTION;
public var lib :XflLibrary;
public function DocStatus (path :String, rootLen :int, 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 = CHECK;
else if (newValid == Ternary.FALSE) valid = FROWN;
else valid = QUESTION;
});
}
public function get isValid () :Boolean { return valid == CHECK; }
public function updateModified (newModified :Ternary) :void {
changeField("modified", function (..._) :void {
if (newModified == Ternary.TRUE) modified = CHECK;
else if (newModified == Ternary.FALSE) modified = " ";
else modified = QUESTION;
});
}
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 QUESTION :String = "?";
protected static const FROWN :String = "☹";
protected static const CHECK :String = "✓";
}
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.export {
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.MouseEvent;
import flash.filesystem.File;
import flash.net.SharedObject;
import flash.utils.IDataOutput;
import flump.executor.Executor;
import flump.executor.Future;
import flump.export.Ternary;
import flump.xfl.ParseError;
import flump.xfl.XflLibrary;
import mx.collections.ArrayList;
import mx.events.CollectionEvent;
import mx.events.PropertyChangeEvent;
import spark.components.DataGrid;
import spark.components.DropDownList;
import spark.components.List;
import spark.components.Window;
import spark.events.GridSelectionEvent;
import com.threerings.util.F;
import com.threerings.util.Log;
import com.threerings.util.StringUtil;
import starling.display.Sprite;
public class Exporter
{
public static const NA :NativeApplication = NativeApplication.nativeApplication;
public function Exporter (win :ExporterWindow) {
Log.setLevel("", Log.INFO);
_win = win;
_errors = _win.errors;
_libraries = _win.libraries;
function updatePreviewAndExport (..._) :void {
_win.export.enabled = _exportChooser.dir != null && _libraries.selectionLength > 0 &&
_libraries.selectedItems.some(function (status :DocStatus, ..._) :Boolean {
return status.isValid;
});
var status :DocStatus = _libraries.selectedItem as DocStatus;
_win.preview.enabled = status != null && status.isValid;
if (_exportChooser.dir == null) return;
_conf.exportDir = _confFile.parent.getRelativePath(_exportChooser.dir, /*useDotDot=*/true);
}
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"), 0);
newMenuItem.keyEquivalent = "n";
newMenuItem.addEventListener(Event.SELECT, function (..._) :void {
_confFile = null;
_conf = new FlumpConf();
updatePublisher();
});
var openMenuItem :NativeMenuItem =
fileMenuItem.submenu.addItemAt(new NativeMenuItem("Open..."), 1);
openMenuItem.keyEquivalent = "o";
openMenuItem.addEventListener(Event.SELECT, function (..._) :void {
var file :File = new File();
file.addEventListener(Event.SELECT, function (..._) :void {
_confFile = file;
openConf();
updatePublisher();
});
file.browseForOpen("Open Flump Configuration");
});
fileMenuItem.submenu.addItemAt(new NativeMenuItem("Sep", /*separator=*/true), 2);
const saveMenuItem :NativeMenuItem =
fileMenuItem.submenu.addItemAt(new NativeMenuItem("Save"), 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));
});
};
function saveAs (..._) :void {
var file :File = new File();
file.addEventListener(Event.SELECT, function (..._) :void {
_confFile = file;
trace("Conf file is now " + _confFile.nativePath);
_settings.data["CONF_FILE"] = _confFile.nativePath;
_settings.flush();
saveConf();
});
file.browseForSave("Save Flump Configuration");
};
saveMenuItem.addEventListener(Event.SELECT, function (..._) :void {
if (_confFile == null) saveAs();
else saveConf();
});
function openConf () :void {
try {
_conf = FlumpConf.fromJSON(JSONFormat.readJSON(_confFile));
_win.title = _confFile.name;
var dir :String = _confFile.parent.nativePath + File.separator + _conf.importDir;
setImport(new File(dir));
} catch (e :Error) {
log.warning("Unable to parse conf", e);
_errors.dataProvider.addItem(new ParseError(_confFile.nativePath,
ParseError.CRIT, "Unable to read configuration"));
_confFile = null;
}
};
const saveAsMenuItem :NativeMenuItem =
fileMenuItem.submenu.addItemAt(new NativeMenuItem("Save As..."), 4);
saveAsMenuItem.keyEquivalent = "S";
saveAsMenuItem.addEventListener(Event.SELECT, saveAs);
if (_settings.data.hasOwnProperty("CONF_FILE")) {
_confFile = new File(_settings.data["CONF_FILE"]);
openConf();
}
var curSelection :DocStatus = null;
_libraries.addEventListener(GridSelectionEvent.SELECTION_CHANGE, function (..._) :void {
log.info("Changed", "selected", _libraries.selectedIndices);
updatePreviewAndExport();
if (curSelection != null) {
curSelection.removeEventListener(PropertyChangeEvent.PROPERTY_CHANGE, updatePreviewAndExport);
}
var newSelection :DocStatus = _libraries.selectedItem as DocStatus;
if (newSelection != null) {
newSelection.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, updatePreviewAndExport);
}
curSelection = newSelection;
});
_win.reload.addEventListener(MouseEvent.CLICK, function (..._) :void {
setImport(_importChooser.dir);
updatePreviewAndExport();
});
_win.export.addEventListener(MouseEvent.CLICK, function (..._) :void {
for each (var status :DocStatus in _libraries.selectedItems) {
exportFlashDocument(status);
}
});
_win.preview.addEventListener(MouseEvent.CLICK, function (..._) :void {
showPreviewWindow(_libraries.selectedItem.lib);
});
_importChooser = new DirChooser(null, _win.importRoot, _win.browseImport);
_importChooser.changed.add(setImport);
setImport(_importChooser.dir);
_exportChooser = new DirChooser(null, _win.exportRoot, _win.browseExport);
_exportChooser.changed.add(updatePreviewAndExport);
function updatePublisher (..._) :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;
}
if (_exportChooser.dir == null || _conf.exports.length == 0) _publisher = null;
else _publisher = new Publisher(_exportChooser.dir, Vector.<ExportConf>(_conf.exports));
var formatNames :Array = [];
for each (var export :ExportConf in _conf.exports) formatNames.push(export.name);
_win.formatOverview.text = formatNames.join(", ");
};
_exportChooser.changed.add(updatePublisher);
var editFormats :EditFormatsWindow;
_win.editFormats.addEventListener(MouseEvent.CLICK, function (..._) :void {
if (editFormats == null || editFormats.closed) {
editFormats = new EditFormatsWindow();
editFormats.open();
} else editFormats.orderToFront();
var dataProvider :ArrayList = new ArrayList(_conf.exports);
dataProvider.addEventListener(CollectionEvent.COLLECTION_CHANGE, updatePublisher);
editFormats.exports.dataProvider = dataProvider;
editFormats.buttonAdd.addEventListener(MouseEvent.CLICK, function (..._) :void {
var export :ExportConf = new ExportConf();
export.name = "format" + (_conf.exports.length+1);
if (_conf.exports.length > 0) {
export.format = _conf.exports[0].format;
}
dataProvider.addItem(export);
});
editFormats.exports.addEventListener(GridSelectionEvent.SELECTION_CHANGE, function (..._) :void {
editFormats.buttonRemove.enabled = (editFormats.exports.selectedItem != null);
});
editFormats.buttonRemove.addEventListener(MouseEvent.CLICK, function (..._) :void {
for each (var export :ExportConf in editFormats.exports.selectedItems) {
dataProvider.removeItem(export);
}
});
});
updatePublisher();
_win.addEventListener(Event.CLOSE, function (..._) :void { NA.exit(0); });
}
protected function setImport (root :File) :void {
_libraries.dataProvider.removeAll();
_errors.dataProvider.removeAll();
if (root == null) return;
_rootLen = root.nativePath.length + 1;
if (_docFinder != null) _docFinder.shutdownNow();
_docFinder = new Executor();
findFlashDocuments(root, _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 var _previewController :PreviewController;
protected var _previewWindow :PreviewWindow;
protected var _previewControls :PreviewControlsWindow;
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) {
_errors.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;
_publisher.publish(status.lib);
stage.quality = prevQuality;
status.updateModified(Ternary.FALSE);
}
protected function addFlashDocument (file :File) :void {
var name :String = file.nativePath.substring(_rootLen).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, _rootLen, Ternary.UNKNOWN, Ternary.UNKNOWN, null);
_libraries.dataProvider.addItem(status);
load.succeeded.add(function (lib :XflLibrary) :void {
status.lib = lib;
status.updateModified(Ternary.of(_publisher == null || _publisher.modified(lib)));
for each (var err :ParseError in lib.getErrors()) _errors.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 _rootLen :int;
protected var _publisher :Publisher;
protected var _docFinder :Executor;
protected var _win :ExporterWindow;
protected var _libraries :DataGrid;
protected var _errors :DataGrid;
protected var _exportChooser :DirChooser;
protected var _importChooser :DirChooser;
protected var _authoredResolution :DropDownList;
protected var _conf :FlumpConf = new FlumpConf();
protected var _confFile :File;
protected const _settings :SharedObject = SharedObject.getLocal("flump/Exporter");
private static const log :Log = Log.getLog(Exporter);
}
}
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 = QUESTION;
public var lib :XflLibrary;
public function DocStatus (path :String, rootLen :int, 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 = CHECK;
else if (newValid == Ternary.FALSE) valid = FROWN;
else valid = QUESTION;
});
}
public function get isValid () :Boolean { return valid == CHECK; }
public function updateModified (newModified :Ternary) :void {
changeField("modified", function (..._) :void {
if (newModified == Ternary.TRUE) modified = CHECK;
else if (newModified == Ternary.FALSE) modified = " ";
else modified = QUESTION;
});
}
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 QUESTION :String = "?";
protected static const FROWN :String = "☹";
protected static const CHECK :String = "✓";
}
|
Read the import dir when a config is opened
|
Read the import dir when a config is opened
|
ActionScript
|
mit
|
tconkling/flump,funkypandagame/flump,mathieuanthoine/flump,mathieuanthoine/flump,tconkling/flump,mathieuanthoine/flump,funkypandagame/flump
|
9a29feb368d61262e9462133507c80b956905bfc
|
frameworks/projects/framework/src/mx/core/DebuggableWorker.as
|
frameworks/projects/framework/src/mx/core/DebuggableWorker.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 mx.core {
import flash.display.Sprite;
import flash.system.Capabilities;
import flash.utils.setInterval;
/**
* DebuggableWorker should be used as a base class
* for workers instead of Sprite.
* it allows the debugging of those workers using FDB.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 3.4
* @productversion Flex 4
*/
public class DebuggableWorker extends Sprite {
include "../core/Version.as";
public function DebuggableWorker() {
// Stick a timer here so that we will execute script every 1.5s
// no matter what.
// This is strictly for the debugger to be able to halt.
// Note: isDebugger is true only with a Debugger Player.
if (Capabilities.isDebugger == true) {
setInterval(debugTickler, 1500);
}
}
/**
* @private
* This is here so we get the this pointer set to Application.
*/
private function debugTickler():void {
// We need some bytes of code in order to have a place to break.
var i:int = 0;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package mx.core {
import flash.display.Sprite;
import flash.system.Capabilities;
import flash.utils.setInterval;
/**
* DebuggableWorker should be used as a base class
* for workers instead of Sprite.
* it allows the debugging of those workers using FDB.
*
* @langversion 3.0
* @playerversion Flash 11.4
* @playerversion AIR 3.4
* @productversion Flex 4
*/
public class DebuggableWorker extends Sprite {
include "../core/Version.as";
public function DebuggableWorker() {
// Stick a timer here so that we will execute script every 1.5s
// no matter what.
// This is strictly for the debugger to be able to halt.
// Note: isDebugger is true only with a Debugger Player.
if (Capabilities.isDebugger == true) {
setInterval(debugTickler, 1500);
}
}
/**
* @private
* This is here so we get the "this" pointer set to this worker instance.
*/
private function debugTickler():void {
// We need some bytes of code in order to have a place to break.
var i:int = 0;
}
}
}
|
Create a base Class for workers making them debuggable via FDB - Adjusted minimum AIR version and typo.
|
FLEX-34294: Create a base Class for workers making them debuggable via FDB
- Adjusted minimum AIR version and typo.
|
ActionScript
|
apache-2.0
|
apache/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk
|
d4f1e7763cb205a80930163a354c51d1ab20f83a
|
src/as/com/threerings/presents/client/Communicator.as
|
src/as/com/threerings/presents/client/Communicator.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.presents.client {
import flash.errors.IOError;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.TimerEvent;
import flash.net.Socket;
import flash.utils.ByteArray;
import flash.utils.Endian;
import flash.utils.Timer;
import com.threerings.util.Log;
import com.threerings.io.FrameAvailableEvent;
import com.threerings.io.FrameReader;
import com.threerings.io.ObjectInputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.presents.data.AuthCodes;
import com.threerings.presents.net.AuthRequest;
import com.threerings.presents.net.AuthResponse;
import com.threerings.presents.net.AuthResponseData;
import com.threerings.presents.net.DownstreamMessage;
import com.threerings.presents.net.LogoffRequest;
import com.threerings.presents.net.UpstreamMessage;
import com.threerings.presents.net.ThrottleUpdatedMessage;
public class Communicator
{
public function Communicator (client :Client)
{
_client = client;
}
public function logon () :void
{
// create our input/output business
_outBuffer = new ByteArray();
_outBuffer.endian = Endian.BIG_ENDIAN;
_outStream = new ObjectOutputStream(_outBuffer);
_inStream = new ObjectInputStream();
attemptLogon(0);
}
public function logoff () :void
{
if (_socket == null) {
return;
}
postMessage(new LogoffRequest());
}
public function postMessage (msg :UpstreamMessage) :void
{
_outq.push(msg);
if (_writer != null) {
sendPendingMessages(null);
} else {
log.warning("Posting message prior to opening socket", "msg", msg);
}
}
/**
* Attempts to logon on using the port at the specified index.
*/
protected function attemptLogon (portIdx :int) :Boolean
{
var ports :Array = _client.getPorts();
_portIdx = portIdx; // note the port we're about to try
if (_portIdx >= ports.length) {
return false;
}
if (_portIdx != 0) {
_client.reportLogonTribulations(new LogonError(AuthCodes.TRYING_NEXT_PORT, true));
removeListeners();
}
// create the socket and set up listeners
_socket = new Socket();
_socket.endian = Endian.BIG_ENDIAN;
_socket.addEventListener(Event.CONNECT, socketOpened);
_socket.addEventListener(IOErrorEvent.IO_ERROR, socketError);
_socket.addEventListener(Event.CLOSE, socketClosed);
_frameReader = new FrameReader(_socket);
_frameReader.addEventListener(FrameAvailableEvent.FRAME_AVAILABLE, inputFrameReceived);
var host :String = _client.getHostname();
var pport :int = ports[0];
var ppidx :int = Math.max(0, ports.indexOf(pport));
var port :int = (ports[(_portIdx + ppidx) % ports.length] as int);
log.info("Connecting [host=" + host + ", port=" + port + "].");
_socket.connect(host, port);
return true;
}
protected function removeListeners () :void
{
_socket.removeEventListener(Event.CONNECT, socketOpened);
_socket.removeEventListener(IOErrorEvent.IO_ERROR, socketError);
_socket.removeEventListener(Event.CLOSE, socketClosed);
_frameReader.removeEventListener(FrameAvailableEvent.FRAME_AVAILABLE, inputFrameReceived);
}
protected function shutdown (logonError :Error) :void
{
if (_socket != null) {
if (_socket.connected) {
try {
_socket.close();
} catch (err :Error) {
log.warning("Error closing failed socket [error=" + err + "].");
}
}
removeListeners();
_socket = null;
_outStream = null;
_inStream = null;
_frameReader = null;
_outBuffer = null;
}
if (_writer != null) {
_writer.stop();
_writer = null;
}
_client.notifyObservers(ClientEvent.CLIENT_DID_LOGOFF, null);
_client.cleanup(logonError);
}
/**
* Sends all pending messages from our outgoing message queue. If we hit our throttle while
* sending, we stop and wait for the next time around when we'll try sending them again.
*/
protected function sendPendingMessages (event :TimerEvent) :void
{
while (_outq.length > 0) {
// if we've exceeded our throttle, stop for now
if (_client.getOutgoingMessageThrottle().throttleOp()) {
if (!_notedThrottle) {
log.info("Throttling outgoing messages", "queue", _outq.length,
"throttle", _client.getOutgoingMessageThrottle());
_notedThrottle = true;
}
return;
}
_notedThrottle = false;
// grab the next message from the queue and send it
var msg :UpstreamMessage = (_outq.shift() as UpstreamMessage);
sendMessage(msg);
// if this was a logoff request, shutdown
if (msg is LogoffRequest) {
shutdown(null);
} else if (msg is ThrottleUpdatedMessage) {
_client.finalizeOutgoingMessageThrottle(ThrottleUpdatedMessage(msg).messagesPerSec);
}
}
}
/**
* Writes a single message to our outgoing socket.
*/
protected function sendMessage (msg :UpstreamMessage) :void
{
if (_outStream == null) {
log.warning("No socket, dropping msg [msg=" + msg + "].");
return;
}
// write the message (ends up in _outBuffer)
_outStream.writeObject(msg);
// Log.debug("outBuffer: " + StringUtil.unhexlate(_outBuffer));
// Frame it by writing the length, then the bytes.
// We add 4 to the length, because the length is of the entire frame
// including the 4 bytes used to encode the length!
_socket.writeInt(_outBuffer.length + 4);
_socket.writeBytes(_outBuffer);
_socket.flush();
// clean up the output buffer
_outBuffer.length = 0;
_outBuffer.position = 0;
// make a note of our most recent write time
updateWriteStamp();
}
/**
* Called when a frame of data from the server is ready to be decoded into a DownstreamMessage.
*/
protected function inputFrameReceived (event :FrameAvailableEvent) :void
{
// convert the frame data into a message from the server
var frameData :ByteArray = event.getFrameData();
_inStream.setSource(frameData);
var msg :DownstreamMessage;
try {
msg = (_inStream.readObject(DownstreamMessage) as DownstreamMessage);
} catch (e :Error) {
log.warning("Error processing downstream message: " + e);
log.logStackTrace(e);
return;
}
if (frameData.bytesAvailable > 0) {
log.warning("Beans! We didn't fully read a frame, is there a bug in some streaming " +
"code? [bytesLeftOver=" + frameData.bytesAvailable + ", msg=" + msg + "].");
}
if (_omgr != null) {
// if we're logged on, then just do the normal thing
_omgr.processMessage(msg);
return;
}
// otherwise, this would be the AuthResponse to our logon attempt
var rsp :AuthResponse = (msg as AuthResponse);
var data :AuthResponseData = rsp.getData();
if (data.code !== AuthResponseData.SUCCESS) {
shutdown(new Error(data.code));
return;
}
// logon success
_omgr = new ClientDObjectMgr(this, _client);
_client.setAuthResponseData(data);
}
/**
* Called when the connection to the server was successfully opened.
*/
protected function socketOpened (event :Event) :void
{
// reset our port index now that we're successfully logged on; this way if the socket
// fails, we won't think that we're in the middle of trying to logon
_portIdx = -1;
// check for a logoff message
for each (var message :UpstreamMessage in _outq) {
if (message is LogoffRequest) {
// don't bother authing, just bail
log.info("Logged off prior to socket opening, shutting down");
shutdown(null);
return;
}
}
// kick off our writer thread now that we know we're ready to write
_writer = new Timer(1);
_writer.addEventListener(TimerEvent.TIMER, sendPendingMessages);
_writer.start();
// clear the queue, the server doesn't like anything sent prior to auth
_outq.length = 0;
// well that's great! let's logon
postMessage(new AuthRequest(_client.getCredentials(), _client.getVersion(),
_client.getBootGroups()));
}
/**
* Called when there is an io error with the socket.
*/
protected function socketError (event :IOErrorEvent) :void
{
// if we're still trying ports, try the next one.
if (_portIdx != -1) {
if (attemptLogon(_portIdx+1)) {
return;
}
}
// total failure
log.warning("Socket error: " + event, "target", event.target);
Log.dumpStack();
shutdown(new Error("Socket closed unexpectedly."));
}
/**
* Called when the connection to the server was closed.
*/
protected function socketClosed (event :Event) :void
{
log.info("Socket was closed: " + event);
_client.notifyObservers(ClientEvent.CLIENT_CONNECTION_FAILED);
shutdown(null);
}
/**
* Returns the time at which we last sent a packet to the server.
*/
internal function getLastWrite () :uint
{
return _lastWrite;
}
/**
* Makes a note of the time at which we last communicated with the server.
*/
internal function updateWriteStamp () :void
{
_lastWrite = flash.utils.getTimer();
}
protected var _client :Client;
protected var _omgr :ClientDObjectMgr;
protected var _outBuffer :ByteArray;
protected var _outStream :ObjectOutputStream;
protected var _inStream :ObjectInputStream;
protected var _frameReader :FrameReader;
protected var _socket :Socket;
protected var _lastWrite :uint;
protected var _outq :Array = new Array();
protected var _writer :Timer;
protected var _notedThrottle :Boolean = false;
protected const log :Log = Log.getLog(this);
/** The current port we'll try to connect to. */
protected var _portIdx :int = -1;
}
}
|
//
// $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.presents.client {
import flash.errors.IOError;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.TimerEvent;
import flash.net.Socket;
import flash.utils.ByteArray;
import flash.utils.Endian;
import flash.utils.Timer;
import com.threerings.util.Log;
import com.threerings.io.FrameAvailableEvent;
import com.threerings.io.FrameReader;
import com.threerings.io.ObjectInputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.presents.data.AuthCodes;
import com.threerings.presents.net.AuthRequest;
import com.threerings.presents.net.AuthResponse;
import com.threerings.presents.net.AuthResponseData;
import com.threerings.presents.net.DownstreamMessage;
import com.threerings.presents.net.LogoffRequest;
import com.threerings.presents.net.UpstreamMessage;
import com.threerings.presents.net.ThrottleUpdatedMessage;
public class Communicator
{
public function Communicator (client :Client)
{
_client = client;
}
public function logon () :void
{
// create our input/output business
_outBuffer = new ByteArray();
_outBuffer.endian = Endian.BIG_ENDIAN;
_outStream = new ObjectOutputStream(_outBuffer);
_inStream = new ObjectInputStream();
attemptLogon(0);
}
public function logoff () :void
{
if (_socket == null) {
return;
}
postMessage(new LogoffRequest());
}
public function postMessage (msg :UpstreamMessage) :void
{
_outq.push(msg);
if (_writer != null) {
sendPendingMessages(null);
} else {
log.warning("Posting message prior to opening socket", "msg", msg);
}
}
/**
* Attempts to logon on using the port at the specified index.
*/
protected function attemptLogon (portIdx :int) :Boolean
{
var ports :Array = _client.getPorts();
_portIdx = portIdx; // note the port we're about to try
if (_portIdx >= ports.length) {
return false;
}
if (_portIdx != 0) {
_client.reportLogonTribulations(new LogonError(AuthCodes.TRYING_NEXT_PORT, true));
removeListeners();
}
// create the socket and set up listeners
_socket = new Socket();
_socket.endian = Endian.BIG_ENDIAN;
_socket.addEventListener(Event.CONNECT, socketOpened);
_socket.addEventListener(IOErrorEvent.IO_ERROR, socketError);
_socket.addEventListener(Event.CLOSE, socketClosed);
_frameReader = new FrameReader(_socket);
_frameReader.addEventListener(FrameAvailableEvent.FRAME_AVAILABLE, inputFrameReceived);
var host :String = _client.getHostname();
var pport :int = ports[0];
var ppidx :int = Math.max(0, ports.indexOf(pport));
var port :int = (ports[(_portIdx + ppidx) % ports.length] as int);
log.info("Connecting", "host", host, "port", port, "svcs", _client.getBootGroups());
_socket.connect(host, port);
return true;
}
protected function removeListeners () :void
{
_socket.removeEventListener(Event.CONNECT, socketOpened);
_socket.removeEventListener(IOErrorEvent.IO_ERROR, socketError);
_socket.removeEventListener(Event.CLOSE, socketClosed);
_frameReader.removeEventListener(FrameAvailableEvent.FRAME_AVAILABLE, inputFrameReceived);
}
protected function shutdown (logonError :Error) :void
{
if (_socket != null) {
if (_socket.connected) {
try {
_socket.close();
} catch (err :Error) {
log.warning("Error closing failed socket [error=" + err + "].");
}
}
removeListeners();
_socket = null;
_outStream = null;
_inStream = null;
_frameReader = null;
_outBuffer = null;
}
if (_writer != null) {
_writer.stop();
_writer = null;
}
_client.notifyObservers(ClientEvent.CLIENT_DID_LOGOFF, null);
_client.cleanup(logonError);
}
/**
* Sends all pending messages from our outgoing message queue. If we hit our throttle while
* sending, we stop and wait for the next time around when we'll try sending them again.
*/
protected function sendPendingMessages (event :TimerEvent) :void
{
while (_outq.length > 0) {
// if we've exceeded our throttle, stop for now
if (_client.getOutgoingMessageThrottle().throttleOp()) {
if (!_notedThrottle) {
log.info("Throttling outgoing messages", "queue", _outq.length,
"throttle", _client.getOutgoingMessageThrottle());
_notedThrottle = true;
}
return;
}
_notedThrottle = false;
// grab the next message from the queue and send it
var msg :UpstreamMessage = (_outq.shift() as UpstreamMessage);
sendMessage(msg);
// if this was a logoff request, shutdown
if (msg is LogoffRequest) {
shutdown(null);
} else if (msg is ThrottleUpdatedMessage) {
_client.finalizeOutgoingMessageThrottle(ThrottleUpdatedMessage(msg).messagesPerSec);
}
}
}
/**
* Writes a single message to our outgoing socket.
*/
protected function sendMessage (msg :UpstreamMessage) :void
{
if (_outStream == null) {
log.warning("No socket, dropping msg [msg=" + msg + "].");
return;
}
// write the message (ends up in _outBuffer)
_outStream.writeObject(msg);
// Log.debug("outBuffer: " + StringUtil.unhexlate(_outBuffer));
// Frame it by writing the length, then the bytes.
// We add 4 to the length, because the length is of the entire frame
// including the 4 bytes used to encode the length!
_socket.writeInt(_outBuffer.length + 4);
_socket.writeBytes(_outBuffer);
_socket.flush();
// clean up the output buffer
_outBuffer.length = 0;
_outBuffer.position = 0;
// make a note of our most recent write time
updateWriteStamp();
}
/**
* Called when a frame of data from the server is ready to be decoded into a DownstreamMessage.
*/
protected function inputFrameReceived (event :FrameAvailableEvent) :void
{
// convert the frame data into a message from the server
var frameData :ByteArray = event.getFrameData();
_inStream.setSource(frameData);
var msg :DownstreamMessage;
try {
msg = (_inStream.readObject(DownstreamMessage) as DownstreamMessage);
} catch (e :Error) {
log.warning("Error processing downstream message: " + e);
log.logStackTrace(e);
return;
}
if (frameData.bytesAvailable > 0) {
log.warning("Beans! We didn't fully read a frame, is there a bug in some streaming " +
"code? [bytesLeftOver=" + frameData.bytesAvailable + ", msg=" + msg + "].");
}
if (_omgr != null) {
// if we're logged on, then just do the normal thing
_omgr.processMessage(msg);
return;
}
// otherwise, this would be the AuthResponse to our logon attempt
var rsp :AuthResponse = (msg as AuthResponse);
var data :AuthResponseData = rsp.getData();
if (data.code !== AuthResponseData.SUCCESS) {
shutdown(new Error(data.code));
return;
}
// logon success
_omgr = new ClientDObjectMgr(this, _client);
_client.setAuthResponseData(data);
}
/**
* Called when the connection to the server was successfully opened.
*/
protected function socketOpened (event :Event) :void
{
// reset our port index now that we're successfully logged on; this way if the socket
// fails, we won't think that we're in the middle of trying to logon
_portIdx = -1;
// check for a logoff message
for each (var message :UpstreamMessage in _outq) {
if (message is LogoffRequest) {
// don't bother authing, just bail
log.info("Logged off prior to socket opening, shutting down");
shutdown(null);
return;
}
}
// send our authentication request (do so directly rather than putting it on the outgoing
// write queue)
sendMessage(new AuthRequest(_client.getCredentials(), _client.getVersion(),
_client.getBootGroups()));
// kick off our writer thread now that we know we're ready to write
_writer = new Timer(1);
_writer.addEventListener(TimerEvent.TIMER, sendPendingMessages);
_writer.start();
// clear the queue, the server doesn't like anything sent prior to auth
_outq.length = 0;
}
/**
* Called when there is an io error with the socket.
*/
protected function socketError (event :IOErrorEvent) :void
{
// if we're still trying ports, try the next one.
if (_portIdx != -1) {
if (attemptLogon(_portIdx+1)) {
return;
}
}
// total failure
log.warning("Socket error: " + event, "target", event.target);
Log.dumpStack();
shutdown(new Error("Socket closed unexpectedly."));
}
/**
* Called when the connection to the server was closed.
*/
protected function socketClosed (event :Event) :void
{
log.info("Socket was closed: " + event);
_client.notifyObservers(ClientEvent.CLIENT_CONNECTION_FAILED);
shutdown(null);
}
/**
* Returns the time at which we last sent a packet to the server.
*/
internal function getLastWrite () :uint
{
return _lastWrite;
}
/**
* Makes a note of the time at which we last communicated with the server.
*/
internal function updateWriteStamp () :void
{
_lastWrite = flash.utils.getTimer();
}
protected var _client :Client;
protected var _omgr :ClientDObjectMgr;
protected var _outBuffer :ByteArray;
protected var _outStream :ObjectOutputStream;
protected var _inStream :ObjectInputStream;
protected var _frameReader :FrameReader;
protected var _socket :Socket;
protected var _lastWrite :uint;
protected var _outq :Array = new Array();
protected var _writer :Timer;
protected var _notedThrottle :Boolean = false;
protected const log :Log = Log.getLog(this);
/** The current port we'll try to connect to. */
protected var _portIdx :int = -1;
}
}
|
Send our auth request directly instead of running it through the queue. Also log our boot groups to make it easier to distinguish which "server" we're logging onto.
|
Send our auth request directly instead of running it through the queue. Also
log our boot groups to make it easier to distinguish which "server" we're
logging onto.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@5675 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
2256b1aab02218db7253868b337cacaa15e927cd
|
as3/xobjas3/src/com/rpath/xobj/XObjUtils.as
|
as3/xobjas3/src/com/rpath/xobj/XObjUtils.as
|
/*
#
# Copyright (c) 2008 rPath, Inc.
#
# This program is distributed under the terms of the MIT License as found
# in a file called LICENSE. If it is not present, the license
# is always available at http://www.opensource.org/licenses/mit-license.php.
#
# This program is distributed in the hope that it will be useful, but
# without any waranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the MIT License for full details.
*/
package com.rpath.xobj
{
import mx.collections.ArrayCollection;
import mx.utils.DescribeTypeCache;
import mx.utils.ObjectProxy;
import flash.utils.getQualifiedClassName;
import flash.utils.getDefinitionByName;
import flash.xml.XMLNode;
import mx.utils.object_proxy;
use namespace object_proxy;
public class XObjUtils
{
public static const DEFAULT_NAMESPACE_PREFIX:String = "_default_";
/**
* @private
*/
private static var CLASS_INFO_CACHE:Object = {};
/**
* Returns the local name of an XMLNode.
*
* @return The local name of an XMLNode.
*/
public static function getLocalName(xmlNode:XMLNode):String
{
return getNCName(xmlNode.nodeName);
}
public static function getNCName(name:String):String
{
var myPrefixIndex:int = name.indexOf(":");
if (myPrefixIndex != -1)
{
name = name.substring(myPrefixIndex+1);
}
return name;
}
public static function encodeElementTag(qname:XObjQName, node:XMLNode):String
{
var elementTag:String = XObjUtils.getNCName(qname.localName);
var prefix:String = node.getPrefixForNamespace(qname.uri);
if (prefix)
elementTag = prefix + ":" + elementTag;
return elementTag;
}
/**
* Return a Class instance based on a string class name
* @private
*/
public static function getClassByName(className:String):Class
{
var classReference:Class = null;
try
{
classReference = getDefinitionByName(className) as Class;
}
catch (e:ReferenceError)
{
trace("Request for unknown class "+className);
}
return classReference;
}
private static var typePropertyCache:Object = {};
public static function isTypeArray(type:Class):Boolean
{
if (type == null)
return false;
var foo:* = new type();
return (foo is Array);
}
public static function isTypeArrayCollection(type:Class):Boolean
{
if (type == null)
return false;
var foo:* = new type();
return (foo is ArrayCollection);
}
public static function typeInfoForProperty(object:*, className:String, propName:String):Object
{
var isArray:Boolean = false;
var result:Object = {typeName: null, isArray: false, isArrayCollection: false};
if (className == "Object" || className == "mx.utils::ObjectProxy")
return result;
var propertyCacheKey:String = className + "." + propName;
var arrayElementType:String;
result = typePropertyCache[propertyCacheKey];
if (result == null)
{
result = {typeName: null, isArray: false, isArrayCollection: false};
// go look it up (expensive)
// very important to use the instance object here, not the classname
// using the classname results in the typeInfo cache
// returning class not instance info later on! Bad cache!
var typeDesc:* = DescribeTypeCache.describeType(object);
var typeInfo:XML = typeDesc.typeDescription;
result.typeName = typeInfo..accessor.(@name == propName)[email protected]().replace( /::/, "." );
if (result.typeName == null || result.typeName == "")
{
result.typeName = typeInfo..variable.(@name == propName)[email protected]().replace( /::/, "." );
arrayElementType = typeInfo..variable.(@name == propName).metadata.(@name == 'ArrayElementType')[email protected]().replace( /::/, "." );
}
else
arrayElementType = typeInfo..accessor.(@name == propName).metadata.(@name == 'ArrayElementType')[email protected]().replace( /::/, "." );
if (result.typeName == "Array")
{
result.isArray = true;
result.typeName = null; // assume generic object unless told otherwise
}
else if (result.typeName == "ArrayCollection")
{
result.isArrayCollection = true;
result.typeName = null; // assume generic object unless told otherwise
}
if (arrayElementType != "")
{
// use type specified
result.typeName = arrayElementType;
}
if (result.typeName == "Object"
|| result.typeName == "mx.utils::ObjectProxy"
|| result.typeName == "Undefined"
|| result.typeName == "*"
|| result.typeName == "")
{
result.typeName = null;
}
// cache the result for next time
typePropertyCache[propertyCacheKey] = result;
}
return result;
}
/**
* Use our own version of getClassInfo to support various metadata
* tags we use. See ObjectUtil.getClassInfo for more info about
* the baisc functionality of this method.
*/
public static function getClassInfo(obj:Object,
excludes:Array = null,
options:Object = null):Object
{
var n:int;
var i:int;
if (obj is ObjectProxy)
obj = ObjectProxy(obj).object_proxy::object;
if (options == null)
options = { includeReadOnly: true, uris: null, includeTransient: true };
var result:Object;
var propertyNames:Array = [];
var cacheKey:String;
var className:String;
var classAlias:String;
var properties:XMLList;
var prop:XML;
var dynamic:Boolean = false;
var metadataInfo:Object;
if (typeof(obj) == "xml")
{
className = "XML";
properties = obj.text();
if (properties.length())
propertyNames.push("*");
properties = obj.attributes();
}
else
{
var classInfo:XML = DescribeTypeCache.describeType(obj).typeDescription;
className = [email protected]();
classAlias = [email protected]();
dynamic = ([email protected]() == "true");
if (options.includeReadOnly)
properties = classInfo..accessor.(@access != "writeonly") + classInfo..variable;
else
properties = classInfo..accessor.(@access == "readwrite") + classInfo..variable;
var numericIndex:Boolean = false;
}
// If type is not dynamic, check our cache for class info...
if (!dynamic)
{
cacheKey = getCacheKey(obj, excludes, options);
result = CLASS_INFO_CACHE[cacheKey];
if (result != null)
return result;
}
result = {};
result["name"] = className;
result["alias"] = classAlias;
result["properties"] = propertyNames;
result["dynamic"] = dynamic;
result["metadata"] = metadataInfo = recordMetadata(properties);
var excludeObject:Object = {};
if (excludes)
{
n = excludes.length;
for (i = 0; i < n; i++)
{
excludeObject[excludes[i]] = 1;
}
}
//TODO this seems slightly fragile, why not use the 'is' operator?
var isArray:Boolean = (className == "Array");
var isDict:Boolean = (className == "flash.utils::Dictionary");
if (isDict)
{
// dictionaries can have multiple keys of the same type,
// (they can index by reference rather than QName, String, or number),
// which cannot be looked up by QName, so use references to the actual key
for (var key:* in obj)
{
propertyNames.push(key);
}
}
else if (dynamic)
{
for (var p:String in obj)
{
if (excludeObject[p] != 1)
{
if (isArray)
{
var pi:Number = parseInt(p);
if (isNaN(pi))
propertyNames.push(new QName("", p));
else
propertyNames.push(pi);
}
else
{
propertyNames.push(new QName("", p));
}
}
}
numericIndex = isArray && !isNaN(Number(p));
}
if (isArray || isDict || className == "Object")
{
// Do nothing since we've already got the dynamic members
}
else if (className == "XML")
{
n = properties.length();
for (i = 0; i < n; i++)
{
p = properties[i].name();
if (excludeObject[p] != 1)
propertyNames.push(new QName("", "@" + p));
}
}
else
{
n = properties.length();
var uris:Array = options.uris;
var uri:String;
var qName:QName;
for (i = 0; i < n; i++)
{
prop = properties[i];
p = [email protected]();
uri = [email protected]();
if (excludeObject[p] == 1)
continue;
if (!options.includeTransient && internalHasMetadata(metadataInfo, p, "Transient"))
continue;
if (internalHasMetadata(metadataInfo, p, "xobjTransient"))
continue;
if (uris != null)
{
if (uris.length == 1 && uris[0] == "*")
{
qName = new QName(uri, p);
try
{
obj[qName]; // access the property to ensure it is supported
propertyNames.push();
}
catch(e:Error)
{
// don't keep property name
}
}
else
{
for (var j:int = 0; j < uris.length; j++)
{
uri = uris[j];
if ([email protected]() == uri)
{
qName = new QName(uri, p);
try
{
obj[qName];
propertyNames.push(qName);
}
catch(e:Error)
{
// don't keep property name
}
}
}
}
}
else if (uri.length == 0)
{
qName = new QName(uri, p);
try
{
obj[qName];
propertyNames.push(qName);
}
catch(e:Error)
{
// don't keep property name
}
}
}
}
propertyNames.sort(Array.CASEINSENSITIVE |
(numericIndex ? Array.NUMERIC : 0));
// dictionary keys can be indexed by an object reference
// there's a possibility that two keys will have the same toString()
// so we don't want to remove dupes
if (!isDict)
{
// for Arrays, etc., on the other hand...
// remove any duplicates, i.e. any items that can't be distingushed by toString()
for (i = 0; i < propertyNames.length - 1; i++)
{
// the list is sorted so any duplicates should be adjacent
// two properties are only equal if both the uri and local name are identical
if (propertyNames[i].toString() == propertyNames[i + 1].toString())
{
propertyNames.splice(i, 1);
i--; // back up
}
}
}
// For normal, non-dynamic classes we cache the class info
if (!dynamic)
{
cacheKey = getCacheKey(obj, excludes, options);
CLASS_INFO_CACHE[cacheKey] = result;
}
return result;
}
/**
* @private
*/
private static function internalHasMetadata(metadataInfo:Object, propName:String, metadataName:String):Boolean
{
if (metadataInfo != null)
{
var metadata:Object = metadataInfo[propName];
if (metadata != null)
{
if (metadata[metadataName] != null)
return true;
}
}
return false;
}
/**
* @private
*/
private static function recordMetadata(properties:XMLList):Object
{
var result:Object = null;
try
{
for each (var prop:XML in properties)
{
var propName:String = prop.attribute("name").toString();
var metadataList:XMLList = prop.metadata;
if (metadataList.length() > 0)
{
if (result == null)
result = {};
var metadata:Object = {};
result[propName] = metadata;
for each (var md:XML in metadataList)
{
var mdName:String = md.attribute("name").toString();
var argsList:XMLList = md.arg;
var value:Object = {};
for each (var arg:XML in argsList)
{
var argKey:String = arg.attribute("key").toString();
if (argKey != null)
{
var argValue:String = arg.attribute("value").toString();
value[argKey] = argValue;
}
}
var existing:Object = metadata[mdName];
if (existing != null)
{
var existingArray:Array;
if (existing is Array)
existingArray = existing as Array;
else
existingArray = [];
existingArray.push(value);
existing = existingArray;
}
else
{
existing = value;
}
metadata[mdName] = existing;
}
}
}
}
catch(e:Error)
{
}
return result;
}
/**
* @private
*/
private static function getCacheKey(o:Object, excludes:Array = null, options:Object = null):String
{
var key:String = getQualifiedClassName(o);
if (excludes != null)
{
for (var i:uint = 0; i < excludes.length; i++)
{
var excl:String = excludes[i] as String;
if (excl != null)
key += excl;
}
}
if (options != null)
{
for (var flag:String in options)
{
key += flag;
var value:String = options[flag] as String;
if (value != null)
key += value;
}
}
return key;
}
}
}
|
/*
#
# Copyright (c) 2008 rPath, Inc.
#
# This program is distributed under the terms of the MIT License as found
# in a file called LICENSE. If it is not present, the license
# is always available at http://www.opensource.org/licenses/mit-license.php.
#
# This program is distributed in the hope that it will be useful, but
# without any waranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the MIT License for full details.
*/
package com.rpath.xobj
{
import mx.collections.ArrayCollection;
import mx.utils.DescribeTypeCache;
import mx.utils.ObjectProxy;
import flash.utils.getQualifiedClassName;
import flash.utils.getDefinitionByName;
import flash.xml.XMLNode;
import mx.utils.object_proxy;
use namespace object_proxy;
public class XObjUtils
{
public static const DEFAULT_NAMESPACE_PREFIX:String = "_default_";
/**
* @private
*/
private static var CLASS_INFO_CACHE:Object = {};
/**
* Returns the local name of an XMLNode.
*
* @return The local name of an XMLNode.
*/
public static function getLocalName(xmlNode:XMLNode):String
{
return getNCName(xmlNode.nodeName);
}
public static function getNCName(name:String):String
{
var myPrefixIndex:int = name.indexOf(":");
if (myPrefixIndex != -1)
{
name = name.substring(myPrefixIndex+1);
}
return name;
}
public static function encodeElementTag(qname:XObjQName, node:XMLNode):String
{
var elementTag:String = XObjUtils.getNCName(qname.localName);
var prefix:String = node.getPrefixForNamespace(qname.uri);
if (prefix)
elementTag = prefix + ":" + elementTag;
return elementTag;
}
/**
* Return a Class instance based on a string class name
* @private
*/
public static function getClassByName(className:String):Class
{
var classReference:Class = null;
try
{
classReference = getDefinitionByName(className) as Class;
}
catch (e:ReferenceError)
{
trace("Request for unknown class "+className);
}
return classReference;
}
private static var typePropertyCache:Object = {};
public static function isTypeArray(type:Class):Boolean
{
if (type == null)
return false;
var foo:* = new type();
return (foo is Array);
}
public static function isTypeArrayCollection(type:Class):Boolean
{
if (type == null)
return false;
var foo:* = new type();
return (foo is ArrayCollection);
}
public static function typeInfoForProperty(object:*, className:String, propName:String):Object
{
var isArray:Boolean = false;
var result:Object = {typeName: null, isArray: false, isArrayCollection: false};
if (propName == "label")
trace("stop");
if (className == "Object" || className == "mx.utils::ObjectProxy")
return result;
var propertyCacheKey:String = className + "." + propName;
var arrayElementType:String;
result = typePropertyCache[propertyCacheKey];
if (result == null)
{
result = {typeName: null, isArray: false, isArrayCollection: false};
// go look it up (expensive)
// very important to use the instance object here, not the classname
// using the classname results in the typeInfo cache
// returning class not instance info later on! Bad cache!
var typeDesc:* = DescribeTypeCache.describeType(object);
var typeInfo:XML = typeDesc.typeDescription;
result.typeName = typeInfo..accessor.(@name == propName)[email protected]().replace( /::/, "." );
if (result.typeName == null || result.typeName == "")
{
result.typeName = typeInfo..variable.(@name == propName)[email protected]().replace( /::/, "." );
arrayElementType = typeInfo..variable.(@name == propName).metadata.(@name == 'ArrayElementType')[email protected]().replace( /::/, "." );
}
else
arrayElementType = typeInfo..accessor.(@name == propName).metadata.(@name == 'ArrayElementType')[email protected]().replace( /::/, "." );
if (result.typeName == "Array")
{
result.isArray = true;
result.typeName = null; // assume generic object unless told otherwise
}
else if (result.typeName == "mx.collections.ArrayCollection")
{
result.isArrayCollection = true;
result.typeName = null; // assume generic object unless told otherwise
}
if (arrayElementType != "")
{
// use type specified
result.typeName = arrayElementType;
}
if (result.typeName == "Object"
|| result.typeName == "mx.utils::ObjectProxy"
|| result.typeName == "Undefined"
|| result.typeName == "*"
|| result.typeName == "")
{
result.typeName = null;
}
// cache the result for next time
typePropertyCache[propertyCacheKey] = result;
}
return result;
}
/**
* Use our own version of getClassInfo to support various metadata
* tags we use. See ObjectUtil.getClassInfo for more info about
* the baisc functionality of this method.
*/
public static function getClassInfo(obj:Object,
excludes:Array = null,
options:Object = null):Object
{
var n:int;
var i:int;
if (obj is ObjectProxy)
obj = ObjectProxy(obj).object_proxy::object;
if (options == null)
options = { includeReadOnly: true, uris: null, includeTransient: true };
var result:Object;
var propertyNames:Array = [];
var cacheKey:String;
var className:String;
var classAlias:String;
var properties:XMLList;
var prop:XML;
var dynamic:Boolean = false;
var metadataInfo:Object;
if (typeof(obj) == "xml")
{
className = "XML";
properties = obj.text();
if (properties.length())
propertyNames.push("*");
properties = obj.attributes();
}
else
{
var classInfo:XML = DescribeTypeCache.describeType(obj).typeDescription;
className = [email protected]();
classAlias = [email protected]();
dynamic = ([email protected]() == "true");
if (options.includeReadOnly)
properties = classInfo..accessor.(@access != "writeonly") + classInfo..variable;
else
properties = classInfo..accessor.(@access == "readwrite") + classInfo..variable;
var numericIndex:Boolean = false;
}
// If type is not dynamic, check our cache for class info...
if (!dynamic)
{
cacheKey = getCacheKey(obj, excludes, options);
result = CLASS_INFO_CACHE[cacheKey];
if (result != null)
return result;
}
result = {};
result["name"] = className;
result["alias"] = classAlias;
result["properties"] = propertyNames;
result["dynamic"] = dynamic;
result["metadata"] = metadataInfo = recordMetadata(properties);
var excludeObject:Object = {};
if (excludes)
{
n = excludes.length;
for (i = 0; i < n; i++)
{
excludeObject[excludes[i]] = 1;
}
}
//TODO this seems slightly fragile, why not use the 'is' operator?
var isArray:Boolean = (className == "Array");
var isDict:Boolean = (className == "flash.utils::Dictionary");
if (isDict)
{
// dictionaries can have multiple keys of the same type,
// (they can index by reference rather than QName, String, or number),
// which cannot be looked up by QName, so use references to the actual key
for (var key:* in obj)
{
propertyNames.push(key);
}
}
else if (dynamic)
{
for (var p:String in obj)
{
if (excludeObject[p] != 1)
{
if (isArray)
{
var pi:Number = parseInt(p);
if (isNaN(pi))
propertyNames.push(new QName("", p));
else
propertyNames.push(pi);
}
else
{
propertyNames.push(new QName("", p));
}
}
}
numericIndex = isArray && !isNaN(Number(p));
}
if (isArray || isDict || className == "Object")
{
// Do nothing since we've already got the dynamic members
}
else if (className == "XML")
{
n = properties.length();
for (i = 0; i < n; i++)
{
p = properties[i].name();
if (excludeObject[p] != 1)
propertyNames.push(new QName("", "@" + p));
}
}
else
{
n = properties.length();
var uris:Array = options.uris;
var uri:String;
var qName:QName;
for (i = 0; i < n; i++)
{
prop = properties[i];
p = [email protected]();
uri = [email protected]();
if (excludeObject[p] == 1)
continue;
if (!options.includeTransient && internalHasMetadata(metadataInfo, p, "Transient"))
continue;
if (internalHasMetadata(metadataInfo, p, "xobjTransient"))
continue;
if (uris != null)
{
if (uris.length == 1 && uris[0] == "*")
{
qName = new QName(uri, p);
try
{
obj[qName]; // access the property to ensure it is supported
propertyNames.push();
}
catch(e:Error)
{
// don't keep property name
}
}
else
{
for (var j:int = 0; j < uris.length; j++)
{
uri = uris[j];
if ([email protected]() == uri)
{
qName = new QName(uri, p);
try
{
obj[qName];
propertyNames.push(qName);
}
catch(e:Error)
{
// don't keep property name
}
}
}
}
}
else if (uri.length == 0)
{
qName = new QName(uri, p);
try
{
obj[qName];
propertyNames.push(qName);
}
catch(e:Error)
{
// don't keep property name
}
}
}
}
propertyNames.sort(Array.CASEINSENSITIVE |
(numericIndex ? Array.NUMERIC : 0));
// dictionary keys can be indexed by an object reference
// there's a possibility that two keys will have the same toString()
// so we don't want to remove dupes
if (!isDict)
{
// for Arrays, etc., on the other hand...
// remove any duplicates, i.e. any items that can't be distingushed by toString()
for (i = 0; i < propertyNames.length - 1; i++)
{
// the list is sorted so any duplicates should be adjacent
// two properties are only equal if both the uri and local name are identical
if (propertyNames[i].toString() == propertyNames[i + 1].toString())
{
propertyNames.splice(i, 1);
i--; // back up
}
}
}
// For normal, non-dynamic classes we cache the class info
if (!dynamic)
{
cacheKey = getCacheKey(obj, excludes, options);
CLASS_INFO_CACHE[cacheKey] = result;
}
return result;
}
/**
* @private
*/
private static function internalHasMetadata(metadataInfo:Object, propName:String, metadataName:String):Boolean
{
if (metadataInfo != null)
{
var metadata:Object = metadataInfo[propName];
if (metadata != null)
{
if (metadata[metadataName] != null)
return true;
}
}
return false;
}
/**
* @private
*/
private static function recordMetadata(properties:XMLList):Object
{
var result:Object = null;
try
{
for each (var prop:XML in properties)
{
var propName:String = prop.attribute("name").toString();
var metadataList:XMLList = prop.metadata;
if (metadataList.length() > 0)
{
if (result == null)
result = {};
var metadata:Object = {};
result[propName] = metadata;
for each (var md:XML in metadataList)
{
var mdName:String = md.attribute("name").toString();
var argsList:XMLList = md.arg;
var value:Object = {};
for each (var arg:XML in argsList)
{
var argKey:String = arg.attribute("key").toString();
if (argKey != null)
{
var argValue:String = arg.attribute("value").toString();
value[argKey] = argValue;
}
}
var existing:Object = metadata[mdName];
if (existing != null)
{
var existingArray:Array;
if (existing is Array)
existingArray = existing as Array;
else
existingArray = [];
existingArray.push(value);
existing = existingArray;
}
else
{
existing = value;
}
metadata[mdName] = existing;
}
}
}
}
catch(e:Error)
{
}
return result;
}
/**
* @private
*/
private static function getCacheKey(o:Object, excludes:Array = null, options:Object = null):String
{
var key:String = getQualifiedClassName(o);
if (excludes != null)
{
for (var i:uint = 0; i < excludes.length; i++)
{
var excl:String = excludes[i] as String;
if (excl != null)
key += excl;
}
}
if (options != null)
{
for (var flag:String in options)
{
key += flag;
var value:String = options[flag] as String;
if (value != null)
key += value;
}
}
return key;
}
}
}
|
Fix for handling ArrayCollections declared directly
|
Fix for handling ArrayCollections declared directly
|
ActionScript
|
apache-2.0
|
sassoftware/xobj,sassoftware/xobj,sassoftware/xobj,sassoftware/xobj
|
4c49fef5d0fa1965ef51598ffa998da78ef6849e
|
src/aerys/minko/scene/controller/SkeletonController.as
|
src/aerys/minko/scene/controller/SkeletonController.as
|
package aerys.minko.scene.controller
{
/**
* The SkeletonController aggregates AnimationController objects
* and control them in order to start/stop playing animations on
* multiple scene nodes at the same time and control a whole
* skeleton.
*
* @author Jean-Marc Le Roux
*
*/
public final class SkeletonController
{
private var _animations : Vector.<AnimationController> = null;
public function SkeletonController(animations : Vector.<AnimationController>)
{
_animations = animations.slice();
}
public function get animations() : Vector.<AnimationController>
{
return _animations;
}
public function goto(time : Object) : SkeletonController
{
var numAnimations : uint = _animations.length;
for (var animId : uint = 0; animId < numAnimations; ++animId)
(_animations[animId] as AnimationController).goto(time);
return this;
}
public function stop() : SkeletonController
{
var numAnimations : uint = _animations.length;
for (var animId : uint = 0; animId < numAnimations; ++animId)
(_animations[animId] as AnimationController).stop();
return this;
}
public function play() : SkeletonController
{
var numAnimations : uint = _animations.length;
for (var animId : uint = 0; animId < numAnimations; ++animId)
(_animations[animId] as AnimationController).play();
return this;
}
public function setPlaybackWindow(beginTime : Object = null,
endTime : Object = null) : SkeletonController
{
var numAnimations : uint = _animations.length;
for (var animId : uint = 0; animId < numAnimations; ++animId)
(_animations[animId] as AnimationController).setPlaybackWindow(beginTime, endTime);
return this;
}
public function resetPlaybackWindow() : SkeletonController
{
var numAnimations : uint = _animations.length;
for (var animId : uint = 0; animId < numAnimations; ++animId)
(_animations[animId] as AnimationController).resetPlaybackWindow();
return this;
}
}
}
|
package aerys.minko.scene.controller
{
/**
* The SkeletonController aggregates AnimationController objects
* and control them in order to start/stop playing animations on
* multiple scene nodes at the same time and control a whole
* skeleton.
*
* @author Jean-Marc Le Roux
*
*/
public final class SkeletonController
{
private var _animations : Vector.<AnimationController> = null;
public function SkeletonController(animations : Vector.<AnimationController>)
{
_animations = animations.slice();
}
public function get animations() : Vector.<AnimationController>
{
return _animations;
}
public function seek(time : Object) : SkeletonController
{
var numAnimations : uint = _animations.length;
for (var animId : uint = 0; animId < numAnimations; ++animId)
(_animations[animId] as AnimationController).seek(time);
return this;
}
public function stop() : SkeletonController
{
var numAnimations : uint = _animations.length;
for (var animId : uint = 0; animId < numAnimations; ++animId)
(_animations[animId] as AnimationController).stop();
return this;
}
public function play() : SkeletonController
{
var numAnimations : uint = _animations.length;
for (var animId : uint = 0; animId < numAnimations; ++animId)
(_animations[animId] as AnimationController).play();
return this;
}
public function setPlaybackWindow(beginTime : Object = null,
endTime : Object = null) : SkeletonController
{
var numAnimations : uint = _animations.length;
for (var animId : uint = 0; animId < numAnimations; ++animId)
(_animations[animId] as AnimationController).setPlaybackWindow(beginTime, endTime);
return this;
}
public function resetPlaybackWindow() : SkeletonController
{
var numAnimations : uint = _animations.length;
for (var animId : uint = 0; animId < numAnimations; ++animId)
(_animations[animId] as AnimationController).resetPlaybackWindow();
return this;
}
}
}
|
fix broken reference to AnimationController.goto()
|
fix broken reference to AnimationController.goto()
|
ActionScript
|
mit
|
aerys/minko-as3
|
5004d32dfa1dc67c6ea54f4a233a216daece766e
|
Game/Resources/elevatorScene/Scripts/LightsOutScript.as
|
Game/Resources/elevatorScene/Scripts/LightsOutScript.as
|
class LightsOutScript {
Hub @hub;
Entity @self;
Entity @board;
array<Entity@> buttons(25);
array<bool> buttonStates(25);
int numPressedButtons = 0;
bool gameWon = false;
LightsOutScript(Entity @entity){
@hub = Managers();
@self = @entity;
@board = GetEntityByGUID(1511530025);
for (int row = 0; row < 5; ++row) {
for (int column = 0; column < 5; ++column) {
Entity @btn = board.GetChild("btn-" + row + "-" + column);
@buttons[row * 5 + column] = btn.GetChild("btn-" + row + "-" + column).GetChild("button");
buttonStates[row * 5 + column] = false;
}
}
Toggle(0);
}
void Toggle(int index) {
bool pressed = !buttonStates[index];
buttonStates[index] = pressed;
if (pressed) {
buttons[index].position.x = -0.06f;
numPressedButtons += 1;
} else {
buttons[index].position.x = 0.0f;
numPressedButtons -= 1;
}
}
bool IsValid(int index) {
return index >= 0 && index <= 24;
}
// Index goes first row 0 -> 4, second row 5 -> 9 etc.
void ButtonPress(int index) {
if (gameWon) {
return;
}
print("Pressed button nr `" + index + "`\n");
int left = index - 1;
if (IsValid(left)) {
Toggle(left);
}
int right = index + 1;
if (IsValid(right)) {
Toggle(right);
}
int up = index - 5;
if (IsValid(up)) {
Toggle(up);
}
int down = index + 5;
if (IsValid(down)) {
Toggle(down);
}
Toggle(index);
if (numPressedButtons == 25) {
gameWon = true;
//SendMessage(somewhere);
}
}
void b_0_0() {
ButtonPress(0);
}
void b_0_1() {
ButtonPress(1);
}
void b_0_2() {
ButtonPress(2);
}
void b_0_3() {
ButtonPress(3);
}
void b_0_4() {
ButtonPress(4);
}
void b_1_0() {
ButtonPress(5);
}
void b_1_1() {
ButtonPress(6);
}
void b_1_2() {
ButtonPress(7);
}
void b_1_3() {
ButtonPress(8);
}
void b_1_4() {
ButtonPress(9);
}
void b_2_0() {
ButtonPress(10);
}
void b_2_1() {
ButtonPress(11);
}
void b_2_2() {
ButtonPress(12);
}
void b_2_3() {
ButtonPress(13);
}
void b_2_4() {
ButtonPress(14);
}
void b_3_0() {
ButtonPress(15);
}
void b_3_1() {
ButtonPress(16);
}
void b_3_2() {
ButtonPress(17);
}
void b_3_3() {
ButtonPress(18);
}
void b_3_4() {
ButtonPress(19);
}
void b_4_0() {
ButtonPress(20);
}
void b_4_1() {
ButtonPress(21);
}
void b_4_2() {
ButtonPress(22);
}
void b_4_3() {
ButtonPress(23);
}
void b_4_4() {
ButtonPress(24);
}
}
|
class LightsOutScript {
Hub @hub;
Entity @self;
Entity @board;
array<Entity@> buttons(25);
array<bool> buttonStates(25);
int numPressedButtons = 0;
bool gameWon = false;
LightsOutScript(Entity @entity){
@hub = Managers();
@self = @entity;
@board = GetEntityByGUID(1511530025);
for (int row = 0; row < 5; ++row) {
for (int column = 0; column < 5; ++column) {
Entity @btn = board.GetChild("btn-" + row + "-" + column);
@buttons[row * 5 + column] = btn.GetChild("btn-" + row + "-" + column).GetChild("button");
buttonStates[row * 5 + column] = false;
}
}
Toggle(0);
}
void Toggle(int index) {
bool pressed = !buttonStates[index];
buttonStates[index] = pressed;
if (pressed) {
buttons[index].position.x = -0.06f;
numPressedButtons += 1;
} else {
buttons[index].position.x = 0.0f;
numPressedButtons -= 1;
}
}
bool IsValid(int index) {
return index >= 0 && index <= 24;
}
// Index goes first row 0 -> 4, second row 5 -> 9 etc.
void ButtonPress(int index) {
if (gameWon) {
return;
}
print("Pressed button nr `" + index + "`\n");
int left = index - 1;
if (IsValid(left)) {
Toggle(left);
}
int right = index + 1;
if (IsValid(right)) {
Toggle(right);
}
int up = index - 5;
if (IsValid(up)) {
Toggle(up);
}
int down = index + 5;
if (IsValid(down)) {
Toggle(down);
}
Toggle(index);
if (numPressedButtons == 25) {
gameWon = true;
//SendMessage(somewhere);
print("Won the game of lights out.\n");
}
}
void b_0_0() {
ButtonPress(0);
}
void b_0_1() {
ButtonPress(1);
}
void b_0_2() {
ButtonPress(2);
}
void b_0_3() {
ButtonPress(3);
}
void b_0_4() {
ButtonPress(4);
}
void b_1_0() {
ButtonPress(5);
}
void b_1_1() {
ButtonPress(6);
}
void b_1_2() {
ButtonPress(7);
}
void b_1_3() {
ButtonPress(8);
}
void b_1_4() {
ButtonPress(9);
}
void b_2_0() {
ButtonPress(10);
}
void b_2_1() {
ButtonPress(11);
}
void b_2_2() {
ButtonPress(12);
}
void b_2_3() {
ButtonPress(13);
}
void b_2_4() {
ButtonPress(14);
}
void b_3_0() {
ButtonPress(15);
}
void b_3_1() {
ButtonPress(16);
}
void b_3_2() {
ButtonPress(17);
}
void b_3_3() {
ButtonPress(18);
}
void b_3_4() {
ButtonPress(19);
}
void b_4_0() {
ButtonPress(20);
}
void b_4_1() {
ButtonPress(21);
}
void b_4_2() {
ButtonPress(22);
}
void b_4_3() {
ButtonPress(23);
}
void b_4_4() {
ButtonPress(24);
}
}
|
Print a message when the player won lights out.
|
Print a message when the player won lights out.
|
ActionScript
|
mit
|
Chainsawkitten/LargeGameProjectEngine,Chainsawkitten/LargeGameProjectEngine
|
80cbcdb39621c395d8dfc757265658613001a75f
|
src/as/com/threerings/util/Log.as
|
src/as/com/threerings/util/Log.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.utils.getQualifiedClassName;
/**
* A simple logging mechanism.
*
* Typical usage for creating a Log to be used by the entire class would be:
* public class MyClass
* {
* private static const log :Log = Log.getLog(MyClass);
* ...
*
* OR, if you just need a one-off Log:
* protected function doStuff (thingy :Thingy) :void
* {
* if (thingy == null) {
* Log.getLog(this).warn("thiny is null!");
* ....
*/
public class Log
{
/**
* Retrieve a Log for the specififed class.
*
* @param spec can be any Object or Class specifier.
*/
public static function getLog (spec :*) :Log
{
// let's just use the full classname
var path :String = getQualifiedClassName(spec).replace("::", ".");
return new Log(path);
}
/**
* A convenience function for quickly and easily inserting printy
* statements during application development.
*/
public static function testing (... params) :void
{
var log :Log = new Log("testing");
log.debug.apply(log, params);
}
/**
* A convenience function for quickly printing a stack trace
* to the log, useful for debugging.
*/
public static function dumpStack () :void
{
testing(new Error("dumpStack").getStackTrace());
}
/**
* Add a logging target.
*/
public static function addTarget (target :LogTarget) :void
{
_targets.push(target);
}
/**
* Remove a logging target.
*/
public static function removeTarget (target :LogTarget) :void
{
var dex :int = _targets.indexOf(target);
if (dex != -1) {
_targets.splice(dex, 1);
}
}
/**
* @private
*/
public function Log (spec :String)
{
_spec = spec;
}
/**
* Log a message with 'debug' priority.
*/
public function debug (... messages) :void
{
doLog("[debug]", messages);
}
/**
* Log a message with 'info' priority.
*/
public function info (... messages) :void
{
doLog("[INFO]", messages);
}
/**
* Log a message with 'debug' priority.
*/
public function warning (... messages) :void
{
doLog("[WARNING]", messages);
}
/**
* Log a message with 'debug' priority.
*/
public function logStackTrace (error :Error) :void
{
warning(error.getStackTrace());
}
protected function doLog (level :String, messages :Array) :void
{
// TODO: better Date formatting?
messages.unshift(new Date().toLocaleTimeString(), level, _spec);
trace.apply(null, messages);
// possibly also dispatch to any other log targets.
if (_targets.length > 0) {
var asOne :String = messages.join(" ");
for each (var target :LogTarget in _targets) {
target.log(asOne);
}
}
}
/** Our log specification. */
protected var _spec :String;
protected static var _targets :Array = [];
}
}
|
//
// $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.utils.getQualifiedClassName;
/**
* A simple logging mechanism.
*
* Typical usage for creating a Log to be used by the entire class would be:
* public class MyClass
* {
* private static const log :Log = Log.getLog(MyClass);
* ...
*
* OR, if you just need a one-off Log:
* protected function doStuff (thingy :Thingy) :void
* {
* if (thingy == null) {
* Log.getLog(this).warn("thiny is null!");
* ....
*/
public class Log
{
/**
* Retrieve a Log for the specififed class.
*
* @param spec can be any Object or Class specifier.
*/
public static function getLog (spec :*) :Log
{
// let's just use the full classname
var path :String = getQualifiedClassName(spec).replace("::", ".");
return new Log(path);
}
/**
* A convenience function for quickly and easily inserting printy
* statements during application development.
*/
public static function testing (... params) :void
{
var log :Log = new Log("testing");
log.debug.apply(log, params);
}
/**
* A convenience function for quickly printing a stack trace
* to the log, useful for debugging.
*/
public static function dumpStack () :void
{
testing(new Error("dumpStack").getStackTrace());
}
/**
* Add a logging target.
*/
public static function addTarget (target :LogTarget) :void
{
_targets.push(target);
}
/**
* Remove a logging target.
*/
public static function removeTarget (target :LogTarget) :void
{
var dex :int = _targets.indexOf(target);
if (dex != -1) {
_targets.splice(dex, 1);
}
}
/**
* @private
*/
public function Log (spec :String)
{
_spec = spec;
}
/**
* Log a message with 'debug' priority.
*/
public function debug (... messages) :void
{
doLog("[debug]", messages);
}
/**
* Log a message with 'info' priority.
*/
public function info (... messages) :void
{
doLog("[INFO]", messages);
}
/**
* Log a message with 'debug' priority.
*/
public function warning (... messages) :void
{
doLog("[WARNING]", messages);
}
/**
* Log a message with 'debug' priority.
*/
public function logStackTrace (error :Error) :void
{
warning(error.getStackTrace());
}
protected function doLog (level :String, messages :Array) :void
{
messages.unshift(getTimeStamp(), level, _spec);
trace.apply(null, messages);
// possibly also dispatch to any other log targets.
if (_targets.length > 0) {
var asOne :String = messages.join(" ");
for each (var target :LogTarget in _targets) {
target.log(asOne);
}
}
}
protected function getTimeStamp () :String
{
var d :Date = new Date();
// return d.toLocaleTimeString();
// format it like the date format in our java logs
return d.fullYear + "/" +
StringUtil.prepad(String(d.month + 1), 2, "0") + "/" +
StringUtil.prepad(String(d.date), 2, "0") + " " +
StringUtil.prepad(String(d.hours), 2, "0") + ":" +
StringUtil.prepad(String(d.minutes), 2, "0") + ":" +
StringUtil.prepad(String(d.seconds), 2, "0") + ":" +
StringUtil.prepad(String(d.milliseconds), 3, "0");
}
/** Our log specification. */
protected var _spec :String;
protected static var _targets :Array = [];
}
}
|
Format our timestamp like the timestamp in our Java logs.
|
Format our timestamp like the timestamp in our Java logs.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4927 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
3567b6d7554546762b12c0404f12f4f980a8a7c6
|
src/aerys/minko/render/Viewport.as
|
src/aerys/minko/render/Viewport.as
|
package aerys.minko.render
{
import aerys.minko.ns.minko_render;
import aerys.minko.render.resource.Context3DResource;
import aerys.minko.type.KeyboardManager;
import aerys.minko.type.MouseManager;
import aerys.minko.type.Signal;
import flash.display.DisplayObject;
import flash.display.Graphics;
import flash.display.Shape;
import flash.display.Sprite;
import flash.display.Stage;
import flash.display.Stage3D;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TouchEvent;
import flash.geom.Point;
/**
* The Viewport is the display area where a 3D scene can be rendered.
*
* @author Jean-Marc Le Roux
*
*/
public class Viewport extends Sprite
{
private static const ZERO2 : Point = new Point();
private var _stage3d : Stage3D = null;
private var _context3d : Context3DResource = null;
private var _width : uint = 0;
private var _height : uint = 0;
private var _autoResize : Boolean = false;
private var _antiAliasing : uint = 0;
private var _backgroundColor : uint = 0;
private var _backBuffer : RenderTarget = null;
private var _invalidBackBuffer : Boolean = false;
private var _alwaysOnTop : Boolean = false;
private var _mask : Shape = new Shape();
private var _mouseManager : MouseManager = new MouseManager();
private var _keyboardManager : KeyboardManager = new KeyboardManager();
private var _resized : Signal = new Signal('Viewport.resized');
minko_render function get context3D() : Context3DResource
{
return _context3d;
}
minko_render function get backBuffer() : RenderTarget
{
var positionOnStage : Point = localToGlobal(ZERO2);
if (_stage3d.x != positionOnStage.x || _stage3d.y != positionOnStage.y)
updateStage3D()
return _backBuffer;
}
public function get ready() : Boolean
{
return _stage3d != null && _stage3d.context3D != null && _backBuffer != null;
}
/**
* Whether the viewport is visible or not.
* @return
*
*/
override public function get visible() : Boolean
{
return _stage3d.visible;
}
override public function set visible(value : Boolean) : void
{
_stage3d.visible = value;
super.visible = value;
}
override public function set x(value : Number) : void
{
super.x = value;
updateStage3D();
}
override public function set y(value : Number) : void
{
super.y = value;
updateStage3D();
}
/**
* The width of the display area.
* @return
*
*/
override public function get width() : Number
{
return _width;
}
override public function set width(value : Number) : void
{
resize(value, _height);
}
/**
* The height of the display area.
* @return
*
*/
override public function get height() : Number
{
return _height;
}
override public function set height(value : Number) : void
{
resize(_width, value);
}
public function get alwaysOnTop() : Boolean
{
return _alwaysOnTop;
}
public function set alwaysOnTop(value : Boolean) : void
{
_alwaysOnTop = value;
}
public function get keyboardManager() : KeyboardManager
{
return _keyboardManager;
}
public function get mouseManager() : MouseManager
{
return _mouseManager;
}
/**
* The signal executed when the viewport is resized.
* Callback functions for this signal should accept the following
* arguments:
* <ul>
* <li>viewport : Viewport, the viewport executing the signal</li>
* <li>width : Number, the new width of the viewport</li>
* <li>height : Number, the new height of the viewport</li>
* </ul>
* @return
*
*/
public function get resized() : Signal
{
return _resized;
}
/**
* The background color of the display area. This value must use the
* RGB format.
* @return
*
*/
public function get backgroundColor() : uint
{
return _backgroundColor;
}
public function set backgroundColor(value : uint) : void
{
_backgroundColor = value;
updateBackBuffer();
}
/**
* The anti-aliasing to use (0, 2, 4, 8 or 16). The actual anti-aliasing
* used for rendering depends on the hardware capabilities. If the specified
* anti-aliasing value is not supported, the value 0 will be used.
* @return
*
*/
public function get antiAliasing() : uint
{
return _antiAliasing;
}
public function set antiAliasing(value : uint) : void
{
_antiAliasing = value;
updateStage3D();
}
/**
* The driver informations provided by the Stage3D API.
*/
public function get driverInfo() : String
{
return _stage3d && _stage3d.context3D
? _stage3d.context3D.driverInfo
: null;
}
public function Viewport(antiAliasing : uint = 0,
width : uint = 0,
height : uint = 0)
{
_antiAliasing = antiAliasing;
if (width == 0 && height == 0)
_autoResize = true;
_width = width;
_height = height;
initialize();
}
private function initialize() : void
{
_mouseManager.bind(this);
addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
addEventListener(Event.REMOVED_FROM_STAGE, removedFromStageHandler);
}
private function addedToStageHandler(event : Event) : void
{
_keyboardManager.bind(stage);
parent.addEventListener(Event.RESIZE, parentResizedHandler);
stage.addEventListener(Event.ADDED_TO_STAGE, displayObjectAddedToStageHandler);
stage.addEventListener(Event.REMOVED_FROM_STAGE, displayObjectRemovedFromStageHandler);
setupOnStage(stage);
}
private function removedFromStageHandler(event : Event) : void
{
_keyboardManager.unbind(stage);
parent.removeEventListener(Event.RESIZE, parentResizedHandler);
stage.removeEventListener(Event.ADDED_TO_STAGE, displayObjectAddedToStageHandler);
stage.removeEventListener(Event.REMOVED_FROM_STAGE, displayObjectRemovedFromStageHandler);
if (_stage3d != null)
_stage3d.visible = false;
}
private function setupOnStage(stage : Stage, stage3dId : uint = 0) : void
{
if (_autoResize)
{
_width = stage.stageWidth;
_height = stage.stageHeight;
}
if (!_stage3d)
{
_stage3d = stage.stage3Ds[stage3dId];
_stage3d.addEventListener(Event.CONTEXT3D_CREATE, context3dCreatedHandler);
_stage3d.requestContext3D();
}
else
{
_stage3d.visible = true;
}
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
}
/**
* Dispose the Viewport and all the Stage3D related objects. After this operation,
* the Viewport cannot be used anymore and is ready for garbage collection.
*/
public function dispose():void
{
if (_stage3d != null)
{
_stage3d.removeEventListener(Event.CONTEXT3D_CREATE, context3dCreatedHandler);
_stage3d = null;
}
if (_context3d != null)
{
_context3d.dispose();
_context3d = null;
}
return ;
}
/**
* Resize the display area. The "resized" signal is executed when the new width and
* height have be set.
* @param width
* @param height
*
*/
public function resize(width : Number, height : Number) : void
{
_autoResize = false;
setSize(width, height);
}
private function setSize(width : Number, height : Number) : void
{
if (width == _width && _height == height)
return ;
_width = width;
_height = height;
updateStage3D();
updateBackBuffer();
_resized.execute(this, width, height);
}
private function stageResizedHandler(event : Event) : void
{
updateMask();
}
private function parentResizedHandler(event : Event) : void
{
if (_autoResize)
{
if (parent == stage)
setSize(stage.stageWidth, stage.stageHeight);
else
setSize(parent.width, parent.height);
}
}
private function context3dCreatedHandler(event : Event) : void
{
_context3d = new Context3DResource(_stage3d.context3D);
updateStage3D();
updateBackBuffer();
dispatchEvent(new Event(Event.INIT));
}
private function updateBackBuffer() : void
{
if (_width == 0 || _height == 0 || _stage3d == null || _stage3d.context3D == null)
return ;
_invalidBackBuffer = false;
_stage3d.context3D.configureBackBuffer(_width, _height, _antiAliasing, true);
_backBuffer = new RenderTarget(_width, _height, null, 0, _backgroundColor);
graphics.clear();
graphics.beginFill(0, 0);
graphics.drawRect(0, 0, _width, _height);
}
private function updateStage3D() : void
{
if (_stage3d == null)
return ;
var upperLeft : Point = localToGlobal(ZERO2);
_stage3d.x = upperLeft.x;
_stage3d.y = upperLeft.y;
if (_width > 2048)
{
_stage3d.x = (_width - 2048) * 0.5;
_width = 2048;
}
else
_stage3d.x = upperLeft.x;
if (_height > 2048)
{
_stage3d.y = (_height - 2048) * 0.5;
_height = 2048;
}
else
_stage3d.y = upperLeft.y;
updateMask();
}
private function updateMask() : void
{
if (!stage)
return ;
var numChildren : uint = stage.numChildren;
var i : uint = 0;
if (_alwaysOnTop)
{
var gfx : Graphics = _mask.graphics;
var stageWidth : int = stage.stageWidth;
var stageHeight : int = stage.stageHeight;
gfx.clear();
gfx.beginFill(0);
gfx.moveTo(0, 0);
gfx.lineTo(stageWidth, 0);
gfx.lineTo(stageWidth, stageHeight);
gfx.lineTo(0., stageHeight);
gfx.lineTo(0, 0);
gfx.moveTo(_stage3d.x, _stage3d.y);
gfx.lineTo(_stage3d.x, _stage3d.y + height);
gfx.lineTo(_stage3d.x + width, _stage3d.y + height);
gfx.lineTo(_stage3d.x + width, _stage3d.y);
gfx.lineTo(_stage3d.x, _stage3d.y);
gfx.endFill();
for (i = 0; i < numChildren; ++i)
stage.getChildAt(i).mask = _mask;
}
else
{
for (i = 0; i < numChildren; ++i)
{
var child : DisplayObject = stage.getChildAt(i);
if (child.mask == _mask)
child.mask = null;
}
}
}
private function displayObjectAddedToStageHandler(event : Event) : void
{
var displayObject : DisplayObject = event.target as DisplayObject;
if (displayObject.parent == stage)
updateMask();
}
private function displayObjectRemovedFromStageHandler(event : Event) : void
{
var displayObject : DisplayObject = event.target as DisplayObject;
if (_autoResize && displayObject.parent == stage)
displayObject.mask = null;
}
}
}
|
package aerys.minko.render
{
import aerys.minko.ns.minko_render;
import aerys.minko.render.resource.Context3DResource;
import aerys.minko.type.KeyboardManager;
import aerys.minko.type.MouseManager;
import aerys.minko.type.Signal;
import flash.display.DisplayObject;
import flash.display.Graphics;
import flash.display.Shape;
import flash.display.Sprite;
import flash.display.Stage;
import flash.display.Stage3D;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TouchEvent;
import flash.geom.Point;
/**
* The Viewport is the display area where a 3D scene can be rendered.
*
* @author Jean-Marc Le Roux
*
*/
public class Viewport extends Sprite
{
private static const ZERO2 : Point = new Point();
private var _stage3d : Stage3D = null;
private var _context3d : Context3DResource = null;
private var _width : uint = 0;
private var _height : uint = 0;
private var _autoResize : Boolean = false;
private var _antiAliasing : uint = 0;
private var _backgroundColor : uint = 0;
private var _backBuffer : RenderTarget = null;
private var _invalidBackBuffer : Boolean = false;
private var _alwaysOnTop : Boolean = false;
private var _mask : Shape = new Shape();
private var _mouseManager : MouseManager = new MouseManager();
private var _keyboardManager : KeyboardManager = new KeyboardManager();
private var _resized : Signal = new Signal('Viewport.resized');
minko_render function get context3D() : Context3DResource
{
return _context3d;
}
minko_render function get backBuffer() : RenderTarget
{
var positionOnStage : Point = localToGlobal(ZERO2);
if (_stage3d.x != positionOnStage.x || _stage3d.y != positionOnStage.y)
updateStage3D()
return _backBuffer;
}
public function get ready() : Boolean
{
return _stage3d != null && _stage3d.context3D != null && _backBuffer != null;
}
/**
* Whether the viewport is visible or not.
* @return
*
*/
override public function set visible(value : Boolean) : void
{
if (_stage3d)
_stage3d.visible = value;
super.visible = value;
}
override public function set x(value : Number) : void
{
super.x = value;
updateStage3D();
}
override public function set y(value : Number) : void
{
super.y = value;
updateStage3D();
}
/**
* The width of the display area.
* @return
*
*/
override public function get width() : Number
{
return _width;
}
override public function set width(value : Number) : void
{
resize(value, _height);
}
/**
* The height of the display area.
* @return
*
*/
override public function get height() : Number
{
return _height;
}
override public function set height(value : Number) : void
{
resize(_width, value);
}
public function get alwaysOnTop() : Boolean
{
return _alwaysOnTop;
}
public function set alwaysOnTop(value : Boolean) : void
{
_alwaysOnTop = value;
}
public function get keyboardManager() : KeyboardManager
{
return _keyboardManager;
}
public function get mouseManager() : MouseManager
{
return _mouseManager;
}
/**
* The signal executed when the viewport is resized.
* Callback functions for this signal should accept the following
* arguments:
* <ul>
* <li>viewport : Viewport, the viewport executing the signal</li>
* <li>width : Number, the new width of the viewport</li>
* <li>height : Number, the new height of the viewport</li>
* </ul>
* @return
*
*/
public function get resized() : Signal
{
return _resized;
}
/**
* The background color of the display area. This value must use the
* RGB format.
* @return
*
*/
public function get backgroundColor() : uint
{
return _backgroundColor;
}
public function set backgroundColor(value : uint) : void
{
_backgroundColor = value;
updateBackBuffer();
}
/**
* The anti-aliasing to use (0, 2, 4, 8 or 16). The actual anti-aliasing
* used for rendering depends on the hardware capabilities. If the specified
* anti-aliasing value is not supported, the value 0 will be used.
* @return
*
*/
public function get antiAliasing() : uint
{
return _antiAliasing;
}
public function set antiAliasing(value : uint) : void
{
_antiAliasing = value;
updateStage3D();
}
/**
* The driver informations provided by the Stage3D API.
*/
public function get driverInfo() : String
{
return _stage3d && _stage3d.context3D
? _stage3d.context3D.driverInfo
: null;
}
public function Viewport(antiAliasing : uint = 0,
width : uint = 0,
height : uint = 0)
{
_antiAliasing = antiAliasing;
if (width == 0 && height == 0)
_autoResize = true;
_width = width;
_height = height;
initialize();
}
private function initialize() : void
{
_mouseManager.bind(this);
addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
addEventListener(Event.REMOVED_FROM_STAGE, removedFromStageHandler);
}
private function addedToStageHandler(event : Event) : void
{
_keyboardManager.bind(stage);
parent.addEventListener(Event.RESIZE, parentResizedHandler);
stage.addEventListener(Event.ADDED_TO_STAGE, displayObjectAddedToStageHandler);
stage.addEventListener(Event.REMOVED_FROM_STAGE, displayObjectRemovedFromStageHandler);
setupOnStage(stage);
}
private function removedFromStageHandler(event : Event) : void
{
_keyboardManager.unbind(stage);
parent.removeEventListener(Event.RESIZE, parentResizedHandler);
stage.removeEventListener(Event.ADDED_TO_STAGE, displayObjectAddedToStageHandler);
stage.removeEventListener(Event.REMOVED_FROM_STAGE, displayObjectRemovedFromStageHandler);
if (_stage3d != null)
_stage3d.visible = false;
}
private function setupOnStage(stage : Stage, stage3dId : uint = 0) : void
{
if (_autoResize)
{
_width = stage.stageWidth;
_height = stage.stageHeight;
}
if (!_stage3d)
{
_stage3d = stage.stage3Ds[stage3dId];
_stage3d.addEventListener(Event.CONTEXT3D_CREATE, context3dCreatedHandler);
_stage3d.requestContext3D();
}
else
{
_stage3d.visible = visible;
}
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
}
/**
* Dispose the Viewport and all the Stage3D related objects. After this operation,
* the Viewport cannot be used anymore and is ready for garbage collection.
*/
public function dispose():void
{
if (_stage3d != null)
{
_stage3d.removeEventListener(Event.CONTEXT3D_CREATE, context3dCreatedHandler);
_stage3d = null;
}
if (_context3d != null)
{
_context3d.dispose();
_context3d = null;
}
return ;
}
/**
* Resize the display area. The "resized" signal is executed when the new width and
* height have be set.
* @param width
* @param height
*
*/
public function resize(width : Number, height : Number) : void
{
_autoResize = false;
setSize(width, height);
}
private function setSize(width : Number, height : Number) : void
{
if (width == _width && _height == height)
return ;
_width = width;
_height = height;
updateStage3D();
updateBackBuffer();
_resized.execute(this, width, height);
}
private function stageResizedHandler(event : Event) : void
{
updateMask();
}
private function parentResizedHandler(event : Event) : void
{
if (_autoResize)
{
if (parent == stage)
setSize(stage.stageWidth, stage.stageHeight);
else
setSize(parent.width, parent.height);
}
}
private function context3dCreatedHandler(event : Event) : void
{
_context3d = new Context3DResource(_stage3d.context3D);
updateStage3D();
updateBackBuffer();
dispatchEvent(new Event(Event.INIT));
}
private function updateBackBuffer() : void
{
if (_width == 0 || _height == 0 || _stage3d == null || _stage3d.context3D == null)
return ;
_invalidBackBuffer = false;
_stage3d.context3D.configureBackBuffer(_width, _height, _antiAliasing, true);
_backBuffer = new RenderTarget(_width, _height, null, 0, _backgroundColor);
graphics.clear();
graphics.beginFill(0, 0);
graphics.drawRect(0, 0, _width, _height);
}
private function updateStage3D() : void
{
if (_stage3d == null)
return ;
var upperLeft : Point = localToGlobal(ZERO2);
_stage3d.x = upperLeft.x;
_stage3d.y = upperLeft.y;
if (_width > 2048)
{
_stage3d.x = (_width - 2048) * 0.5;
_width = 2048;
}
else
_stage3d.x = upperLeft.x;
if (_height > 2048)
{
_stage3d.y = (_height - 2048) * 0.5;
_height = 2048;
}
else
_stage3d.y = upperLeft.y;
updateMask();
}
private function updateMask() : void
{
if (!stage)
return ;
var numChildren : uint = stage.numChildren;
var i : uint = 0;
if (_alwaysOnTop)
{
var gfx : Graphics = _mask.graphics;
var stageWidth : int = stage.stageWidth;
var stageHeight : int = stage.stageHeight;
gfx.clear();
gfx.beginFill(0);
gfx.moveTo(0, 0);
gfx.lineTo(stageWidth, 0);
gfx.lineTo(stageWidth, stageHeight);
gfx.lineTo(0., stageHeight);
gfx.lineTo(0, 0);
gfx.moveTo(_stage3d.x, _stage3d.y);
gfx.lineTo(_stage3d.x, _stage3d.y + height);
gfx.lineTo(_stage3d.x + width, _stage3d.y + height);
gfx.lineTo(_stage3d.x + width, _stage3d.y);
gfx.lineTo(_stage3d.x, _stage3d.y);
gfx.endFill();
for (i = 0; i < numChildren; ++i)
stage.getChildAt(i).mask = _mask;
}
else
{
for (i = 0; i < numChildren; ++i)
{
var child : DisplayObject = stage.getChildAt(i);
if (child.mask == _mask)
child.mask = null;
}
}
}
private function displayObjectAddedToStageHandler(event : Event) : void
{
var displayObject : DisplayObject = event.target as DisplayObject;
if (displayObject.parent == stage)
updateMask();
}
private function displayObjectRemovedFromStageHandler(event : Event) : void
{
var displayObject : DisplayObject = event.target as DisplayObject;
if (_autoResize && displayObject.parent == stage)
displayObject.mask = null;
}
}
}
|
fix Viewport.visible to work even if it's not added on the Stage and no Stage3D is set
|
fix Viewport.visible to work even if it's not added on the Stage and no Stage3D is set
|
ActionScript
|
mit
|
aerys/minko-as3
|
c0a3df1d5ba375e4eded297b71f7eaa6a659e6e5
|
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.Camera;
import aerys.minko.scene.node.Mesh;
import aerys.minko.scene.node.Scene;
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 (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 broken reference to Camera in VisibilityController
|
fix broken reference to Camera in VisibilityController
|
ActionScript
|
mit
|
aerys/minko-as3
|
c4ae3cde87669950e2f370289f1e72c465798390
|
src/sssplayer/display/SSSPlayer.as
|
src/sssplayer/display/SSSPlayer.as
|
package sssplayer.display {
import flash.geom.Point;
import sssplayer.data.SSSModel;
import sssplayer.data.SSSPartAnime;
import sssplayer.data.SSSProject;
import sssplayer.data.SSSAnime;
import sssplayer.data.SSSPart;
import starling.display.DisplayObject;
import starling.display.Sprite;
import starling.events.Event;
public class SSSPlayer extends Sprite {
private var project:SSSProject;
private var model:SSSModel;
private var _anime:SSSAnime;
public function get anime():SSSAnime {
return this._anime;
}
private var _currentFrame:Number;
public function get currentFrame():Number {
return this._currentFrame;
}
public function set currentFrame(value:Number):void {
this._currentFrame = value;
this.updateParts();
}
private var _partPlayers:Vector.<SSSPartPlayer>;
public function get partPlayers():Vector.<SSSPartPlayer> {
return this._partPlayers.concat();
}
private var _isPlaying:Boolean = false;
public function get isPlaying():Boolean {
return this._isPlaying;
}
public function set isPlaying(value:Boolean):void {
if (value == this._isPlaying) {
return;
}
if (value) {
this.addEventListener(Event.ENTER_FRAME, this.onEnterFrame);
} else {
this.removeEventListener(Event.ENTER_FRAME, this.onEnterFrame);
}
this._isPlaying = value;
}
private var _loop:Boolean = true;
public function get loop():Boolean {
return this._loop;
}
public function set loop(value:Boolean):void {
this._loop = value;
}
private var _withFlatten:Boolean = false;
public function get withFlatten():Boolean {
return this._withFlatten;
}
public function set withFlatten(value:Boolean):void {
if (value == this._withFlatten) {
return;
}
this._withFlatten = value;
if (value) {
this.flatten();
} else {
this.unflatten();
}
}
public function set color(value:uint):void {
for each (var partPlayer:SSSPartPlayer in this._partPlayers) {
partPlayer.color = value;
}
}
public function SSSPlayer(project:SSSProject) {
super();
this.project = project;
}
public function setAnime(name:String):SSSPlayer {
this.model = this.project.modelForAnime(name);
this._anime = this.project.anime(name);
this.prepareChildren();
this._currentFrame = 0;
this.updateParts();
return this;
}
public function startAnime(name:String):SSSPlayer {
this.setAnime(name);
this.isPlaying = true;
return this;
}
public function play():void {
this.isPlaying = true;
}
public function stop():void {
this.isPlaying = false;
}
private function onEnterFrame(event:Event):void {
if (++this._currentFrame >= this._anime.frameCount) {
if (this._loop) {
this._currentFrame = 0;
} else {
this._currentFrame--;
this.stop();
}
this.dispatchEventWith(Event.COMPLETE);
}
this.updateParts();
}
private function prepareChildren():void {
this.removeChildren();
this._partPlayers = new Vector.<SSSPartPlayer>();
for each (var part:SSSPart in this.model.parts) {
var partAnime:SSSPartAnime = this._anime.partAnimes[part.name];
var parentPartPlayer:SSSPartPlayer = null;
if (part.parentIndex > -1) {
parentPartPlayer = this._partPlayers[part.parentIndex];
}
var partPlayer:SSSPartPlayer = new SSSPartPlayer(this.project, this.model, part, partAnime, parentPartPlayer);
this.addChild(partPlayer);
this._partPlayers.push(partPlayer);
}
}
private function updateParts():void {
for each (var partPlayer:SSSPartPlayer in this._partPlayers) {
partPlayer.currentFrame = this._currentFrame;
}
if (this._withFlatten) {
this.flatten();
}
}
public function partPlayerAt(x:Number, y:Number, forTouch:Boolean = false):SSSPartPlayer {
var touchable:Boolean = this.touchable;
this.touchable = true;
var hitObject:DisplayObject = this.hitTest(new Point(x, y), forTouch);
this.touchable = touchable;
if (!hitObject) {
return null;
}
for each (var partPlayer:SSSPartPlayer in this._partPlayers) {
if (hitObject.parent == partPlayer) {
return partPlayer;
}
}
return null;
}
public function partNameAt(x:Number, y:Number, forTouch:Boolean = false):String {
var partPlayer:SSSPartPlayer = this.partPlayerAt(x, y, forTouch);
return partPlayer ? partPlayer.name : null;
}
}
}
|
package sssplayer.display {
import flash.geom.Point;
import sssplayer.data.SSSModel;
import sssplayer.data.SSSPartAnime;
import sssplayer.data.SSSProject;
import sssplayer.data.SSSAnime;
import sssplayer.data.SSSPart;
import starling.display.DisplayObject;
import starling.display.Sprite;
import starling.events.Event;
public class SSSPlayer extends Sprite {
public static const VERSION:String = "0.0.1";
private var project:SSSProject;
private var model:SSSModel;
private var _anime:SSSAnime;
public function get anime():SSSAnime {
return this._anime;
}
private var _currentFrame:Number;
public function get currentFrame():Number {
return this._currentFrame;
}
public function set currentFrame(value:Number):void {
this._currentFrame = value;
this.updateParts();
}
private var _partPlayers:Vector.<SSSPartPlayer>;
public function get partPlayers():Vector.<SSSPartPlayer> {
return this._partPlayers.concat();
}
private var _isPlaying:Boolean = false;
public function get isPlaying():Boolean {
return this._isPlaying;
}
public function set isPlaying(value:Boolean):void {
if (value == this._isPlaying) {
return;
}
if (value) {
this.addEventListener(Event.ENTER_FRAME, this.onEnterFrame);
} else {
this.removeEventListener(Event.ENTER_FRAME, this.onEnterFrame);
}
this._isPlaying = value;
}
private var _loop:Boolean = true;
public function get loop():Boolean {
return this._loop;
}
public function set loop(value:Boolean):void {
this._loop = value;
}
private var _withFlatten:Boolean = false;
public function get withFlatten():Boolean {
return this._withFlatten;
}
public function set withFlatten(value:Boolean):void {
if (value == this._withFlatten) {
return;
}
this._withFlatten = value;
if (value) {
this.flatten();
} else {
this.unflatten();
}
}
public function set color(value:uint):void {
for each (var partPlayer:SSSPartPlayer in this._partPlayers) {
partPlayer.color = value;
}
}
public function SSSPlayer(project:SSSProject) {
super();
this.project = project;
}
public function setAnime(name:String):SSSPlayer {
this.model = this.project.modelForAnime(name);
this._anime = this.project.anime(name);
this.prepareChildren();
this._currentFrame = 0;
this.updateParts();
return this;
}
public function startAnime(name:String):SSSPlayer {
this.setAnime(name);
this.isPlaying = true;
return this;
}
public function play():void {
this.isPlaying = true;
}
public function stop():void {
this.isPlaying = false;
}
private function onEnterFrame(event:Event):void {
if (++this._currentFrame >= this._anime.frameCount) {
if (this._loop) {
this._currentFrame = 0;
} else {
this._currentFrame--;
this.stop();
}
this.dispatchEventWith(Event.COMPLETE);
}
this.updateParts();
}
private function prepareChildren():void {
this.removeChildren();
this._partPlayers = new Vector.<SSSPartPlayer>();
for each (var part:SSSPart in this.model.parts) {
var partAnime:SSSPartAnime = this._anime.partAnimes[part.name];
var parentPartPlayer:SSSPartPlayer = null;
if (part.parentIndex > -1) {
parentPartPlayer = this._partPlayers[part.parentIndex];
}
var partPlayer:SSSPartPlayer = new SSSPartPlayer(this.project, this.model, part, partAnime, parentPartPlayer);
this.addChild(partPlayer);
this._partPlayers.push(partPlayer);
}
}
private function updateParts():void {
for each (var partPlayer:SSSPartPlayer in this._partPlayers) {
partPlayer.currentFrame = this._currentFrame;
}
if (this._withFlatten) {
this.flatten();
}
}
public function partPlayerAt(x:Number, y:Number, forTouch:Boolean = false):SSSPartPlayer {
var touchable:Boolean = this.touchable;
this.touchable = true;
var hitObject:DisplayObject = this.hitTest(new Point(x, y), forTouch);
this.touchable = touchable;
if (!hitObject) {
return null;
}
for each (var partPlayer:SSSPartPlayer in this._partPlayers) {
if (hitObject.parent == partPlayer) {
return partPlayer;
}
}
return null;
}
public function partNameAt(x:Number, y:Number, forTouch:Boolean = false):String {
var partPlayer:SSSPartPlayer = this.partPlayerAt(x, y, forTouch);
return partPlayer ? partPlayer.name : null;
}
}
}
|
set version
|
set version
|
ActionScript
|
bsd-2-clause
|
promotal/SS5Player,promotal/SS5Player
|
db0bfd74eadaa2e188d075459acaca6404bb716d
|
src/com/rails2u/debug/Benchmark.as
|
src/com/rails2u/debug/Benchmark.as
|
package com.rails2u.debug {
import flash.utils.Dictionary;
import flash.events.Event;
import flash.utils.getTimer;
/**
* Simple Benchmark class
*
* example:
* <listing version="3.0">
* Benchmark.start('check');
* // code
* Benchmark.end('check');
* </listing>
*
* <listing version="3.0">
* Benchmark.benchmark('check2', function() {
* // code
* }, this);
* </listing>
*/
public class Benchmark {
private static var dict:Object = {};
public static function start(name:String):void {
dict[name] = getTimer();
}
public static function benchmark(name:String, callback:Function, bindObject:Object = null):Number {
start(name);
callback.apply(bindObject);
return end(name);
}
public static function end(name:String):Number {
var re:uint = getTimer() - dict[name];
log(name + ':' + ' ' + re + 'ms');
return re;
}
}
}
|
package com.rails2u.debug {
import flash.utils.Dictionary;
import flash.events.Event;
import flash.utils.getTimer;
/**
* Simple Benchmark class
*
* example:
* <listing version="3.0">
* Benchmark.start('check');
* // code
* Benchmark.end('check');
* </listing>
*
* <listing version="3.0">
* Benchmark.benchmark('check2', function() {
* // code
* }, this);
* </listing>
*/
public class Benchmark {
private static var dict:Object = {};
public static function start(name:String):void {
dict[name] = getTimer();
}
public static function benchmark(name:String, callback:Function, bindObject:Object = null):Number {
start(name);
callback.call(bindObject);
return end(name);
}
public static function loop(name:String, callback:Function, bindObject:Object = null, times:uint = 100):Number {
start(name);
for (var i:uint = 0; i < times; i++)
callback.call(bindObject);
return end(name);
}
public static function end(name:String):Number {
var re:uint = getTimer() - dict[name];
log(name + ':' + ' ' + re + 'ms');
return re;
}
}
}
|
add loop method
|
add loop method
git-svn-id: 864080e30cc358c5edb906449bbf014f90258007@42 96db6a20-122f-0410-8d9f-89437bbe4005
|
ActionScript
|
mit
|
hotchpotch/as3rails2u,hotchpotch/as3rails2u
|
f5fe98a76bb3e24483142466da1d9fc8a2d9dbfa
|
runtime/src/main/as/flump/xfl/XflMovie.as
|
runtime/src/main/as/flump/xfl/XflMovie.as
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.xfl {
public class XflMovie extends XflTopLevelComponent
{
use namespace xflns;
public var libraryItem :String;
public var symbol :String;
public var layers :Array;
// The hash of the XML file for this symbol in the library
public var md5 :String;
public function XflMovie (baseLocation :String, xml :XML, md5 :String) {
const converter :XmlConverter = new XmlConverter(xml);
libraryItem = converter.getStringAttr("name");
super(baseLocation + ":" + libraryItem);
this.md5 = md5;
symbol = converter.getStringAttr("linkageClassName", null);
const layerEls :XMLList = xml.timeline.DOMTimeline[0].layers.DOMLayer;
if (new XmlConverter(layerEls[0]).getStringAttr("name") == "flipbook") {
layers = [new XflLayer(location, layerEls[0], _errors, true)];
if (symbol == null) {
addError(ParseError.CRIT, "Flipbook movie '" + libraryItem + "' not exported");
}
for each (var kf :XflKeyframe in layers[0].keyframes) {
kf.id = libraryItem + "_flipbook_" + kf.index;
}
} else {
layers = new Array();
for each (var layerEl :XML in layerEls) {
if (new XmlConverter(layerEl).getStringAttr("layerType", "") != "guide") {
layers.unshift(new XflLayer(location, layerEl, _errors, false));
}
}
}
}
public function checkSymbols (lib :XflLibrary) :void {
if (flipbook && !lib.hasSymbol(symbol)) {
addError(ParseError.CRIT, "Flipbook movie '" + symbol + "' not exported");
} else for each (var layer :XflLayer in layers) layer.checkSymbols(lib);
}
public function get frames () :int {
var frames :int = 0;
for each (var layer :XflLayer in layers) frames = Math.max(frames, layer.frames);
return frames;
}
public function get flipbook () :Boolean { return layers[0].flipbook; }
public function toJSON (_:*) :Object {
return {
symbol: symbol,
layers: layers,
md5: md5
};
}
public function toXML () :XML
{
var xml :XML = <movie
name={libraryItem}
md5={md5}
/>;
for each (var layer :XflLayer in layers) {
xml.appendChild(layer.toXML());
}
return xml;
}
}
}
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.xfl {
public class XflMovie extends XflTopLevelComponent
{
use namespace xflns;
public var libraryItem :String;
public var symbol :String;
public var layers :Array;
// The hash of the XML file for this symbol in the library
public var md5 :String;
public function XflMovie (baseLocation :String, xml :XML, md5 :String) {
const converter :XmlConverter = new XmlConverter(xml);
libraryItem = converter.getStringAttr("name");
super(baseLocation + ":" + libraryItem);
this.md5 = md5;
symbol = converter.getStringAttr("linkageClassName", null);
const layerEls :XMLList = xml.timeline.DOMTimeline[0].layers.DOMLayer;
if (new XmlConverter(layerEls[0]).getStringAttr("name") == "flipbook") {
layers = [new XflLayer(location, layerEls[0], _errors, true)];
if (symbol == null) {
addError(ParseError.CRIT, "Flipbook movie '" + libraryItem + "' not exported");
}
for each (var kf :XflKeyframe in layers[0].keyframes) {
kf.id = libraryItem + "_flipbook_" + kf.index;
}
} else {
layers = new Array();
for each (var layerEl :XML in layerEls) {
if (new XmlConverter(layerEl).getStringAttr("layerType", "") != "guide") {
layers.unshift(new XflLayer(location, layerEl, _errors, false));
}
}
}
}
public function checkSymbols (lib :XflLibrary) :void {
if (flipbook && !lib.hasSymbol(symbol)) {
addError(ParseError.CRIT, "Flipbook movie '" + symbol + "' not exported");
} else for each (var layer :XflLayer in layers) layer.checkSymbols(lib);
}
public function get frames () :int {
var frames :int = 0;
for each (var layer :XflLayer in layers) frames = Math.max(frames, layer.frames);
return frames;
}
public function get flipbook () :Boolean { return layers[0].flipbook; }
public function toJSON (_:*) :Object {
return {
symbol: symbol,
layers: layers,
md5: md5
};
}
public function toXML () :XML
{
var xml :XML = <movie
name={symbol}
md5={md5}
/>;
for each (var layer :XflLayer in layers) {
xml.appendChild(layer.toXML());
}
return xml;
}
}
}
|
Use the symbol name for exported movies.
|
Use the symbol name for exported movies.
|
ActionScript
|
mit
|
tconkling/flump,funkypandagame/flump,funkypandagame/flump,mathieuanthoine/flump,mathieuanthoine/flump,tconkling/flump,mathieuanthoine/flump
|
c6ac1e810658ad9868a649bf40e00631aa6e205d
|
src/main/actionscript/com/dotfold/dotvimstat/model/VideoEntity.as
|
src/main/actionscript/com/dotfold/dotvimstat/model/VideoEntity.as
|
package com.dotfold.dotvimstat.model
{
/**
* VideoEntity.
*
* Model class mapped to Vimeo video object.
*
* @author jamesmcnamee
*
*/
public class VideoEntity extends BaseEntity
{
/**
* Constructor.
*/
public function VideoEntity()
{
super();
}
public var description:String;
public var duration:int;
public var embed_privacy:String;
public var height:int;
public var mobile_url:String;
public var stats_number_of_comments:int;
public var stats_number_of_likes:int;
public var stats_number_of_plays:int;
public var tags:String;
public var thumbnail_large:String;
public var thumbnail_medium:String;
public var thumbnail_small:String;
public var title:String;
public var upload_date:String;
public var url:String;
public var user_name:String;
public var user_portrait_huge:String;
public var user_portrait_large:String;
public var user_portrait_medium:String;
public var user_portrait_small:String;
public var user_url:String;
public var width:int;
}
}
|
package com.dotfold.dotvimstat.model
{
import com.dotfold.dotvimstat.model.enum.ImageSize;
import com.dotfold.dotvimstat.model.image.EntityImage;
import com.dotfold.dotvimstat.model.image.EntityImageCollection;
/**
* VideoEntity.
*
* Model class mapped to Vimeo video object.
*
* @author jamesmcnamee
*
*/
public class VideoEntity extends BaseEntity
{
/**
* Constructor.
*/
public function VideoEntity()
{
super();
}
public var description:String;
public var duration:int;
public var embed_privacy:String;
public var height:int;
public var mobile_url:String;
public var stats_number_of_comments:int;
public var stats_number_of_likes:int;
public var stats_number_of_plays:int;
public var tags:String;
public var title:String;
public var upload_date:Date;
public var url:String;
public var user_name:String;
public var user_url:String;
public var width:int;
//
// Images
//
private var _thumbnail_small:String;
public function get thumbnail_small():String
{
return _thumbnail_small;
}
public function set thumbnail_small(value:String):void
{
_thumbnail_small = value;
var image:EntityImage = new EntityImage();
image.url = value;
image.size = ImageSize.SMALL;
thumbnail_images.addItem(image);
}
private var _thumbnail_medium:String;
public function get thumbnail_medium():String
{
return _thumbnail_medium;
}
public function set thumbnail_medium(value:String):void
{
_thumbnail_medium = value;
var image:EntityImage = new EntityImage();
image.url = value;
image.size = ImageSize.MEDIUM;
thumbnail_images.addItem(image);
}
private var _thumbnail_large:String;
public function get thumbnail_large():String
{
return _thumbnail_large;
}
public function set thumbnail_large(value:String):void
{
_thumbnail_large = value;
var image:EntityImage = new EntityImage();
image.url = value;
image.size = ImageSize.LARGE;
thumbnail_images.addItem(image);
}
private var _user_portrait_small:String
public function get user_portrait_small():String
{
return _user_portrait_small;
}
public function set user_portrait_small(value:String):void
{
_user_portrait_small = value;
var image:EntityImage = new EntityImage();
image.url = value;
image.size = ImageSize.SMALL;
user_portrait_images.addItem(image);
}
private var _user_portrait_medium:String
public function get user_portrait_medium():String
{
return _user_portrait_medium;
}
public function set user_portrait_medium(value:String):void
{
_user_portrait_medium = value;
var image:EntityImage = new EntityImage();
image.url = value;
image.size = ImageSize.MEDIUM;
user_portrait_images.addItem(image);
}
private var _user_portrait_large:String
public function get user_portrait_large():String
{
return _user_portrait_large;
}
public function set user_portrait_large(value:String):void
{
_user_portrait_large = value;
var image:EntityImage = new EntityImage();
image.url = value;
image.size = ImageSize.LARGE;
user_portrait_images.addItem(image);
}
private var _user_portrait_huge:String
public function get user_portrait_huge():String
{
return _user_portrait_huge;
}
public function set user_portrait_huge(value:String):void
{
_user_portrait_huge = value;
var image:EntityImage = new EntityImage();
image.url = value;
image.size = ImageSize.HUGE;
user_portrait_images.addItem(image);
}
public var user_portrait_images:EntityImageCollection = new EntityImageCollection();
public var thumbnail_images:EntityImageCollection = new EntityImageCollection();
}
}
|
update video entity
|
[feat] update video entity
- use read dates
- improved image handling, use collection and ImageSize enum
|
ActionScript
|
mit
|
dotfold/dotvimstat
|
82eb0cba751154670882fd652b0409d8bea914d8
|
lib/goplayer/PackerSpecification.as
|
lib/goplayer/PackerSpecification.as
|
package goplayer
{
import org.asspec.specification.AbstractSpecification
import flash.display.Sprite
public class PackerSpecification extends AbstractSpecification
{
override protected function execute() : void
{
it("should pack two static items correctly", function () : void {
const a : Sprite = getSquare(1)
const b : Sprite = getSquare(1)
Packer.packLeft(a, b)
specify(b.x).should.equal(1)
})
}
private static function getSquare(side : Number) : Sprite
{
const result : Sprite = new Sprite
result.graphics.beginFill(0)
result.graphics.drawRect(0, 0, side, side)
result.graphics.endFill()
return result
}
}
}
|
package goplayer
{
import org.asspec.specification.AbstractSpecification
import flash.display.Sprite
public class PackerSpecification extends AbstractSpecification
{
override protected function execute() : void
{
const a : Sprite = getSquare(1)
const b : Sprite = getSquare(1)
it("should pack using internal widths", function () : void {
Packer.packLeft(a, b)
specify(b.x).should.equal(1)
})
it("should honor explicit widths", function () : void {
Packer.packLeft([a, 2], b)
specify(b.x).should.equal(2)
})
}
private static function getSquare(side : Number) : Sprite
{
const result : Sprite = new Sprite
result.graphics.beginFill(0)
result.graphics.drawRect(0, 0, side, side)
result.graphics.endFill()
return result
}
}
}
|
Add test using explicit width to PackerSpecification.
|
Add test using explicit width to PackerSpecification.
|
ActionScript
|
mit
|
dbrock/goplayer,dbrock/goplayer
|
9542cd33460eeca73bf5f7fbdc1128e36fc52b85
|
flash/org/windmill/astest/ASTest.as
|
flash/org/windmill/astest/ASTest.as
|
/*
Copyright 2009, Matthew Eernisse ([email protected]) and Slide, 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.
*/
package org.windmill.astest {
import org.windmill.WMLogger;
import flash.utils.*;
public class ASTest {
public static var testClassList:Array = [];
public static var testList:Array = [];
public static function run(files:Array = null):void {
//['/flash/TestFoo.swf', '/flash/TestBar.swf']
// If we're passed some files, load 'em up first
// the loader will call back to this again when
// it's done, with no args
if (files) {
ASTest.loadTestFiles(files);
return;
}
ASTest.getCompleteListOfTests();
ASTest.start();
}
public static function loadTestFiles(files:Array):void {
ASTest.testClassList = [];
WMLoader.load(files);
}
public static function start():void {
for each (var obj:Object in ASTest.testList) {
try {
WMLogger.log('Running ' + obj.className + '.' + obj.methodName);
obj.instance[obj.methodName].call(obj.instance);
}
catch (e:Error) {
WMLogger.log(e.message);
}
}
}
public static function getCompleteListOfTests():void {
var createTestItem:Function = function (item:Object,
methodName:String):Object {
return {
methodName: methodName,
instance: item.instance,
className: item.className,
classDescription: item.classDescription
};
}
var testList:Array = [];
// No args -- this is being re-invoked from WMLoader
// now that we have our tests loaded
for each (var item:Object in ASTest.testClassList) {
WMLogger.log('className: ' + item.className);
var currTestList:Array = [];
var descr:XML;
var hasSetup:Boolean = false;
var hasTeardown:Boolean = false;
descr = flash.utils.describeType(
item.classDescription);
var meth:*;
for each (meth in descr..method) {
var methodName:String = [email protected]();
if (/^test/.test(methodName)) {
currTestList.push(createTestItem(item, methodName));
}
// If there's a setup or teardown somewhere in there
// flag them so we can prepend/append after adding all
// the tests
if (methodName == 'setup') {
hasSetup = true;
}
if (methodName == 'teardown') {
hasTeardown = true;
}
}
// Prepend list with setup if one exists
if (hasSetup) {
currTestList.unshift(createTestItem(item, 'setup'));
}
// Append list with teardown if one exists
if (hasTeardown) {
currTestList.push(createTestItem(item, 'teardown'));
}
testList = testList.concat.apply(testList, currTestList);
}
ASTest.testList = testList;
}
}
}
|
/*
Copyright 2009, Matthew Eernisse ([email protected]) and Slide, 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.
*/
package org.windmill.astest {
import org.windmill.WMLogger;
import flash.utils.*;
public class ASTest {
public static var testClassList:Array = [];
public static var testList:Array = [];
public static function run(files:Array = null):void {
//['/flash/TestFoo.swf', '/flash/TestBar.swf']
// If we're passed some files, load 'em up first
// the loader will call back to this again when
// it's done, with no args
if (files) {
ASTest.loadTestFiles(files);
return;
}
ASTest.getCompleteListOfTests();
ASTest.start();
}
public static function loadTestFiles(files:Array):void {
ASTest.testClassList = [];
ASTest.testList = [];
WMLoader.load(files);
}
public static function start():void {
for each (var obj:Object in ASTest.testList) {
try {
WMLogger.log('Running ' + obj.className + '.' + obj.methodName);
obj.instance[obj.methodName].call(obj.instance);
}
catch (e:Error) {
WMLogger.log(e.message);
}
}
}
public static function getCompleteListOfTests():void {
var createTestItem:Function = function (item:Object,
methodName:String):Object {
return {
methodName: methodName,
instance: item.instance,
className: item.className,
classDescription: item.classDescription
};
}
var testList:Array = [];
// No args -- this is being re-invoked from WMLoader
// now that we have our tests loaded
for each (var item:Object in ASTest.testClassList) {
WMLogger.log('className: ' + item.className);
var currTestList:Array = [];
var descr:XML;
var hasSetup:Boolean = false;
var hasTeardown:Boolean = false;
descr = flash.utils.describeType(
item.classDescription);
var meth:*;
for each (meth in descr..method) {
var methodName:String = [email protected]();
if (/^test/.test(methodName)) {
currTestList.push(createTestItem(item, methodName));
}
// If there's a setup or teardown somewhere in there
// flag them so we can prepend/append after adding all
// the tests
if (methodName == 'setup') {
hasSetup = true;
}
if (methodName == 'teardown') {
hasTeardown = true;
}
}
// Prepend list with setup if one exists
if (hasSetup) {
currTestList.unshift(createTestItem(item, 'setup'));
}
// Append list with teardown if one exists
if (hasTeardown) {
currTestList.push(createTestItem(item, 'teardown'));
}
testList = testList.concat.apply(testList, currTestList);
}
ASTest.testList = testList;
}
}
}
|
Clear out the test list between test runs.
|
Clear out the test list between test runs.
|
ActionScript
|
apache-2.0
|
windmill/windmill,windmill/windmill,windmill/windmill,windmill/windmill,windmill/windmill,windmill/windmill
|
7694bc2002928d2208235b94a368d908f1f9a62e
|
src/aerys/minko/scene/controller/debug/WireframeDebugController.as
|
src/aerys/minko/scene/controller/debug/WireframeDebugController.as
|
package aerys.minko.scene.controller.debug
{
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.geometry.primitive.LineGeometry;
import aerys.minko.render.geometry.stream.iterator.TriangleIterator;
import aerys.minko.render.geometry.stream.iterator.TriangleReference;
import aerys.minko.render.material.line.LineMaterial;
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.type.math.Matrix4x4;
import flash.utils.Dictionary;
public final class WireframeDebugController extends AbstractController
{
private static var _wireframeMaterial : LineMaterial;
private var _targetToWireframe : Dictionary = new Dictionary();
private var _geometryToMesh : Dictionary = new Dictionary();
private var _visible : Boolean = true;
public function get material() : LineMaterial
{
return _wireframeMaterial
|| (_wireframeMaterial = new LineMaterial({diffuseColor : 0x509dc7ff, lineThickness : 1.}));
}
public function set visible(value : Boolean) : void
{
_visible = value;
for each (var wireframe : Mesh in _targetToWireframe)
wireframe.visible = value;
}
public function get visible() : Boolean
{
return _visible;
}
public function WireframeDebugController()
{
super(Mesh);
initialize();
}
private function initialize() : void
{
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function targetAddedHandler(ctrl : WireframeDebugController,
target : Mesh) : void
{
if (target.scene)
addedHandler(target, target.parent);
else
target.added.add(addedHandler);
target.removed.add(removedHandler);
}
private function addedHandler(target : Mesh,
ancestor : Group) : void
{
if (!target.scene || target.geometry == null)
return ;
var triangles : TriangleIterator = new TriangleIterator(
target.geometry.getVertexStream(),
target.geometry.indexStream
);
var linesGeom : LineGeometry = new LineGeometry();
for each (var triangle : TriangleReference in triangles)
{
linesGeom.moveTo(triangle.v0.x, triangle.v0.y, triangle.v0.z)
.lineTo(triangle.v1.x, triangle.v1.y, triangle.v1.z)
.lineTo(triangle.v2.x, triangle.v2.y, triangle.v2.z)
.lineTo(triangle.v0.x, triangle.v0.y, triangle.v0.z);
}
var lines : Mesh = new Mesh(linesGeom, this.material);
lines.visible = _visible;
_targetToWireframe[target] = lines;
if (!target.localToWorldTransformChanged.hasCallback(updateTransform))
target.localToWorldTransformChanged.add(updateTransform);
updateTransform(target, target.getLocalToWorldTransform());
target.scene.addChild(lines);
}
private function updateTransform(child : ISceneNode, childLocalToWorld : Matrix4x4) : void
{
var lineMesh : Mesh = _targetToWireframe[child];
if (lineMesh == null)
child.localToWorldTransformChanged.remove(updateTransform);
else
lineMesh.transform.copyFrom(childLocalToWorld);
}
private function removeWireframes(target : Mesh) : void
{
if (_targetToWireframe[target])
_targetToWireframe[target].parent = null;
_targetToWireframe[target] = null;
}
private function targetRemovedHandler(ctrl : WireframeDebugController,
target : Mesh) : void
{
if (target.added.hasCallback(addedHandler))
target.added.remove(addedHandler);
target.removed.remove(removedHandler);
if (target.localToWorldTransformChanged.hasCallback(updateTransform))
target.localToWorldTransformChanged.remove(updateTransform);
removeWireframes(target);
}
private function removedHandler(target : Mesh, ancestor : Group) : void
{
removeWireframes(target);
}
override public function clone():AbstractController
{
return null;
}
}
}
|
package aerys.minko.scene.controller.debug
{
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.geometry.primitive.LineGeometry;
import aerys.minko.render.geometry.stream.iterator.TriangleIterator;
import aerys.minko.render.geometry.stream.iterator.TriangleReference;
import aerys.minko.render.material.line.LineMaterial;
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.type.math.Matrix4x4;
import flash.utils.Dictionary;
public final class WireframeDebugController extends AbstractController
{
private static var _wireframeMaterial : LineMaterial;
private var _targetToWireframe : Dictionary = new Dictionary();
private var _geometryToMesh : Dictionary = new Dictionary();
private var _visible : Boolean = true;
public function get material() : LineMaterial
{
return _wireframeMaterial
|| (_wireframeMaterial = new LineMaterial({diffuseColor : 0x509dc7ff, lineThickness : 1.}));
}
public function set visible(value : Boolean) : void
{
_visible = value;
for each (var wireframe : Mesh in _targetToWireframe)
{
if (wireframe)
wireframe.visible = value;
}
}
public function get visible() : Boolean
{
return _visible;
}
public function WireframeDebugController()
{
super(Mesh);
initialize();
}
private function initialize() : void
{
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function targetAddedHandler(ctrl : WireframeDebugController,
target : Mesh) : void
{
if (target.scene)
addedHandler(target, target.parent);
else
target.added.add(addedHandler);
target.removed.add(removedHandler);
}
private function addedHandler(target : Mesh,
ancestor : Group) : void
{
if (!target.scene || target.geometry == null)
return ;
var triangles : TriangleIterator = new TriangleIterator(
target.geometry.getVertexStream(),
target.geometry.indexStream
);
var linesGeom : LineGeometry = new LineGeometry();
for each (var triangle : TriangleReference in triangles)
{
linesGeom.moveTo(triangle.v0.x, triangle.v0.y, triangle.v0.z)
.lineTo(triangle.v1.x, triangle.v1.y, triangle.v1.z)
.lineTo(triangle.v2.x, triangle.v2.y, triangle.v2.z)
.lineTo(triangle.v0.x, triangle.v0.y, triangle.v0.z);
}
var lines : Mesh = new Mesh(linesGeom, this.material);
lines.visible = _visible;
_targetToWireframe[target] = lines;
if (!target.localToWorldTransformChanged.hasCallback(updateTransform))
target.localToWorldTransformChanged.add(updateTransform);
updateTransform(target, target.getLocalToWorldTransform());
target.scene.addChild(lines);
}
private function updateTransform(child : ISceneNode, childLocalToWorld : Matrix4x4) : void
{
var lineMesh : Mesh = _targetToWireframe[child];
if (lineMesh == null)
child.localToWorldTransformChanged.remove(updateTransform);
else
lineMesh.transform.copyFrom(childLocalToWorld);
}
private function removeWireframes(target : Mesh) : void
{
if (_targetToWireframe[target])
_targetToWireframe[target].parent = null;
_targetToWireframe[target] = null;
}
private function targetRemovedHandler(ctrl : WireframeDebugController,
target : Mesh) : void
{
if (target.added.hasCallback(addedHandler))
target.added.remove(addedHandler);
target.removed.remove(removedHandler);
if (target.localToWorldTransformChanged.hasCallback(updateTransform))
target.localToWorldTransformChanged.remove(updateTransform);
removeWireframes(target);
}
private function removedHandler(target : Mesh, ancestor : Group) : void
{
removeWireframes(target);
}
override public function clone():AbstractController
{
return null;
}
}
}
|
Fix bug when a mesh is null during one frame
|
Fix bug when a mesh is null during one frame
|
ActionScript
|
mit
|
aerys/minko-as3
|
4a2674bacf3dea1c8b4630fcdb7e062acf093998
|
src/org/puremvc/as3/multicore/utilities/pipes/plumbing/FilterTest.as
|
src/org/puremvc/as3/multicore/utilities/pipes/plumbing/FilterTest.as
|
/*
PureMVC AS3/MultiCore Pipes Utility Unit Tests
Copyright (c) 2008 Cliff Hall<[email protected]>
Your reuse is governed by the Creative Commons Attribution 3.0 License
*/
package org.puremvc.as3.multicore.utilities.pipes.plumbing
{
import flexunit.framework.TestCase;
import flexunit.framework.TestSuite;
import org.puremvc.as3.multicore.utilities.pipes.interfaces.IPipeFitting;
import org.puremvc.as3.multicore.utilities.pipes.interfaces.IPipeMessage;
import org.puremvc.as3.multicore.utilities.pipes.messages.FilterControlMessage;
import org.puremvc.as3.multicore.utilities.pipes.messages.Message;
/**
* Test the Filter class.
*/
public class FilterTest extends TestCase
{
/**
* Constructor.
*
* @param methodName the name of the test method an instance to run
*/
public function FilterTest( methodName:String )
{
super( methodName );
}
/**
* Create the TestSuite.
*/
public static function suite():TestSuite
{
var ts:TestSuite = new TestSuite();
ts.addTest( new FilterTest( "testConnectingIOPipes" ) );
ts.addTest( new FilterTest( "testFilteringNormalMessage" ) );
ts.addTest( new FilterTest( "testBypassAndFilterModeToggle" ) );
ts.addTest( new FilterTest( "testSetParamsByControlMessage" ) );
ts.addTest( new FilterTest( "testSetFilterByControlMessage" ) );
return ts;
}
/**
* Test connecting input and output pipes to a filter.
*/
public function testConnectingIOPipes():void
{
// create output pipes 1
var pipe1:IPipeFitting = new Pipe();
var pipe2:IPipeFitting = new Pipe();
// create filter
var filter:Filter = new Filter( 'TestFilter' );
// connect input fitting
var connectedInput:Boolean = pipe1.connect( filter );
// connect output fitting
var connectedOutput:Boolean = filter.connect( pipe2 );
// test assertions
assertTrue( "Expecting pipe1 is Pipe", pipe1 is Pipe );
assertTrue( "Expecting pipe2 is Pipe", pipe2 is Pipe );
assertTrue( "Expecting filter is Filter", filter is Filter );
assertTrue( "Expecting connected input", connectedInput );
assertTrue( "Expecting connected output", connectedOutput );
}
/**
* Test applying filter to a normal message.
*/
public function testFilteringNormalMessage():void
{
// create messages to send to the queue
var message:IPipeMessage = new Message( Message.NORMAL, { width:10, height:2 });
// create filter, attach an anonymous listener to the filter output to receive the message,
// pass in an anonymous function an parameter object
var filter:Filter = new Filter( 'scale',
new PipeListener( this ,callBackMethod ),
function( message:IPipeMessage, params:Object ):void { message.getHeader().width *= params.factor; message.getHeader().height *= params.factor; },
{ factor:10 }
);
// write messages to the filter
var written:Boolean = filter.write( message );
// test assertions
assertTrue( "Expecting message is IPipeMessage", message is IPipeMessage );
assertTrue( "Expecting filter is Filter", filter is Filter );
assertTrue( "Expecting wrote message to filter", written );
assertTrue( "Expecting received 1 messages", messagesReceived.length == 1 );
// test filtered message assertions
var recieved:IPipeMessage = messagesReceived.shift() as IPipeMessage;
assertTrue( "Expecting recieved is IPipeMessage", recieved is IPipeMessage );
assertTrue( "Expecting recieved === message", recieved === message ); // object equality
assertTrue( "Expecting recieved.getHeader().width == 100", recieved.getHeader().width == 100 );
assertTrue( "Expecting recieved.getHeader().height == 20", recieved.getHeader().height == 20 );
}
/**
* Test setting filter to bypass mode, writing, then setting back to filter mode and writing.
*/
public function testBypassAndFilterModeToggle():void
{
// create messages to send to the queue
var message:IPipeMessage = new Message( Message.NORMAL, { width:10, height:2 });
// create filter, attach an anonymous listener to the filter output to receive the message,
// pass in an anonymous function an parameter object
var filter:Filter = new Filter( 'scale',
new PipeListener( this ,callBackMethod ),
function( message:IPipeMessage, params:Object ):void { message.getHeader().width *= params.factor; message.getHeader().height *= params.factor; },
{ factor:10 }
);
// create bypass control message
var bypassMessage:FilterControlMessage = new FilterControlMessage(FilterControlMessage.BYPASS, 'scale');
// write bypass control message to the filter
var bypassWritten:Boolean = filter.write( bypassMessage );
// write normal message to the filter
var written1:Boolean = filter.write( message );
// test assertions
assertTrue( "Expecting message is IPipeMessage", message is IPipeMessage );
assertTrue( "Expecting filter is Filter", filter is Filter );
assertTrue( "Expecting wrote bypass message to filter", bypassWritten );
assertTrue( "Expecting wrote normal message to filter", written1 );
assertTrue( "Expecting received 1 messages", messagesReceived.length == 1 );
// test filtered message assertions (no change to message)
var recieved1:IPipeMessage = messagesReceived.shift() as IPipeMessage;
assertTrue( "Expecting recieved1 is IPipeMessage", recieved1 is IPipeMessage );
assertTrue( "Expecting recieved1 === message", recieved1 === message ); // object equality
assertTrue( "Expecting recieved1.getHeader().width == 10", recieved1.getHeader().width == 10 );
assertTrue( "Expecting recieved1.getHeader().height == 2", recieved1.getHeader().height == 2 );
// create filter control message
var filterMessage:FilterControlMessage = new FilterControlMessage(FilterControlMessage.FILTER, 'scale');
// write bypass control message to the filter
var filterWritten:Boolean = filter.write( filterMessage );
// write normal message to the filter again
var written2:Boolean = filter.write( message );
// test assertions
assertTrue( "Expecting wrote bypass message to filter", bypassWritten );
assertTrue( "Expecting wrote normal message to filter", written1 );
assertTrue( "Expecting received 1 messages", messagesReceived.length == 1 );
// test filtered message assertions (message filtered)
var recieved2:IPipeMessage = messagesReceived.shift() as IPipeMessage;
assertTrue( "Expecting recieved2 is IPipeMessage", recieved2 is IPipeMessage );
assertTrue( "Expecting recieved2 === message", recieved2 === message ); // object equality
assertTrue( "Expecting recieved2.getHeader().width == 100", recieved2.getHeader().width == 100 );
assertTrue( "Expecting recieved2.getHeader().height == 20", recieved2.getHeader().height == 20 );
}
/**
* Test setting filter parameters by sending control message.
*/
public function testSetParamsByControlMessage():void
{
// create messages to send to the queue
var message:IPipeMessage = new Message( Message.NORMAL, { width:10, height:2 });
// create filter, attach an anonymous listener to the filter output to receive the message,
// pass in an anonymous function an parameter object
var filter:Filter = new Filter( 'scale',
new PipeListener( this ,callBackMethod ),
function( message:IPipeMessage, params:Object ):void { message.getHeader().width *= params.factor; message.getHeader().height *= params.factor; },
{ factor:10 }
);
// create setParams control message
var setParamsMessage:FilterControlMessage = new FilterControlMessage(FilterControlMessage.SET_PARAMS, 'scale', null, {factor:5});
// write filter control message to the filter
var setParamsWritten:Boolean = filter.write( setParamsMessage );
// write normal message to the filter
var written:Boolean = filter.write( message );
// test assertions
assertTrue( "Expecting message is IPipeMessage", message is IPipeMessage );
assertTrue( "Expecting filter is Filter", filter is Filter );
assertTrue( "Expecting wrote bypass message to filter", setParamsWritten );
assertTrue( "Expecting wrote normal message to filter", written );
assertTrue( "Expecting received 1 messages", messagesReceived.length == 1 );
// test filtered message assertions (message filtered with overridden parameters)
var recieved:IPipeMessage = messagesReceived.shift() as IPipeMessage;
assertTrue( "Expecting recieved is IPipeMessage", recieved is IPipeMessage );
assertTrue( "Expecting recieved === message", recieved === message ); // object equality
assertTrue( "Expecting recieved.getHeader().width == 50", recieved.getHeader().width == 50 );
assertTrue( "Expecting recieved.getHeader().height == 10", recieved.getHeader().height == 10 );
}
/**
* Test setting filter function by sending control message.
*/
public function testSetFilterByControlMessage():void
{
// create messages to send to the queue
var message:IPipeMessage = new Message( Message.NORMAL, { width:10, height:2 });
// create filter, attach an anonymous listener to the filter output to receive the message,
// pass in an anonymous function an parameter object
var filter:Filter = new Filter( 'scale',
new PipeListener( this ,callBackMethod ),
function( message:IPipeMessage, params:Object ):void { message.getHeader().width *= params.factor; message.getHeader().height *= params.factor; },
{ factor:10 }
);
// create setParams control message
var setFilterMessage:FilterControlMessage = new FilterControlMessage(FilterControlMessage.SET_FILTER, 'scale', function( message:IPipeMessage, params:Object ):void { message.getHeader().width /= params.factor; message.getHeader().height /= params.factor; } );
// write filter control message to the filter
var setFilterWritten:Boolean = filter.write( setFilterMessage );
// write normal message to the filter
var written:Boolean = filter.write( message );
// test assertions
assertTrue( "Expecting message is IPipeMessage", message is IPipeMessage );
assertTrue( "Expecting filter is Filter", filter is Filter );
assertTrue( "Expecting wrote bypass message to filter", setFilterWritten );
assertTrue( "Expecting wrote normal message to filter", written );
assertTrue( "Expecting received 1 messages", messagesReceived.length == 1 );
// test filtered message assertions (message filtered with overridden filter function)
var recieved:IPipeMessage = messagesReceived.shift() as IPipeMessage;
assertTrue( "Expecting recieved is IPipeMessage", recieved is IPipeMessage );
assertTrue( "Expecting recieved === message", recieved === message ); // object equality
assertTrue( "Expecting recieved.getHeader().width == 1", recieved.getHeader().width == 1 );
assertTrue( "Expecting recieved.getHeader().height == .2", recieved.getHeader().height == .2 );
}
/**
* Array of received messages.
* <P>
* Used by <code>callBackMedhod</code> as a place to store
* the recieved messages.</P>
*/
private var messagesReceived:Array = new Array();
/**
* Callback given to <code>PipeListener</code> for incoming message.
* <P>
* Used by <code>testReceiveMessageViaPipeListener</code>
* to get the output of pipe back into this test to see
* that a message passes through the pipe.</P>
*/
private function callBackMethod( message:IPipeMessage ):void
{
this.messagesReceived.push( message );
}
}
}
|
/*
PureMVC AS3/MultiCore Pipes Utility Unit Tests
Copyright (c) 2008 Cliff Hall<[email protected]>
Your reuse is governed by the Creative Commons Attribution 3.0 License
*/
package org.puremvc.as3.multicore.utilities.pipes.plumbing
{
import flexunit.framework.TestCase;
import flexunit.framework.TestSuite;
import org.puremvc.as3.multicore.utilities.pipes.interfaces.IPipeFitting;
import org.puremvc.as3.multicore.utilities.pipes.interfaces.IPipeMessage;
import org.puremvc.as3.multicore.utilities.pipes.messages.FilterControlMessage;
import org.puremvc.as3.multicore.utilities.pipes.messages.Message;
/**
* Test the Filter class.
*/
public class FilterTest extends TestCase
{
/**
* Constructor.
*
* @param methodName the name of the test method an instance to run
*/
public function FilterTest( methodName:String )
{
super( methodName );
}
/**
* Create the TestSuite.
*/
public static function suite():TestSuite
{
var ts:TestSuite = new TestSuite();
ts.addTest( new FilterTest( "testConnectingAndDisconnectingIOPipes" ) );
ts.addTest( new FilterTest( "testFilteringNormalMessage" ) );
ts.addTest( new FilterTest( "testBypassAndFilterModeToggle" ) );
ts.addTest( new FilterTest( "testSetParamsByControlMessage" ) );
ts.addTest( new FilterTest( "testSetFilterByControlMessage" ) );
return ts;
}
/**
* Test connecting input and output pipes to a filter as well as disconnecting the output.
*/
public function testConnectingAndDisconnectingIOPipes():void
{
// create output pipes 1
var pipe1:IPipeFitting = new Pipe();
var pipe2:IPipeFitting = new Pipe();
// create filter
var filter:Filter = new Filter( 'TestFilter' );
// connect input fitting
var connectedInput:Boolean = pipe1.connect( filter );
// connect output fitting
var connectedOutput:Boolean = filter.connect( pipe2 );
// test assertions
assertTrue( "Expecting pipe1 is Pipe", pipe1 is Pipe );
assertTrue( "Expecting pipe2 is Pipe", pipe2 is Pipe );
assertTrue( "Expecting filter is Filter", filter is Filter );
assertTrue( "Expecting connected input", connectedInput );
assertTrue( "Expecting connected output", connectedOutput );
// disconnect pipe 2 from filter
var disconnectedPipe:IPipeFitting = filter.disconnect();
assertTrue( "Expecting disconnected pipe2 from filter", disconnectedPipe === pipe2 );
}
/**
* Test applying filter to a normal message.
*/
public function testFilteringNormalMessage():void
{
// create messages to send to the queue
var message:IPipeMessage = new Message( Message.NORMAL, { width:10, height:2 });
// create filter, attach an anonymous listener to the filter output to receive the message,
// pass in an anonymous function an parameter object
var filter:Filter = new Filter( 'scale',
new PipeListener( this ,callBackMethod ),
function( message:IPipeMessage, params:Object ):void { message.getHeader().width *= params.factor; message.getHeader().height *= params.factor; },
{ factor:10 }
);
// write messages to the filter
var written:Boolean = filter.write( message );
// test assertions
assertTrue( "Expecting message is IPipeMessage", message is IPipeMessage );
assertTrue( "Expecting filter is Filter", filter is Filter );
assertTrue( "Expecting wrote message to filter", written );
assertTrue( "Expecting received 1 messages", messagesReceived.length == 1 );
// test filtered message assertions
var recieved:IPipeMessage = messagesReceived.shift() as IPipeMessage;
assertTrue( "Expecting recieved is IPipeMessage", recieved is IPipeMessage );
assertTrue( "Expecting recieved === message", recieved === message ); // object equality
assertTrue( "Expecting recieved.getHeader().width == 100", recieved.getHeader().width == 100 );
assertTrue( "Expecting recieved.getHeader().height == 20", recieved.getHeader().height == 20 );
}
/**
* Test setting filter to bypass mode, writing, then setting back to filter mode and writing.
*/
public function testBypassAndFilterModeToggle():void
{
// create messages to send to the queue
var message:IPipeMessage = new Message( Message.NORMAL, { width:10, height:2 });
// create filter, attach an anonymous listener to the filter output to receive the message,
// pass in an anonymous function an parameter object
var filter:Filter = new Filter( 'scale',
new PipeListener( this ,callBackMethod ),
function( message:IPipeMessage, params:Object ):void { message.getHeader().width *= params.factor; message.getHeader().height *= params.factor; },
{ factor:10 }
);
// create bypass control message
var bypassMessage:FilterControlMessage = new FilterControlMessage(FilterControlMessage.BYPASS, 'scale');
// write bypass control message to the filter
var bypassWritten:Boolean = filter.write( bypassMessage );
// write normal message to the filter
var written1:Boolean = filter.write( message );
// test assertions
assertTrue( "Expecting message is IPipeMessage", message is IPipeMessage );
assertTrue( "Expecting filter is Filter", filter is Filter );
assertTrue( "Expecting wrote bypass message to filter", bypassWritten );
assertTrue( "Expecting wrote normal message to filter", written1 );
assertTrue( "Expecting received 1 messages", messagesReceived.length == 1 );
// test filtered message assertions (no change to message)
var recieved1:IPipeMessage = messagesReceived.shift() as IPipeMessage;
assertTrue( "Expecting recieved1 is IPipeMessage", recieved1 is IPipeMessage );
assertTrue( "Expecting recieved1 === message", recieved1 === message ); // object equality
assertTrue( "Expecting recieved1.getHeader().width == 10", recieved1.getHeader().width == 10 );
assertTrue( "Expecting recieved1.getHeader().height == 2", recieved1.getHeader().height == 2 );
// create filter control message
var filterMessage:FilterControlMessage = new FilterControlMessage(FilterControlMessage.FILTER, 'scale');
// write bypass control message to the filter
var filterWritten:Boolean = filter.write( filterMessage );
// write normal message to the filter again
var written2:Boolean = filter.write( message );
// test assertions
assertTrue( "Expecting wrote bypass message to filter", bypassWritten );
assertTrue( "Expecting wrote normal message to filter", written1 );
assertTrue( "Expecting received 1 messages", messagesReceived.length == 1 );
// test filtered message assertions (message filtered)
var recieved2:IPipeMessage = messagesReceived.shift() as IPipeMessage;
assertTrue( "Expecting recieved2 is IPipeMessage", recieved2 is IPipeMessage );
assertTrue( "Expecting recieved2 === message", recieved2 === message ); // object equality
assertTrue( "Expecting recieved2.getHeader().width == 100", recieved2.getHeader().width == 100 );
assertTrue( "Expecting recieved2.getHeader().height == 20", recieved2.getHeader().height == 20 );
}
/**
* Test setting filter parameters by sending control message.
*/
public function testSetParamsByControlMessage():void
{
// create messages to send to the queue
var message:IPipeMessage = new Message( Message.NORMAL, { width:10, height:2 });
// create filter, attach an anonymous listener to the filter output to receive the message,
// pass in an anonymous function an parameter object
var filter:Filter = new Filter( 'scale',
new PipeListener( this ,callBackMethod ),
function( message:IPipeMessage, params:Object ):void { message.getHeader().width *= params.factor; message.getHeader().height *= params.factor; },
{ factor:10 }
);
// create setParams control message
var setParamsMessage:FilterControlMessage = new FilterControlMessage(FilterControlMessage.SET_PARAMS, 'scale', null, {factor:5});
// write filter control message to the filter
var setParamsWritten:Boolean = filter.write( setParamsMessage );
// write normal message to the filter
var written:Boolean = filter.write( message );
// test assertions
assertTrue( "Expecting message is IPipeMessage", message is IPipeMessage );
assertTrue( "Expecting filter is Filter", filter is Filter );
assertTrue( "Expecting wrote bypass message to filter", setParamsWritten );
assertTrue( "Expecting wrote normal message to filter", written );
assertTrue( "Expecting received 1 messages", messagesReceived.length == 1 );
// test filtered message assertions (message filtered with overridden parameters)
var recieved:IPipeMessage = messagesReceived.shift() as IPipeMessage;
assertTrue( "Expecting recieved is IPipeMessage", recieved is IPipeMessage );
assertTrue( "Expecting recieved === message", recieved === message ); // object equality
assertTrue( "Expecting recieved.getHeader().width == 50", recieved.getHeader().width == 50 );
assertTrue( "Expecting recieved.getHeader().height == 10", recieved.getHeader().height == 10 );
}
/**
* Test setting filter function by sending control message.
*/
public function testSetFilterByControlMessage():void
{
// create messages to send to the queue
var message:IPipeMessage = new Message( Message.NORMAL, { width:10, height:2 });
// create filter, attach an anonymous listener to the filter output to receive the message,
// pass in an anonymous function an parameter object
var filter:Filter = new Filter( 'scale',
new PipeListener( this ,callBackMethod ),
function( message:IPipeMessage, params:Object ):void { message.getHeader().width *= params.factor; message.getHeader().height *= params.factor; },
{ factor:10 }
);
// create setParams control message
var setFilterMessage:FilterControlMessage = new FilterControlMessage(FilterControlMessage.SET_FILTER, 'scale', function( message:IPipeMessage, params:Object ):void { message.getHeader().width /= params.factor; message.getHeader().height /= params.factor; } );
// write filter control message to the filter
var setFilterWritten:Boolean = filter.write( setFilterMessage );
// write normal message to the filter
var written:Boolean = filter.write( message );
// test assertions
assertTrue( "Expecting message is IPipeMessage", message is IPipeMessage );
assertTrue( "Expecting filter is Filter", filter is Filter );
assertTrue( "Expecting wrote bypass message to filter", setFilterWritten );
assertTrue( "Expecting wrote normal message to filter", written );
assertTrue( "Expecting received 1 messages", messagesReceived.length == 1 );
// test filtered message assertions (message filtered with overridden filter function)
var recieved:IPipeMessage = messagesReceived.shift() as IPipeMessage;
assertTrue( "Expecting recieved is IPipeMessage", recieved is IPipeMessage );
assertTrue( "Expecting recieved === message", recieved === message ); // object equality
assertTrue( "Expecting recieved.getHeader().width == 1", recieved.getHeader().width == 1 );
assertTrue( "Expecting recieved.getHeader().height == .2", recieved.getHeader().height == .2 );
}
/**
* Array of received messages.
* <P>
* Used by <code>callBackMedhod</code> as a place to store
* the recieved messages.</P>
*/
private var messagesReceived:Array = new Array();
/**
* Callback given to <code>PipeListener</code> for incoming message.
* <P>
* Used by <code>testReceiveMessageViaPipeListener</code>
* to get the output of pipe back into this test to see
* that a message passes through the pipe.</P>
*/
private function callBackMethod( message:IPipeMessage ):void
{
this.messagesReceived.push( message );
}
}
}
|
test disconnect
|
test disconnect
|
ActionScript
|
bsd-3-clause
|
PureMVC/puremvc-as3-util-pipes-unittests
|
4b09ce7d12bb9da4c8995cfa6265810511c60ed3
|
tamarin-central/thane/thane_core.as
|
tamarin-central/thane/thane_core.as
|
//
// $Id: $
package flash.errors {
public class MemoryError extends Error
{
}
public class IllegalOperationError extends Error
{
public function IllegalOperationError (str :String = null)
{
}
}
}
package flash.events {
import flash.utils.Dictionary;
public class Event
{
public static const CONNECT :String = "connect";
public static const CLOSE :String = "close";
public function Event (type :String, bubbles :Boolean = false, cancelable :Boolean = false)
{
if (bubbles || cancelable) {
throw new Error("Not implemented");
}
_type = type;
}
public function get type () :String
{
return _type;
}
public function get target () :Object
{
return null;
}
public function clone () :Event
{
return new Event(_type);
}
private var _type :String;
}
public class EventDispatcher
{
public function addEventListener (
type :String, listener :Function, useCapture :Boolean = false,
priority :int = 0, useWeakReference :Boolean = false) :void
{
if (useCapture || priority != 0 || useWeakReference) {
throw new Error("Fancy addEventListener not implemented");
}
var listeners :Array = _listenerMap[type] as Array;
if (listeners == null) {
_listenerMap[type] = listeners = new Array();
} else if (-1 == _listenerMap.indexOf(listener)) {
return;
}
listeners.push(listener);
}
public function removeEventListener (
type :String, listener :Function, useCapture :Boolean = false) :void
{
if (useCapture) {
throw new Error("Fancy removeListener not implemented");
}
var listeners :Array = _listenerMap[type] as Array;
if (listeners != null) {
var ix :int = listeners.indexOf(listener);
if (ix >= 0) {
listeners.splice(ix, 1);
}
}
}
public function dispatchEvent (event :Event) :Boolean
{
var listeners :Array = _listenerMap[event.type] as Array;
for each (var listener :Function in listeners) {
try {
listener(event);
} catch (err :Error) {
trace("Event[" + event + "] dispatch error: " + err);
}
}
// TODO: "A value of true unless preventDefault() is called on the event,
// in which case it returns false. "
return true;
}
private var _listenerMap :Dictionary = new Dictionary();
}
public class TimerEvent extends Event
{
public static const TIMER :String = "timer";
public static const TIMER_COMPLETE :String = "timerComplete";
public function TimerEvent (
type :String, bubbles :Boolean = false, cancelable :Boolean = false, text :String = "")
{
super(type, bubbles, cancelable);
}
}
}
package flash.utils {
import flash.events.EventDispatcher;
import avmplus.*;
public function describeType (c :Object) :XML
{
throw new Error("describeType() Not implemented");
}
public function getDefinitionByName (c :String) :Class
{
return getClassByName(c);
}
public function getQualifiedClassName (c :Object) :String
{
return "Test";
throw new Error("Not implemented");
}
public function getTimer () :int
{
return System.getTimer();
}
public interface IDataInput
{
function readBytes(bytes :ByteArray, offset :uint=0, length :uint=0) :void;
function readBoolean() :Boolean;
function readByte() :int;
function readUnsignedByte() :uint;
function readShort() :int;
function readUnsignedShort() :uint;
function readInt() :int;
function readUnsignedInt() :uint;
function readFloat() :Number;
function readDouble() :Number;
function readUTF() :String;
function readUTFBytes(length :uint) :String;
function get bytesAvailable() :uint;
function get endian() :String;
function set endian(type :String) :void;
}
public interface IDataOutput
{
function writeBytes(bytes :ByteArray, offset :uint = 0, length :uint = 0) :void;
function writeBoolean(value :Boolean) :void;
function writeByte(value :int) :void;
function writeShort(value :int) :void;
function writeInt(value :int) :void;
function writeUnsignedInt(value :uint) :void;
function writeFloat(value :Number) :void;
function writeDouble(value :Number) :void;
function writeUTF(value :String) :void;
function writeUTFBytes(value :String) :void;
function get endian() :String;
function set endian(type :String) :void;
}
}
|
//
// $Id: $
package flash.errors {
public class MemoryError extends Error
{
}
public class IllegalOperationError extends Error
{
public function IllegalOperationError (str :String = null)
{
}
}
}
package flash.events {
import flash.utils.Dictionary;
public class Event
{
public static const CONNECT :String = "connect";
public static const CLOSE :String = "close";
public function Event (type :String, bubbles :Boolean = false, cancelable :Boolean = false)
{
if (bubbles || cancelable) {
throw new Error("Not implemented");
}
_type = type;
}
public function get type () :String
{
return _type;
}
public function get target () :Object
{
return null;
}
public function clone () :Event
{
return new Event(_type);
}
private var _type :String;
}
public class EventDispatcher
{
public function addEventListener (
type :String, listener :Function, useCapture :Boolean = false,
priority :int = 0, useWeakReference :Boolean = false) :void
{
if (useCapture || priority != 0 || useWeakReference) {
throw new Error("Fancy addEventListener not implemented");
}
var listeners :Array = _listenerMap[type] as Array;
if (listeners == null) {
_listenerMap[type] = listeners = new Array();
} else if (-1 == _listenerMap.indexOf(listener)) {
return;
}
listeners.push(listener);
}
public function removeEventListener (
type :String, listener :Function, useCapture :Boolean = false) :void
{
if (useCapture) {
throw new Error("Fancy removeListener not implemented");
}
var listeners :Array = _listenerMap[type] as Array;
if (listeners != null) {
var ix :int = listeners.indexOf(listener);
if (ix >= 0) {
listeners.splice(ix, 1);
}
}
}
public function dispatchEvent (event :Event) :Boolean
{
var listeners :Array = _listenerMap[event.type] as Array;
for each (var listener :Function in listeners) {
try {
listener(event);
} catch (err :Error) {
trace("Event[" + event + "] dispatch error: " + err);
}
}
// TODO: "A value of true unless preventDefault() is called on the event,
// in which case it returns false. "
return true;
}
private var _listenerMap :Dictionary = new Dictionary();
}
public class TimerEvent extends Event
{
public static const TIMER :String = "timer";
public static const TIMER_COMPLETE :String = "timerComplete";
public function TimerEvent (
type :String, bubbles :Boolean = false, cancelable :Boolean = false, text :String = "")
{
super(type, bubbles, cancelable);
}
}
}
package flash.utils {
import flash.events.EventDispatcher;
import flash.events.TimerEvent;
import avmplus.*;
public function describeType (c :Object) :XML
{
throw new Error("describeType() Not implemented");
}
public function getDefinitionByName (c :String) :Class
{
return getClassByName(c);
}
public function getQualifiedClassName (c :Object) :String
{
return "Test";
throw new Error("Not implemented");
}
var timers :Dictionary = new Dictionary();
var timerIx :uint = 1;
public function setTimeout (closure :Function, delay :Number, ... arguments) :uint
{
return createTimer(closure, delay, true, arguments);
}
public function setInterval (closure :Function, delay :Number, ... arguments) :uint
{
return createTimer(closure, delay, false, arguments);
}
public function clearTimeout (id :uint): void
{
destroyTimer(id);
}
public function clearInterval (id :uint): void
{
destroyTimer(id);
}
public function getTimer () :int
{
return System.getTimer();
}
function createTimer (closure :Function, delay :Number, timeout :Boolean, ... arguments) :uint
{
var timer :Timer = new Timer(delay, timeout ? 1 : 0);
var fun :Function = function (event :TimerEvent) :void {
if (timeout) {
destroyTimer(timerIx);
}
closure.apply(null, arguments);
};
timer.addEventListener(TimerEvent.TIMER, fun);
timers[timerIx] = [ timer, fun ];
return timerIx ++;
}
function destroyTimer (id :uint) :void
{
var bits :Array = timers[id];
if (bits) {
bits[0].removeEventListener(TimerEvent.TIMER, bits[1]);
bits[0].stop();
delete timers[id];
}
}
public interface IDataInput
{
function readBytes(bytes :ByteArray, offset :uint=0, length :uint=0) :void;
function readBoolean() :Boolean;
function readByte() :int;
function readUnsignedByte() :uint;
function readShort() :int;
function readUnsignedShort() :uint;
function readInt() :int;
function readUnsignedInt() :uint;
function readFloat() :Number;
function readDouble() :Number;
function readUTF() :String;
function readUTFBytes(length :uint) :String;
function get bytesAvailable() :uint;
function get endian() :String;
function set endian(type :String) :void;
}
public interface IDataOutput
{
function writeBytes(bytes :ByteArray, offset :uint = 0, length :uint = 0) :void;
function writeBoolean(value :Boolean) :void;
function writeByte(value :int) :void;
function writeShort(value :int) :void;
function writeInt(value :int) :void;
function writeUnsignedInt(value :uint) :void;
function writeFloat(value :Number) :void;
function writeDouble(value :Number) :void;
function writeUTF(value :String) :void;
function writeUTFBytes(value :String) :void;
function get endian() :String;
function set endian(type :String) :void;
}
}
|
Implement flash.utils.setTimeout() and friends. We don't use them, but user code surely does. Is it kosher to instantiate a lookup table like this, right in the global context? Is it private to my code?
|
Implement flash.utils.setTimeout() and friends. We don't use them, but user code surely does. Is it kosher to instantiate a lookup table like this, right in the global context? Is it private to my code?
|
ActionScript
|
bsd-2-clause
|
greyhavens/thane,greyhavens/thane,greyhavens/thane,greyhavens/thane,greyhavens/thane,greyhavens/thane,greyhavens/thane
|
044d5b0207b552ac376d96033d614b2d08aa67a8
|
dolly-framework/src/test/resources/dolly/data/PropertyLevelCopyableCloneableClass.as
|
dolly-framework/src/test/resources/dolly/data/PropertyLevelCopyableCloneableClass.as
|
package dolly.data {
public class PropertyLevelCopyableCloneableClass {
[Copyable]
[Cloneable]
public static var staticProperty1:String;
[Copyable]
[Cloneable]
private var _writableField1:String;
[Copyable]
[Cloneable]
private var _readOnlyField1:String = "read-only field value";
[Cloneable]
public var property1:String;
public function PropertyLevelCopyableCloneableClass() {
}
[Copyable]
[Cloneable]
public function get writableField1():String {
return _writableField1;
}
public function set writableField1(value:String):void {
_writableField1 = value;
}
[Copyable]
[Cloneable]
public function get readOnlyField1():String {
return _readOnlyField1;
}
}
}
|
package dolly.data {
public class PropertyLevelCopyableCloneableClass {
[Copyable]
[Cloneable]
public static var staticProperty1:String = "Value of first-level static property.";
[Copyable]
[Cloneable]
private var _writableField1:String = "Value of first-level writable field.";
[Cloneable]
public var property1:String = "Value of first-level public property.";
public function PropertyLevelCopyableCloneableClass() {
}
[Copyable]
[Cloneable]
public function get writableField1():String {
return _writableField1;
}
public function set writableField1(value:String):void {
_writableField1 = value;
}
[Copyable]
[Cloneable]
public function get readOnlyField1():String {
return "Value of first-level read-only field.";
}
}
}
|
Change properties' values.
|
Change properties' values.
|
ActionScript
|
mit
|
Yarovoy/dolly
|
da8a9e9b145d5cb1aebc04764e9ed66856a31c9b
|
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 ("frame", Native.player_frame_get, null);
/*** 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) {
print ("---");
return;
}
while (frame) {
print (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 ("frame", Native.player_frame_get, null);
/*** 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;
|
make backtrace function actually work
|
make backtrace function actually work
|
ActionScript
|
lgpl-2.1
|
freedesktop-unofficial-mirror/swfdec__swfdec,mltframework/swfdec,freedesktop-unofficial-mirror/swfdec__swfdec,mltframework/swfdec,freedesktop-unofficial-mirror/swfdec__swfdec
|
3ce00f15bbbe507a81f14685ad6ad642a78a8cb5
|
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
|
34924e4c365fc59fa78964e03ae0218d90680e9e
|
src/Player.as
|
src/Player.as
|
package {
import flash.display.Sprite;
import flash.display.Stage;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.display.StageDisplayState;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.external.ExternalInterface;
import flash.media.Video;
import flash.system.Security;
import com.axis.http.url;
import com.axis.IClient;
import com.axis.ClientEvent;
import com.axis.rtspclient.RTSPClient;
import com.axis.rtspclient.IRTSPHandle;
import com.axis.rtspclient.RTSPoverTCPHandle;
import com.axis.rtspclient.RTSPoverHTTPHandle;
import com.axis.httpclient.HTTPClient;
import com.axis.rtmpclient.RTMPClient;
import com.axis.audioclient.AxisTransmit;
[SWF(frameRate="60")]
[SWF(backgroundColor="#efefef")]
public class Player extends Sprite {
private var config:Object = {
'buffer' : 1,
'scaleUp' : false
};
private var video:Video;
private var audioTransmit:AxisTransmit = new AxisTransmit();
private var meta:Object = {};
private var client:IClient;
public function Player() {
var self:Player = this;
Security.allowDomain("*");
Security.allowInsecureDomain("*");
ExternalInterface.marshallExceptions = true;
/* Media player API */
ExternalInterface.addCallback("play", play);
ExternalInterface.addCallback("pause", pause);
ExternalInterface.addCallback("resume", resume);
ExternalInterface.addCallback("stop", stop);
/* Audio Transmission API */
ExternalInterface.addCallback("startAudioTransmit", audioTransmitStartInterface);
ExternalInterface.addCallback("stopAudioTransmit", audioTransmitStopInterface);
this.stage.align = StageAlign.TOP_LEFT;
this.stage.scaleMode = StageScaleMode.NO_SCALE;
addEventListener(Event.ADDED_TO_STAGE, onStageAdded);
video = new Video(stage.stageWidth, stage.stageHeight);
addChild(video);
this.stage.doubleClickEnabled = true;
this.stage.addEventListener(MouseEvent.DOUBLE_CLICK, fullscreen);
this.stage.addEventListener(Event.FULLSCREEN, function(event:Event):void {
videoResize();
});
}
public function fullscreen(event:MouseEvent):void
{
this.stage.displayState = (StageDisplayState.NORMAL === stage.displayState) ?
StageDisplayState.FULL_SCREEN : StageDisplayState.NORMAL;
}
public function videoResize():void
{
var stagewidth:uint = (StageDisplayState.NORMAL === stage.displayState) ?
stage.stageWidth : stage.fullScreenWidth;
var stageheight:uint = (StageDisplayState.NORMAL === stage.displayState) ?
stage.stageHeight : stage.fullScreenHeight;
var scale:Number = ((stagewidth / meta.width) > (stageheight / meta.height)) ?
(stageheight / meta.height) : (stagewidth / meta.width);
video.width = meta.width;
video.height = meta.height;
if ((scale < 1.0) || (scale > 1.0 && true === config.scaleUp)) {
trace('scaling video, scale:', scale.toFixed(2), ' (aspect ratio: ' + (video.width / video.height).toFixed(2) + ')');
video.width = meta.width * scale;
video.height = meta.height * scale;
}
video.x = (stagewidth - video.width) / 2;
video.y = (stageheight - video.height) / 2;
}
public function play(iurl:String = null):void
{
var urlParsed:Object = url.parse(iurl);
if (client) {
client.stop();
video.clear();
}
switch (urlParsed.protocol) {
case 'rtsph':
/* RTSP over HTTP */
client = new RTSPClient(this.video, urlParsed, new RTSPoverHTTPHandle(urlParsed));
break;
case 'rtsp':
/* RTSP over TCP */
client = new RTSPClient(this.video, urlParsed, new RTSPoverTCPHandle(urlParsed));
break;
case 'http':
/* Progressive download over HTTP */
client = new HTTPClient(this.video, urlParsed);
break;
case 'rtmp':
/* RTMP */
client = new RTMPClient(this.video, urlParsed);
break;
default:
trace('Unknown streaming protocol:', urlParsed.protocol)
return;
}
client.addEventListener(ClientEvent.NETSTREAM_CREATED, onNetStreamCreated);
client.start();
}
public function pause():void
{
client.pause();
}
public function resume():void
{
client.resume();
}
public function stop():void
{
client.stop();
}
public function audioTransmitStopInterface():void {
audioTransmit.stop();
}
public function audioTransmitStartInterface(url:String = null):void {
audioTransmit.start(url);
}
private function onStageAdded(e:Event):void {
trace('stage added');
}
public function onMetaData(item:Object):void
{
this.meta = item;
this.videoResize();
}
public function onNetStreamCreated(ev:ClientEvent):void
{
ev.data.ns.bufferTime = config.bufferTime;
ev.data.ns.client = this;
}
}
}
|
package {
import flash.display.Sprite;
import flash.display.Stage;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.display.StageDisplayState;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.external.ExternalInterface;
import flash.media.Video;
import flash.system.Security;
import com.axis.http.url;
import com.axis.IClient;
import com.axis.ClientEvent;
import com.axis.rtspclient.RTSPClient;
import com.axis.rtspclient.IRTSPHandle;
import com.axis.rtspclient.RTSPoverTCPHandle;
import com.axis.rtspclient.RTSPoverHTTPHandle;
import com.axis.httpclient.HTTPClient;
import com.axis.rtmpclient.RTMPClient;
import com.axis.audioclient.AxisTransmit;
[SWF(frameRate="60")]
[SWF(backgroundColor="#efefef")]
public class Player extends Sprite {
private var config:Object = {
'buffer' : 1,
'scaleUp' : false
};
private var video:Video;
private var audioTransmit:AxisTransmit = new AxisTransmit();
private var meta:Object = {};
private var client:IClient;
public function Player() {
var self:Player = this;
Security.allowDomain("*");
Security.allowInsecureDomain("*");
ExternalInterface.marshallExceptions = true;
/* Media player API */
ExternalInterface.addCallback("play", play);
ExternalInterface.addCallback("pause", pause);
ExternalInterface.addCallback("resume", resume);
ExternalInterface.addCallback("stop", stop);
/* Audio Transmission API */
ExternalInterface.addCallback("startAudioTransmit", audioTransmitStartInterface);
ExternalInterface.addCallback("stopAudioTransmit", audioTransmitStopInterface);
this.stage.align = StageAlign.TOP_LEFT;
this.stage.scaleMode = StageScaleMode.NO_SCALE;
addEventListener(Event.ADDED_TO_STAGE, onStageAdded);
video = new Video(stage.stageWidth, stage.stageHeight);
addChild(video);
this.stage.doubleClickEnabled = true;
this.stage.addEventListener(MouseEvent.DOUBLE_CLICK, fullscreen);
this.stage.addEventListener(Event.FULLSCREEN, function(event:Event):void {
videoResize();
});
}
public function fullscreen(event:MouseEvent):void
{
this.stage.displayState = (StageDisplayState.NORMAL === stage.displayState) ?
StageDisplayState.FULL_SCREEN : StageDisplayState.NORMAL;
}
public function videoResize():void
{
var stagewidth:uint = (StageDisplayState.NORMAL === stage.displayState) ?
stage.stageWidth : stage.fullScreenWidth;
var stageheight:uint = (StageDisplayState.NORMAL === stage.displayState) ?
stage.stageHeight : stage.fullScreenHeight;
var scale:Number = ((stagewidth / meta.width) > (stageheight / meta.height)) ?
(stageheight / meta.height) : (stagewidth / meta.width);
video.width = meta.width;
video.height = meta.height;
if ((scale < 1.0) || (scale > 1.0 && true === config.scaleUp)) {
trace('scaling video, scale:', scale.toFixed(2), ' (aspect ratio: ' + (video.width / video.height).toFixed(2) + ')');
video.width = meta.width * scale;
video.height = meta.height * scale;
}
video.x = (stagewidth - video.width) / 2;
video.y = (stageheight - video.height) / 2;
}
public function play(iurl:String = null):void
{
var urlParsed:Object = url.parse(iurl);
if (client) {
stop();
}
switch (urlParsed.protocol) {
case 'rtsph':
/* RTSP over HTTP */
client = new RTSPClient(this.video, urlParsed, new RTSPoverHTTPHandle(urlParsed));
break;
case 'rtsp':
/* RTSP over TCP */
client = new RTSPClient(this.video, urlParsed, new RTSPoverTCPHandle(urlParsed));
break;
case 'http':
/* Progressive download over HTTP */
client = new HTTPClient(this.video, urlParsed);
break;
case 'rtmp':
/* RTMP */
client = new RTMPClient(this.video, urlParsed);
break;
default:
trace('Unknown streaming protocol:', urlParsed.protocol)
return;
}
client.addEventListener(ClientEvent.NETSTREAM_CREATED, onNetStreamCreated);
client.start();
}
public function pause():void
{
client.pause();
}
public function resume():void
{
client.resume();
}
public function stop():void
{
client.stop();
video.clear();
}
public function audioTransmitStopInterface():void {
audioTransmit.stop();
}
public function audioTransmitStartInterface(url:String = null):void {
audioTransmit.start(url);
}
private function onStageAdded(e:Event):void {
trace('stage added');
}
public function onMetaData(item:Object):void
{
this.meta = item;
this.videoResize();
}
public function onNetStreamCreated(ev:ClientEvent):void
{
ev.data.ns.bufferTime = config.bufferTime;
ev.data.ns.client = this;
}
}
}
|
Stop and clear video properly.
|
Player: Stop and clear video properly.
|
ActionScript
|
bsd-3-clause
|
AxisCommunications/locomote-video-player,gaetancollaud/locomote-video-player
|
c75baab819be53aaa82a864b3f1eceb1ad1d652f
|
frameworks/projects/HTML/asjs/src/org/apache/flex/html/beads/layouts/VerticalColumnLayout.as
|
frameworks/projects/HTML/asjs/src/org/apache/flex/html/beads/layouts/VerticalColumnLayout.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 org.apache.flex.core.IBeadLayout;
import org.apache.flex.core.IMeasurementBead;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IContainer;
import org.apache.flex.core.IUIBase;
import org.apache.flex.core.UIBase;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
/**
* ColumnLayout is a class that organizes the positioning of children
* of a container into a set of columns where each column's width is set to
* the maximum size of all of the children in that column.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class VerticalColumnLayout implements IBeadLayout
{
/**
* constructor
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function VerticalColumnLayout()
{
}
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;
}
private var _numColumns:int;
/**
* The number of columns.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get numColumns():int
{
return _numColumns;
}
public function set numColumns(value:int):void
{
_numColumns = value;
}
/**
* @copy org.apache.flex.core.IBeadLayout#layout
*/
public function layout():Boolean
{
var sw:Number = UIBase(_strand).width;
var sh:Number = UIBase(_strand).height;
var e:IUIBase;
var i:int;
var col:int = 0;
var columns:Array = [];
for (i = 0; i < numColumns; i++)
columns[i] = 0;
var children:Array = IContainer(_strand).getChildren();
var n:int = children.length;
// determine max widths of columns
for (i = 0; i < n; i++) {
e = children[i];
var thisPrefWidth:int = 0;
if (e is IStrand)
{
var mb:IMeasurementBead = e.getBeadByType(IMeasurementBead) as IMeasurementBead;
if (mb)
thisPrefWidth = mb.measuredWidth;
else
thisPrefWidth = e.width;
}
else
thisPrefWidth = e.width;
columns[col] = Math.max(columns[col], thisPrefWidth);
col = (col + 1) % numColumns;
}
var curx:int = 0;
var cury:int = 0;
var maxHeight:int = 0;
col = 0;
for (i = 0; i < n; i++) {
e = children[i];
e.x = curx;
e.y = cury;
curx += columns[col++];
maxHeight = Math.max(e.height, maxHeight);
if (col == numColumns)
{
cury += maxHeight;
maxHeight = 0;
col = 0;
curx = 0;
}
}
return true;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 org.apache.flex.core.IBeadLayout;
import org.apache.flex.core.IContainer;
import org.apache.flex.core.IMeasurementBead;
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.events.IEventDispatcher;
import org.apache.flex.utils.CSSUtils;
/**
* ColumnLayout is a class that organizes the positioning of children
* of a container into a set of columns where each column's width is set to
* the maximum size of all of the children in that column.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class VerticalColumnLayout implements IBeadLayout
{
/**
* constructor
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function VerticalColumnLayout()
{
}
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;
}
private var _numColumns:int;
/**
* The number of columns.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get numColumns():int
{
return _numColumns;
}
public function set numColumns(value:int):void
{
_numColumns = value;
}
/**
* @copy org.apache.flex.core.IBeadLayout#layout
*/
public function layout():Boolean
{
var host:UIBase = UIBase(_strand);
var sw:Number = host.width;
var sh:Number = host.height;
var e:IUIBase;
var i:int;
var col:int = 0;
var columns:Array = [];
var rows:Array = [];
var data:Array = [];
for (i = 0; i < numColumns; i++)
columns[i] = 0;
var marginLeft:Object;
var marginRight:Object;
var marginTop:Object;
var marginBottom:Object;
var margin:Object;
var ml:Number;
var mr:Number;
var mt:Number;
var mb:Number;
var children:Array = IContainer(_strand).getChildren();
var n:int = children.length;
var rowData:Object = { rowHeight: 0 };
// determine max widths of columns
for (i = 0; i < n; i++) {
e = children[i];
margin = ValuesManager.valuesImpl.getValue(e, "margin");
marginLeft = ValuesManager.valuesImpl.getValue(e, "margin-left");
marginTop = ValuesManager.valuesImpl.getValue(e, "margin-top");
marginRight = ValuesManager.valuesImpl.getValue(e, "margin-right");
marginBottom = ValuesManager.valuesImpl.getValue(e, "margin-bottom");
mt = CSSUtils.getTopValue(marginTop, margin, sh);
mb = CSSUtils.getBottomValue(marginBottom, margin, sh);
mr = CSSUtils.getRightValue(marginRight, margin, sw);
ml = CSSUtils.getLeftValue(marginLeft, margin, sw);
data.push({ mt: mt, mb: mb, mr: mr, ml: ml});
var thisPrefWidth:int = 0;
if (e is IStrand)
{
var measure:IMeasurementBead = e.getBeadByType(IMeasurementBead) as IMeasurementBead;
if (measure)
thisPrefWidth = measure.measuredWidth + ml + mr;
else
thisPrefWidth = e.width + ml + mr;
}
else
thisPrefWidth = e.width + ml + mr;
rowData.rowHeight = Math.max(rowData.rowHeight, e.height + mt + mb);
columns[col] = Math.max(columns[col], thisPrefWidth);
col = col + 1;
if (col == numColumns)
{
rows.push(rowData);
rowData = {rowHeight: 0};
col = 0;
}
}
var lastmb:Number = 0;
var curx:int = 0;
var cury:int = 0;
var maxHeight:int = 0;
col = 0;
for (i = 0; i < n; i++)
{
e = children[i];
e.x = curx + ml;
e.y = cury + data[i].mt;
curx += columns[col++];
maxHeight = Math.max(maxHeight, e.y + e.height + data[i].mb);
if (col == numColumns)
{
cury += rows[0].rowHeight;
rows.shift();
col = 0;
curx = 0;
}
}
return true;
}
}
}
|
fix bugs in this layout
|
fix bugs in this layout
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
59b53203f2d5531d220c3263851c36204095222b
|
src/com/axis/rtspclient/SDP.as
|
src/com/axis/rtspclient/SDP.as
|
package com.axis.rtspclient {
import com.axis.ErrorManager;
import com.axis.Logger;
import flash.utils.ByteArray;
import mx.utils.StringUtil;
public class SDP {
private var version:int = -1;
private var origin:Object;
private var sessionName:String;
private var timing:Object;
private var sessionBlock:Object = new Object();
private var media:Object = new Object();
public function SDP() {
}
public function parse(content:ByteArray):Boolean {
var dataString:String = content.toString();
var success:Boolean = true;
var currentMediaBlock:Object = sessionBlock;
for each (var line:String in content.toString().split("\n")) {
line = line.replace(/\r/, ''); /* Delimiter '\r\n' is allowed, if this is the case, remove '\r' too */
if (0 === line.length) {
/* Empty row (last row perhaps?), skip to next */
continue;
}
switch (line.charAt(0)) {
case 'v':
if (-1 !== version) {
Logger.log('Version present multiple times in SDP');
return false;
}
success &&= parseVersion(line);
break;
case 'o':
if (null !== origin) {
Logger.log('Origin present multiple times in SDP');
return false;
}
success &&= parseOrigin(line);
break;
case 's':
if (null !== sessionName) {
Logger.log('Session Name present multiple times in SDP');
return false;
}
success &&= parseSessionName(line);
break;
case 't':
if (null !== timing) {
Logger.log('Timing present multiple times in SDP');
return false;
}
success &&= parseTiming(line);
break;
case 'm':
if (null !== currentMediaBlock && sessionBlock !== currentMediaBlock) {
/* Complete previous block and store it */
media[currentMediaBlock.type] = currentMediaBlock;
}
/* A wild media block appears */
currentMediaBlock = new Object();
currentMediaBlock.rtpmap = new Object();
parseMediaDescription(line, currentMediaBlock);
break;
case 'a':
parseAttribute(line, currentMediaBlock);
break;
default:
Logger.log('Ignored unknown SDP directive: ' + line);
break;
}
}
media[currentMediaBlock.type] = currentMediaBlock;
return success;
}
private function parseVersion(line:String):Boolean {
var matches:Array = line.match(/^v=([0-9]+)$/);
if (0 === matches.length) {
Logger.log('\'v=\' (Version) formatted incorrectly: ' + line);
return false;
}
version = matches[1];
if (0 !== version) {
Logger.log('Unsupported SDP version:' + version);
return false;
}
return true;
}
private function parseOrigin(line:String):Boolean {
var matches:Array = line.match(/^o=([^ ]+) ([0-9]+) ([0-9]+) (IN) (IP4|IP6) ([^ ]+)$/);
if (0 === matches.length) {
Logger.log('\'o=\' (Origin) formatted incorrectly: ' + line);
return false;
}
this.origin = new Object();
this.origin.username = matches[1];
this.origin.sessionid = matches[2];
this.origin.sessionversion = matches[3];
this.origin.nettype = matches[4];
this.origin.addresstype = matches[5];
this.origin.unicastaddress = matches[6];
return true;
}
private function parseSessionName(line:String):Boolean {
var matches:Array = line.match(/^s=([^\r\n]+)$/);
if (0 === matches.length) {
Logger.log('\'s=\' (Session Name) formatted incorrectly: ' + line);
return false;
}
this.sessionName = matches[1];
return true;
}
private function parseTiming(line:String):Boolean {
var matches:Array = line.match(/^t=([0-9]+) ([0-9]+)$/);
if (0 === matches.length) {
Logger.log('\'t=\' (Timing) formatted incorrectly: ' + line);
return false;
}
this.timing = new Object();
timing.start = matches[1];
timing.stop = matches[2];
return true;
}
private function parseMediaDescription(line:String, media:Object):Boolean {
var matches:Array = line.match(/^m=([^ ]+) ([^ ]+) ([^ ]+)[ ]/);
if (0 === matches.length) {
Logger.log('\'m=\' (Media) formatted incorrectly: ' + line);
return false;
}
media.type = matches[1];
media.port = matches[2];
media.proto = matches[3];
media.fmt = line.substr(matches[0].length).split(' ').map(function(fmt:*, index:int, array:Array):int {
return parseInt(fmt);
});
return true;
}
private function parseAttribute(line:String, media:Object):Boolean {
if (null === media) {
/* Not in a media block, can't be bothered parsing attributes for session */
return true;
}
var matches:Array; /* Used for some cases of below switch-case */
var separator:int = line.indexOf(':');
var attribute:String = line.substr(0, (-1 === separator) ? 0x7FFFFFFF : separator); /* 0x7FF.. is default */
switch (attribute) {
case 'a=recvonly':
case 'a=sendrecv':
case 'a=sendonly':
case 'a=inactive':
media.mode = line.substr('a='.length);
break;
case 'a=control':
media.control = line.substr('a=control:'.length);
break;
case 'a=rtpmap':
matches = line.match(/^a=rtpmap:(\d+) (.*)$/);
if (null === matches) {
Logger.log('Could not parse \'rtpmap\' of \'a=\'');
return false;
}
var payload:int = parseInt(matches[1]);
media.rtpmap[payload] = new Object();
var attrs:Array = matches[2].split('/');
media.rtpmap[payload].name = attrs[0];
media.rtpmap[payload].clock = attrs[1];
if (undefined !== attrs[2]) {
media.rtpmap[payload].encparams = attrs[2];
}
break;
case 'a=fmtp':
matches = line.match(/^a=fmtp:(\d+) (.*)$/);
if (0 === matches.length) {
Logger.log('Could not parse \'fmtp\' of \'a=\'');
return false;
}
media.fmtp = new Object();
for each (var param:String in matches[2].split(';')) {
var idx:int = param.indexOf('=');
media.fmtp[StringUtil.trim(param.substr(0, idx).toLowerCase())] = StringUtil.trim(param.substr(idx + 1));
}
break;
}
return true;
}
public function getSessionBlock():Object {
return this.sessionBlock;
}
public function getMediaBlock(mediaType:String):Object {
return this.media[mediaType];
}
public function getMediaBlockByPayloadType(pt:int):Object {
for each (var m:Object in this.media) {
if (-1 !== m.fmt.indexOf(pt)) {
return m;
}
}
ErrorManager.dispatchError(826, [pt], true);
return null;
}
public function getMediaBlockList():Array {
var res:Array = [];
for each (var m:Object in this.media) {
res.push(m);
}
return res;
}
}
}
|
package com.axis.rtspclient {
import com.axis.ErrorManager;
import com.axis.Logger;
import flash.utils.ByteArray;
import mx.utils.StringUtil;
public class SDP {
private var version:int = -1;
private var origin:Object;
private var sessionName:String;
private var timing:Object;
private var sessionBlock:Object = new Object();
private var media:Object = new Object();
public function SDP() {
}
public function parse(content:ByteArray):Boolean {
var dataString:String = content.toString();
var success:Boolean = true;
var currentMediaBlock:Object = sessionBlock;
Logger.log(dataString);
for each (var line:String in dataString.split("\n")) {
line = line.replace(/\r/, ''); /* Delimiter '\r\n' is allowed, if this is the case, remove '\r' too */
if (0 === line.length) {
/* Empty row (last row perhaps?), skip to next */
continue;
}
switch (line.charAt(0)) {
case 'v':
if (-1 !== version) {
Logger.log('Version present multiple times in SDP');
return false;
}
success &&= parseVersion(line);
break;
case 'o':
if (null !== origin) {
Logger.log('Origin present multiple times in SDP');
return false;
}
success &&= parseOrigin(line);
break;
case 's':
if (null !== sessionName) {
Logger.log('Session Name present multiple times in SDP');
return false;
}
success &&= parseSessionName(line);
break;
case 't':
if (null !== timing) {
Logger.log('Timing present multiple times in SDP');
return false;
}
success &&= parseTiming(line);
break;
case 'm':
if (null !== currentMediaBlock && sessionBlock !== currentMediaBlock) {
/* Complete previous block and store it */
media[currentMediaBlock.type] = currentMediaBlock;
}
/* A wild media block appears */
currentMediaBlock = new Object();
currentMediaBlock.rtpmap = new Object();
parseMediaDescription(line, currentMediaBlock);
break;
case 'a':
parseAttribute(line, currentMediaBlock);
break;
default:
Logger.log('Ignored unknown SDP directive: ' + line);
break;
}
}
media[currentMediaBlock.type] = currentMediaBlock;
return success;
}
private function parseVersion(line:String):Boolean {
var matches:Array = line.match(/^v=([0-9]+)$/);
if (0 === matches.length) {
Logger.log('\'v=\' (Version) formatted incorrectly: ' + line);
return false;
}
version = matches[1];
if (0 !== version) {
Logger.log('Unsupported SDP version:' + version);
return false;
}
return true;
}
private function parseOrigin(line:String):Boolean {
var matches:Array = line.match(/^o=([^ ]+) ([0-9]+) ([0-9]+) (IN) (IP4|IP6) ([^ ]+)$/);
if (0 === matches.length) {
Logger.log('\'o=\' (Origin) formatted incorrectly: ' + line);
return false;
}
this.origin = new Object();
this.origin.username = matches[1];
this.origin.sessionid = matches[2];
this.origin.sessionversion = matches[3];
this.origin.nettype = matches[4];
this.origin.addresstype = matches[5];
this.origin.unicastaddress = matches[6];
return true;
}
private function parseSessionName(line:String):Boolean {
var matches:Array = line.match(/^s=([^\r\n]+)$/);
if (0 === matches.length) {
Logger.log('\'s=\' (Session Name) formatted incorrectly: ' + line);
return false;
}
this.sessionName = matches[1];
return true;
}
private function parseTiming(line:String):Boolean {
var matches:Array = line.match(/^t=([0-9]+) ([0-9]+)$/);
if (0 === matches.length) {
Logger.log('\'t=\' (Timing) formatted incorrectly: ' + line);
return false;
}
this.timing = new Object();
timing.start = matches[1];
timing.stop = matches[2];
return true;
}
private function parseMediaDescription(line:String, media:Object):Boolean {
var matches:Array = line.match(/^m=([^ ]+) ([^ ]+) ([^ ]+)[ ]/);
if (0 === matches.length) {
Logger.log('\'m=\' (Media) formatted incorrectly: ' + line);
return false;
}
media.type = matches[1];
media.port = matches[2];
media.proto = matches[3];
media.fmt = line.substr(matches[0].length).split(' ').map(function(fmt:*, index:int, array:Array):int {
return parseInt(fmt);
});
return true;
}
private function parseAttribute(line:String, media:Object):Boolean {
if (null === media) {
/* Not in a media block, can't be bothered parsing attributes for session */
return true;
}
var matches:Array; /* Used for some cases of below switch-case */
var separator:int = line.indexOf(':');
var attribute:String = line.substr(0, (-1 === separator) ? 0x7FFFFFFF : separator); /* 0x7FF.. is default */
switch (attribute) {
case 'a=recvonly':
case 'a=sendrecv':
case 'a=sendonly':
case 'a=inactive':
media.mode = line.substr('a='.length);
break;
case 'a=control':
media.control = line.substr('a=control:'.length);
break;
case 'a=rtpmap':
matches = line.match(/^a=rtpmap:(\d+) (.*)$/);
if (null === matches) {
Logger.log('Could not parse \'rtpmap\' of \'a=\'');
return false;
}
var payload:int = parseInt(matches[1]);
media.rtpmap[payload] = new Object();
var attrs:Array = matches[2].split('/');
media.rtpmap[payload].name = attrs[0];
media.rtpmap[payload].clock = attrs[1];
if (undefined !== attrs[2]) {
media.rtpmap[payload].encparams = attrs[2];
}
break;
case 'a=fmtp':
matches = line.match(/^a=fmtp:(\d+) (.*)$/);
if (0 === matches.length) {
Logger.log('Could not parse \'fmtp\' of \'a=\'');
return false;
}
media.fmtp = new Object();
for each (var param:String in matches[2].split(';')) {
var idx:int = param.indexOf('=');
media.fmtp[StringUtil.trim(param.substr(0, idx).toLowerCase())] = StringUtil.trim(param.substr(idx + 1));
}
break;
}
return true;
}
public function getSessionBlock():Object {
return this.sessionBlock;
}
public function getMediaBlock(mediaType:String):Object {
return this.media[mediaType];
}
public function getMediaBlockByPayloadType(pt:int):Object {
for each (var m:Object in this.media) {
if (-1 !== m.fmt.indexOf(pt)) {
return m;
}
}
ErrorManager.dispatchError(826, [pt], true);
return null;
}
public function getMediaBlockList():Array {
var res:Array = [];
for each (var m:Object in this.media) {
res.push(m);
}
return res;
}
}
}
|
Debug log the SDP file
|
SDP: Debug log the SDP file
|
ActionScript
|
bsd-3-clause
|
gaetancollaud/locomote-video-player,AxisCommunications/locomote-video-player
|
f3c816c625f8d95a739bf625d9f3e092407b17e6
|
src/org/jivesoftware/xiff/core/XMPPBOSHConnection.as
|
src/org/jivesoftware/xiff/core/XMPPBOSHConnection.as
|
package org.jivesoftware.xiff.core
{
import flash.events.ErrorEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.xml.XMLDocument;
import flash.xml.XMLNode;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
import org.jivesoftware.xiff.auth.Plain;
import org.jivesoftware.xiff.auth.SASLAuth;
import org.jivesoftware.xiff.data.IQ;
import org.jivesoftware.xiff.data.bind.BindExtension;
import org.jivesoftware.xiff.data.session.SessionExtension;
import org.jivesoftware.xiff.events.ConnectionSuccessEvent;
import org.jivesoftware.xiff.events.DisconnectionEvent;
import org.jivesoftware.xiff.events.IncomingDataEvent;
import org.jivesoftware.xiff.events.LoginEvent;
import org.jivesoftware.xiff.util.Callback;
public class XMPPBOSHConnection extends XMPPConnection
{
private var maxConcurrentRequests:uint = 2;
private var boshVersion:Number = 1.6;
private var headers:Object = {
"post": [],
"get": ['Cache-Control', 'no-store', 'Cache-Control', 'no-cache', 'Pragma', 'no-cache']
};
private var requestCount:int = 0;
private var failedRequests:Array = [];
private var lastPollTime:int = 0;
private var requestQueue:Array = [];
private var responseQueue:Array = [];
private const responseTimer:Timer = new Timer(0.0, 1);
private var isDisconnecting:Boolean = false;
private var boshPollingInterval:Number = 10000;
private var sid:String;
private var rid:Number;
private var wait:int;
private var inactivity:int;
private var pollTimer:Timer;
private var isCurrentlyPolling:Boolean = false;
private var auth:SASLAuth;
private var authHandler:Function;
private var https:Boolean = false;
private var _port:Number = -1;
private var callbacks:Object = {};
public override function connect(streamType:String=null):Boolean
{
BindExtension.enable();
active = false;
loggedIn = false;
var attrs:Object = {
xmlns: "http://jabber.org/protocol/httpbind",
hold: maxConcurrentRequests,
rid: nextRID,
secure: https,
wait: 10,
ver: boshVersion
}
var result:XMLNode = new XMLNode(1, "body");
result.attributes = attrs;
sendRequests(result);
return true;
}
public function set secure(flag:Boolean):void
{
https = flag;
}
public override function set port(portnum:Number):void
{
_port = portnum;
}
public override function get port():Number
{
if(_port == -1)
return https ? 8483 : 8080;
return _port;
}
public function get httpServer():String
{
return (https ? "https" : "http") + "://" + server + ":" + port + "/http-bind/";
}
public override function disconnect():void
{
dispatchEvent(new DisconnectionEvent());
}
public function processConnectionResponse(responseBody:XMLNode):void
{
var attributes:Object = responseBody.attributes;
sid = attributes.sid;
boshPollingInterval = attributes.polling * 1000;
// if we have a polling interval of 1, we want to add an extra second for a little bit of
// padding.
if(boshPollingInterval <= 1000 && boshPollingInterval > 0)
boshPollingInterval += 1000;
wait = attributes.wait;
inactivity = attributes.inactivity;
var serverRequests:int = attributes.requests;
if (serverRequests)
maxConcurrentRequests = Math.min(serverRequests, maxConcurrentRequests);
active = true;
configureConnection(responseBody);
responseTimer.addEventListener(TimerEvent.TIMER_COMPLETE, processResponse);
pollTimer = new Timer(boshPollingInterval, 1);
pollTimer.addEventListener(TimerEvent.TIMER, pollServer);
}
private function processResponse(event:TimerEvent=null):void
{
// Read the data and send it to the appropriate parser
var currentNode:XMLNode = responseQueue.shift();
var nodeName:String = currentNode.nodeName.toLowerCase();
switch( nodeName )
{
case "stream:features":
//we already handled this in httpResponse()
break;
case "stream:error":
handleStreamError( currentNode );
break;
case "iq":
handleIQ( currentNode );
break;
case "message":
handleMessage( currentNode );
break;
case "presence":
handlePresence( currentNode );
break;
case "success":
handleAuthentication( currentNode );
break;
default:
dispatchError( "undefined-condition", "Unknown Error", "modify", 500 );
break;
}
resetResponseProcessor();
}
private function resetResponseProcessor():void
{
if(responseQueue.length > 0)
{
responseTimer.reset();
responseTimer.start();
}
}
private function httpResponse(req:XMLNode, isPollResponse:Boolean, evt:ResultEvent):void
{
requestCount--;
var rawXML:String = evt.result as String;
var xmlData:XMLDocument = new XMLDocument();
xmlData.ignoreWhite = this.ignoreWhite;
xmlData.parseXML( rawXML );
var bodyNode:XMLNode = xmlData.firstChild;
var event:IncomingDataEvent = new IncomingDataEvent();
event.data = xmlData;
dispatchEvent( event );
if(bodyNode.attributes["type"] == "terminal")
{
dispatchError( "BOSH Error", bodyNode.attributes["condition"], "", -1 );
active = false;
}
for each(var childNode:XMLNode in bodyNode.childNodes)
{
if(childNode.nodeName == "stream:features")
{
_expireTagSearch = false;
processConnectionResponse( bodyNode );
}
else
responseQueue.push(childNode);
}
resetResponseProcessor();
//if we just processed a poll response, we're no longer in mid-poll
if(isPollResponse)
isCurrentlyPolling = false;
//if we have queued requests we want to send them before attempting to poll again
//otherwise, if we don't already have a countdown going for the next poll, start one
if (!sendQueuedRequests() && !pollTimer.running)
resetPollTimer();
}
private function httpError(req:XMLNode, isPollResponse:Boolean, evt:FaultEvent):void
{
active = false;
trace("ERROR: " + req + ", \n" + evt.message);
}
protected override function sendXML(body:*):void
{
sendQueuedRequests(body);
}
private function sendQueuedRequests(body:*=null):Boolean
{
if(body)
requestQueue.push(body);
else if(requestQueue.length == 0)
return false;
return sendRequests();
}
//returns true if any requests were sent
private function sendRequests(data:XMLNode = null, isPoll:Boolean=false):Boolean
{
if(requestCount >= maxConcurrentRequests)
return false;
requestCount++;
if(!data)
{
if(isPoll)
{
data = createRequest();
}
else
{
var temp:Array = [];
for(var i:uint = 0; i < 10 && requestQueue.length > 0; i++)
{
temp.push(requestQueue.shift());
}
data = createRequest(temp);
}
}
//build the http request
var request:HTTPService = new HTTPService();
request.method = "post";
request.headers = headers[request.method];
request.url = httpServer;
request.resultFormat = HTTPService.RESULT_FORMAT_TEXT;
request.contentType = "text/xml";
var responseCallback:Callback = new Callback(this, httpResponse, data, isPoll);
var errorCallback:Callback = new Callback(this, httpError, data, isPoll);
request.addEventListener(ResultEvent.RESULT, responseCallback.call, false);
request.addEventListener(FaultEvent.FAULT, errorCallback.call, false);
request.send(data);
resetPollTimer();
return true;
}
private function resetPollTimer():void
{
if(!pollTimer)
return;
pollTimer.reset();
pollTimer.start();
}
private function pollServer(evt:TimerEvent):void
{
//We shouldn't poll if the connection is dead, if we had requests to send instead, or if there's already one in progress
if(!isActive() || sendQueuedRequests() || isCurrentlyPolling)
return;
//this should be safe since sendRequests checks to be sure it's not over the concurrent requests limit, and we just ensured that the queue is empty by calling sendQueuedRequests()
isCurrentlyPolling = sendRequests(null, true);
}
private function get nextRID():Number {
if(!rid)
rid = Math.floor(Math.random() * 1000000);
return ++rid;
}
private function createRequest(bodyContent:Array=null):XMLNode {
var attrs:Object = {
xmlns: "http://jabber.org/protocol/httpbind",
rid: nextRID,
sid: sid
}
var req:XMLNode = new XMLNode(1, "body");
if(bodyContent)
for each(var content:XMLNode in bodyContent)
req.appendChild(content);
req.attributes = attrs;
return req;
}
private function login(username:String, password:String, resource:String):void
{
// if (!myUsername) {
// auth = new XMPP.SASLAuth.Anonymous();
// }
// else {
auth = new Plain(username, password, server);
// }
authHandler = handleAuthentication;
sendXML(auth.request);
}
private function handleAuthentication(responseBody:XMLNode):void
{
// if(!response || response.length == 0) {
// return;
// }
var status:Object = auth.handleResponse(0, responseBody);
if (status.authComplete) {
if (status.authSuccess) {
bindConnection();
}
else {
dispatchEvent(new ErrorEvent(ErrorEvent.ERROR));
disconnect();
}
}
}
private function configureConnection(responseBody:XMLNode):void
{
var features:XMLNode = responseBody.firstChild;
var authentication:Object = {};
for each(var feature:XMLNode in features.childNodes)
{
if (feature.nodeName == "mechanisms")
authentication.auth = configureAuthMechanisms(feature);
else if (feature.nodeName == "bind")
authentication.bind = true;
else if (feature.nodeName == "session")
authentication.session = true;
}
auth = authentication.auth;
dispatchEvent(new ConnectionSuccessEvent());
login(myUsername, myPassword, myResource);
}
private function configureAuthMechanisms(mechanisms:XMLNode):SASLAuth
{
var authMechanism:SASLAuth;
for each(var mechanism:XMLNode in mechanisms.childNodes)
{
if (mechanism.firstChild.nodeValue == "PLAIN")
return new Plain(myUsername, myPassword, server);
// else if (mechanism.firstChild.nodeValue == "ANONYMOUS") {
// authMechanism["anonymous"] = true;
// }
}
if (!authMechanism) {
throw new Error("No auth mechanisms found");
}
return authMechanism;
}
public function handleBindResponse(packet:IQ):void
{
var bind:BindExtension = packet.getExtension("bind") as BindExtension;
var jid:String = bind.getJID();
var parts:Array = jid.split("/");
myResource = parts[1];
parts = parts[0].split("@");
myUsername = parts[0];
server = parts[1];
establishSession();
}
private function bindConnection():void
{
var bindIQ:IQ = new IQ(null, "set");
bindIQ.addExtension(new BindExtension());
//this is laaaaaame, it should be a function
bindIQ.callbackName = "handleBindResponse";
bindIQ.callbackScope = this;
send(bindIQ);
}
public function handleSessionResponse(packet:IQ):void
{
dispatchEvent(new LoginEvent());
}
private function establishSession():void
{
var sessionIQ:IQ = new IQ(null, "set");
sessionIQ.addExtension(new SessionExtension());
sessionIQ.callbackName = "handleSessionResponse";
sessionIQ.callbackScope = this;
send(sessionIQ);
}
//do nothing, we use polling instead
public override function sendKeepAlive():void {}
}
}
|
package org.jivesoftware.xiff.core
{
import flash.events.ErrorEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.xml.XMLDocument;
import flash.xml.XMLNode;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
import org.jivesoftware.xiff.auth.Plain;
import org.jivesoftware.xiff.auth.SASLAuth;
import org.jivesoftware.xiff.data.IQ;
import org.jivesoftware.xiff.data.bind.BindExtension;
import org.jivesoftware.xiff.data.session.SessionExtension;
import org.jivesoftware.xiff.events.ConnectionSuccessEvent;
import org.jivesoftware.xiff.events.DisconnectionEvent;
import org.jivesoftware.xiff.events.IncomingDataEvent;
import org.jivesoftware.xiff.events.LoginEvent;
import org.jivesoftware.xiff.util.Callback;
public class XMPPBOSHConnection extends XMPPConnection
{
private var maxConcurrentRequests:uint = 2;
private var boshVersion:Number = 1.6;
private var headers:Object = {
"post": [],
"get": ['Cache-Control', 'no-store', 'Cache-Control', 'no-cache', 'Pragma', 'no-cache']
};
private var requestCount:int = 0;
private var failedRequests:Array = [];
private var lastPollTime:int = 0;
private var requestQueue:Array = [];
private var responseQueue:Array = [];
private const responseTimer:Timer = new Timer(0.0, 1);
private var isDisconnecting:Boolean = false;
private var boshPollingInterval:Number = 10000;
private var sid:String;
private var rid:Number;
private var wait:int;
private var inactivity:int;
private var pollTimer:Timer;
private var isCurrentlyPolling:Boolean = false;
private var auth:SASLAuth;
private var authHandler:Function;
private var https:Boolean = false;
private var _port:Number = -1;
private var callbacks:Object = {};
public override function connect(streamType:String=null):Boolean
{
BindExtension.enable();
active = false;
loggedIn = false;
var attrs:Object = {
xmlns: "http://jabber.org/protocol/httpbind",
hold: maxConcurrentRequests,
rid: nextRID,
secure: https,
wait: 10,
ver: boshVersion
}
var result:XMLNode = new XMLNode(1, "body");
result.attributes = attrs;
sendRequests(result);
return true;
}
public function set secure(flag:Boolean):void
{
https = flag;
}
public override function set port(portnum:Number):void
{
_port = portnum;
}
public override function get port():Number
{
if(_port == -1)
return https ? 8483 : 8080;
return _port;
}
public function get httpServer():String
{
return (https ? "https" : "http") + "://" + server + ":" + port + "/http-bind/";
}
public override function disconnect():void
{
dispatchEvent(new DisconnectionEvent());
}
public function processConnectionResponse(responseBody:XMLNode):void
{
var attributes:Object = responseBody.attributes;
sid = attributes.sid;
boshPollingInterval = attributes.polling * 1000;
// if we have a polling interval of 1, we want to add an extra second for a little bit of
// padding.
if(boshPollingInterval <= 1000 && boshPollingInterval > 0)
boshPollingInterval += 1000;
wait = attributes.wait;
inactivity = attributes.inactivity;
var serverRequests:int = attributes.requests;
if (serverRequests)
maxConcurrentRequests = Math.min(serverRequests, maxConcurrentRequests);
active = true;
configureConnection(responseBody);
responseTimer.addEventListener(TimerEvent.TIMER_COMPLETE, processResponse);
pollTimer = new Timer(boshPollingInterval, 1);
pollTimer.addEventListener(TimerEvent.TIMER, pollServer);
}
private function processResponse(event:TimerEvent=null):void
{
// Read the data and send it to the appropriate parser
var currentNode:XMLNode = responseQueue.shift();
var nodeName:String = currentNode.nodeName.toLowerCase();
switch( nodeName )
{
case "stream:features":
//we already handled this in httpResponse()
break;
case "stream:error":
handleStreamError( currentNode );
break;
case "iq":
handleIQ( currentNode );
break;
case "message":
handleMessage( currentNode );
break;
case "presence":
handlePresence( currentNode );
break;
case "success":
handleAuthentication( currentNode );
break;
default:
dispatchError( "undefined-condition", "Unknown Error", "modify", 500 );
break;
}
resetResponseProcessor();
}
private function resetResponseProcessor():void
{
if(responseQueue.length > 0)
{
responseTimer.reset();
responseTimer.start();
}
}
private function httpResponse(req:XMLNode, isPollResponse:Boolean, evt:ResultEvent):void
{
requestCount--;
var rawXML:String = evt.result as String;
var xmlData:XMLDocument = new XMLDocument();
xmlData.ignoreWhite = this.ignoreWhite;
xmlData.parseXML( rawXML );
var bodyNode:XMLNode = xmlData.firstChild;
var event:IncomingDataEvent = new IncomingDataEvent();
event.data = xmlData;
dispatchEvent( event );
if(bodyNode.attributes["type"] == "terminal")
{
dispatchError( "BOSH Error", bodyNode.attributes["condition"], "", -1 );
active = false;
}
for each(var childNode:XMLNode in bodyNode.childNodes)
{
if(childNode.nodeName == "stream:features")
{
_expireTagSearch = false;
processConnectionResponse( bodyNode );
}
else
responseQueue.push(childNode);
}
resetResponseProcessor();
//if we just processed a poll response, we're no longer in mid-poll
if(isPollResponse)
isCurrentlyPolling = false;
//if we have queued requests we want to send them before attempting to poll again
//otherwise, if we don't already have a countdown going for the next poll, start one
if (!sendQueuedRequests() && !pollTimer.running)
resetPollTimer();
}
private function httpError(req:XMLNode, isPollResponse:Boolean, evt:FaultEvent):void
{
active = false;
trace("ERROR: " + req + ", \n" + evt.message);
}
protected override function sendXML(body:*):void
{
sendQueuedRequests(body);
}
private function sendQueuedRequests(body:*=null):Boolean
{
if(body)
requestQueue.push(body);
else if(requestQueue.length == 0)
return false;
return sendRequests();
}
//returns true if any requests were sent
private function sendRequests(data:XMLNode = null, isPoll:Boolean=false):Boolean
{
if(requestCount >= maxConcurrentRequests)
return false;
requestCount++;
if(!data)
{
if(isPoll)
{
data = createRequest();
}
else
{
var temp:Array = [];
for(var i:uint = 0; i < 10 && requestQueue.length > 0; i++)
{
temp.push(requestQueue.shift());
}
data = createRequest(temp);
}
}
//build the http request
var request:HTTPService = new HTTPService();
request.method = "post";
request.headers = headers[request.method];
request.url = httpServer;
request.resultFormat = HTTPService.RESULT_FORMAT_TEXT;
request.contentType = "text/xml";
var responseCallback:Callback = new Callback(this, httpResponse, data, isPoll);
var errorCallback:Callback = new Callback(this, httpError, data, isPoll);
request.addEventListener(ResultEvent.RESULT, responseCallback.call, false);
request.addEventListener(FaultEvent.FAULT, errorCallback.call, false);
request.send(data);
resetPollTimer();
return true;
}
private function resetPollTimer():void
{
if(!pollTimer)
return;
pollTimer.reset();
pollTimer.start();
}
private function pollServer(evt:TimerEvent):void
{
//We shouldn't poll if the connection is dead, if we had requests to send instead, or if there's already one in progress
if(!isActive() || sendQueuedRequests() || isCurrentlyPolling)
return;
//this should be safe since sendRequests checks to be sure it's not over the concurrent requests limit, and we just ensured that the queue is empty by calling sendQueuedRequests()
isCurrentlyPolling = sendRequests(null, true);
}
private function get nextRID():Number {
if(!rid)
rid = Math.floor(Math.random() * 1000000);
return ++rid;
}
private function createRequest(bodyContent:Array=null):XMLNode {
var attrs:Object = {
xmlns: "http://jabber.org/protocol/httpbind",
rid: nextRID,
sid: sid
}
var req:XMLNode = new XMLNode(1, "body");
if(bodyContent)
for each(var content:XMLNode in bodyContent)
req.appendChild(content);
req.attributes = attrs;
return req;
}
private function login(username:String, password:String, resource:String):void
{
// if (!myUsername) {
// auth = new XMPP.SASLAuth.Anonymous();
// }
// else {
if(!auth)
auth = new Plain(username, password, server);
// }
authHandler = handleAuthentication;
sendXML(auth.request);
}
private function handleAuthentication(responseBody:XMLNode):void
{
// if(!response || response.length == 0) {
// return;
// }
var status:Object = auth.handleResponse(0, responseBody);
if (status.authComplete) {
if (status.authSuccess) {
bindConnection();
}
else {
dispatchEvent(new ErrorEvent(ErrorEvent.ERROR));
disconnect();
}
}
}
private function configureConnection(responseBody:XMLNode):void
{
var features:XMLNode = responseBody.firstChild;
var authentication:Object = {};
for each(var feature:XMLNode in features.childNodes)
{
if (feature.nodeName == "mechanisms")
authentication.auth = configureAuthMechanisms(feature);
else if (feature.nodeName == "bind")
authentication.bind = true;
else if (feature.nodeName == "session")
authentication.session = true;
}
auth = authentication.auth;
dispatchEvent(new ConnectionSuccessEvent());
login(myUsername, myPassword, myResource);
}
private function configureAuthMechanisms(mechanisms:XMLNode):SASLAuth
{
var authMechanism:SASLAuth;
for each(var mechanism:XMLNode in mechanisms.childNodes)
{
if (mechanism.firstChild.nodeValue == "PLAIN")
return new Plain(myUsername, myPassword, server);
// else if (mechanism.firstChild.nodeValue == "ANONYMOUS") {
// authMechanism["anonymous"] = true;
// }
}
if (!authMechanism) {
throw new Error("No auth mechanisms found");
}
return authMechanism;
}
public function handleBindResponse(packet:IQ):void
{
var bind:BindExtension = packet.getExtension("bind") as BindExtension;
var jid:String = bind.getJID();
var parts:Array = jid.split("/");
myResource = parts[1];
parts = parts[0].split("@");
myUsername = parts[0];
server = parts[1];
establishSession();
}
private function bindConnection():void
{
var bindIQ:IQ = new IQ(null, "set");
bindIQ.addExtension(new BindExtension());
//this is laaaaaame, it should be a function
bindIQ.callbackName = "handleBindResponse";
bindIQ.callbackScope = this;
send(bindIQ);
}
public function handleSessionResponse(packet:IQ):void
{
dispatchEvent(new LoginEvent());
}
private function establishSession():void
{
var sessionIQ:IQ = new IQ(null, "set");
sessionIQ.addExtension(new SessionExtension());
sessionIQ.callbackName = "handleSessionResponse";
sessionIQ.callbackScope = this;
send(sessionIQ);
}
//do nothing, we use polling instead
public override function sendKeepAlive():void {}
}
}
|
Make use of Plain conditional on no other mechanisms being found... really I think this should be deleted, but I need to investigate that
|
Make use of Plain conditional on no other mechanisms being found... really I think this should be deleted, but I need to investigate that
git-svn-id: c197267f952b24206666de142881703007ca05d5@9930 b35dd754-fafc-0310-a699-88a17e54d16e
|
ActionScript
|
apache-2.0
|
nazoking/xiff
|
daa793ed7896b136ed0cb8c85ec02689cafd293a
|
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.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 separator: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();
log("Loading " + 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 {
try {
loadedSwf = MovieClip(ev.target.content);
}
catch(err:Error) {
//AVM1 Movie not supported
exit(5);
return;
}
outputWidth = Math.ceil(ev.target.width);
outputHeight = Math.ceil(ev.target.height);
log("Loaded!");
totalFrames = loadedSwf.totalFrames;
log("Frame count: " + totalFrames);
calculateBBox();
stopClip(loadedSwf);
goToFrame(loadedSwf, 0);
timer = new Timer(1);
timer.addEventListener(TimerEvent.TIMER, step);
timer.start();
}
private function padNumber(input:int, target:int):String {
var out:String = input.toString();
var targetCount:int = target.toString().length;
while(out.length < targetCount) {
out = '0' + out;
}
return out;
}
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])
);
log("Bounding 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 {
counter++;
if(counter <= totalFrames) {
goToFrame(loadedSwf, counter);
saveFrame();
}
else {
timer.stop();
log("Done!");
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 increment:String = '';
if(totalFrames > 1) {
increment = separator + padNumber(counter, totalFrames);
}
var outfileName:String = outputDirPath + File.separator + prefix + increment + ".png"
var file:File = new File(outfileName);
log("Writing: " + 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 matchNameRegExStr:String = '([^\\' + File.separator + ']+)$';
var matchNameRegEx:RegExp = new RegExp(matchNameRegExStr);
var matches:Array = inputFileName.match(matchNameRegEx);
if(!matches) {
// File inputFileName not valid
exit(2);
return "";
}
prefix = matches[1].split('.')[0];
log("Prefix: " + prefix);
var f:File = new File(ev.currentDirectory.nativePath);
f = f.resolvePath(inputFileName);
if(!f.exists) {
log("Input 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 "";
}
log("inpt: " + 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 {
log("cwd: " + ev.currentDirectory.nativePath);
return ev.currentDirectory.nativePath;
}
return "";
}
}
private function log(message:String="", add_new_line:Boolean=true):void {
outfield.appendText((add_new_line ? "\n" : "") + message);
}
//Invoke handler called when started
private function onInvoke(ev:InvokeEvent):void {
inputFilePath = getInputFile(ev);
outputDirPath = getOutputDir(ev);
log("Input file: " + inputFilePath);
log("Output directory: " + outputDirPath);
loadSwf();
}
private function exit(code:int=0):void {
log("Exit: " + code);
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 separator: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);
stage.align = 'TL';
stage.scaleMode = 'noScale';
outfield = new TextField();
outfield.autoSize = TextFieldAutoSize.LEFT;
stage.addChild(outfield);
stage.frameRate = 12;
}
//Loads in file
private function loadSwf():void {
loader = new Loader();
log("Loading " + 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 {
try {
loadedSwf = MovieClip(ev.target.content);
}
catch(err:Error) {
//AVM1 Movie not supported
exit(5);
return;
}
outputWidth = Math.ceil(ev.target.width);
outputHeight = Math.ceil(ev.target.height);
log("Loaded!");
totalFrames = loadedSwf.totalFrames;
log("Frame count: " + totalFrames);
calculateBBox();
stopClip(loadedSwf);
goToFrame(loadedSwf, 0);
timer = new Timer(1);
timer.addEventListener(TimerEvent.TIMER, step);
timer.start();
}
private function padNumber(input:int, target:int):String {
var out:String = input.toString();
var targetCount:int = target.toString().length;
while(out.length < targetCount) {
out = '0' + out;
}
return out;
}
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])
);
log("Bounding 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 {
counter++;
if(counter <= totalFrames) {
goToFrame(loadedSwf, counter);
saveFrame();
}
else {
timer.stop();
log("Done!");
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 increment:String = '';
if(totalFrames > 1) {
increment = separator + padNumber(counter, totalFrames);
}
var outfileName:String = outputDirPath + File.separator + prefix + increment + ".png"
var file:File = new File(outfileName);
log("Writing: " + 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 matchNameRegExStr:String = '([^\\' + File.separator + ']+)$';
var matchNameRegEx:RegExp = new RegExp(matchNameRegExStr);
var matches:Array = inputFileName.match(matchNameRegEx);
if(!matches) {
// File inputFileName not valid
exit(2);
return "";
}
prefix = matches[1].split('.')[0];
log("Prefix: " + prefix);
var f:File = new File(ev.currentDirectory.nativePath);
f = f.resolvePath(inputFileName);
if(!f.exists) {
log("Input 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 "";
}
log("inpt: " + 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 {
log("cwd: " + ev.currentDirectory.nativePath);
return ev.currentDirectory.nativePath;
}
return "";
}
}
private function log(message:String="", add_new_line:Boolean=true):void {
outfield.appendText((add_new_line ? "\n" : "") + message);
}
//Invoke handler called when started
private function onInvoke(ev:InvokeEvent):void {
inputFilePath = getInputFile(ev);
outputDirPath = getOutputDir(ev);
log("Input file: " + inputFilePath);
log("Output directory: " + outputDirPath);
loadSwf();
}
private function exit(code:int=0):void {
log("Exit: " + code);
NativeApplication.nativeApplication.exit(code);
}
}
}
|
Align interface.
|
Align interface.
|
ActionScript
|
mit
|
mdahlstrand/swf2png
|
a75c4e05fdad7bb534a996b5f197fcfcd713472b
|
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.utils.Version;
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 flash.display.DisplayObject;
import flash.events.Event;
import flash.events.EventDispatcher;
/* force import for type in the includes */
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: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.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"
}
}
|
replace class Version by core.version
|
replace class Version by core.version
|
ActionScript
|
apache-2.0
|
jeremy-wischusen/gaforflash,soumavachakraborty/gaforflash,dli-iclinic/gaforflash,Miyaru/gaforflash,soumavachakraborty/gaforflash,Vigmar/gaforflash,DimaBaliakin/gaforflash,drflash/gaforflash,jisobkim/gaforflash,Miyaru/gaforflash,Vigmar/gaforflash,mrthuanvn/gaforflash,jeremy-wischusen/gaforflash,mrthuanvn/gaforflash,DimaBaliakin/gaforflash,drflash/gaforflash,dli-iclinic/gaforflash,jisobkim/gaforflash
|
822816d2a60243d5afa426e42e691a9fa39ce91f
|
runtime/src/main/as/flump/xfl/XflKeyframe.as
|
runtime/src/main/as/flump/xfl/XflKeyframe.as
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.xfl {
import flash.geom.Matrix;
import flump.MatrixUtil;
public class XflKeyframe extends XflComponent
{
use namespace xflns;
public var index :int;
/** The length of this keyframe in frames. */
public var duration :Number;
/** The name of the libraryItem in this keyframe, or null if there is no libraryItem. */
public var libraryItem :String;
/** The name of the symbol in this keyframe, or null if there is no symbol. */
public var symbol :String;
/** The label on this keyframe, or null if there isn't one */
public var label :String;
/** Exploded values from matrix */
public var x :Number = 0.0, y :Number = 0.0, scaleX :Number = 1.0, scaleY :Number = 1.0,
rotation :Number = 0.0;
/** Transformation point */
public var pivotX :Number = 0.0, pivotY :Number = 0.0;
public function XflKeyframe (baseLocation :String, xml :XML, errors :Vector.<ParseError>,
flipbook :Boolean) {
const converter :XmlConverter = new XmlConverter(xml);
index = converter.getIntAttr("index");
super(baseLocation + ":" + index, errors);
duration = converter.getNumberAttr("duration", 1);
label = converter.getStringAttr("name", null);
if (flipbook) return;
var symbolXml :XML;
for each (var frameEl :XML in xml.elements.elements()) {
if (frameEl.name().localName == "DOMSymbolInstance") {
if (symbolXml != null) {
addError(ParseError.CRIT, "There can be only one symbol instance at " +
"a time in a keyframe.");
} else symbolXml = frameEl;
} else {
addError(ParseError.CRIT, "Non-symbols may not be in exported movie " +
"layers");
}
}
if (symbolXml == null) return; // Purely labelled frame
libraryItem = new XmlConverter(symbolXml).getStringAttr("libraryItemName");
const matrixXml :XML = symbolXml.matrix.Matrix[0];
const matrixConverter :XmlConverter =
matrixXml == null ? null : new XmlConverter(matrixXml);
function m (name :String, def :Number) :Number {
return matrixConverter == null ? def : matrixConverter.getNumberAttr(name, def);
}
var matrix :Matrix =
new Matrix(m("a", 1), m("b", 0), m("c", 0), m("d", 1), m("tx", 0), m("ty", 0));
// handle "motionTweenRotate" (in this case, the rotation is not embedded in the matrix)
if (converter.hasAttr("motionTweenRotateTimes") && duration > 1) {
rotation = converter.getNumberAttr("motionTweenRotateTimes") * Math.PI * 2;
if (converter.getStringAttr("motionTweenRotate") == "clockwise") {
rotation *= -1;
}
MatrixUtil.setRotation(matrix, rotation);
} else {
rotation = MatrixUtil.rotation(matrix);
}
x = matrix.tx;
y = matrix.ty;
scaleX = MatrixUtil.scaleX(matrix);
scaleY = MatrixUtil.scaleY(matrix);
var pivotXml :XML = symbolXml.transformationPoint.Point[0];
if (pivotXml != null) {
var pivotConverter :XmlConverter = new XmlConverter(pivotXml);
pivotX = pivotConverter.getNumberAttr("x", 0);
pivotY = pivotConverter.getNumberAttr("y", 0);
x += pivotX;
y += pivotY;
}
}
public function checkSymbols (lib :XflLibrary) :void {
if (symbol != null && !lib.hasSymbol(symbol)) {
addError(ParseError.CRIT, "Symbol '" + symbol + "' not exported");
}
}
public function toJSON (_:*) :Object {
var json :Object = {
index: index,
duration: duration
};
if (libraryItem != null) {
json.ref = symbol;
json.t = [ x, y, scaleX, scaleY, rotation ];
// json.alpha = 1;
}
if (label != null) {
json.label = label;
}
return json;
}
}
}
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.xfl {
import flash.geom.Matrix;
import flump.MatrixUtil;
public class XflKeyframe extends XflComponent
{
use namespace xflns;
public var index :int;
/** The length of this keyframe in frames. */
public var duration :Number;
/** The name of the libraryItem in this keyframe, or null if there is no libraryItem. */
public var libraryItem :String;
/** The name of the symbol in this keyframe, or null if there is no symbol. */
public var symbol :String;
/** The label on this keyframe, or null if there isn't one */
public var label :String;
/** Exploded values from matrix */
public var x :Number = 0.0, y :Number = 0.0, scaleX :Number = 1.0, scaleY :Number = 1.0,
rotation :Number = 0.0;
/** Transformation point */
public var pivotX :Number = 0.0, pivotY :Number = 0.0;
public function XflKeyframe (baseLocation :String, xml :XML, errors :Vector.<ParseError>,
flipbook :Boolean) {
const converter :XmlConverter = new XmlConverter(xml);
index = converter.getIntAttr("index");
super(baseLocation + ":" + index, errors);
duration = converter.getNumberAttr("duration", 1);
label = converter.getStringAttr("name", null);
if (flipbook) return;
var symbolXml :XML;
for each (var frameEl :XML in xml.elements.elements()) {
if (frameEl.name().localName == "DOMSymbolInstance") {
if (symbolXml != null) {
addError(ParseError.CRIT, "There can be only one symbol instance at " +
"a time in a keyframe.");
} else symbolXml = frameEl;
} else {
addError(ParseError.CRIT, "Non-symbols may not be in exported movie " +
"layers");
}
}
if (symbolXml == null) return; // Purely labelled frame
libraryItem = new XmlConverter(symbolXml).getStringAttr("libraryItemName");
const matrixXml :XML = symbolXml.matrix.Matrix[0];
const matrixConverter :XmlConverter =
matrixXml == null ? null : new XmlConverter(matrixXml);
function m (name :String, def :Number) :Number {
return matrixConverter == null ? def : matrixConverter.getNumberAttr(name, def);
}
var matrix :Matrix =
new Matrix(m("a", 1), m("b", 0), m("c", 0), m("d", 1), m("tx", 0), m("ty", 0));
// handle "motionTweenRotate" (in this case, the rotation is not embedded in the matrix)
if (converter.hasAttr("motionTweenRotateTimes") && duration > 1) {
rotation = converter.getNumberAttr("motionTweenRotateTimes") * Math.PI * 2;
if (converter.getStringAttr("motionTweenRotate") == "clockwise") {
rotation *= -1;
}
MatrixUtil.setRotation(matrix, rotation);
} else {
rotation = MatrixUtil.rotation(matrix);
}
x = matrix.tx;
y = matrix.ty;
scaleX = MatrixUtil.scaleX(matrix);
scaleY = MatrixUtil.scaleY(matrix);
var pivotXml :XML = symbolXml.transformationPoint.Point[0];
if (pivotXml != null) {
var pivotConverter :XmlConverter = new XmlConverter(pivotXml);
pivotX = pivotConverter.getNumberAttr("x", 0);
pivotY = pivotConverter.getNumberAttr("y", 0);
x += pivotX;
y += pivotY;
}
}
public function checkSymbols (lib :XflLibrary) :void {
if (symbol != null && !lib.hasSymbol(symbol)) {
addError(ParseError.CRIT, "Symbol '" + symbol + "' not exported");
}
}
public function toJSON (_:*) :Object {
var json :Object = {
index: index,
duration: duration
};
if (symbol != null) {
json.ref = symbol;
json.t = [ x, y, scaleX, scaleY, rotation ];
json.pivot = [ pivotX, pivotY ];
// json.alpha = 1;
}
if (label != null) {
json.label = label;
}
return json;
}
}
}
|
Include the pivot point in the JSON export.
|
Include the pivot point in the JSON export.
|
ActionScript
|
mit
|
mathieuanthoine/flump,funkypandagame/flump,tconkling/flump,mathieuanthoine/flump,mathieuanthoine/flump,tconkling/flump,funkypandagame/flump
|
981bc9370a1dd0c7c8065883e5184269b54ea9f6
|
snowplow-as3-tracker/src/com/snowplowanalytics/snowplow/tracker/emitter/Emitter.as
|
snowplow-as3-tracker/src/com/snowplowanalytics/snowplow/tracker/emitter/Emitter.as
|
/*
* Copyright (c) 2015 Snowplow Analytics Ltd. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package com.snowplowanalytics.snowplow.tracker.emitter
{
import com.adobe.net.URI;
import com.snowplowanalytics.snowplow.tracker.Constants;
import com.snowplowanalytics.snowplow.tracker.Util;
import com.snowplowanalytics.snowplow.tracker.event.EmitterEvent;
import com.snowplowanalytics.snowplow.tracker.payload.IPayload;
import com.snowplowanalytics.snowplow.tracker.payload.SchemaPayload;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
public class Emitter extends EventDispatcher
{
private var _uri:URI;
private var _buffer:Array = [];
protected var bufferSize:int = BufferOption.DEFAULT;
protected var httpMethod:String = URLRequestMethod.GET;
/**
* Create an Emitter instance with a collector URL and HttpMethod to send requests.
* @param URI The collector URL. Don't include "http://" - this is done automatically.
* @param httpMethod The HTTP request method. If GET, <code>BufferOption</code> is set to <code>Instant</code>.
* @param protocol The protocol for the call. Either http or https. Defaults to https.
*/
public function Emitter(uri:String, httpMethod:String = URLRequestMethod.GET, protocol:String = "https") {
if (httpMethod == URLRequestMethod.GET) {
_uri = new URI(protocol + "://" + uri + "/i");
} else { // POST
_uri = new URI(protocol + "://" + uri + "/" + Constants.PROTOCOL_VENDOR + "/" + Constants.PROTOCOL_VERSION);
}
this.httpMethod = httpMethod;
}
/**
* Sets whether the buffer should send events instantly or after the buffer has reached
* it's limit. By default, this is set to BufferOption Default.
* @param option Set the BufferOption enum to Instant send events upon creation.
*/
public function setBufferSize(option:int):void {
this.bufferSize = option;
}
/**
* Add event payloads to the emitter's buffer
* @param payload Payload to be added
*/
public function addToBuffer(payload:IPayload):void {
_buffer.push(payload);
if (_buffer.length == bufferSize)
flushBuffer();
}
/**
* Sends all events in the buffer to the collector.
*/
public function checkBufferComplete(successCount:int, totalCount:int, totalPayloads:int, unsentPayloads:Array):void {
if (totalCount == totalPayloads)
{
if (unsentPayloads.length == 0)
{
dispatchEvent(new EmitterEvent(EmitterEvent.SUCCESS, successCount));
}
else
{
dispatchEvent(new EmitterEvent(EmitterEvent.FAILURE, successCount, unsentPayloads, "Not all items in buffer were sent"));
}
}
}
/**
* Sends all events in the buffer to the collector.
*/
public function flushBuffer():void {
if (_buffer.length == 0) {
trace("Buffer is empty, exiting flush operation.");
return;
}
if (httpMethod == URLRequestMethod.GET) {
var successCount:int = 0;
var totalCount:int = 0;
var totalPayloads:int = _buffer.length;
var unsentPayloads:Array = [];
for each (var getPayload:IPayload in _buffer) {
sendGetData(getPayload,
function onGetSuccess (data:*):void {
successCount++;
totalCount++;
checkBufferComplete(successCount, totalCount, totalPayloads, unsentPayloads);
},
function onGetError ():void {
totalCount++;
unsentPayloads.push(payload);
checkBufferComplete(successCount, totalCount, totalPayloads, unsentPayloads);
}
);
}
} else if (httpMethod == URLRequestMethod.POST) {
var unsentPayload:Array = [];
var postPayload:SchemaPayload = new SchemaPayload();
postPayload.setSchema(Constants.SCHEMA_PAYLOAD_DATA);
var eventMaps:Array = [];
for each (var payload:IPayload in _buffer) {
eventMaps.push(payload.getMap());
}
postPayload.setData(eventMaps);
sendPostData(postPayload,
function onPostSuccess (data:*):void
{
dispatchEvent(new EmitterEvent(EmitterEvent.SUCCESS, _buffer.length));
},
function onPostError (event:Event):void
{
unsentPayload.push(postPayload);
dispatchEvent(new EmitterEvent(EmitterEvent.FAILURE, 0, unsentPayloads, event.toString()));
}
);
}
// Empties current buffer
Util.clearArray(_buffer);
}
protected function sendPostData(payload:IPayload, successCallback:Function, errorCallback:Function):void
{
Util.getResponse(_uri.toString(),
successCallback,
errorCallback,
URLRequestMethod.POST,
payload.toString());
}
protected function sendGetData(payload:IPayload, successCallback:Function, errorCallback:Function):void
{
var hashMap:Object = payload.getMap();
_uri.setQueryByMap(hashMap);
Util.getResponse(_uri.toString(),
successCallback,
errorCallback);
}
}
}
|
/*
* Copyright (c) 2015 Snowplow Analytics Ltd. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package com.snowplowanalytics.snowplow.tracker.emitter
{
import com.adobe.net.URI;
import com.snowplowanalytics.snowplow.tracker.Constants;
import com.snowplowanalytics.snowplow.tracker.Util;
import com.snowplowanalytics.snowplow.tracker.event.EmitterEvent;
import com.snowplowanalytics.snowplow.tracker.payload.IPayload;
import com.snowplowanalytics.snowplow.tracker.payload.SchemaPayload;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
public class Emitter extends EventDispatcher
{
private var _uri:URI;
private var _buffer:Array = [];
protected var bufferSize:int = BufferOption.DEFAULT;
protected var httpMethod:String = URLRequestMethod.GET;
/**
* Create an Emitter instance with a collector URL and HttpMethod to send requests.
* @param URI The collector URL. Don't include "http://" - this is done automatically.
* @param httpMethod The HTTP request method. If GET, <code>BufferOption</code> is set to <code>Instant</code>.
* @param protocol The protocol for the call. Either http or https. Defaults to http.
*/
public function Emitter(uri:String, httpMethod:String = URLRequestMethod.GET, protocol:String = "http") {
if (httpMethod == URLRequestMethod.GET) {
_uri = new URI(protocol + "://" + uri + "/i");
} else { // POST
_uri = new URI(protocol + "://" + uri + "/" + Constants.PROTOCOL_VENDOR + "/" + Constants.PROTOCOL_VERSION);
}
this.httpMethod = httpMethod;
}
/**
* Sets whether the buffer should send events instantly or after the buffer has reached
* it's limit. By default, this is set to BufferOption Default.
* @param option Set the BufferOption enum to Instant send events upon creation.
*/
public function setBufferSize(option:int):void {
this.bufferSize = option;
}
/**
* Add event payloads to the emitter's buffer
* @param payload Payload to be added
*/
public function addToBuffer(payload:IPayload):void {
_buffer.push(payload);
if (_buffer.length == bufferSize)
flushBuffer();
}
/**
* Sends all events in the buffer to the collector.
*/
public function checkBufferComplete(successCount:int, totalCount:int, totalPayloads:int, unsentPayloads:Array):void {
if (totalCount == totalPayloads)
{
if (unsentPayloads.length == 0)
{
dispatchEvent(new EmitterEvent(EmitterEvent.SUCCESS, successCount));
}
else
{
dispatchEvent(new EmitterEvent(EmitterEvent.FAILURE, successCount, unsentPayloads, "Not all items in buffer were sent"));
}
}
}
/**
* Sends all events in the buffer to the collector.
*/
public function flushBuffer():void {
if (_buffer.length == 0) {
trace("Buffer is empty, exiting flush operation.");
return;
}
if (httpMethod == URLRequestMethod.GET) {
var successCount:int = 0;
var totalCount:int = 0;
var totalPayloads:int = _buffer.length;
var unsentPayloads:Array = [];
for each (var getPayload:IPayload in _buffer) {
sendGetData(getPayload,
function onGetSuccess (data:*):void {
successCount++;
totalCount++;
checkBufferComplete(successCount, totalCount, totalPayloads, unsentPayloads);
},
function onGetError ():void {
totalCount++;
unsentPayloads.push(payload);
checkBufferComplete(successCount, totalCount, totalPayloads, unsentPayloads);
}
);
}
} else if (httpMethod == URLRequestMethod.POST) {
var unsentPayload:Array = [];
var postPayload:SchemaPayload = new SchemaPayload();
postPayload.setSchema(Constants.SCHEMA_PAYLOAD_DATA);
var eventMaps:Array = [];
for each (var payload:IPayload in _buffer) {
eventMaps.push(payload.getMap());
}
postPayload.setData(eventMaps);
sendPostData(postPayload,
function onPostSuccess (data:*):void
{
dispatchEvent(new EmitterEvent(EmitterEvent.SUCCESS, _buffer.length));
},
function onPostError (event:Event):void
{
unsentPayload.push(postPayload);
dispatchEvent(new EmitterEvent(EmitterEvent.FAILURE, 0, unsentPayloads, event.toString()));
}
);
}
// Empties current buffer
Util.clearArray(_buffer);
}
protected function sendPostData(payload:IPayload, successCallback:Function, errorCallback:Function):void
{
Util.getResponse(_uri.toString(),
successCallback,
errorCallback,
URLRequestMethod.POST,
payload.toString());
}
protected function sendGetData(payload:IPayload, successCallback:Function, errorCallback:Function):void
{
var hashMap:Object = payload.getMap();
_uri.setQueryByMap(hashMap);
Util.getResponse(_uri.toString(),
successCallback,
errorCallback);
}
}
}
|
change Emitter default protocol back to HTTP
|
change Emitter default protocol back to HTTP
|
ActionScript
|
apache-2.0
|
snowplow/snowplow-actionscript3-tracker,snowplow/snowplow-actionscript3-tracker,snowplow/snowplow-actionscript3-tracker
|
06ccaabe86edbc093479b6a481f1985a7a775b70
|
src/com/mangui/HLS/muxing/TS.as
|
src/com/mangui/HLS/muxing/TS.as
|
package com.mangui.HLS.muxing {
import com.mangui.HLS.muxing.*;
import com.mangui.HLS.utils.Log;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.TimerEvent;
import flash.utils.ByteArray;
import flash.utils.Timer;
/** Representation of an MPEG transport stream. **/
public class TS extends EventDispatcher {
/** TS Sync byte. **/
public static const SYNCBYTE:uint = 0x47;
/** TS Packet size in byte. **/
public static const PACKETSIZE:uint = 188;
/** Identifier for read complete event **/
public static const READCOMPLETE:String = "readComplete"
private static const COUNT:uint = 5000;
/** Packet ID of the AAC audio stream. **/
private var _aacId:Number = 257;
/** List with audio frames. **/
public var audioTags:Vector.<Tag> = new Vector.<Tag>();
/** List of packetized elementary streams with AAC. **/
private var _audioPES:Vector.<PES> = new Vector.<PES>();
/** Packet ID of the video stream. **/
private var _avcId:Number = 256;
/** PES packet that contains the first keyframe. **/
private var _firstKey:Number = -1;
/** Packet ID of the MP3 audio stream. **/
private var _mp3Id:Number = -1;
/** Packet ID of the PAT (is always 0). **/
private var _patId:Number = 0;
/** Packet ID of the Program Map Table. **/
private var _pmtId:Number = -1;
/** List with video frames. **/
/** Packet ID of the SDT (is always 17). **/
private var _sdtId:Number = 17;
public var videoTags:Vector.<Tag> = new Vector.<Tag>();
/** List of packetized elementary streams with AVC. **/
private var _videoPES:Vector.<PES> = new Vector.<PES>();
/** Timer for reading packets **/
public var _timer:Timer;
/** Byte data to be read **/
private var _data:ByteArray;
/** Transmux the M2TS file into an FLV file. **/
public function TS(data:ByteArray) {
// Extract the elementary streams.
_data = data;
_timer = new Timer(0,0);
_timer.addEventListener(TimerEvent.TIMER, _readData);
};
/** Read a small chunk of packets each time to avoid blocking **/
private function _readData(e:Event):void {
var i:uint = 0;
while(_data.bytesAvailable && i < COUNT) {
_readPacket();
i++;
}
if (!_data.bytesAvailable) {
_timer.stop();
_extractFrames();
}
}
/** start the timer in order to start reading data **/
public function startReading():void {;
_timer.start();
}
/** setup the video and audio tag vectors from the read data **/
private function _extractFrames():void {
if (_videoPES.length == 0 && _audioPES.length == 0 ) {
throw new Error("No AAC audio and no AVC video stream found.");
}
// Extract the ADTS or MPEG audio frames.
if(_aacId > 0) {
_readADTS();
} else {
_readMPEG();
}
// Extract the NALU video frames.
_readNALU();
dispatchEvent(new Event(TS.READCOMPLETE));
}
/** Get audio configuration data. **/
public function getADIF():ByteArray {
if(_aacId > 0) {
return AAC.getADIF(_audioPES[0].data,_audioPES[0].payload);
} else {
return new ByteArray();
}
};
/** Get video configuration data. **/
public function getAVCC():ByteArray {
if(_firstKey == -1) {
return new ByteArray();
}
return AVC.getAVCC(_videoPES[_firstKey].data,_videoPES[_firstKey].payload);
};
/** Read ADTS frames from audio PES streams. **/
private function _readADTS():void {
var frames:Array;
var overflow:Number = 0;
var tag:Tag;
var stamp:Number;
for(var i:Number=0; i<_audioPES.length; i++) {
// Parse the PES headers.
_audioPES[i].parse();
// Correct for Segmenter's "optimize", which cuts frames in half.
if(overflow > 0) {
_audioPES[i-1].data.position = _audioPES[i-1].data.length;
_audioPES[i-1].data.writeBytes(_audioPES[i].data,_audioPES[i].payload,overflow);
_audioPES[i].payload += overflow;
}
// Store ADTS frames in array.
frames = AAC.getFrames(_audioPES[i].data,_audioPES[i].payload);
for(var j:Number=0; j< frames.length; j++) {
// Increment the timestamp of subsequent frames.
stamp = Math.round(_audioPES[i].pts + j * 1024 * 1000 / frames[j].rate);
tag = new Tag(Tag.AAC_RAW, stamp, stamp, false);
if(i == _audioPES.length-1 && j == frames.length - 1) {
tag.push(_audioPES[i].data, frames[j].start, _audioPES[i].data.length - frames[j].start);
} else {
tag.push(_audioPES[i].data, frames[j].start, frames[j].length);
}
audioTags.push(tag);
}
// Correct for Segmenter's "optimize", which cuts frames in half.
overflow = frames[frames.length-1].start +
frames[frames.length-1].length - _audioPES[i].data.length;
}
};
/** Read MPEG data from audio PES streams. **/
private function _readMPEG():void {
var tag:Tag;
for(var i:Number=0; i<_audioPES.length; i++) {
_audioPES[i].parse();
tag = new Tag(Tag.MP3_RAW, _audioPES[i].pts,_audioPES[i].dts, false);
tag.push(_audioPES[i].data, _audioPES[i].payload, _audioPES[i].data.length-_audioPES[i].payload);
audioTags.push(tag);
}
};
/** Read NALU frames from video PES streams. **/
private function _readNALU():void {
var overflow:Number;
var units:Array;
var last:Number;
for(var i:Number=0; i<_videoPES.length; i++) {
// Parse the PES headers and NAL units.
try {
_videoPES[i].parse();
} catch (error:Error) {
Log.txt(error.message);
continue;
}
units = AVC.getNALU(_videoPES[i].data,_videoPES[i].payload);
// If there's no NAL unit, push all data in the previous tag.
if(!units.length) {
videoTags[videoTags.length-1].push(_videoPES[i].data, _videoPES[i].payload,
_videoPES[i].data.length - _videoPES[i].payload);
continue;
}
// If NAL units are offset, push preceding data into the previous tag.
overflow = units[0].start - units[0].header - _videoPES[i].payload;
if(overflow) {
videoTags[videoTags.length-1].push(_videoPES[i].data,_videoPES[i].payload,overflow);
}
videoTags.push(new Tag(Tag.AVC_NALU,_videoPES[i].pts,_videoPES[i].dts,false));
// Only push NAL units 1 to 5 into tag.
for(var j:Number = 0; j < units.length; j++) {
if (units[j].type < 6) {
videoTags[videoTags.length-1].push(_videoPES[i].data,units[j].start,units[j].length);
// Unit type 5 indicates a keyframe.
if(units[j].type == 5) {
videoTags[videoTags.length-1].keyframe = true;
if(_firstKey == -1) {
_firstKey = i;
}
}
}
}
}
};
/** Read TS packet. **/
private function _readPacket():void {
// Each packet is 188 bytes.
var todo:uint = TS.PACKETSIZE;
// Sync byte.
if(_data.readByte() != TS.SYNCBYTE) {
throw new Error("Could not parse TS file: sync byte not found.");
}
todo--;
// Payload unit start indicator.
var stt:uint = (_data.readUnsignedByte() & 64) >> 6;
_data.position--;
// Packet ID (last 13 bits of UI16).
var pid:uint = _data.readUnsignedShort() & 8191;
// Check for adaptation field.
todo -=2;
var atf:uint = (_data.readByte() & 48) >> 4;
todo --;
// Read adaptation field if available.
if(atf > 1) {
// Length of adaptation field.
var len:uint = _data.readUnsignedByte();
todo--;
// Random access indicator (keyframe).
//var rai:uint = data.readUnsignedByte() & 64;
_data.position += len;
todo -= len;
// Return if there's only adaptation field.
if(atf == 2 || len == 183) {
_data.position += todo;
return;
}
}
var pes:ByteArray = new ByteArray();
// Parse the PES, split by Packet ID.
switch (pid) {
case _patId:
todo -= _readPAT();
break;
case _pmtId:
todo -= _readPMT();
break;
case _aacId:
case _mp3Id:
if(stt) {
pes.writeBytes(_data,_data.position,todo);
_audioPES.push(new PES(pes,true));
} else if (_audioPES.length) {
_audioPES[_audioPES.length-1].data.writeBytes(_data,_data.position,todo);
} else {
Log.txt("Discarding TS audio packet with id "+pid);
}
break;
case _avcId:
if(stt) {
pes.writeBytes(_data,_data.position,todo);
_videoPES.push(new PES(pes,false));
} else if (_videoPES.length) {
_videoPES[_videoPES.length-1].data.writeBytes(_data,_data.position,todo);
} else {
Log.txt("Discarding TS video packet with id "+pid);
}
break;
case _sdtId:
break;
default:
// Ignored other packet IDs
Log.txt("Discarding unassignable TS packets with id "+pid);
break;
}
// Jump to the next packet.
_data.position += todo;
};
/** Read the Program Association Table. **/
private function _readPAT():Number {
// Check the section length for a single PMT.
_data.position += 3;
if(_data.readUnsignedByte() > 13) {
throw new Error("Multiple PMT/NIT entries are not supported.");
}
// Grab the PMT ID.
_data.position += 7;
_pmtId = _data.readUnsignedShort() & 8191;
return 13;
};
/** Read the Program Map Table. **/
private function _readPMT():Number {
// Check the section length for a single PMT.
_data.position += 3;
var len:uint = _data.readByte();
var read:uint = 13;
_data.position += 8;
var pil:Number = _data.readByte();
_data.position += pil;
read += pil;
// Loop through the streams in the PMT.
while(read < len) {
var typ:uint = _data.readByte();
var sid:uint = _data.readUnsignedShort() & 8191;
if(typ == 0x0F) {
_aacId = sid;
} else if (typ == 0x1B) {
_avcId = sid;
} else if (typ == 0x03) {
_mp3Id = sid;
}
// Possible section length.
_data.position++;
var sel:uint = _data.readByte() & 0x0F;
_data.position += sel;
read += sel + 5;
}
return len;
};
}
}
|
package com.mangui.HLS.muxing {
import com.mangui.HLS.muxing.*;
import com.mangui.HLS.utils.Log;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.TimerEvent;
import flash.utils.ByteArray;
import flash.utils.Timer;
/** Representation of an MPEG transport stream. **/
public class TS extends EventDispatcher {
/** TS Sync byte. **/
public static const SYNCBYTE:uint = 0x47;
/** TS Packet size in byte. **/
public static const PACKETSIZE:uint = 188;
/** Identifier for read complete event **/
public static const READCOMPLETE:String = "readComplete"
private static const COUNT:uint = 5000;
/** Packet ID of the AAC audio stream. **/
private var _aacId:Number = -1;
/** List with audio frames. **/
public var audioTags:Vector.<Tag> = new Vector.<Tag>();
/** List of packetized elementary streams with AAC. **/
private var _audioPES:Vector.<PES> = new Vector.<PES>();
/** Packet ID of the video stream. **/
private var _avcId:Number = -1;
/** PES packet that contains the first keyframe. **/
private var _firstKey:Number = -1;
/** Packet ID of the MP3 audio stream. **/
private var _mp3Id:Number = -1;
/** Packet ID of the PAT (is always 0). **/
private var _patId:Number = 0;
/** Packet ID of the Program Map Table. **/
private var _pmtId:Number = -1;
/** List with video frames. **/
/** Packet ID of the SDT (is always 17). **/
private var _sdtId:Number = 17;
public var videoTags:Vector.<Tag> = new Vector.<Tag>();
/** List of packetized elementary streams with AVC. **/
private var _videoPES:Vector.<PES> = new Vector.<PES>();
/** Timer for reading packets **/
public var _timer:Timer;
/** Byte data to be read **/
private var _data:ByteArray;
/** Transmux the M2TS file into an FLV file. **/
public function TS(data:ByteArray) {
// Extract the elementary streams.
_data = data;
_timer = new Timer(0,0);
_timer.addEventListener(TimerEvent.TIMER, _readData);
};
/** Read a small chunk of packets each time to avoid blocking **/
private function _readData(e:Event):void {
var i:uint = 0;
while(_data.bytesAvailable && i < COUNT) {
_readPacket();
i++;
}
if (!_data.bytesAvailable) {
_timer.stop();
_extractFrames();
}
}
/** start the timer in order to start reading data **/
public function startReading():void {;
_timer.start();
}
/** setup the video and audio tag vectors from the read data **/
private function _extractFrames():void {
if (_videoPES.length == 0 && _audioPES.length == 0 ) {
throw new Error("No AAC audio and no AVC video stream found.");
}
// Extract the ADTS or MPEG audio frames.
if(_aacId > 0) {
_readADTS();
} else {
_readMPEG();
}
// Extract the NALU video frames.
_readNALU();
dispatchEvent(new Event(TS.READCOMPLETE));
}
/** Get audio configuration data. **/
public function getADIF():ByteArray {
if(_aacId > 0) {
return AAC.getADIF(_audioPES[0].data,_audioPES[0].payload);
} else {
return new ByteArray();
}
};
/** Get video configuration data. **/
public function getAVCC():ByteArray {
if(_firstKey == -1) {
return new ByteArray();
}
return AVC.getAVCC(_videoPES[_firstKey].data,_videoPES[_firstKey].payload);
};
/** Read ADTS frames from audio PES streams. **/
private function _readADTS():void {
var frames:Array;
var overflow:Number = 0;
var tag:Tag;
var stamp:Number;
for(var i:Number=0; i<_audioPES.length; i++) {
// Parse the PES headers.
_audioPES[i].parse();
// Correct for Segmenter's "optimize", which cuts frames in half.
if(overflow > 0) {
_audioPES[i-1].data.position = _audioPES[i-1].data.length;
_audioPES[i-1].data.writeBytes(_audioPES[i].data,_audioPES[i].payload,overflow);
_audioPES[i].payload += overflow;
}
// Store ADTS frames in array.
frames = AAC.getFrames(_audioPES[i].data,_audioPES[i].payload);
for(var j:Number=0; j< frames.length; j++) {
// Increment the timestamp of subsequent frames.
stamp = Math.round(_audioPES[i].pts + j * 1024 * 1000 / frames[j].rate);
tag = new Tag(Tag.AAC_RAW, stamp, stamp, false);
if(i == _audioPES.length-1 && j == frames.length - 1) {
tag.push(_audioPES[i].data, frames[j].start, _audioPES[i].data.length - frames[j].start);
} else {
tag.push(_audioPES[i].data, frames[j].start, frames[j].length);
}
audioTags.push(tag);
}
// Correct for Segmenter's "optimize", which cuts frames in half.
overflow = frames[frames.length-1].start +
frames[frames.length-1].length - _audioPES[i].data.length;
}
};
/** Read MPEG data from audio PES streams. **/
private function _readMPEG():void {
var tag:Tag;
for(var i:Number=0; i<_audioPES.length; i++) {
_audioPES[i].parse();
tag = new Tag(Tag.MP3_RAW, _audioPES[i].pts,_audioPES[i].dts, false);
tag.push(_audioPES[i].data, _audioPES[i].payload, _audioPES[i].data.length-_audioPES[i].payload);
audioTags.push(tag);
}
};
/** Read NALU frames from video PES streams. **/
private function _readNALU():void {
var overflow:Number;
var units:Array;
var last:Number;
for(var i:Number=0; i<_videoPES.length; i++) {
// Parse the PES headers and NAL units.
try {
_videoPES[i].parse();
} catch (error:Error) {
Log.txt(error.message);
continue;
}
units = AVC.getNALU(_videoPES[i].data,_videoPES[i].payload);
// If there's no NAL unit, push all data in the previous tag.
if(!units.length) {
videoTags[videoTags.length-1].push(_videoPES[i].data, _videoPES[i].payload,
_videoPES[i].data.length - _videoPES[i].payload);
continue;
}
// If NAL units are offset, push preceding data into the previous tag.
overflow = units[0].start - units[0].header - _videoPES[i].payload;
if(overflow) {
videoTags[videoTags.length-1].push(_videoPES[i].data,_videoPES[i].payload,overflow);
}
videoTags.push(new Tag(Tag.AVC_NALU,_videoPES[i].pts,_videoPES[i].dts,false));
// Only push NAL units 1 to 5 into tag.
for(var j:Number = 0; j < units.length; j++) {
if (units[j].type < 6) {
videoTags[videoTags.length-1].push(_videoPES[i].data,units[j].start,units[j].length);
// Unit type 5 indicates a keyframe.
if(units[j].type == 5) {
videoTags[videoTags.length-1].keyframe = true;
if(_firstKey == -1) {
_firstKey = i;
}
}
}
}
}
};
/** Read TS packet. **/
private function _readPacket():void {
// Each packet is 188 bytes.
var todo:uint = TS.PACKETSIZE;
// Sync byte.
if(_data.readByte() != TS.SYNCBYTE) {
throw new Error("Could not parse TS file: sync byte not found.");
}
todo--;
// Payload unit start indicator.
var stt:uint = (_data.readUnsignedByte() & 64) >> 6;
_data.position--;
// Packet ID (last 13 bits of UI16).
var pid:uint = _data.readUnsignedShort() & 8191;
// Check for adaptation field.
todo -=2;
var atf:uint = (_data.readByte() & 48) >> 4;
todo --;
// Read adaptation field if available.
if(atf > 1) {
// Length of adaptation field.
var len:uint = _data.readUnsignedByte();
todo--;
// Random access indicator (keyframe).
//var rai:uint = data.readUnsignedByte() & 64;
_data.position += len;
todo -= len;
// Return if there's only adaptation field.
if(atf == 2 || len == 183) {
_data.position += todo;
return;
}
}
var pes:ByteArray = new ByteArray();
// Parse the PES, split by Packet ID.
switch (pid) {
case _patId:
todo -= _readPAT();
break;
case _pmtId:
todo -= _readPMT();
break;
case _aacId:
case _mp3Id:
if(stt) {
pes.writeBytes(_data,_data.position,todo);
_audioPES.push(new PES(pes,true));
} else if (_audioPES.length) {
_audioPES[_audioPES.length-1].data.writeBytes(_data,_data.position,todo);
} else {
Log.txt("Discarding TS audio packet with id "+pid);
}
break;
case _avcId:
if(stt) {
pes.writeBytes(_data,_data.position,todo);
_videoPES.push(new PES(pes,false));
} else if (_videoPES.length) {
_videoPES[_videoPES.length-1].data.writeBytes(_data,_data.position,todo);
} else {
Log.txt("Discarding TS video packet with id "+pid);
}
break;
case _sdtId:
break;
default:
// Ignored other packet IDs
Log.txt("Discarding unassignable TS packets with id "+pid);
break;
}
// Jump to the next packet.
_data.position += todo;
};
/** Read the Program Association Table. **/
private function _readPAT():Number {
// Check the section length for a single PMT.
_data.position += 3;
if(_data.readUnsignedByte() > 13) {
throw new Error("Multiple PMT/NIT entries are not supported.");
}
// Grab the PMT ID.
_data.position += 7;
_pmtId = _data.readUnsignedShort() & 8191;
return 13;
};
/** Read the Program Map Table. **/
private function _readPMT():Number {
// Check the section length for a single PMT.
_data.position += 3;
var len:uint = _data.readByte();
var read:uint = 13;
_data.position += 8;
var pil:Number = _data.readByte();
_data.position += pil;
read += pil;
// Loop through the streams in the PMT.
while(read < len) {
var typ:uint = _data.readByte();
var sid:uint = _data.readUnsignedShort() & 8191;
if(typ == 0x0F) {
_aacId = sid;
} else if (typ == 0x1B) {
_avcId = sid;
} else if (typ == 0x03) {
_mp3Id = sid;
}
// Possible section length.
_data.position++;
var sel:uint = _data.readByte() & 0x0F;
_data.position += sel;
read += sel + 5;
}
return len;
};
}
}
|
fix initial pid value, should be undefined (-1)
|
fix initial pid value, should be undefined (-1)
|
ActionScript
|
mpl-2.0
|
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
|
ec79768cc82658b8cf7586c3c61f92ebca313ae3
|
src/aerys/minko/type/enum/Blending.as
|
src/aerys/minko/type/enum/Blending.as
|
package aerys.minko.type.enum
{
import aerys.minko.ns.minko_render;
import flash.display3D.Context3DBlendFactor;
/**
* The Blending class is an enumeration of the most common values possible
* for the Shader.blending property and the BlendingShaderPart.blend() method.
*
* @author Jean-Marc Le Roux
*
* @see aerys.minko.type.enum.BlendingSource
* @see aerys.minko.type.enum.BlendingDestination
* @see aerys.minko.render.shader.Shader
* @see aerys.minko.render.shader.part.BlendingShaderPart
*
*/
public final class Blending
{
public static const NORMAL : uint = BlendingSource.ONE
| BlendingDestination.ZERO;
public static const ALPHA : uint = BlendingSource.SOURCE_ALPHA
| BlendingDestination.ONE_MINUS_SOURCE_ALPHA;
public static const ADDITIVE : uint = BlendingSource.SOURCE_ALPHA
| BlendingDestination.ONE;
public static const LIGHT : uint = BlendingSource.ZERO
| BlendingDestination.SOURCE_COLOR;
minko_render static const STRINGS : Vector.<String> = new <String>[
Context3DBlendFactor.DESTINATION_ALPHA,
Context3DBlendFactor.DESTINATION_COLOR,
Context3DBlendFactor.ONE,
Context3DBlendFactor.ONE_MINUS_DESTINATION_ALPHA,
Context3DBlendFactor.ONE_MINUS_DESTINATION_COLOR,
Context3DBlendFactor.ONE_MINUS_SOURCE_ALPHA,
Context3DBlendFactor.SOURCE_ALPHA,
Context3DBlendFactor.SOURCE_COLOR,
Context3DBlendFactor.ZERO
];
}
}
|
package aerys.minko.type.enum
{
import aerys.minko.ns.minko_render;
import flash.display3D.Context3DBlendFactor;
/**
* The Blending class is an enumeration of the most common values possible
* for the Shader.blending property and the BlendingShaderPart.blend() method.
*
* @author Jean-Marc Le Roux
*
* @see aerys.minko.type.enum.BlendingSource
* @see aerys.minko.type.enum.BlendingDestination
* @see aerys.minko.render.shader.Shader
* @see aerys.minko.render.shader.part.BlendingShaderPart
*
*/
public final class Blending
{
public static const OPAQUE : uint = BlendingSource.ONE
| BlendingDestination.ZERO;
public static const ALPHA : uint = BlendingSource.SOURCE_ALPHA
| BlendingDestination.ONE_MINUS_SOURCE_ALPHA;
// public static const ADDITIVE : uint = BlendingSource.SOURCE_ALPHA
// | BlendingDestination.ONE;
public static const ADDITIVE : uint = BlendingSource.DESTINATION_ALPHA
| BlendingDestination.ONE;
public static const LIGHT : uint = BlendingSource.ZERO
| BlendingDestination.SOURCE_COLOR;
minko_render static const STRINGS : Vector.<String> = new <String>[
Context3DBlendFactor.DESTINATION_ALPHA,
Context3DBlendFactor.DESTINATION_COLOR,
Context3DBlendFactor.ONE,
Context3DBlendFactor.ONE_MINUS_DESTINATION_ALPHA,
Context3DBlendFactor.ONE_MINUS_DESTINATION_COLOR,
Context3DBlendFactor.ONE_MINUS_SOURCE_ALPHA,
Context3DBlendFactor.SOURCE_ALPHA,
Context3DBlendFactor.SOURCE_COLOR,
Context3DBlendFactor.ZERO
];
}
}
|
rename Blending.NORMAL to Blending.OPAQUE
|
rename Blending.NORMAL to Blending.OPAQUE
|
ActionScript
|
mit
|
aerys/minko-as3
|
3f1092377c3eb6c88da66b0fb8ccfa8a38700544
|
src/org/hola/JSURLStream.as
|
src/org/hola/JSURLStream.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.hola {
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.external.ExternalInterface;
import flash.net.URLRequest;
import flash.net.URLStream;
import flash.utils.ByteArray;
import flash.utils.getTimer;
import flash.utils.Timer;
import org.hola.ZErr;
import org.hola.Base64;
import org.mangui.hls.loader.FragmentLoader;
public dynamic class JSURLStream extends URLStream {
private var _connected : Boolean;
private var _resource : ByteArray = new ByteArray();
public var holaManaged:Boolean = false;
public static var jsApiInited:Boolean = false;
public static var reqCount:Number = 0;
public var req_id:String;
public static var reqs:Object = {};
public function JSURLStream(){
holaManaged = FragmentLoader.g_hls_mode;
addEventListener(Event.OPEN, onOpen);
ExternalInterface.marshallExceptions = true;
super();
// Connect calls to JS.
if (ExternalInterface.available && !jsApiInited){
ZErr.log('JSURLStream init api');
jsApiInited = true;
ExternalInterface.addCallback('hola_onFragmentData',
hola_onFragmentData);
}
}
protected function _trigger(cb:String, data:Object) : void {
if (!ExternalInterface.available) {
// XXX arik: need ZErr.throw
ZErr.log('invalid trigger');
throw new Error('invalid trigger');
}
ExternalInterface.call('window.hola_'+cb,
{objectID: ExternalInterface.objectID, data: data});
}
override public function get connected() : Boolean {
if (!holaManaged)
return super.connected;
return _connected;
}
override public function get bytesAvailable() : uint {
if (!holaManaged)
return super.bytesAvailable;
return _resource.bytesAvailable;
}
override public function readByte() : int {
if (!holaManaged)
return super.readByte();
return _resource.readByte();
}
override public function readUnsignedShort() : uint {
if (!holaManaged)
return super.readUnsignedShort();
return _resource.readUnsignedShort();
}
override public function readBytes(bytes : ByteArray, offset : uint = 0, length : uint = 0) : void {
if (!holaManaged)
return super.readBytes(bytes, offset, length);
_resource.readBytes(bytes, offset, length);
}
override public function close() : void {
if (holaManaged && reqs[req_id])
_trigger('abortFragment', {req_id: req_id});
if (super.connected)
super.close();
_connected = false;
}
override public function load(request : URLRequest) : void {
// XXX arik: cleanup previous if hola mode changed
holaManaged = FragmentLoader.g_hls_mode;
reqCount++;
req_id = 'req'+reqCount;
if (!holaManaged)
return super.load(request);
reqs[req_id] = this;
_resource = new ByteArray();
_trigger('requestFragment', {url: request.url, req_id: req_id});
this.dispatchEvent(new Event(Event.OPEN));
}
private function onOpen(event : Event) : void { _connected = true; }
protected static function hola_onFragmentData(o:Object):void{
var stream:JSURLStream;
try {
stream = reqs[o.req_id];
if (!stream)
throw new Error('req_id not found '+o.req_id);
if (o.error)
{
delete reqs[o.req_id];
return stream.resourceLoadingError();
}
if (o.data)
{
var data:ByteArray = Base64.decode_str(o.data);
data.position = 0;
if (stream._resource)
{
var prev:uint = stream._resource.position;
data.readBytes(stream._resource,
stream._resource.length);
stream._resource.position = prev;
}
else
stream._resource = data;
// XXX arik: get finalLength from js
var finalLength:uint = stream._resource.length;
stream.dispatchEvent(new ProgressEvent(
ProgressEvent.PROGRESS, false, false,
stream._resource.length, finalLength));
}
if (o.status)
{
delete reqs[o.req_id];
// XXX arik: dispatch httpStatus/httpResponseStatus
stream.resourceLoadingSuccess();
}
} catch(err:Error){
ZErr.log('Error in hola_onFragmentData', ''+err,
''+err.getStackTrace());
delete reqs[o.req_id];
if (stream)
stream.resourceLoadingError();
throw err;
}
}
protected function resourceLoadingError() : void {
this.dispatchEvent(new IOErrorEvent(IOErrorEvent.IO_ERROR));
}
protected function resourceLoadingSuccess() : void {
this.dispatchEvent(new Event(Event.COMPLETE));
}
}
}
|
/* 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.hola {
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.external.ExternalInterface;
import flash.net.URLRequest;
import flash.net.URLStream;
import flash.utils.ByteArray;
import flash.utils.getTimer;
import flash.utils.Timer;
import org.hola.ZErr;
import org.hola.Base64;
import org.hola.WorkerUtils;
import org.hola.HEvent;
import org.mangui.hls.loader.FragmentLoader;
public dynamic class JSURLStream extends URLStream {
private var _connected : Boolean;
private var _resource : ByteArray = new ByteArray();
private var _curr_data : Object;
public var holaManaged:Boolean = false;
public static var jsApiInited:Boolean = false;
public static var reqCount:Number = 0;
public var req_id:String;
public static var reqs:Object = {};
public function JSURLStream(){
holaManaged = FragmentLoader.g_hls_mode;
addEventListener(Event.OPEN, onOpen);
ExternalInterface.marshallExceptions = true;
super();
// Connect calls to JS.
if (ExternalInterface.available && !jsApiInited){
ZErr.log('JSURLStream init api');
jsApiInited = true;
ExternalInterface.addCallback('hola_onFragmentData',
hola_onFragmentData);
}
}
protected function _trigger(cb:String, data:Object) : void {
if (!ExternalInterface.available) {
// XXX arik: need ZErr.throw
ZErr.log('invalid trigger');
throw new Error('invalid trigger');
}
ExternalInterface.call('window.hola_'+cb,
{objectID: ExternalInterface.objectID, data: data});
}
override public function get connected() : Boolean {
if (!holaManaged)
return super.connected;
return _connected;
}
override public function get bytesAvailable() : uint {
if (!holaManaged)
return super.bytesAvailable;
return _resource.bytesAvailable;
}
override public function readByte() : int {
if (!holaManaged)
return super.readByte();
return _resource.readByte();
}
override public function readUnsignedShort() : uint {
if (!holaManaged)
return super.readUnsignedShort();
return _resource.readUnsignedShort();
}
override public function readBytes(bytes : ByteArray,
offset : uint = 0, length : uint = 0) : void
{
if (!holaManaged)
return super.readBytes(bytes, offset, length);
_resource.readBytes(bytes, offset, length);
}
override public function close() : void {
if (holaManaged)
{
if (reqs[req_id])
_trigger('abortFragment', {req_id: req_id});
WorkerUtils.removeEventListener(HEvent.WORKER_MESSAGE, onmsg);
}
if (super.connected)
super.close();
_connected = false;
}
override public function load(request : URLRequest) : void {
// XXX arik: cleanup previous if hola mode changed
holaManaged = FragmentLoader.g_hls_mode;
reqCount++;
req_id = 'req'+reqCount;
ZErr.log("load "+req_id);
if (!holaManaged)
return super.load(request);
WorkerUtils.addEventListener(HEvent.WORKER_MESSAGE, onmsg);
reqs[req_id] = this;
_resource = new ByteArray();
_trigger('requestFragment', {url: request.url, req_id: req_id});
this.dispatchEvent(new Event(Event.OPEN));
}
private function onOpen(event : Event) : void { _connected = true; }
private function decode(str : String) : void {
var data : ByteArray;
if (!WorkerUtils.worker)
{
if (str)
data = Base64.decode_str(str);
return on_decoded_data(data);
}
data = new ByteArray();
data.shareable = true;
data.writeUTFBytes(str);
WorkerUtils.send({cmd: "b64.decode", id: req_id});
WorkerUtils.send(data);
}
private function onmsg(e : HEvent) : void {
var msg : Object = e.data;
if (!req_id || req_id!=msg.id || msg.cmd!="b64.decode")
return;
var data : ByteArray = WorkerUtils.recv();
on_decoded_data(data);
}
private function on_decoded_data(data : ByteArray) : void {
if (data)
{
data.position = 0;
if (_resource)
{
var prev:uint = _resource.position;
data.readBytes(_resource, _resource.length);
_resource.position = prev;
}
else
_resource = data;
// XXX arik: get finalLength from js
var finalLength:uint = _resource.length;
dispatchEvent(new ProgressEvent( ProgressEvent.PROGRESS, false,
false, _resource.length, finalLength));
}
// XXX arik: dispatch httpStatus/httpResponseStatus
if (_curr_data.status)
resourceLoadingSuccess();
}
private function on_fragment_data(o : Object) : void {
_curr_data = o;
if (o.error)
return resourceLoadingError();
decode(o.data);
}
protected static function hola_onFragmentData(o:Object):void{
var stream:JSURLStream;
try {
if (!(stream = reqs[o.req_id]))
throw new Error('req_id not found '+o.req_id);
stream.on_fragment_data(o);
} catch(err:Error){
ZErr.log('Error in hola_onFragmentData', ''+err,
''+err.getStackTrace());
if (stream)
stream.resourceLoadingError();
throw err;
}
}
protected function resourceLoadingError() : void {
delete reqs[req_id];
dispatchEvent(new IOErrorEvent(IOErrorEvent.IO_ERROR));
}
protected function resourceLoadingSuccess() : void {
delete reqs[req_id];
dispatchEvent(new Event(Event.COMPLETE));
}
}
}
|
support base64 decoding in a worker
|
support base64 decoding in a worker
|
ActionScript
|
mpl-2.0
|
hola/flashls,hola/flashls
|
b185c1b800213dfccd253279aae99dae3555f840
|
frameworks/as/projects/FlexJSJX/src/org/apache/flex/html/beads/layouts/LayoutChangeNotifier.as
|
frameworks/as/projects/FlexJSJX/src/org/apache/flex/html/beads/layouts/LayoutChangeNotifier.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 org.apache.flex.core.IBead;
import org.apache.flex.core.IBeadView;
import org.apache.flex.core.IStrand;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
/**
* The LayoutChangeNotifier notifies layouts when a property
* it is watching changes.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class LayoutChangeNotifier implements IBead
{
/**
* constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function LayoutChangeNotifier()
{
}
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;
}
private var _value:* = undefined;
/**
* The number of tiles to fit horizontally into the layout.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set watchedProperty(value:Object):void
{
if (_value !== value)
{
_value = value;
if (_strand is IBeadView)
IBeadView(_strand).host.dispatchEvent(new Event("layoutNeeded"));
else
IEventDispatcher(_strand).dispatchEvent(new Event("layoutNeeded"));
}
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 org.apache.flex.core.IBead;
import org.apache.flex.core.IBeadView;
import org.apache.flex.core.IStrand;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
/**
* The LayoutChangeNotifier notifies layouts when a property
* it is watching changes.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class LayoutChangeNotifier implements IBead
{
/**
* constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function LayoutChangeNotifier()
{
}
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;
}
private var _value:* = undefined;
/**
* The value of the property being watched. This is usually
* a data binding expression.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set initialValue(value:Object):void
{
_value = value;
}
/**
* The value of the property being watched. This is usually
* a data binding expression.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set watchedProperty(value:Object):void
{
if (_value !== value)
{
_value = value;
if (_strand is IBeadView)
IBeadView(_strand).host.dispatchEvent(new Event("layoutNeeded"));
else
IEventDispatcher(_strand).dispatchEvent(new Event("layoutNeeded"));
}
}
}
}
|
add initial value to prevent a few unnecessary layout passes
|
add initial value to prevent a few unnecessary layout passes
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
f61062e7023a8f6040e4414cd1d329d8c8792712
|
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.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);
}
}
}
|
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 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 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);
}
}
}
|
add Vector4.lerp() and remove Vector4::copy(), use new Vector4().copyFrom() instead
|
add Vector4.lerp() and remove Vector4::copy(), use new Vector4().copyFrom() instead
|
ActionScript
|
mit
|
aerys/minko-as3
|
113d1ca27cfabb7aa6ef5e46019d17c05b1388a9
|
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;
final 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);
minko_math static const UPDATE_NONE : uint = 0;
minko_math static const UPDATE_LENGTH : uint = 1;
minko_math static const UPDATE_LENGTH_SQ : uint = 2;
minko_math 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();
minko_math 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
{
var sourceVector : Vector3D = source._vector;
return set(sourceVector.x, sourceVector.y, sourceVector.z, sourceVector.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;
final 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);
minko_math static const UPDATE_NONE : uint = 0;
minko_math static const UPDATE_LENGTH : uint = 1;
minko_math static const UPDATE_LENGTH_SQ : uint = 2;
minko_math 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();
minko_math 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
{
var sourceVector : Vector3D = source._vector;
return set(sourceVector.x, sourceVector.y, sourceVector.z, sourceVector.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 static function fromVector3D(vector : Vector3D, out : Vector4 = null) : Vector4
{
out ||= FACTORY.create() as Vector4;
out.x = vector.x;
out.y = vector.y;
out.z = vector.z;
out.w = 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 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);
}
}
}
|
Add Vector4.fromVector3D().
|
Add Vector4.fromVector3D().
|
ActionScript
|
mit
|
aerys/minko-as3
|
99144865d9ad60c055960f32098bb9da4909524f
|
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())
{
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();
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();
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 + '\'.'
);
}
}
}
|
fix ambigous = operator in if boolean expression to comply with ASC 2.0 compiler
|
fix ambigous = operator in if boolean expression to comply with ASC 2.0 compiler
|
ActionScript
|
mit
|
aerys/minko-as3
|
ff274735a9cefd48eef08ab2ea8d125cda7b68bf
|
src/as/com/threerings/io/TypedArray.as
|
src/as/com/threerings/io/TypedArray.as
|
package com.threerings.io {
import com.threerings.util.ClassUtil;
import com.threerings.util.Cloneable;
public dynamic class TypedArray extends Array
implements Cloneable
{
/**
* Create a TypedArray
*
* @param jtype The java classname of this array, for example "[I" to
* represent an int[], or "[Ljava.lang.Object;" for Object[].
*/
public function TypedArray (jtype :String)
{
_jtype = jtype;
}
/**
* Convenience method to get the java type of an array containing
* objects of the specified class.
*/
public static function getJavaType (of :Class) :String
{
if (of === Boolean) {
return "[Z";
} else if (of === int) { // Number will be int if something like 3.0
return "[I";
} else if (of === Number) {
return "[D";
}
var cname :String = Translations.getToServer(
ClassUtil.getClassName(of));
return "[L" + cname + ";";
}
/**
* A factory method to create a TypedArray for holding objects
* of the specified type.
*/
public static function create (of :Class) :TypedArray
{
return new TypedArray(getJavaType(of));
}
public function getJavaType () :String
{
return _jtype;
}
// from Cloneable
public function clone () :Object
{
var clazz :Class = ClassUtil.getClass(this);
var copy :TypedArray = new clazz(_jtype);
for (var ii :int = length - 1; ii >= 0; ii--) {
copy[ii] = this[ii];
}
return copy;
}
/** The 'type' of this array, which doesn't really mean anything
* except gives it a clue as to how to stream to our server. */
protected var _jtype :String;
}
}
|
package com.threerings.io {
import flash.utils.ByteArray;
import com.threerings.util.ClassUtil;
import com.threerings.util.Cloneable;
public dynamic class TypedArray extends Array
implements Cloneable
{
/**
* Create a TypedArray
*
* @param jtype The java classname of this array, for example "[I" to
* represent an int[], or "[Ljava.lang.Object;" for Object[].
*/
public function TypedArray (jtype :String)
{
_jtype = jtype;
}
/**
* Convenience method to get the java type of an array containing
* objects of the specified class.
*/
public static function getJavaType (of :Class) :String
{
if (of === Boolean) {
return "[Z";
} else if (of === int) { // Number will be int if something like 3.0
return "[I";
} else if (of === Number) {
return "[D";
} else if (of === ByteArray) {
return "[[B";
}
var cname :String = Translations.getToServer(
ClassUtil.getClassName(of));
return "[L" + cname + ";";
}
/**
* A factory method to create a TypedArray for holding objects
* of the specified type.
*/
public static function create (of :Class) :TypedArray
{
return new TypedArray(getJavaType(of));
}
public function getJavaType () :String
{
return _jtype;
}
// from Cloneable
public function clone () :Object
{
var clazz :Class = ClassUtil.getClass(this);
var copy :TypedArray = new clazz(_jtype);
for (var ii :int = length - 1; ii >= 0; ii--) {
copy[ii] = this[ii];
}
return copy;
}
/** The 'type' of this array, which doesn't really mean anything
* except gives it a clue as to how to stream to our server. */
protected var _jtype :String;
}
}
|
Allow creation of an array of arrays of bytes...
|
Allow creation of an array of arrays of bytes...
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4332 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
dbdedf7359708f79d0a5dbdad1af6ad4842e9bd2
|
src/fm/wavesurfer/audio/AudioLoader.as
|
src/fm/wavesurfer/audio/AudioLoader.as
|
package fm.wavesurfer.audio {
import fm.wavesurfer.audio.events.LoadProgressEvent;
import flash.events.ProgressEvent;
import fm.wavesurfer.audio.events.LoadErrorEvent;
import flash.events.IOErrorEvent;
import fm.wavesurfer.audio.events.LoadedEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.media.Sound;
import flash.media.SoundLoaderContext;
import flash.net.URLRequest;
/**
* @author laurent
*/
public class AudioLoader extends EventDispatcher {
private var sound : Sound;
private var url : String;
public function AudioLoader() {
sound = new Sound();
sound.addEventListener(Event.COMPLETE, onSoundLoaded);
sound.addEventListener(IOErrorEvent.IO_ERROR, onSoundLoadError);
sound.addEventListener(ProgressEvent.PROGRESS, onSoundLoadProgress);
}
public function load(url : String) : void {
this.url = url;
sound.load(new URLRequest(url), new SoundLoaderContext());
}
private function onSoundLoaded(event : Event) : void {
var audio : AudioData = new AudioData(sound);
dispatchEvent(new LoadedEvent(audio));
}
private function onSoundLoadError(event : IOErrorEvent) : void {
dispatchEvent(new LoadErrorEvent(url));
}
private function onSoundLoadProgress(event : ProgressEvent) : void {
var total : Number = event.bytesTotal ? event.bytesTotal : 1;
dispatchEvent(new LoadProgressEvent(Math.min(1, event.bytesLoaded / total)));
}
}
}
|
package fm.wavesurfer.audio {
import fm.wavesurfer.audio.events.LoadProgressEvent;
import flash.events.ProgressEvent;
import fm.wavesurfer.audio.events.LoadErrorEvent;
import flash.events.IOErrorEvent;
import fm.wavesurfer.audio.events.LoadedEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.media.Sound;
import flash.media.SoundLoaderContext;
import flash.net.URLRequest;
/**
* @author laurent
*/
public class AudioLoader extends EventDispatcher {
private var sound : Sound;
private var url : String;
public function AudioLoader() {
sound = new Sound();
sound.addEventListener(Event.COMPLETE, onSoundLoaded);
sound.addEventListener(IOErrorEvent.IO_ERROR, onSoundLoadError);
sound.addEventListener(ProgressEvent.PROGRESS, onSoundLoadProgress);
}
public function load(url : String) : void {
this.url = url;
sound.load(new URLRequest(url), new SoundLoaderContext(1000, true));
}
private function onSoundLoaded(event : Event) : void {
var audio : AudioData = new AudioData(sound);
dispatchEvent(new LoadedEvent(audio));
}
private function onSoundLoadError(event : IOErrorEvent) : void {
dispatchEvent(new LoadErrorEvent(url));
}
private function onSoundLoadProgress(event : ProgressEvent) : void {
var total : Number = event.bytesTotal ? event.bytesTotal : 1;
dispatchEvent(new LoadProgressEvent(Math.min(1, event.bytesLoaded / total)));
}
}
}
|
Load crossdomain by default
|
Load crossdomain by default
|
ActionScript
|
mit
|
laurentvd/wavesurfer.swf,laurentvd/wavesurfer.swf
|
70c8b3cae14fe3fdf7c0ed31393fb54b44d2a4e9
|
src/flash/utils/FlashUtilScript.as
|
src/flash/utils/FlashUtilScript.as
|
package flash.utils {
import avmplus.FLASH10_FLAGS;
public function describeType(value):XML {
return avmplus.describeType(value, FLASH10_FLAGS);
}
[native("FlashUtilScript::getAliasName")]
public native function getAliasName(value):String;
public function getQualifiedClassName(value):String {
return avmplus.getQualifiedClassName(value);
}
[native("FlashUtilScript::getDefinitionByName")]
public native function getDefinitionByName(name:String):Object;
public function getQualifiedSuperclassName(value):String {
return avmplus.getQualifiedSuperclassName(value);
}
[native("FlashUtilScript::getTimer")]
public native function getTimer():int;
[native("FlashUtilScript::escapeMultiByte")]
public native function escapeMultiByte(value:String):String;
[native("FlashUtilScript::unescapeMultiByte")]
public native function unescapeMultiByte(value:String):String;
}
|
/*
* 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
*
* 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.utils {
import avmplus.FLASH10_FLAGS;
public function describeType(value):XML {
return avmplus.describeType(value, FLASH10_FLAGS);
}
[native("FlashUtilScript::getAliasName")]
public native function getAliasName(value):String;
public function getQualifiedClassName(value):String {
return avmplus.getQualifiedClassName(value);
}
[native("FlashUtilScript::getDefinitionByName")]
public native function getDefinitionByName(name:String):Object;
public function getQualifiedSuperclassName(value):String {
return avmplus.getQualifiedSuperclassName(value);
}
[native("FlashUtilScript::getTimer")]
public native function getTimer():int;
[native("FlashUtilScript::escapeMultiByte")]
public native function escapeMultiByte(value:String):String;
[native("FlashUtilScript::unescapeMultiByte")]
public native function unescapeMultiByte(value:String):String;
}
|
Add license header to flash/utils/FlashUtilScript.as
|
Add license header to flash/utils/FlashUtilScript.as
|
ActionScript
|
apache-2.0
|
mbebenita/shumway,mozilla/shumway,tschneidereit/shumway,mozilla/shumway,tschneidereit/shumway,yurydelendik/shumway,yurydelendik/shumway,yurydelendik/shumway,mbebenita/shumway,mozilla/shumway,tschneidereit/shumway,mbebenita/shumway,tschneidereit/shumway,mozilla/shumway,mbebenita/shumway,tschneidereit/shumway,yurydelendik/shumway,tschneidereit/shumway,yurydelendik/shumway,mozilla/shumway,yurydelendik/shumway,mbebenita/shumway,tschneidereit/shumway,yurydelendik/shumway,mozilla/shumway,mbebenita/shumway,mbebenita/shumway,mozilla/shumway,yurydelendik/shumway,mozilla/shumway,mbebenita/shumway,tschneidereit/shumway
|
260494accc36d64989625301b05d14b6abbc4594
|
WeaveUI/src/weave/ui/JavaScriptCanvas.as
|
WeaveUI/src/weave/ui/JavaScriptCanvas.as
|
package weave.ui
{
import weave.compiler.StandardLib;
import weave.api.core.ILinkableObject;
import mx.containers.Canvas;
import mx.controls.Image;
import flash.events.Event;
import flash.utils.Timer;
import flash.utils.getTimer;
import flash.events.TimerEvent;
public class JavaScriptCanvas extends Canvas implements ILinkableObject
{
private var buffers:Vector.<Image> = new Vector.<Image>(2, true);
private var buffer_index:int = 0;
private var lastUpdate:int = 0;
private var forceReadTimer:Timer;
public var sourceId:String = null;
public function JavaScriptCanvas()
{
super();
}
override protected function createChildren():void
{
lastUpdate = getTimer();
forceReadTimer = new Timer(250);
buffers[0] = new Image();
buffers[1] = new Image();
buffers[0].addEventListener(Event.COMPLETE, readFromCanvas);
buffers[1].addEventListener(Event.COMPLETE, readFromCanvas);
forceReadTimer.addEventListener(TimerEvent.TIMER, readFromCanvas);
addChild(buffers[0]);
addChild(buffers[1]);
super.createChildren();
forceReadTimer.start();
}
public function readFromCanvas(evt:Event):void
{
/* Only execute on the timer tick if we haven't loaded recently */
if (evt.type == TimerEvent.TIMER && (getTimer() < (lastUpdate + 200)) ) return;
if (evt.type == TimerEvent.TIMER) weaveTrace("timed out, jumpstarting canvas read");
var content:String;
/* TODO convert to raw ExternalInterface */
if (sourceId) content = JavaScript.exec(
{elementId: sourceId},
"var canvas = document.getElementById(elementId);",
"return canvas && canvas.toDataURL && canvas.toDataURL().split(',').pop();");
if (sourceId && content)
{
setImage(content);
}
}
public function setImage(base64:String):void
{
lastUpdate = getTimer();
setChildIndex(buffers[buffer_index], 0);
buffer_index = (buffer_index + 1) % 2;
buffers[buffer_index].source = StandardLib.atob(base64);
}
}
}
|
package weave.ui
{
import weave.compiler.StandardLib;
import weave.api.core.ILinkableObject;
import weave.core.LinkableString;
import weave.api.newLinkableChild;
import mx.containers.Canvas;
import mx.controls.Image;
import flash.events.Event;
import flash.utils.Timer;
import flash.utils.getTimer;
import flash.events.TimerEvent;
public class JavaScriptCanvas extends Canvas implements ILinkableObject
{
private var buffers:Vector.<Image> = new Vector.<Image>(2, true);
private var buffer_index:int = 0;
private var lastUpdate:int = 0;
private var forceReadTimer:Timer;
public const elementId:LinkableString = newLinkableChild(this, LinkableString);
public function JavaScriptCanvas()
{
super();
}
override protected function createChildren():void
{
lastUpdate = getTimer();
forceReadTimer = new Timer(250);
buffers[0] = new Image();
buffers[1] = new Image();
buffers[0].addEventListener(Event.COMPLETE, readFromCanvas);
buffers[1].addEventListener(Event.COMPLETE, readFromCanvas);
forceReadTimer.addEventListener(TimerEvent.TIMER, readFromCanvas);
addChild(buffers[0]);
addChild(buffers[1]);
super.createChildren();
forceReadTimer.start();
}
public function readFromCanvas(evt:Event):void
{
/* Only execute on the timer tick if we haven't loaded recently */
if (evt.type == TimerEvent.TIMER && (getTimer() < (lastUpdate + 200)) ) return;
var content:String;
/* TODO convert to raw ExternalInterface */
if (elementId.value) content = JavaScript.exec(
{elementId: elementId.value},
"var canvas = document.getElementById(elementId);",
"return canvas && canvas.toDataURL && canvas.toDataURL().split(',').pop();");
if (elementId.value && content)
{
setImage(content);
}
}
public function setImage(base64:String):void
{
lastUpdate = getTimer();
setChildIndex(buffers[buffer_index], 0);
buffer_index = (buffer_index + 1) % 2;
buffers[buffer_index].source = StandardLib.atob(base64);
}
}
}
|
Make JavaScriptCanvas linkable
|
Make JavaScriptCanvas linkable
|
ActionScript
|
mpl-2.0
|
WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS
|
f8cfdc7dfe7d887e7751f42791a1cac1252f1a58
|
dolly-framework/src/main/actionscript/dolly/Cloner.as
|
dolly-framework/src/main/actionscript/dolly/Cloner.as
|
package dolly {
import dolly.core.dolly_internal;
import dolly.core.errors.CloningError;
import dolly.core.metadata.MetadataName;
import org.as3commons.reflect.Accessor;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.IMetadataContainer;
import org.as3commons.reflect.Type;
import org.as3commons.reflect.Variable;
use namespace dolly_internal;
public class Cloner {
private static function isTypeCloneable(type:Type):Boolean {
return type.hasMetadata(MetadataName.CLONEABLE);
}
private static function isVariableCloneable(variable:Variable, skipMetadataChecking:Boolean = true):Boolean {
return !variable.isStatic && (skipMetadataChecking || variable.hasMetadata(MetadataName.CLONEABLE));
}
private static function isAccessorCloneable(accessor:Accessor, skipMetadataChecking:Boolean = true):Boolean {
return !accessor.isStatic && accessor.isReadable() && accessor.isWriteable() &&
(skipMetadataChecking || accessor.hasMetadata(MetadataName.CLONEABLE));
}
dolly_internal static function getCloneableFieldsForType(type:Type):Vector.<Field> {
const result:Vector.<Field> = new Vector.<Field>();
var variable:Variable;
var accessor:Accessor;
const isClassCloneable:Boolean = isTypeCloneable(type);
if (isClassCloneable) {
for each(variable in type.variables) {
if (isVariableCloneable(variable)) {
result.push(variable);
}
}
for each(accessor in type.accessors) {
if (isAccessorCloneable(accessor)) {
result.push(accessor);
}
}
} else {
const metadataContainers:Array = type.getMetadataContainers(MetadataName.CLONEABLE);
for each(var metadataContainer:IMetadataContainer in metadataContainers) {
if (metadataContainer is Variable) {
variable = metadataContainer as Variable;
if (isVariableCloneable(variable, false)) {
result.push(variable);
}
} else if (metadataContainer is Accessor) {
accessor = metadataContainer as Accessor;
if (isAccessorCloneable(accessor, false)) {
result.push(accessor);
}
}
}
}
return result;
}
public static function clone(source:*):* {
const type:Type = Type.forInstance(source);
if (!isTypeCloneable(type)) {
throw new CloningError(
CloningError.CLASS_IS_NOT_CLONEABLE_MESSAGE,
CloningError.CLASS_IS_NOT_CLONEABLE_CODE
);
}
const clone:* = new (type.clazz)();
// Find all public writable fields in a hierarchy of a source object
// and assign their values to a clone object.
const fieldsToClone:Vector.<Field> = getCloneableFieldsForType(type);
var name:String;
for each(var field:Field in fieldsToClone) {
name = field.name;
clone[name] = source[name];
}
return clone;
}
}
}
|
package dolly {
import dolly.core.dolly_internal;
import dolly.core.errors.CloningError;
import dolly.core.metadata.MetadataName;
import org.as3commons.reflect.Accessor;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.as3commons.reflect.Variable;
use namespace dolly_internal;
public class Cloner {
private static function isTypeCloneable(type:Type):Boolean {
return type.hasMetadata(MetadataName.CLONEABLE);
}
private static function isVariableCloneable(variable:Variable, skipMetadataChecking:Boolean = true):Boolean {
return !variable.isStatic && (skipMetadataChecking || variable.hasMetadata(MetadataName.CLONEABLE));
}
private static function isAccessorCloneable(accessor:Accessor, skipMetadataChecking:Boolean = true):Boolean {
return !accessor.isStatic && accessor.isReadable() && accessor.isWriteable() &&
(skipMetadataChecking || accessor.hasMetadata(MetadataName.CLONEABLE));
}
dolly_internal static function getCloneableFieldsForType(type:Type):Vector.<Field> {
const result:Vector.<Field> = new Vector.<Field>();
var variable:Variable;
var accessor:Accessor;
for each(variable in type.variables) {
if (isVariableCloneable(variable)) {
result.push(variable);
}
}
for each(accessor in type.accessors) {
if (isAccessorCloneable(accessor)) {
result.push(accessor);
}
}
return result;
}
public static function clone(source:*):* {
const type:Type = Type.forInstance(source);
if (!isTypeCloneable(type)) {
throw new CloningError(
CloningError.CLASS_IS_NOT_CLONEABLE_MESSAGE,
CloningError.CLASS_IS_NOT_CLONEABLE_CODE
);
}
const clone:* = new (type.clazz)();
// Find all public writable fields in a hierarchy of a source object
// and assign their values to a clone object.
const fieldsToClone:Vector.<Field> = getCloneableFieldsForType(type);
var name:String;
for each(var field:Field in fieldsToClone) {
name = field.name;
clone[name] = source[name];
}
return clone;
}
}
}
|
Remove checking for marking source as cloneable.
|
Remove checking for marking source as cloneable.
|
ActionScript
|
mit
|
Yarovoy/dolly
|
cb9663d1734b0fb943752b8eeb24418aa9049639
|
src/widgets/Geoprocessing/parameters/FeatureLayerParameter.as
|
src/widgets/Geoprocessing/parameters/FeatureLayerParameter.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 widgets.Geoprocessing.parameters
{
import com.esri.ags.FeatureSet;
import com.esri.ags.SpatialReference;
import com.esri.ags.layers.FeatureLayer;
import com.esri.ags.layers.supportClasses.FeatureCollection;
import com.esri.ags.layers.supportClasses.LayerDetails;
import com.esri.ags.portal.PopUpRenderer;
import com.esri.ags.portal.supportClasses.PopUpInfo;
import com.esri.ags.renderers.ClassBreaksRenderer;
import com.esri.ags.renderers.IRenderer;
import com.esri.ags.renderers.SimpleRenderer;
import com.esri.ags.renderers.UniqueValueRenderer;
import com.esri.ags.symbols.Symbol;
import mx.core.ClassFactory;
public class FeatureLayerParameter extends BaseParameter implements IGPFeatureParameter
{
//--------------------------------------------------------------------------
//
// Constants
//
//--------------------------------------------------------------------------
public static const DRAW_SOURCE:String = "drawtool";
public static const LAYERS_SOURCE:String = "layers";
public static const MAP_EXTENT_SOURCE:String = "extent";
public static const POINT:String = "point";
public static const POLYGON:String = "polygon";
public static const POLYLINE:String = "polyline";
public static const SIMPLE_MARKER:String = "simplemarker";
public static const SIMPLE_FILL:String = "simplefill";
public static const SIMPLE_LINE:String = "simpleline";
public static const PICTURE_MARKER:String = "picturemarker";
public static const SIMPLE_RENDERER:String = "simple";
public static const CLASS_BREAKS_RENDERER:String = "classbreaks";
public static const UNIQUE_VALUE_RENDERER:String = "uniquevalue";
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
public function FeatureLayerParameter()
{
_layer = new FeatureLayer();
_layer.featureCollection = new FeatureCollection(new FeatureSet([]), new LayerDetails());
}
//--------------------------------------------------------------------------
//
// Properties
//
//--------------------------------------------------------------------------
//----------------------------------
// geometryType
//----------------------------------
private var _geometryType:String;
public function get geometryType():String
{
return _geometryType;
}
public function set geometryType(value:String):void
{
_geometryType = value;
}
//----------------------------------
// mode
//----------------------------------
private var _mode:String;
public function get mode():String
{
return _mode;
}
public function set mode(value:String):void
{
_mode = value;
}
//----------------------------------
// layerNames
//----------------------------------
private var _layerNames:Array;
public function get layerNames():Array
{
return _layerNames;
}
public function set layerNames(value:Array):void
{
_layerNames = value;
}
//----------------------------------
// popUpInfo
//----------------------------------
private var _popUpInfo:PopUpInfo;
public function get popUpInfo():PopUpInfo
{
return _popUpInfo;
}
public function set popUpInfo(value:PopUpInfo):void
{
_popUpInfo = value;
}
//----------------------------------
// layer
//----------------------------------
private var _layer:FeatureLayer;
public function get layer():FeatureLayer
{
return _layer;
}
//----------------------------------
// renderer
//----------------------------------
private var _renderer:IRenderer;
public function get renderer():IRenderer
{
return _renderer;
}
public function set renderer(value:IRenderer):void
{
_renderer = value;
_layer.renderer = value;
}
//----------------------------------
// layerName
//----------------------------------
private var _layerName:String;
public function get layerName():String
{
return _layerName;
}
public function set layerName(value:String):void
{
_layerName = value;
_layer.name = value;
}
//----------------------------------
// popUpRenderer
//----------------------------------
public function get popUpRenderer():ClassFactory
{
var popUpRenderer:ClassFactory;
if (_popUpInfo)
{
popUpRenderer = new ClassFactory(PopUpRenderer);
var popUpInfo:PopUpInfo = _popUpInfo;
popUpRenderer.properties = { popUpInfo: popUpInfo };
}
return popUpRenderer;
}
//----------------------------------
// spatialReference
//----------------------------------
private var _spatialReference:SpatialReference;
public function get spatialReference():SpatialReference
{
return _spatialReference;
}
public function set spatialReference(value:SpatialReference):void
{
_spatialReference = value;
}
//----------------------------------
// defaultSymbol
//----------------------------------
public function get defaultSymbol():Symbol
{
var symbol:Symbol;
if (_renderer is SimpleRenderer)
{
symbol = (_renderer as SimpleRenderer).symbol;
}
else if (_renderer is ClassBreaksRenderer)
{
symbol = (_renderer as ClassBreaksRenderer).defaultSymbol;
}
else if (_renderer is UniqueValueRenderer)
{
symbol = (_renderer as UniqueValueRenderer).defaultSymbol;
}
return symbol;
}
//--------------------------------------------------------------------------
//
// Overridden properties
//
//--------------------------------------------------------------------------
//----------------------------------
// type
//----------------------------------
override public function get type():String
{
return GPParameterTypes.FEATURE_RECORD_SET_LAYER;
}
//----------------------------------
// name
//----------------------------------
override public function set name(value:String):void
{
super.name = value;
_layer.id = value;
}
//--------------------------------------------------------------------------
//
// Overridden methods
//
//--------------------------------------------------------------------------
override public function hasValidValue():Boolean
{
return _layer.featureCollection.featureSet.features.length > 0;
}
public override function getRequestObjectValue():Object
{
return _layer.featureCollection.featureSet;
}
}
}
|
///////////////////////////////////////////////////////////////////////////
// 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 widgets.Geoprocessing.parameters
{
import com.esri.ags.FeatureSet;
import com.esri.ags.SpatialReference;
import com.esri.ags.layers.FeatureLayer;
import com.esri.ags.layers.supportClasses.FeatureCollection;
import com.esri.ags.layers.supportClasses.LayerDetails;
import com.esri.ags.portal.PopUpRenderer;
import com.esri.ags.portal.supportClasses.PopUpInfo;
import com.esri.ags.renderers.ClassBreaksRenderer;
import com.esri.ags.renderers.IRenderer;
import com.esri.ags.renderers.SimpleRenderer;
import com.esri.ags.renderers.UniqueValueRenderer;
import com.esri.ags.symbols.Symbol;
import mx.core.ClassFactory;
public class FeatureLayerParameter extends BaseParameter implements IGPFeatureParameter
{
//--------------------------------------------------------------------------
//
// Constants
//
//--------------------------------------------------------------------------
public static const DRAW_SOURCE:String = "drawtool";
public static const LAYERS_SOURCE:String = "layers";
public static const MAP_EXTENT_SOURCE:String = "extent";
public static const POINT:String = "point";
public static const POLYGON:String = "polygon";
public static const POLYLINE:String = "polyline";
public static const SIMPLE_MARKER:String = "simplemarker";
public static const SIMPLE_FILL:String = "simplefill";
public static const SIMPLE_LINE:String = "simpleline";
public static const PICTURE_MARKER:String = "picturemarker";
public static const SIMPLE_RENDERER:String = "simple";
public static const CLASS_BREAKS_RENDERER:String = "classbreaks";
public static const UNIQUE_VALUE_RENDERER:String = "uniquevalue";
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
public function FeatureLayerParameter()
{
_layer = new FeatureLayer();
_layer.featureCollection = new FeatureCollection(new FeatureSet([]), new LayerDetails());
_layer.outFields = [ "*" ];
}
//--------------------------------------------------------------------------
//
// Properties
//
//--------------------------------------------------------------------------
//----------------------------------
// geometryType
//----------------------------------
private var _geometryType:String;
public function get geometryType():String
{
return _geometryType;
}
public function set geometryType(value:String):void
{
_geometryType = value;
}
//----------------------------------
// mode
//----------------------------------
private var _mode:String;
public function get mode():String
{
return _mode;
}
public function set mode(value:String):void
{
_mode = value;
}
//----------------------------------
// layerNames
//----------------------------------
private var _layerNames:Array;
public function get layerNames():Array
{
return _layerNames;
}
public function set layerNames(value:Array):void
{
_layerNames = value;
}
//----------------------------------
// popUpInfo
//----------------------------------
private var _popUpInfo:PopUpInfo;
public function get popUpInfo():PopUpInfo
{
return _popUpInfo;
}
public function set popUpInfo(value:PopUpInfo):void
{
_popUpInfo = value;
}
//----------------------------------
// layer
//----------------------------------
private var _layer:FeatureLayer;
public function get layer():FeatureLayer
{
return _layer;
}
//----------------------------------
// renderer
//----------------------------------
private var _renderer:IRenderer;
public function get renderer():IRenderer
{
return _renderer;
}
public function set renderer(value:IRenderer):void
{
_renderer = value;
_layer.renderer = value;
}
//----------------------------------
// layerName
//----------------------------------
private var _layerName:String;
public function get layerName():String
{
return _layerName;
}
public function set layerName(value:String):void
{
_layerName = value;
_layer.name = value;
}
//----------------------------------
// popUpRenderer
//----------------------------------
public function get popUpRenderer():ClassFactory
{
var popUpRenderer:ClassFactory;
if (_popUpInfo)
{
popUpRenderer = new ClassFactory(PopUpRenderer);
var popUpInfo:PopUpInfo = _popUpInfo;
popUpRenderer.properties = { popUpInfo: popUpInfo };
}
return popUpRenderer;
}
//----------------------------------
// spatialReference
//----------------------------------
private var _spatialReference:SpatialReference;
public function get spatialReference():SpatialReference
{
return _spatialReference;
}
public function set spatialReference(value:SpatialReference):void
{
_spatialReference = value;
}
//----------------------------------
// defaultSymbol
//----------------------------------
public function get defaultSymbol():Symbol
{
var symbol:Symbol;
if (_renderer is SimpleRenderer)
{
symbol = (_renderer as SimpleRenderer).symbol;
}
else if (_renderer is ClassBreaksRenderer)
{
symbol = (_renderer as ClassBreaksRenderer).defaultSymbol;
}
else if (_renderer is UniqueValueRenderer)
{
symbol = (_renderer as UniqueValueRenderer).defaultSymbol;
}
return symbol;
}
//--------------------------------------------------------------------------
//
// Overridden properties
//
//--------------------------------------------------------------------------
//----------------------------------
// type
//----------------------------------
override public function get type():String
{
return GPParameterTypes.FEATURE_RECORD_SET_LAYER;
}
//----------------------------------
// name
//----------------------------------
override public function set name(value:String):void
{
super.name = value;
_layer.id = value;
}
//--------------------------------------------------------------------------
//
// Overridden methods
//
//--------------------------------------------------------------------------
override public function set paramInfo(value:Object):void
{
if (value)
{
super.paramInfo = value;
if (value.defaultValue)
{
var featureSet:FeatureSet = FeatureSet.fromJSON(value.defaultValue);
layer.featureCollection.layerDefinition.fields = featureSet.fields;
}
}
}
override public function hasValidValue():Boolean
{
return _layer.featureCollection.featureSet.features.length > 0;
}
public override function getRequestObjectValue():Object
{
return _layer.featureCollection.featureSet;
}
}
}
|
Configure FeatureLayerParam out fields & layer definition fields.
|
Configure FeatureLayerParam out fields & layer definition fields.
|
ActionScript
|
apache-2.0
|
CanterburyRegionalCouncil/arcgis-viewer-flex,CanterburyRegionalCouncil/arcgis-viewer-flex,Esri/arcgis-viewer-flex,Esri/arcgis-viewer-flex,CanterburyRegionalCouncil/arcgis-viewer-flex
|
17d64726a42bd82e24ffd3c43e62076f3f59dacd
|
src/as/com/threerings/flash/Animation.as
|
src/as/com/threerings/flash/Animation.as
|
//
// $Id$
//
// Nenya library - tools for developing networked games
// Copyright (C) 2002-2007 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.flash {
public interface Animation
{
/**
* The primary working method for your animation.
*/
function updateAnimation (elapsed :Number) :void;
}
}
|
//
// $Id$
//
// Nenya library - tools for developing networked games
// Copyright (C) 2002-2007 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.flash {
public interface Animation
{
/**
* The primary working method for your animation. The argument indicates how
* many milliseconds have passed since the previous update.
*/
function updateAnimation (elapsed :Number) :void;
}
}
|
Clarify nature of argument.
|
Clarify nature of argument.
git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@315 ed5b42cb-e716-0410-a449-f6a68f950b19
|
ActionScript
|
lgpl-2.1
|
threerings/nenya,threerings/nenya
|
1af3cf8bb71e9bf7bccacdf4d144680e87170cbb
|
src/aerys/minko/render/shader/Shader.as
|
src/aerys/minko/render/shader/Shader.as
|
package aerys.minko.render.shader
{
import aerys.minko.Minko;
import aerys.minko.ns.minko;
import aerys.minko.render.renderer.state.RendererState;
import aerys.minko.render.ressource.TextureRessource;
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.compiler.register.RegisterType;
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.visitor.data.LocalData;
import aerys.minko.scene.visitor.data.StyleStack;
import aerys.minko.type.log.DebugLevel;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
import aerys.minko.type.vertex.format.VertexComponent;
import flash.utils.ByteArray;
import flash.utils.Dictionary;
import aerys.minko.render.ressource.ShaderRessource;
public class Shader extends ShaderRessource
{
use namespace minko;
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 static function create(outputPosition : INode,
outputColor : INode) : Shader
{
var compiler : Compiler = new Compiler();
compiler.load(outputPosition, outputColor);
if (Minko.debugLevel & DebugLevel.SHADER_ATTR_ALLOC)
{
Minko.log(DebugLevel.SHADER_ATTR_ALLOC, compiler.writeAttributeAllocationSummary());
}
if (Minko.debugLevel & DebugLevel.SHADER_CONST_ALLOC)
{
Minko.log(DebugLevel.SHADER_CONST_ALLOC, compiler.writeConstantAllocationSummary(true));
Minko.log(DebugLevel.SHADER_CONST_ALLOC, compiler.writeConstantAllocationSummary(false));
}
if (Minko.debugLevel & DebugLevel.SHADER_AGAL)
{
Minko.log(DebugLevel.SHADER_AGAL, compiler.compileAgalVertexShader(), compiler);
Minko.log(DebugLevel.SHADER_AGAL, compiler.compileAgalFragmentShader(), compiler);
}
if (Minko.debugLevel & DebugLevel.SHADER_DOTTY)
{
Minko.log(DebugLevel.SHADER_DOTTY, compiler.writeDotGraph(), compiler);
}
return compiler.compileShader();
}
public function Shader(vertexShader : ByteArray,
fragmentShader : ByteArray,
vertexInput : Vector.<VertexComponent>,
vertexShaderConstantData : Vector.<Number>,
fragmentShaderConstantData : Vector.<Number>,
vertexShaderParameters : Vector.<ParameterAllocation>,
fragmentShaderParameters : Vector.<ParameterAllocation>,
samplers : Vector.<int>)
{
_vsConstData = vertexShaderConstantData;
_fsConstData = fragmentShaderConstantData;
_vsParams = vertexShaderParameters;
_fsParams = fragmentShaderParameters;
_samplers = samplers;
super(vertexShader, fragmentShader, vertexInput);
if (_vsConstData.length > RegisterLimit.VS_MAX_CONSTANT * 4)
throw new Error();
if (_fsConstData.length > RegisterLimit.FG_MAX_CONSTANT * 4)
throw new Error();
}
public function fillRenderState(state : RendererState,
style : StyleStack,
local : LocalData,
world : Dictionary) : Boolean
{
setTextures(state, style, local, world);
setConstants(state, style, local, world);
state.shader = this;
return true;
}
protected function setTextures(state : RendererState,
styleStack : StyleStack,
localData : LocalData,
worldData : Object) : void
{
var texture : TextureRessource = 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 TextureRessource;
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(0, _vsConstData);
state.setFragmentConstants(0, _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;
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)
{
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.Minko;
import aerys.minko.ns.minko;
import aerys.minko.render.renderer.state.RendererState;
import aerys.minko.render.ressource.TextureRessource;
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.compiler.register.RegisterType;
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.visitor.data.LocalData;
import aerys.minko.scene.visitor.data.StyleStack;
import aerys.minko.type.log.DebugLevel;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
import aerys.minko.type.vertex.format.VertexComponent;
import flash.utils.ByteArray;
import flash.utils.Dictionary;
import aerys.minko.render.ressource.ShaderRessource;
public class Shader extends ShaderRessource
{
use namespace minko;
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 static function create(outputPosition : INode,
outputColor : INode) : Shader
{
var compiler : Compiler = new Compiler();
compiler.load(outputPosition, outputColor);
if (Minko.debugLevel & DebugLevel.SHADER_ATTR_ALLOC)
{
Minko.log(DebugLevel.SHADER_ATTR_ALLOC, compiler.writeAttributeAllocationSummary());
}
if (Minko.debugLevel & DebugLevel.SHADER_CONST_ALLOC)
{
Minko.log(DebugLevel.SHADER_CONST_ALLOC, compiler.writeConstantAllocationSummary(true));
Minko.log(DebugLevel.SHADER_CONST_ALLOC, compiler.writeConstantAllocationSummary(false));
}
if (Minko.debugLevel & DebugLevel.SHADER_AGAL)
{
Minko.log(DebugLevel.SHADER_AGAL, compiler.compileAgalVertexShader(), compiler);
Minko.log(DebugLevel.SHADER_AGAL, compiler.compileAgalFragmentShader(), compiler);
}
if (Minko.debugLevel & DebugLevel.SHADER_DOTTY)
{
Minko.log(DebugLevel.SHADER_DOTTY, compiler.writeDotGraph(), compiler);
}
return compiler.compileShader();
}
public function Shader(vertexShader : ByteArray,
fragmentShader : ByteArray,
vertexInput : Vector.<VertexComponent>,
vertexShaderConstantData : Vector.<Number>,
fragmentShaderConstantData : Vector.<Number>,
vertexShaderParameters : Vector.<ParameterAllocation>,
fragmentShaderParameters : Vector.<ParameterAllocation>,
samplers : Vector.<int>)
{
_vsConstData = vertexShaderConstantData;
_fsConstData = fragmentShaderConstantData;
_vsParams = vertexShaderParameters;
_fsParams = fragmentShaderParameters;
_samplers = samplers;
super(vertexShader, fragmentShader, vertexInput);
if (_vsConstData.length > RegisterLimit.VS_MAX_CONSTANT * 4)
throw new Error();
if (_fsConstData.length > RegisterLimit.FG_MAX_CONSTANT * 4)
throw new Error();
}
public function fillRenderState(state : RendererState,
style : StyleStack,
local : LocalData,
world : Dictionary) : Boolean
{
setTextures(state, style, local, world);
setConstants(state, style, local, world);
state.shader = this;
return true;
}
protected function setTextures(state : RendererState,
styleStack : StyleStack,
localData : LocalData,
worldData : Object) : void
{
var texture : TextureRessource = 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 TextureRessource;
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(0, _vsConstData);
state.setFragmentConstants(0, _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;
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 bug on uploading vector4 arrays shader parameters to renderStates
|
Fix bug on uploading vector4 arrays shader parameters to renderStates
|
ActionScript
|
mit
|
aerys/minko-as3
|
d91948e962c34375824688f28fb9aa4df6cf87b2
|
frameworks/projects/framework/src/mx/core/RuntimeDPIProvider.as
|
frameworks/projects/framework/src/mx/core/RuntimeDPIProvider.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 mx.core
{
import flash.display.DisplayObject;
import flash.display.Stage;
import flash.system.Capabilities;
import mx.core.mx_internal;
import mx.managers.SystemManager;
use namespace mx_internal;
/**
* The RuntimeDPIProvider class provides the default mapping of
* similar device DPI values into predefined DPI classes.
* An Application may have its runtimeDPIProvider property set to a
* subclass of RuntimeDPIProvider to override Flex's default mappings.
* Overriding Flex's default mappings will cause changes in the Application's
* automatic scaling behavior.
*
* <p>Overriding Flex's default mappings is usually only necessary for devices
* that incorrectly report their screenDPI and for devices that may scale better
* in a different DPI class.</p>
*
* <p>Flex's default mappings are:
* <table class="innertable">
* <tr><td>160 DPI</td><td><140 DPI</td></tr>
* <tr><td>160 DPI</td><td>>=140 DPI and <=200 DPI</td></tr>
* <tr><td>240 DPI</td><td>>=200 DPI and <=280 DPI</td></tr>
* <tr><td>320 DPI</td><td>>=280 DPI and <=400 DPI</td></tr>
* <tr><td>480 DPI</td><td>>=400 DPI and <=560 DPI</td></tr>
* <tr><td>640 DPI</td><td>>=640 DPI</td></tr>
* </table>
* </p>
*
*
*
* <p>Subclasses of RuntimeDPIProvider should only depend on runtime APIs
* and should not depend on any classes specific to the Flex framework except
* <code>mx.core.DPIClassification</code>.</p>
*
* @includeExample examples/RuntimeDPIProviderApp.mxml -noswf
* @includeExample examples/RuntimeDPIProviderExample.as -noswf
* @includeExample examples/views/RuntimeDPIProviderAppView.mxml -noswf
*
* @see mx.core.DPIClassification
* @see spark.components.Application#applicationDPI
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public class RuntimeDPIProvider
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public function RuntimeDPIProvider()
{
}
/**
* Returns the runtime DPI of the current device by mapping its
* <code>flash.system.Capabilities.screenDPI</code> to one of several DPI
* values in <code>mx.core.DPIClassification</code>.
*
* A number of devices can have slightly different DPI values and Flex maps these
* into the several DPI classes.
*
* Flex uses this method to calculate the current DPI value when an Application
* authored for a specific DPI is adapted to the current one through scaling.
*
* <p> Exceptions: </p>
* <ul>
* <li>All non-retina iPads receive 160 DPI </li>
* <li>All retina iPads receive 320 DPI </li>
* </ul>
*
* @param dpi The DPI value.
* @return The corresponding <code>DPIClassification</code> value.
* isI
* @see flash.system.Capabilities
* @see mx.core.DPIClassification
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public function get runtimeDPI():Number
{
var isIOS:Boolean = Capabilities.version.indexOf("IOS") == 0;
var screenDPI : Number= Capabilities.screenDPI;
if (isIOS) {
var root:DisplayObject = SystemManager.getSWFRoot(this);
if (root != null ) {
var stage:Stage = root.stage;
if (stage != null){
var scX:Number = stage.fullScreenWidth;
var scY:Number = stage.fullScreenHeight;
/* as of Dec 2013, iPad (resp. iPad retina) are the only iOS devices to have 1024 (resp. 2048) screen width or height
cf http://en.wikipedia.org/wiki/List_of_displays_by_pixel_density#Apple
* */
if ((scX == 2048 || scY == 2048))
return DPIClassification.DPI_320;
else if (scX == 1024 || scY == 1024)
return DPIClassification.DPI_160;
}
}
}
return classifyDPI(screenDPI);
}
/**
* @private
* Matches the specified DPI to a <code>DPIClassification</code> value.
* A number of devices can have slightly different DPI values and classifyDPI
* maps these into the several DPI classes.
*
* This method is specifically kept for Design View. Flex uses RuntimeDPIProvider
* to calculate DPI classes.
*
* @param dpi The DPI value.
* @return The corresponding <code>DPIClassification</code> value.
*/
mx_internal static function classifyDPI(dpi:Number):Number
{
if (dpi <= 140)
return DPIClassification.DPI_120;
if (dpi <= 200)
return DPIClassification.DPI_160;
if (dpi <= 280)
return DPIClassification.DPI_240;
if (dpi <= 400)
return DPIClassification.DPI_320;
if (dpi <= 560)
return DPIClassification.DPI_480;
return DPIClassification.DPI_640;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package mx.core
{
import flash.display.DisplayObject;
import flash.display.Stage;
import flash.system.Capabilities;
import mx.core.mx_internal;
import mx.managers.SystemManager;
use namespace mx_internal;
/**
* The RuntimeDPIProvider class provides the default mapping of
* similar device DPI values into predefined DPI classes.
* An Application may have its runtimeDPIProvider property set to a
* subclass of RuntimeDPIProvider to override Flex's default mappings.
* Overriding Flex's default mappings will cause changes in the Application's
* automatic scaling behavior.
*
* <p>Overriding Flex's default mappings is usually only necessary for devices
* that incorrectly report their screenDPI and for devices that may scale better
* in a different DPI class.</p>
*
* <p>Flex's default mappings are:
* <table class="innertable">
* <tr><td>160 DPI</td><td><140 DPI</td></tr>
* <tr><td>160 DPI</td><td>>=140 DPI and <=200 DPI</td></tr>
* <tr><td>240 DPI</td><td>>=200 DPI and <=280 DPI</td></tr>
* <tr><td>320 DPI</td><td>>=280 DPI and <=400 DPI</td></tr>
* <tr><td>480 DPI</td><td>>=400 DPI and <=560 DPI</td></tr>
* <tr><td>640 DPI</td><td>>=640 DPI</td></tr>
* </table>
* </p>
*
*
*
* <p>Subclasses of RuntimeDPIProvider should only depend on runtime APIs
* and should not depend on any classes specific to the Flex framework except
* <code>mx.core.DPIClassification</code>.</p>
*
* @includeExample examples/RuntimeDPIProviderApp.mxml -noswf
* @includeExample examples/RuntimeDPIProviderExample.as -noswf
* @includeExample examples/views/RuntimeDPIProviderAppView.mxml -noswf
*
* @see mx.core.DPIClassification
* @see spark.components.Application#applicationDPI
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public class RuntimeDPIProvider
{
mx_internal static const IPAD_MAX_EXTENT:int = 1024;
mx_internal static const IPAD_RETINA_MAX_EXTENT: int = 2048;
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public function RuntimeDPIProvider()
{
}
/**
* Returns the runtime DPI of the current device by mapping its
* <code>flash.system.Capabilities.screenDPI</code> to one of several DPI
* values in <code>mx.core.DPIClassification</code>.
*
* A number of devices can have slightly different DPI values and Flex maps these
* into the several DPI classes.
*
* Flex uses this method to calculate the current DPI value when an Application
* authored for a specific DPI is adapted to the current one through scaling.
*
* <p> Exceptions: </p>
* <ul>
* <li>All non-retina iPads receive 160 DPI </li>
* <li>All retina iPads receive 320 DPI </li>
* </ul>
*
* @param dpi The DPI value.
* @return The corresponding <code>DPIClassification</code> value.
* isI
* @see flash.system.Capabilities
* @see mx.core.DPIClassification
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public function get runtimeDPI():Number
{
var isIOS:Boolean = Capabilities.version.indexOf("IOS") == 0;
var screenDPI : Number= Capabilities.screenDPI;
if (isIOS) {
var root:DisplayObject = SystemManager.getSWFRoot(this);
if (root != null ) {
var stage:Stage = root.stage;
if (stage != null){
var scX:Number = stage.fullScreenWidth;
var scY:Number = stage.fullScreenHeight;
/* as of Dec 2013, iPad (resp. iPad retina) are the only iOS devices to have 1024 (resp. 2048) screen width or height
cf http://en.wikipedia.org/wiki/List_of_displays_by_pixel_density#Apple
* */
if ((scX == IPAD_RETINA_MAX_EXTENT || scY == IPAD_RETINA_MAX_EXTENT))
return DPIClassification.DPI_320;
else if (scX == IPAD_MAX_EXTENT || scY == IPAD_MAX_EXTENT)
return DPIClassification.DPI_160;
}
}
}
return classifyDPI(screenDPI);
}
/**
* @private
* Matches the specified DPI to a <code>DPIClassification</code> value.
* A number of devices can have slightly different DPI values and classifyDPI
* maps these into the several DPI classes.
*
* This method is specifically kept for Design View. Flex uses RuntimeDPIProvider
* to calculate DPI classes.
*
* @param dpi The DPI value.
* @return The corresponding <code>DPIClassification</code> value.
*/
mx_internal static function classifyDPI(dpi:Number):Number
{
if (dpi <= 140)
return DPIClassification.DPI_120;
if (dpi <= 200)
return DPIClassification.DPI_160;
if (dpi <= 280)
return DPIClassification.DPI_240;
if (dpi <= 400)
return DPIClassification.DPI_320;
if (dpi <= 560)
return DPIClassification.DPI_480;
return DPIClassification.DPI_640;
}
}
}
|
UPDATE FIX FLEX-33861 Flex Incorrectly Scaling Down Application set 1024 and 2048 as static vars so that they can be changed if needed
|
UPDATE FIX FLEX-33861 Flex Incorrectly Scaling Down Application
set 1024 and 2048 as static vars so that they can be changed if needed
|
ActionScript
|
apache-2.0
|
shyamalschandra/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk
|
0cd4a12c8ce23d4ab9dc5a8952fcc093536d7823
|
frameworks/projects/framework/src/mx/core/FlexVersion.as
|
frameworks/projects/framework/src/mx/core/FlexVersion.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 mx.core
{
import mx.resources.ResourceManager;
[ResourceBundle("core")]
/**
* This class controls the backward-compatibility of the framework.
* With every new release, some aspects of the framework such as behaviors,
* styles, and default settings, are changed which can affect your application.
* By setting the <code>compatibilityVersion</code> property, the behavior can be changed
* to match previous releases.
* This is a 'global' flag; you cannot apply one version to one component or group of components
* and a different version to another component or group of components.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public class FlexVersion
{
include "../core/Version.as";
//--------------------------------------------------------------------------
//
// Class constants
//
//--------------------------------------------------------------------------
/**
* The current released version of the Flex SDK, encoded as a uint.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static const CURRENT_VERSION:uint = 0x040B0000;
/**
* The <code>compatibilityVersion</code> value of Flex 4.11,
* encoded numerically as a <code>uint</code>.
* Code can compare this constant against
* the <code>compatibilityVersion</code>
* to implement version-specific behavior.
*
* @langversion 3.0
* @playerversion Flash 11
* @playerversion AIR 3
* @productversion Apache Flex 4.11
*/
public static const VERSION_4_11:uint = 0x040B0000;
/**
* The <code>compatibilityVersion</code> value of Flex 4.10,
* encoded numerically as a <code>uint</code>.
* Code can compare this constant against
* the <code>compatibilityVersion</code>
* to implement version-specific behavior.
*
* @langversion 3.0
* @playerversion Flash 11
* @playerversion AIR 3
* @productversion Apache Flex 4.10
*/
public static const VERSION_4_10:uint = 0x040A0000;
/**
* The <code>compatibilityVersion</code> value of Flex 4.9,
* encoded numerically as a <code>uint</code>.
* Code can compare this constant against
* the <code>compatibilityVersion</code>
* to implement version-specific behavior.
*
* @langversion 3.0
* @playerversion Flash 11
* @playerversion AIR 3
* @productversion Apache Flex 4.9
*/
public static const VERSION_4_9:uint = 0x04090000;
/**
* The <code>compatibilityVersion</code> value of Flex 4.8,
* encoded numerically as a <code>uint</code>.
* Code can compare this constant against
* the <code>compatibilityVersion</code>
* to implement version-specific behavior.
*
* @langversion 3.0
* @playerversion Flash 11
* @playerversion AIR 3
* @productversion Apache Flex 4.8
*/
public static const VERSION_4_8:uint = 0x04080000;
/**
* The <code>compatibilityVersion</code> value of Flex 4.6,
* encoded numerically as a <code>uint</code>.
* Code can compare this constant against
* the <code>compatibilityVersion</code>
* to implement version-specific behavior.
*
* @langversion 3.0
* @playerversion Flash 11
* @playerversion AIR 3
* @productversion Flex 4.6
*/
public static const VERSION_4_6:uint = 0x04060000;
/**
* The <code>compatibilityVersion</code> value of Flex 4.5,
* encoded numerically as a <code>uint</code>.
* Code can compare this constant against
* the <code>compatibilityVersion</code>
* to implement version-specific behavior.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static const VERSION_4_5:uint = 0x04050000;
/**
* The <code>compatibilityVersion</code> value of Flex 4.0,
* encoded numerically as a <code>uint</code>.
* Code can compare this constant against
* the <code>compatibilityVersion</code>
* to implement version-specific behavior.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static const VERSION_4_0:uint = 0x04000000;
/**
* The <code>compatibilityVersion</code> value of Flex 3.0,
* encoded numerically as a <code>uint</code>.
* Code can compare this constant against
* the <code>compatibilityVersion</code>
* to implement version-specific behavior.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static const VERSION_3_0:uint = 0x03000000;
/**
* The <code>compatibilityVersion</code> value of Flex 2.0.1,
* encoded numerically as a <code>uint</code>.
* Code can compare this constant against
* the <code>compatibilityVersion</code>
* to implement version-specific behavior.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static const VERSION_2_0_1:uint = 0x02000001;
/**
* The <code>compatibilityVersion</code> value of Flex 2.0,
* encoded numerically as a <code>uint</code>.
* Code can compare this constant against
* the <code>compatibilityVersion</code>
* to implement version-specific behavior.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static const VERSION_2_0:uint = 0x02000000;
/**
* A String passed as a parameter
* to the <code>compatibilityErrorFunction()</code> method
* if the compatibility version has already been set.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static const VERSION_ALREADY_SET:String = "versionAlreadySet";
// Also used as resource string, so be careful changing it.
/**
* A String passed as a parameter
* to the <code>compatibilityErrorFunction()</code> method
* if the compatibility version has already been read.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static const VERSION_ALREADY_READ:String = "versionAlreadyRead";
// Also used as resource string, so be careful changing it.
//--------------------------------------------------------------------------
//
// Class properties
//
//--------------------------------------------------------------------------
//----------------------------------
// compatibilityErrorFunction
//----------------------------------
/**
* @private
* Storage for the compatibilityErrorFunction property.
*/
private static var _compatibilityErrorFunction:Function;
/**
* A function that gets called when the compatibility version
* is set more than once, or set after it has been read.
* If this function is not set, the SDK throws an error.
* If set, File calls this function, but it is
* up to the developer to decide how to handle the call.
* This function will also be called if the function is set more than once.
* The function takes two parameters: the first is a <code>uint</code>
* which is the version that was attempted to be set; the second
* is a string that is the reason it failed, either
* <code>VERSION_ALREADY_SET</code> or <code>VERSION_ALREADY_READ</code>.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static function get compatibilityErrorFunction():Function
{
return _compatibilityErrorFunction;
}
/**
* @private
*/
public static function set compatibilityErrorFunction(value:Function):void
{
_compatibilityErrorFunction = value;
}
//----------------------------------
// compatibilityVersion
//----------------------------------
/**
* @private
* Storage for the compatibilityVersion property.
*/
private static var _compatibilityVersion:uint = CURRENT_VERSION;
/**
* @private
*/
private static var compatibilityVersionChanged:Boolean = false;
/**
* @private
*/
private static var compatibilityVersionRead:Boolean = false;
/**
* The current version that the framework maintains compatibility for.
* This defaults to <code>CURRENT_VERSION</code>.
* It can be changed only once; changing it a second time
* results in a call to the <code>compatibilityErrorFunction()</code> method
* if it exists, or results in a runtime error.
* Changing it after the <code>compatibilityVersion</code> property has been read results in an error
* because code that is dependent on the version has already run.
* There are no notifications; the assumption is that this is set only once, and this it is set
* early enough that no code that depends on it has run yet.
*
* @default FlexVersion.CURRENT_VERSION
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static function get compatibilityVersion():uint
{
compatibilityVersionRead = true;
return _compatibilityVersion;
}
/**
* @private
*/
public static function set compatibilityVersion(value:uint):void
{
if (value == _compatibilityVersion)
return;
var s:String;
if (compatibilityVersionChanged)
{
if (compatibilityErrorFunction == null)
{
s = ResourceManager.getInstance().getString(
"core", VERSION_ALREADY_SET);
throw new Error(s);
}
else
compatibilityErrorFunction(value, VERSION_ALREADY_SET);
}
if (compatibilityVersionRead)
{
if (compatibilityErrorFunction == null)
{
s = ResourceManager.getInstance().getString(
"core", VERSION_ALREADY_READ);
throw new Error(s);
}
else
compatibilityErrorFunction(value, VERSION_ALREADY_READ);
}
_compatibilityVersion = value;
compatibilityVersionChanged = true;
}
//----------------------------------
// compatibilityVersionString
//----------------------------------
/**
* The compatibility version, as a string of the form "X.X.X".
* This is a pass-through to the <code>compatibilityVersion</code>
* property, which converts the number to and from a more
* human-readable String version.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static function get compatibilityVersionString():String
{
var major:uint = (compatibilityVersion >> 24) & 0xFF;
var minor:uint = (compatibilityVersion >> 16) & 0xFF;
var update:uint = compatibilityVersion & 0xFFFF;
return major.toString() + "." +
minor.toString() + "." +
update.toString();
}
/**
* @private
*/
public static function set compatibilityVersionString(value:String):void
{
var pieces:Array = value.split(".");
var major:uint = parseInt(pieces[0]);
var minor:uint = parseInt(pieces[1]);
var update:uint = parseInt(pieces[2]);
compatibilityVersion = (major << 24) + (minor << 16) + update;
}
/**
* @private
* A back door for changing the compatibility version.
* This is provided for Flash Builder's Design View,
* which needs to be able to change compatibility mode.
* In general, we won't support late changes to compatibility,
* because the framework won't watch for changes.
* Design View will need to set this early during initialization.
*/
mx_internal static function changeCompatibilityVersionString(
value:String):void
{
var pieces:Array = value.split(".");
var major:uint = parseInt(pieces[0]);
var minor:uint = parseInt(pieces[1]);
var update:uint = parseInt(pieces[2]);
_compatibilityVersion = (major << 24) + (minor << 16) + update;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package mx.core
{
import mx.resources.ResourceManager;
[ResourceBundle("core")]
/**
* This class controls the backward-compatibility of the framework.
* With every new release, some aspects of the framework such as behaviors,
* styles, and default settings, are changed which can affect your application.
* By setting the <code>compatibilityVersion</code> property, the behavior can be changed
* to match previous releases.
* This is a 'global' flag; you cannot apply one version to one component or group of components
* and a different version to another component or group of components.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public class FlexVersion
{
include "../core/Version.as";
//--------------------------------------------------------------------------
//
// Class constants
//
//--------------------------------------------------------------------------
/**
* The current released version of the Flex SDK, encoded as a uint.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static const CURRENT_VERSION:uint = 0x040C0000;
/**
* The <code>compatibilityVersion</code> value of Flex 4.12,
* encoded numerically as a <code>uint</code>.
* Code can compare this constant against
* the <code>compatibilityVersion</code>
* to implement version-specific behavior.
*
* @langversion 3.0
* @playerversion Flash 11
* @playerversion AIR 3
* @productversion Apache Flex 4.12
*/
public static const VERSION_4_12:uint = 0x040C0000;
/**
* The <code>compatibilityVersion</code> value of Flex 4.11,
* encoded numerically as a <code>uint</code>.
* Code can compare this constant against
* the <code>compatibilityVersion</code>
* to implement version-specific behavior.
*
* @langversion 3.0
* @playerversion Flash 11
* @playerversion AIR 3
* @productversion Apache Flex 4.11
*/
public static const VERSION_4_11:uint = 0x040B0000;
/**
* The <code>compatibilityVersion</code> value of Flex 4.10,
* encoded numerically as a <code>uint</code>.
* Code can compare this constant against
* the <code>compatibilityVersion</code>
* to implement version-specific behavior.
*
* @langversion 3.0
* @playerversion Flash 11
* @playerversion AIR 3
* @productversion Apache Flex 4.10
*/
public static const VERSION_4_10:uint = 0x040A0000;
/**
* The <code>compatibilityVersion</code> value of Flex 4.9,
* encoded numerically as a <code>uint</code>.
* Code can compare this constant against
* the <code>compatibilityVersion</code>
* to implement version-specific behavior.
*
* @langversion 3.0
* @playerversion Flash 11
* @playerversion AIR 3
* @productversion Apache Flex 4.9
*/
public static const VERSION_4_9:uint = 0x04090000;
/**
* The <code>compatibilityVersion</code> value of Flex 4.8,
* encoded numerically as a <code>uint</code>.
* Code can compare this constant against
* the <code>compatibilityVersion</code>
* to implement version-specific behavior.
*
* @langversion 3.0
* @playerversion Flash 11
* @playerversion AIR 3
* @productversion Apache Flex 4.8
*/
public static const VERSION_4_8:uint = 0x04080000;
/**
* The <code>compatibilityVersion</code> value of Flex 4.6,
* encoded numerically as a <code>uint</code>.
* Code can compare this constant against
* the <code>compatibilityVersion</code>
* to implement version-specific behavior.
*
* @langversion 3.0
* @playerversion Flash 11
* @playerversion AIR 3
* @productversion Flex 4.6
*/
public static const VERSION_4_6:uint = 0x04060000;
/**
* The <code>compatibilityVersion</code> value of Flex 4.5,
* encoded numerically as a <code>uint</code>.
* Code can compare this constant against
* the <code>compatibilityVersion</code>
* to implement version-specific behavior.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static const VERSION_4_5:uint = 0x04050000;
/**
* The <code>compatibilityVersion</code> value of Flex 4.0,
* encoded numerically as a <code>uint</code>.
* Code can compare this constant against
* the <code>compatibilityVersion</code>
* to implement version-specific behavior.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static const VERSION_4_0:uint = 0x04000000;
/**
* The <code>compatibilityVersion</code> value of Flex 3.0,
* encoded numerically as a <code>uint</code>.
* Code can compare this constant against
* the <code>compatibilityVersion</code>
* to implement version-specific behavior.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static const VERSION_3_0:uint = 0x03000000;
/**
* The <code>compatibilityVersion</code> value of Flex 2.0.1,
* encoded numerically as a <code>uint</code>.
* Code can compare this constant against
* the <code>compatibilityVersion</code>
* to implement version-specific behavior.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static const VERSION_2_0_1:uint = 0x02000001;
/**
* The <code>compatibilityVersion</code> value of Flex 2.0,
* encoded numerically as a <code>uint</code>.
* Code can compare this constant against
* the <code>compatibilityVersion</code>
* to implement version-specific behavior.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static const VERSION_2_0:uint = 0x02000000;
/**
* A String passed as a parameter
* to the <code>compatibilityErrorFunction()</code> method
* if the compatibility version has already been set.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static const VERSION_ALREADY_SET:String = "versionAlreadySet";
// Also used as resource string, so be careful changing it.
/**
* A String passed as a parameter
* to the <code>compatibilityErrorFunction()</code> method
* if the compatibility version has already been read.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static const VERSION_ALREADY_READ:String = "versionAlreadyRead";
// Also used as resource string, so be careful changing it.
//--------------------------------------------------------------------------
//
// Class properties
//
//--------------------------------------------------------------------------
//----------------------------------
// compatibilityErrorFunction
//----------------------------------
/**
* @private
* Storage for the compatibilityErrorFunction property.
*/
private static var _compatibilityErrorFunction:Function;
/**
* A function that gets called when the compatibility version
* is set more than once, or set after it has been read.
* If this function is not set, the SDK throws an error.
* If set, File calls this function, but it is
* up to the developer to decide how to handle the call.
* This function will also be called if the function is set more than once.
* The function takes two parameters: the first is a <code>uint</code>
* which is the version that was attempted to be set; the second
* is a string that is the reason it failed, either
* <code>VERSION_ALREADY_SET</code> or <code>VERSION_ALREADY_READ</code>.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static function get compatibilityErrorFunction():Function
{
return _compatibilityErrorFunction;
}
/**
* @private
*/
public static function set compatibilityErrorFunction(value:Function):void
{
_compatibilityErrorFunction = value;
}
//----------------------------------
// compatibilityVersion
//----------------------------------
/**
* @private
* Storage for the compatibilityVersion property.
*/
private static var _compatibilityVersion:uint = CURRENT_VERSION;
/**
* @private
*/
private static var compatibilityVersionChanged:Boolean = false;
/**
* @private
*/
private static var compatibilityVersionRead:Boolean = false;
/**
* The current version that the framework maintains compatibility for.
* This defaults to <code>CURRENT_VERSION</code>.
* It can be changed only once; changing it a second time
* results in a call to the <code>compatibilityErrorFunction()</code> method
* if it exists, or results in a runtime error.
* Changing it after the <code>compatibilityVersion</code> property has been read results in an error
* because code that is dependent on the version has already run.
* There are no notifications; the assumption is that this is set only once, and this it is set
* early enough that no code that depends on it has run yet.
*
* @default FlexVersion.CURRENT_VERSION
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static function get compatibilityVersion():uint
{
compatibilityVersionRead = true;
return _compatibilityVersion;
}
/**
* @private
*/
public static function set compatibilityVersion(value:uint):void
{
if (value == _compatibilityVersion)
return;
var s:String;
if (compatibilityVersionChanged)
{
if (compatibilityErrorFunction == null)
{
s = ResourceManager.getInstance().getString(
"core", VERSION_ALREADY_SET);
throw new Error(s);
}
else
compatibilityErrorFunction(value, VERSION_ALREADY_SET);
}
if (compatibilityVersionRead)
{
if (compatibilityErrorFunction == null)
{
s = ResourceManager.getInstance().getString(
"core", VERSION_ALREADY_READ);
throw new Error(s);
}
else
compatibilityErrorFunction(value, VERSION_ALREADY_READ);
}
_compatibilityVersion = value;
compatibilityVersionChanged = true;
}
//----------------------------------
// compatibilityVersionString
//----------------------------------
/**
* The compatibility version, as a string of the form "X.X.X".
* This is a pass-through to the <code>compatibilityVersion</code>
* property, which converts the number to and from a more
* human-readable String version.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static function get compatibilityVersionString():String
{
var major:uint = (compatibilityVersion >> 24) & 0xFF;
var minor:uint = (compatibilityVersion >> 16) & 0xFF;
var update:uint = compatibilityVersion & 0xFFFF;
return major.toString() + "." +
minor.toString() + "." +
update.toString();
}
/**
* @private
*/
public static function set compatibilityVersionString(value:String):void
{
var pieces:Array = value.split(".");
var major:uint = parseInt(pieces[0]);
var minor:uint = parseInt(pieces[1]);
var update:uint = parseInt(pieces[2]);
compatibilityVersion = (major << 24) + (minor << 16) + update;
}
/**
* @private
* A back door for changing the compatibility version.
* This is provided for Flash Builder's Design View,
* which needs to be able to change compatibility mode.
* In general, we won't support late changes to compatibility,
* because the framework won't watch for changes.
* Design View will need to set this early during initialization.
*/
mx_internal static function changeCompatibilityVersionString(
value:String):void
{
var pieces:Array = value.split(".");
var major:uint = parseInt(pieces[0]);
var minor:uint = parseInt(pieces[1]);
var update:uint = parseInt(pieces[2]);
_compatibilityVersion = (major << 24) + (minor << 16) + update;
}
}
}
|
Make 4.12 the new version
|
Make 4.12 the new version
|
ActionScript
|
apache-2.0
|
danteinforno/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk
|
88dbd76509787f0f8e9298cb5485c95575d412bb
|
src/org/mangui/hls/loader/LevelLoader.as
|
src/org/mangui/hls/loader/LevelLoader.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.loader {
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.utils.clearTimeout;
import flash.utils.getTimer;
import flash.utils.setTimeout;
import org.mangui.hls.constant.HLSLoaderTypes;
import org.mangui.hls.constant.HLSPlayStates;
import org.mangui.hls.constant.HLSTypes;
import org.mangui.hls.event.HLSError;
import org.mangui.hls.event.HLSEvent;
import org.mangui.hls.event.HLSLoadMetrics;
import org.mangui.hls.HLS;
import org.mangui.hls.HLSSettings;
import org.mangui.hls.model.Fragment;
import org.mangui.hls.model.Level;
import org.mangui.hls.playlist.AltAudioTrack;
import org.mangui.hls.playlist.DataUri;
import org.mangui.hls.playlist.Manifest;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
public class LevelLoader {
/** Reference to the hls framework controller. **/
private var _hls : HLS;
/** levels vector. **/
private var _levels : Vector.<Level>;
/** Object that fetches the manifest. **/
private var _urlloader : URLLoader;
/** Link to the M3U8 file. **/
private var _url : String;
/** are all playlists filled ? **/
private var _canStart : Boolean;
/** Timeout ID for reloading live playlists. **/
private var _timeoutID : uint;
/** Streaming type (live, ondemand). **/
private var _type : String;
/** last reload manifest time **/
private var _reloadPlaylistTimer : uint;
/** current load level **/
private var _loadLevel : int;
/** reference to manifest being loaded **/
private var _manifestLoading : Manifest;
/** is this loader closed **/
private var _closed : Boolean = false;
/* playlist retry timeout */
private var _retryTimeout : Number;
private var _retryCount : int;
/* alt audio tracks */
private var _altAudioTracks : Vector.<AltAudioTrack>;
/* manifest load metrics */
private var _metrics : HLSLoadMetrics;
/** Setup the loader. **/
public function LevelLoader(hls : HLS) {
_hls = hls;
_hls.addEventListener(HLSEvent.PLAYBACK_STATE, _stateHandler);
_hls.addEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler);
_levels = new Vector.<Level>();
};
public function dispose() : void {
_close();
if(_urlloader) {
_urlloader.removeEventListener(Event.COMPLETE, _loadCompleteHandler);
_urlloader.removeEventListener(ProgressEvent.PROGRESS, _loadProgressHandler);
_urlloader.removeEventListener(IOErrorEvent.IO_ERROR, _errorHandler);
_urlloader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, _errorHandler);
_urlloader = null;
}
_hls.removeEventListener(HLSEvent.PLAYBACK_STATE, _stateHandler);
_hls.removeEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler);
}
/** Loading failed; return errors. **/
private function _errorHandler(event : ErrorEvent) : void {
var txt : String;
var code : int;
if (event is SecurityErrorEvent) {
code = HLSError.MANIFEST_LOADING_CROSSDOMAIN_ERROR;
txt = "Cannot load M3U8: crossdomain access denied:" + event.text;
} else if (event is IOErrorEvent && _levels.length && (HLSSettings.manifestLoadMaxRetry == -1 || _retryCount < HLSSettings.manifestLoadMaxRetry)) {
CONFIG::LOGGING {
Log.warn("I/O Error while trying to load Playlist, retry in " + _retryTimeout + " ms");
}
_timeoutID = setTimeout(_loadActiveLevelPlaylist, _retryTimeout);
/* exponential increase of retry timeout, capped to manifestLoadMaxRetryTimeout */
_retryTimeout = Math.min(HLSSettings.manifestLoadMaxRetryTimeout, 2 * _retryTimeout);
_retryCount++;
return;
} else {
code = HLSError.MANIFEST_LOADING_IO_ERROR;
txt = "Cannot load M3U8: " + event.text;
}
var hlsError : HLSError = new HLSError(code, _url, txt);
_hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, hlsError));
};
/** Return the current manifest. **/
public function get levels() : Vector.<Level> {
return _levels;
};
/** Return the stream type. **/
public function get type() : String {
return _type;
};
public function get altAudioTracks() : Vector.<AltAudioTrack> {
return _altAudioTracks;
}
/** Load the manifest file. **/
public function load(url : String) : void {
if(!_urlloader) {
//_urlloader = new URLLoader();
var urlLoaderClass : Class = _hls.URLloader as Class;
_urlloader = (new urlLoaderClass()) as URLLoader;
_urlloader.addEventListener(Event.COMPLETE, _loadCompleteHandler);
_urlloader.addEventListener(ProgressEvent.PROGRESS, _loadProgressHandler);
_urlloader.addEventListener(IOErrorEvent.IO_ERROR, _errorHandler);
_urlloader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, _errorHandler);
}
_close();
_closed = false;
_url = url;
_levels = new Vector.<Level>();
_canStart = false;
_reloadPlaylistTimer = getTimer();
_retryTimeout = 1000;
_retryCount = 0;
_altAudioTracks = null;
_hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_LOADING, url));
_metrics = new HLSLoadMetrics(HLSLoaderTypes.MANIFEST);
_metrics.loading_request_time = getTimer();
if (DataUri.isDataUri(url)) {
CONFIG::LOGGING {
Log.debug("Identified main manifest <" + url + "> as a data URI.");
}
_metrics.loading_begin_time = getTimer();
var data : String = new DataUri(url).extractData();
_metrics.loading_end_time = getTimer();
_parseManifest(data || "");
} else {
_urlloader.load(new URLRequest(url));
}
};
/** loading progress handler, use to determine loading latency **/
private function _loadProgressHandler(event : Event) : void {
if(_metrics.loading_begin_time == 0) {
_metrics.loading_begin_time = getTimer();
}
};
/** Manifest loaded; check and parse it **/
private function _loadCompleteHandler(event : Event) : void {
_metrics.loading_end_time = getTimer();
// successful loading, reset retry counter
_retryTimeout = 1000;
_retryCount = 0;
_parseManifest(String(_urlloader.data));
};
/** parse a playlist **/
private function _parseLevelPlaylist(string : String, url : String, level : int, metrics : HLSLoadMetrics) : void {
if (string != null && string.length != 0) {
CONFIG::LOGGING {
Log.debug("level " + level + " playlist:\n" + string);
}
var frags : Vector.<Fragment> = Manifest.getFragments(string, url, level);
// set fragment and update sequence number range
_levels[level].updateFragments(frags);
_levels[level].targetduration = Manifest.getTargetDuration(string);
_hls.dispatchEvent(new HLSEvent(HLSEvent.PLAYLIST_DURATION_UPDATED, _levels[level].duration));
}
// Check whether the stream is live or not finished yet
if (Manifest.hasEndlist(string)) {
_type = HLSTypes.VOD;
_hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_ENDLIST, level));
} else {
_type = HLSTypes.LIVE;
/* in order to determine playlist reload timer,
check playback position against playlist duration.
if we are near the edge of a live playlist, reload playlist quickly
to discover quicker new fragments and avoid buffer starvation.
*/
var _reloadInterval : Number = 1000*Math.min((_levels[level].duration - _hls.position)/2,_levels[level].averageduration);
// avoid spamming the server if we are at the edge ... wait 500ms between 2 reload at least
var timeout : Number = Math.max(500, _reloadPlaylistTimer + _reloadInterval - getTimer());
CONFIG::LOGGING {
Log.debug("Level " + level + " Live Playlist parsing finished: reload in " + timeout.toFixed(0) + " ms");
}
_timeoutID = setTimeout(_loadActiveLevelPlaylist, timeout);
}
if (!_canStart) {
_canStart = (_levels[level].fragments.length > 0);
if (_canStart) {
CONFIG::LOGGING {
Log.debug("first level filled with at least 1 fragment, notify event");
}
_hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_LOADED, _levels, _metrics));
}
}
metrics.id = _levels[level].start_seqnum;
metrics.id2 = _levels[level].end_seqnum;
_hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_LOADED, metrics));
_manifestLoading = null;
};
/** Parse First Level Playlist **/
private function _parseManifest(string : String) : void {
// Check for M3U8 playlist or manifest.
if (string.indexOf(Manifest.HEADER) == 0) {
// 1 level playlist, create unique level and parse playlist
if (string.indexOf(Manifest.FRAGMENT) > 0) {
var level : Level = new Level();
level.url = _url;
_levels.push(level);
_metrics.parsing_end_time = getTimer();
_hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_PARSED, _levels));
_hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_LOADING, 0));
CONFIG::LOGGING {
Log.debug("1 Level Playlist, load it");
}
_loadLevel = 0;
_metrics.type = HLSLoaderTypes.LEVEL_MAIN;
_parseLevelPlaylist(string, _url, 0,_metrics);
} else if (string.indexOf(Manifest.LEVEL) > 0) {
CONFIG::LOGGING {
Log.debug("adaptive playlist:\n" + string);
}
// adaptative playlist, extract levels from playlist, get them and parse them
_levels = Manifest.extractLevels(string, _url);
var levelsLength : int = _levels.length;
if (levelsLength == 0) {
hlsError = new HLSError(HLSError.MANIFEST_PARSING_ERROR, _url, "No level found in Manifest");
_hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, hlsError));
}
_metrics.parsing_end_time = getTimer();
_loadLevel = -1;
_hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_PARSED, _levels));
if (string.indexOf(Manifest.ALTERNATE_AUDIO) > 0) {
CONFIG::LOGGING {
Log.debug("alternate audio level found");
}
// parse alternate audio tracks
_altAudioTracks = Manifest.extractAltAudioTracks(string, _url);
CONFIG::LOGGING {
if (_altAudioTracks.length > 0) {
Log.debug(_altAudioTracks.length + " alternate audio tracks found");
}
}
}
}
} else {
var hlsError : HLSError = new HLSError(HLSError.MANIFEST_PARSING_ERROR, _url, "Manifest is not a valid M3U8 file");
_hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, hlsError));
}
};
/** load/reload active M3U8 playlist **/
private function _loadActiveLevelPlaylist() : void {
if (_closed) {
return;
}
_reloadPlaylistTimer = getTimer();
// load active M3U8 playlist only
_manifestLoading = new Manifest();
_hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_LOADING, _loadLevel));
_manifestLoading.loadPlaylist(_hls,_levels[_loadLevel].url, _parseLevelPlaylist, _errorHandler, _loadLevel, _type, HLSSettings.flushLiveURLCache);
};
/** When level switch occurs, assess the need of (re)loading new level playlist **/
private function _levelSwitchHandler(event : HLSEvent) : void {
if (_loadLevel != event.level) {
_loadLevel = event.level;
CONFIG::LOGGING {
Log.debug("switch to level " + _loadLevel);
}
if (_type == HLSTypes.LIVE || _levels[_loadLevel].fragments.length == 0) {
_closed = false;
CONFIG::LOGGING {
Log.debug("(re)load Playlist");
}
if(_manifestLoading) {
_manifestLoading.close();
_manifestLoading = null;
}
clearTimeout(_timeoutID);
_timeoutID = setTimeout(_loadActiveLevelPlaylist, 0);
}
}
};
private function _close() : void {
CONFIG::LOGGING {
Log.debug("cancel any manifest load in progress");
}
_closed = true;
clearTimeout(_timeoutID);
try {
_urlloader.close();
if (_manifestLoading) {
_manifestLoading.close();
}
} catch(e : Error) {
}
}
/** When the framework idles out, stop reloading manifest **/
private function _stateHandler(event : HLSEvent) : void {
if (event.state == HLSPlayStates.IDLE) {
_close();
}
};
}
}
|
/* 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.loader {
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.utils.clearTimeout;
import flash.utils.getTimer;
import flash.utils.setTimeout;
import org.mangui.hls.constant.HLSLoaderTypes;
import org.mangui.hls.constant.HLSPlayStates;
import org.mangui.hls.constant.HLSTypes;
import org.mangui.hls.event.HLSError;
import org.mangui.hls.event.HLSEvent;
import org.mangui.hls.event.HLSLoadMetrics;
import org.mangui.hls.HLS;
import org.mangui.hls.HLSSettings;
import org.mangui.hls.model.Fragment;
import org.mangui.hls.model.Level;
import org.mangui.hls.playlist.AltAudioTrack;
import org.mangui.hls.playlist.DataUri;
import org.mangui.hls.playlist.Manifest;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
public class LevelLoader {
/** Reference to the hls framework controller. **/
private var _hls : HLS;
/** levels vector. **/
private var _levels : Vector.<Level>;
/** Object that fetches the manifest. **/
private var _urlloader : URLLoader;
/** Link to the M3U8 file. **/
private var _url : String;
/** are all playlists filled ? **/
private var _canStart : Boolean;
/** Timeout ID for reloading live playlists. **/
private var _timeoutID : uint;
/** Streaming type (live, ondemand). **/
private var _type : String;
/** last reload manifest time **/
private var _reloadPlaylistTimer : uint;
/** current load level **/
private var _loadLevel : int;
/** reference to manifest being loaded **/
private var _manifestLoading : Manifest;
/** is this loader closed **/
private var _closed : Boolean = false;
/* playlist retry timeout */
private var _retryTimeout : Number;
private var _retryCount : int;
/* alt audio tracks */
private var _altAudioTracks : Vector.<AltAudioTrack>;
/* manifest load metrics */
private var _metrics : HLSLoadMetrics;
/** Setup the loader. **/
public function LevelLoader(hls : HLS) {
_hls = hls;
_hls.addEventListener(HLSEvent.PLAYBACK_STATE, _stateHandler);
_hls.addEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler);
_levels = new Vector.<Level>();
};
public function dispose() : void {
_close();
if(_urlloader) {
_urlloader.removeEventListener(Event.COMPLETE, _loadCompleteHandler);
_urlloader.removeEventListener(ProgressEvent.PROGRESS, _loadProgressHandler);
_urlloader.removeEventListener(IOErrorEvent.IO_ERROR, _errorHandler);
_urlloader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, _errorHandler);
_urlloader = null;
}
_hls.removeEventListener(HLSEvent.PLAYBACK_STATE, _stateHandler);
_hls.removeEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler);
}
/** Loading failed; return errors. **/
private function _errorHandler(event : ErrorEvent) : void {
var txt : String;
var code : int;
if (event is SecurityErrorEvent) {
code = HLSError.MANIFEST_LOADING_CROSSDOMAIN_ERROR;
txt = "Cannot load M3U8: crossdomain access denied:" + event.text;
} else if (event is IOErrorEvent && _levels.length && (HLSSettings.manifestLoadMaxRetry == -1 || _retryCount < HLSSettings.manifestLoadMaxRetry)) {
CONFIG::LOGGING {
Log.warn("I/O Error while trying to load Playlist, retry in " + _retryTimeout + " ms");
}
_timeoutID = setTimeout(_loadActiveLevelPlaylist, _retryTimeout);
/* exponential increase of retry timeout, capped to manifestLoadMaxRetryTimeout */
_retryTimeout = Math.min(HLSSettings.manifestLoadMaxRetryTimeout, 2 * _retryTimeout);
_retryCount++;
return;
} else {
code = HLSError.MANIFEST_LOADING_IO_ERROR;
txt = "Cannot load M3U8: " + event.text;
}
var hlsError : HLSError = new HLSError(code, _url, txt);
_hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, hlsError));
};
/** Return the current manifest. **/
public function get levels() : Vector.<Level> {
return _levels;
};
/** Return the stream type. **/
public function get type() : String {
return _type;
};
public function get altAudioTracks() : Vector.<AltAudioTrack> {
return _altAudioTracks;
}
/** Load the manifest file. **/
public function load(url : String) : void {
if(!_urlloader) {
//_urlloader = new URLLoader();
var urlLoaderClass : Class = _hls.URLloader as Class;
_urlloader = (new urlLoaderClass()) as URLLoader;
_urlloader.addEventListener(Event.COMPLETE, _loadCompleteHandler);
_urlloader.addEventListener(ProgressEvent.PROGRESS, _loadProgressHandler);
_urlloader.addEventListener(IOErrorEvent.IO_ERROR, _errorHandler);
_urlloader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, _errorHandler);
}
_close();
_closed = false;
_url = url;
_levels = new Vector.<Level>();
_canStart = false;
_reloadPlaylistTimer = getTimer();
_retryTimeout = 1000;
_retryCount = 0;
_altAudioTracks = null;
_hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_LOADING, url));
_metrics = new HLSLoadMetrics(HLSLoaderTypes.MANIFEST);
_metrics.loading_request_time = getTimer();
if (DataUri.isDataUri(url)) {
CONFIG::LOGGING {
Log.debug("Identified main manifest <" + url + "> as a data URI.");
}
_metrics.loading_begin_time = getTimer();
var data : String = new DataUri(url).extractData();
_metrics.loading_end_time = getTimer();
_parseManifest(data || "");
} else {
_urlloader.load(new URLRequest(url));
}
};
/** loading progress handler, use to determine loading latency **/
private function _loadProgressHandler(event : Event) : void {
if(_metrics.loading_begin_time == 0) {
_metrics.loading_begin_time = getTimer();
}
};
/** Manifest loaded; check and parse it **/
private function _loadCompleteHandler(event : Event) : void {
_metrics.loading_end_time = getTimer();
// successful loading, reset retry counter
_retryTimeout = 1000;
_retryCount = 0;
_parseManifest(String(_urlloader.data));
};
/** parse a playlist **/
private function _parseLevelPlaylist(string : String, url : String, level : int, metrics : HLSLoadMetrics) : void {
if (string != null && string.length != 0) {
// successful loading, reset retry counter
_retryTimeout = 1000;
_retryCount = 0;
CONFIG::LOGGING {
Log.debug("level " + level + " playlist:\n" + string);
}
var frags : Vector.<Fragment> = Manifest.getFragments(string, url, level);
// set fragment and update sequence number range
_levels[level].updateFragments(frags);
_levels[level].targetduration = Manifest.getTargetDuration(string);
_hls.dispatchEvent(new HLSEvent(HLSEvent.PLAYLIST_DURATION_UPDATED, _levels[level].duration));
}
// Check whether the stream is live or not finished yet
if (Manifest.hasEndlist(string)) {
_type = HLSTypes.VOD;
_hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_ENDLIST, level));
} else {
_type = HLSTypes.LIVE;
/* in order to determine playlist reload timer,
check playback position against playlist duration.
if we are near the edge of a live playlist, reload playlist quickly
to discover quicker new fragments and avoid buffer starvation.
*/
var _reloadInterval : Number = 1000*Math.min((_levels[level].duration - _hls.position)/2,_levels[level].averageduration);
// avoid spamming the server if we are at the edge ... wait 500ms between 2 reload at least
var timeout : Number = Math.max(500, _reloadPlaylistTimer + _reloadInterval - getTimer());
CONFIG::LOGGING {
Log.debug("Level " + level + " Live Playlist parsing finished: reload in " + timeout.toFixed(0) + " ms");
}
_timeoutID = setTimeout(_loadActiveLevelPlaylist, timeout);
}
if (!_canStart) {
_canStart = (_levels[level].fragments.length > 0);
if (_canStart) {
CONFIG::LOGGING {
Log.debug("first level filled with at least 1 fragment, notify event");
}
_hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_LOADED, _levels, _metrics));
}
}
metrics.id = _levels[level].start_seqnum;
metrics.id2 = _levels[level].end_seqnum;
_hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_LOADED, metrics));
_manifestLoading = null;
};
/** Parse First Level Playlist **/
private function _parseManifest(string : String) : void {
// Check for M3U8 playlist or manifest.
if (string.indexOf(Manifest.HEADER) == 0) {
// 1 level playlist, create unique level and parse playlist
if (string.indexOf(Manifest.FRAGMENT) > 0) {
var level : Level = new Level();
level.url = _url;
_levels.push(level);
_metrics.parsing_end_time = getTimer();
_hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_PARSED, _levels));
_hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_LOADING, 0));
CONFIG::LOGGING {
Log.debug("1 Level Playlist, load it");
}
_loadLevel = 0;
_metrics.type = HLSLoaderTypes.LEVEL_MAIN;
_parseLevelPlaylist(string, _url, 0,_metrics);
} else if (string.indexOf(Manifest.LEVEL) > 0) {
CONFIG::LOGGING {
Log.debug("adaptive playlist:\n" + string);
}
// adaptative playlist, extract levels from playlist, get them and parse them
_levels = Manifest.extractLevels(string, _url);
var levelsLength : int = _levels.length;
if (levelsLength == 0) {
hlsError = new HLSError(HLSError.MANIFEST_PARSING_ERROR, _url, "No level found in Manifest");
_hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, hlsError));
}
_metrics.parsing_end_time = getTimer();
_loadLevel = -1;
_hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_PARSED, _levels));
if (string.indexOf(Manifest.ALTERNATE_AUDIO) > 0) {
CONFIG::LOGGING {
Log.debug("alternate audio level found");
}
// parse alternate audio tracks
_altAudioTracks = Manifest.extractAltAudioTracks(string, _url);
CONFIG::LOGGING {
if (_altAudioTracks.length > 0) {
Log.debug(_altAudioTracks.length + " alternate audio tracks found");
}
}
}
}
} else {
var hlsError : HLSError = new HLSError(HLSError.MANIFEST_PARSING_ERROR, _url, "Manifest is not a valid M3U8 file");
_hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, hlsError));
}
};
/** load/reload active M3U8 playlist **/
private function _loadActiveLevelPlaylist() : void {
if (_closed) {
return;
}
_reloadPlaylistTimer = getTimer();
// load active M3U8 playlist only
_manifestLoading = new Manifest();
_hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_LOADING, _loadLevel));
_manifestLoading.loadPlaylist(_hls,_levels[_loadLevel].url, _parseLevelPlaylist, _errorHandler, _loadLevel, _type, HLSSettings.flushLiveURLCache);
};
/** When level switch occurs, assess the need of (re)loading new level playlist **/
private function _levelSwitchHandler(event : HLSEvent) : void {
if (_loadLevel != event.level) {
_loadLevel = event.level;
CONFIG::LOGGING {
Log.debug("switch to level " + _loadLevel);
}
if (_type == HLSTypes.LIVE || _levels[_loadLevel].fragments.length == 0) {
_closed = false;
CONFIG::LOGGING {
Log.debug("(re)load Playlist");
}
if(_manifestLoading) {
_manifestLoading.close();
_manifestLoading = null;
}
clearTimeout(_timeoutID);
_timeoutID = setTimeout(_loadActiveLevelPlaylist, 0);
}
}
};
private function _close() : void {
CONFIG::LOGGING {
Log.debug("cancel any manifest load in progress");
}
_closed = true;
clearTimeout(_timeoutID);
try {
_urlloader.close();
if (_manifestLoading) {
_manifestLoading.close();
}
} catch(e : Error) {
}
}
/** When the framework idles out, stop reloading manifest **/
private function _stateHandler(event : HLSEvent) : void {
if (event.state == HLSPlayStates.IDLE) {
_close();
}
};
}
}
|
fix manifest load retry counter not being reset properly after successfull loading related to #308
|
fix manifest load retry counter not being reset properly after successfull loading
related to #308
|
ActionScript
|
mpl-2.0
|
loungelogic/flashls,tedconf/flashls,neilrackett/flashls,jlacivita/flashls,fixedmachine/flashls,dighan/flashls,vidible/vdb-flashls,codex-corp/flashls,NicolasSiver/flashls,fixedmachine/flashls,hola/flashls,tedconf/flashls,JulianPena/flashls,Boxie5/flashls,aevange/flashls,dighan/flashls,vidible/vdb-flashls,Corey600/flashls,Corey600/flashls,loungelogic/flashls,mangui/flashls,Peer5/flashls,Peer5/flashls,Boxie5/flashls,JulianPena/flashls,mangui/flashls,thdtjsdn/flashls,clappr/flashls,Peer5/flashls,NicolasSiver/flashls,codex-corp/flashls,Peer5/flashls,thdtjsdn/flashls,hola/flashls,neilrackett/flashls,aevange/flashls,clappr/flashls,aevange/flashls,aevange/flashls,jlacivita/flashls
|
cc034862ab8ee7b20c766773eb280d8dee49fde4
|
HLSPlugin/src/com/kaltura/hls/manifest/HLSManifestEncryptionKey.as
|
HLSPlugin/src/com/kaltura/hls/manifest/HLSManifestEncryptionKey.as
|
package com.kaltura.hls.manifest
{
import com.hurlant.util.Hex;
import com.kaltura.hls.crypto.FastAESKey;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import flash.utils.Dictionary;
import flash.utils.getTimer;
CONFIG::LOGGING
{
import org.osmf.logging.Logger;
import org.osmf.logging.Log;
}
/**
* HLSManifestEncryptionKey is used to parse AES decryption key data from a m3u8
* manifest, load the specified key file into memory, and use the key data to decrypt
* audio and video streams. It supports AES-128 encryption with #PKCS7 padding, and uses
* explicitly passed in Initialization Vectors.
*/
public class HLSManifestEncryptionKey extends EventDispatcher
{
CONFIG::LOGGING
{
private static const logger:Logger = Log.getLogger("com.kaltura.hls.manifest.HLSManifestEncryptionKey");
}
private static const LOADER_CACHE:Dictionary = new Dictionary();
private var _key:FastAESKey;
public var usePadding:Boolean = false;
public var iv:String = "";
public var url:String = "";
private var iv0 : uint;
private var iv1 : uint;
private var iv2 : uint;
private var iv3 : uint;
// Keep track of the segments this key applies to
public var startSegmentId:uint = 0;
public var endSegmentId:uint = uint.MAX_VALUE;
private var _keyData:ByteArray;
public var isLoading:Boolean = false;
public function HLSManifestEncryptionKey()
{
}
public function get isLoaded():Boolean { return _keyData != null; }
public override function toString():String
{
return "[HLSManifestEncryptionKey start=" + startSegmentId +", end=" + endSegmentId + ", iv=" + iv + ", url=" + url + ", loaded=" + isLoaded + "]";
}
public static function fromParams( params:String ):HLSManifestEncryptionKey
{
var result:HLSManifestEncryptionKey = new HLSManifestEncryptionKey();
var tokens:Array = KeyParamParser.parseParams( params );
var tokenCount:int = tokens.length;
for ( var i:int = 0; i < tokenCount; i += 2 )
{
var name:String = tokens[ i ];
var value:String = tokens[ i + 1 ];
switch ( name )
{
case "URI" :
result.url = value;
break;
case "IV" :
result.iv = value;
break;
}
}
return result;
}
/**
* Creates an initialization vector from the passed in uint ID, usually
* a segment ID.
*/
public static function createIVFromID( id:uint ):ByteArray
{
var result:ByteArray = new ByteArray();
result.writeUnsignedInt( 0 );
result.writeUnsignedInt( 0 );
result.writeUnsignedInt( 0 );
result.writeUnsignedInt( id );
return result;
}
public static function clearLoaderCache():void
{
for ( var key:String in LOADER_CACHE ) delete LOADER_CACHE[ key ];
}
/**
* Decrypts a video or audio stream using AES-128 with the provided initialization vector.
*/
public function decrypt( data:ByteArray, iv:ByteArray ):ByteArray
{
//logger.debug("got " + data.length + " bytes");
if(data.length == 0)
return data;
var startTime:uint = getTimer();
_key = new FastAESKey(_keyData);
iv.position = 0;
iv0 = iv.readUnsignedInt();
iv1 = iv.readUnsignedInt();
iv2 = iv.readUnsignedInt();
iv3 = iv.readUnsignedInt();
data.position = 0;
data = _decryptCBC(data,data.length);
if ( usePadding ){
data = unpad( data );
}
// logger.debug( "DECRYPTION OF " + data.length + " BYTES TOOK " + ( getTimer() - startTime ) + " MS" );
return data;
}
/* Cypher Block Chaining Decryption, refer to
* http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher-block_chaining_
* for algorithm description
*/
private function _decryptCBC(crypt : ByteArray, len : uint) : ByteArray {
var src : Vector.<uint> = new Vector.<uint>(4);
var dst : Vector.<uint> = new Vector.<uint>(4);
var decrypt : ByteArray = new ByteArray();
decrypt.length = len;
for (var i : uint = 0; i < len / 16; i++) {
// read src byte array
src[0] = crypt.readUnsignedInt();
src[1] = crypt.readUnsignedInt();
src[2] = crypt.readUnsignedInt();
src[3] = crypt.readUnsignedInt();
// AES decrypt src vector into dst vector
_key.decrypt128(src, dst);
// CBC : write output = XOR(decrypted,IV)
decrypt.writeUnsignedInt(dst[0] ^ iv0);
decrypt.writeUnsignedInt(dst[1] ^ iv1);
decrypt.writeUnsignedInt(dst[2] ^ iv2);
decrypt.writeUnsignedInt(dst[3] ^ iv3);
// CBC : next IV = (input)
iv0 = src[0];
iv1 = src[1];
iv2 = src[2];
iv3 = src[3];
}
return decrypt;
}
public function unpad(bytesToUnpad : ByteArray) : ByteArray {
if ((bytesToUnpad.length % 16) != 0)
{
throw new Error("PKCS#5::unpad: ByteArray.length isn't a multiple of the blockSize");
return a;
}
const paddingValue:int = bytesToUnpad[bytesToUnpad.length - 1];
trace("paddingValue: " + paddingValue);
var doUnpad:Boolean = true;
for (var i:int = 0; i<paddingValue; i++) {
var readValue:int = bytesToUnpad[bytesToUnpad.length - (1 + i)];
trace("readvalue " + i + ": " + readValue);
if (paddingValue != readValue)
{
//throw new Error("PKCS#5:unpad: Invalid padding value. expected [" + paddingValue + "], found [" + readValue + "]");
//break;
doUnpad = false;
break;
}
}
if(doUnpad)
{
trace("Unpadding decrypted byteArray");
bytesToUnpad.length -= paddingValue + 1;
}
return bytesToUnpad;
}
public function retrieveStoredIV():ByteArray
{
CONFIG::LOGGING
{
logger.debug("IV of " + iv + " for " + url + ", key=" + Hex.fromArray(_keyData));
}
return Hex.toArray( iv );
}
private static function getLoader( url:String ):URLLoader
{
if ( LOADER_CACHE[ url ] != null ) return LOADER_CACHE[ url ] as URLLoader;
var newLoader:URLLoader = new URLLoader();
newLoader.dataFormat = URLLoaderDataFormat.BINARY;
newLoader.load( new URLRequest( url ) );
LOADER_CACHE[ url ] = newLoader;
return newLoader;
}
public function load():void
{
isLoading = true;
if ( isLoaded ) throw new Error( "Already loaded!" );
var loader:URLLoader = getLoader( url );
if ( loader.bytesTotal > 0 && loader.bytesLoaded == loader.bytesTotal ) onLoad();
else loader.addEventListener( Event.COMPLETE, onLoad );
}
private function onLoad( e:Event = null ):void
{
isLoading = false;
CONFIG::LOGGING
{
logger.debug("KEY LOADED! " + url);
}
var loader:URLLoader = getLoader( url );
_keyData = loader.data as ByteArray;
loader.removeEventListener( Event.COMPLETE, onLoad );
dispatchEvent( new Event( Event.COMPLETE ) );
}
}
}
class KeyParamParser
{
private static const STATE_PARSE_NAME:String = "ParseName";
private static const STATE_BEGIN_PARSE_VALUE:String = "BeginParseValue";
private static const STATE_PARSE_VALUE:String = "ParseValue";
public static function parseParams( paramString:String ):Array
{
var result:Array = [];
var cursor:int = 0;
var state:String = STATE_PARSE_NAME;
var accum:String = "";
var usingQuotes:Boolean = false;
while ( cursor < paramString.length )
{
var char:String = paramString.charAt( cursor );
switch ( state )
{
case STATE_PARSE_NAME:
if ( char == '=' )
{
result.push( accum );
accum = "";
state = STATE_BEGIN_PARSE_VALUE;
}
else accum += char;
break;
case STATE_BEGIN_PARSE_VALUE:
if ( char == '"' ) usingQuotes = true;
else accum += char;
state = STATE_PARSE_VALUE;
break;
case STATE_PARSE_VALUE:
if ( !usingQuotes && char == ',' )
{
result.push( accum );
accum = "";
state = STATE_PARSE_NAME;
break;
}
if ( usingQuotes && char == '"' )
{
usingQuotes = false;
break;
}
accum += char;
break;
}
cursor++;
if ( cursor == paramString.length ) result.push( accum );
}
return result;
}
}
|
package com.kaltura.hls.manifest
{
import com.hurlant.util.Hex;
import com.kaltura.hls.crypto.FastAESKey;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import flash.utils.Dictionary;
import flash.utils.getTimer;
CONFIG::LOGGING
{
import org.osmf.logging.Logger;
import org.osmf.logging.Log;
}
/**
* HLSManifestEncryptionKey is used to parse AES decryption key data from a m3u8
* manifest, load the specified key file into memory, and use the key data to decrypt
* audio and video streams. It supports AES-128 encryption with #PKCS7 padding, and uses
* explicitly passed in Initialization Vectors.
*/
public class HLSManifestEncryptionKey extends EventDispatcher
{
CONFIG::LOGGING
{
private static const logger:Logger = Log.getLogger("com.kaltura.hls.manifest.HLSManifestEncryptionKey");
}
private static const LOADER_CACHE:Dictionary = new Dictionary();
private var _key:FastAESKey;
public var usePadding:Boolean = false;
public var iv:String = "";
public var url:String = "";
private var iv0 : uint;
private var iv1 : uint;
private var iv2 : uint;
private var iv3 : uint;
// Keep track of the segments this key applies to
public var startSegmentId:uint = 0;
public var endSegmentId:uint = uint.MAX_VALUE;
private var _keyData:ByteArray;
public var isLoading:Boolean = false;
public function HLSManifestEncryptionKey()
{
}
public function get isLoaded():Boolean { return _keyData != null; }
public override function toString():String
{
return "[HLSManifestEncryptionKey start=" + startSegmentId +", end=" + endSegmentId + ", iv=" + iv + ", url=" + url + ", loaded=" + isLoaded + "]";
}
public static function fromParams( params:String ):HLSManifestEncryptionKey
{
var result:HLSManifestEncryptionKey = new HLSManifestEncryptionKey();
var tokens:Array = KeyParamParser.parseParams( params );
var tokenCount:int = tokens.length;
for ( var i:int = 0; i < tokenCount; i += 2 )
{
var name:String = tokens[ i ];
var value:String = tokens[ i + 1 ];
switch ( name )
{
case "URI" :
result.url = value;
break;
case "IV" :
result.iv = value;
break;
}
}
return result;
}
/**
* Creates an initialization vector from the passed in uint ID, usually
* a segment ID.
*/
public static function createIVFromID( id:uint ):ByteArray
{
var result:ByteArray = new ByteArray();
result.writeUnsignedInt( 0 );
result.writeUnsignedInt( 0 );
result.writeUnsignedInt( 0 );
result.writeUnsignedInt( id );
return result;
}
public static function clearLoaderCache():void
{
for ( var key:String in LOADER_CACHE ) delete LOADER_CACHE[ key ];
}
/**
* Decrypts a video or audio stream using AES-128 with the provided initialization vector.
*/
public function decrypt( data:ByteArray, iv:ByteArray ):ByteArray
{
//logger.debug("got " + data.length + " bytes");
if(data.length == 0)
return data;
var startTime:uint = getTimer();
_key = new FastAESKey(_keyData);
iv.position = 0;
iv0 = iv.readUnsignedInt();
iv1 = iv.readUnsignedInt();
iv2 = iv.readUnsignedInt();
iv3 = iv.readUnsignedInt();
data.position = 0;
data = _decryptCBC(data,data.length);
if ( usePadding ){
data = unpad( data );
}
// logger.debug( "DECRYPTION OF " + data.length + " BYTES TOOK " + ( getTimer() - startTime ) + " MS" );
return data;
}
/* Cypher Block Chaining Decryption, refer to
* http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher-block_chaining_
* for algorithm description
*/
private function _decryptCBC(crypt : ByteArray, len : uint) : ByteArray {
var src : Vector.<uint> = new Vector.<uint>(4);
var dst : Vector.<uint> = new Vector.<uint>(4);
var decrypt : ByteArray = new ByteArray();
decrypt.length = len;
for (var i : uint = 0; i < len / 16; i++) {
// read src byte array
src[0] = crypt.readUnsignedInt();
src[1] = crypt.readUnsignedInt();
src[2] = crypt.readUnsignedInt();
src[3] = crypt.readUnsignedInt();
// AES decrypt src vector into dst vector
_key.decrypt128(src, dst);
// CBC : write output = XOR(decrypted,IV)
decrypt.writeUnsignedInt(dst[0] ^ iv0);
decrypt.writeUnsignedInt(dst[1] ^ iv1);
decrypt.writeUnsignedInt(dst[2] ^ iv2);
decrypt.writeUnsignedInt(dst[3] ^ iv3);
// CBC : next IV = (input)
iv0 = src[0];
iv1 = src[1];
iv2 = src[2];
iv3 = src[3];
}
return decrypt;
}
public function unpad(bytesToUnpad : ByteArray) : ByteArray {
if ((bytesToUnpad.length % 16) != 0)
{
throw new Error("PKCS#5::unpad: ByteArray.length isn't a multiple of the blockSize");
return a;
}
const paddingValue:int = bytesToUnpad[bytesToUnpad.length - 1];
var doUnpad:Boolean = true;
for (var i:int = 0; i<paddingValue; i++) {
var readValue:int = bytesToUnpad[bytesToUnpad.length - (1 + i)];
if (paddingValue != readValue)
{
//throw new Error("PKCS#5:unpad: Invalid padding value. expected [" + paddingValue + "], found [" + readValue + "]");
//break;
doUnpad = false;
//Break to make sure we don't underrun the byte array with a byte value bigger than 16
break;
}
}
if(doUnpad)
{
//subtract paddingValue + 1 since the value is one less than the number of padded bytes
bytesToUnpad.length -= paddingValue + 1;
}
return bytesToUnpad;
}
public function retrieveStoredIV():ByteArray
{
CONFIG::LOGGING
{
logger.debug("IV of " + iv + " for " + url + ", key=" + Hex.fromArray(_keyData));
}
return Hex.toArray( iv );
}
private static function getLoader( url:String ):URLLoader
{
if ( LOADER_CACHE[ url ] != null ) return LOADER_CACHE[ url ] as URLLoader;
var newLoader:URLLoader = new URLLoader();
newLoader.dataFormat = URLLoaderDataFormat.BINARY;
newLoader.load( new URLRequest( url ) );
LOADER_CACHE[ url ] = newLoader;
return newLoader;
}
public function load():void
{
isLoading = true;
if ( isLoaded ) throw new Error( "Already loaded!" );
var loader:URLLoader = getLoader( url );
if ( loader.bytesTotal > 0 && loader.bytesLoaded == loader.bytesTotal ) onLoad();
else loader.addEventListener( Event.COMPLETE, onLoad );
}
private function onLoad( e:Event = null ):void
{
isLoading = false;
CONFIG::LOGGING
{
logger.debug("KEY LOADED! " + url);
}
var loader:URLLoader = getLoader( url );
_keyData = loader.data as ByteArray;
loader.removeEventListener( Event.COMPLETE, onLoad );
dispatchEvent( new Event( Event.COMPLETE ) );
}
}
}
class KeyParamParser
{
private static const STATE_PARSE_NAME:String = "ParseName";
private static const STATE_BEGIN_PARSE_VALUE:String = "BeginParseValue";
private static const STATE_PARSE_VALUE:String = "ParseValue";
public static function parseParams( paramString:String ):Array
{
var result:Array = [];
var cursor:int = 0;
var state:String = STATE_PARSE_NAME;
var accum:String = "";
var usingQuotes:Boolean = false;
while ( cursor < paramString.length )
{
var char:String = paramString.charAt( cursor );
switch ( state )
{
case STATE_PARSE_NAME:
if ( char == '=' )
{
result.push( accum );
accum = "";
state = STATE_BEGIN_PARSE_VALUE;
}
else accum += char;
break;
case STATE_BEGIN_PARSE_VALUE:
if ( char == '"' ) usingQuotes = true;
else accum += char;
state = STATE_PARSE_VALUE;
break;
case STATE_PARSE_VALUE:
if ( !usingQuotes && char == ',' )
{
result.push( accum );
accum = "";
state = STATE_PARSE_NAME;
break;
}
if ( usingQuotes && char == '"' )
{
usingQuotes = false;
break;
}
accum += char;
break;
}
cursor++;
if ( cursor == paramString.length ) result.push( accum );
}
return result;
}
}
|
Update HLSManifestEncryptionKey.as
|
Update HLSManifestEncryptionKey.as
|
ActionScript
|
agpl-3.0
|
kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF
|
4c695564b07afdd8b5779e349c1ead9d64f8dff7
|
src/org/jivesoftware/xiff/data/Message.as
|
src/org/jivesoftware/xiff/data/Message.as
|
/*
* Copyright (C) 2003-2007
* Nick Velloff <[email protected]>
* Derrick Grigg <[email protected]>
* Sean Voisen <[email protected]>
* Sean Treadway <[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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package org.jivesoftware.xiff.data
{
import org.jivesoftware.xiff.data.ISerializable;
import org.jivesoftware.xiff.data.XMPPStanza;
import org.jivesoftware.xiff.data.ExtensionClassRegistry;
import org.jivesoftware.xiff.data.xhtml.XHTMLExtension;
import flash.xml.XMLNode;
import org.jivesoftware.xiff.events.XIFFErrorEvent;
/**
* A class for abstraction and encapsulation of message data.
*
* @param recipient The JID of the message recipient
* @param sender The JID of the message sender - the server should report an error if this is falsified
* @param msgID The message ID
* @param msgBody The message body in plain-text format
* @param msgHTMLBody The message body in XHTML format
* @param msgType The message type
* @param msgSubject (Optional) The message subject
*/
public class Message extends XMPPStanza implements ISerializable
{
// Static variables for specific type strings
public static var NORMAL_TYPE:String = "normal";
public static var CHAT_TYPE:String = "chat";
public static var GROUPCHAT_TYPE:String = "groupchat";
public static var HEADLINE_TYPE:String = "headline";
public static var ERROR_TYPE:String = "error";
// Private references to nodes within our XML
private var myBodyNode:XMLNode;
private var mySubjectNode:XMLNode;
private var myThreadNode:XMLNode;
private var myTimeStampNode:XMLNode;
private static var isMessageStaticCalled:Boolean = MessageStaticConstructor();
private static var staticConstructorDependency:Array = [ XMPPStanza, XHTMLExtension, ExtensionClassRegistry ];
public function Message( recipient:String=null, msgID:String=null, msgBody:String=null, msgHTMLBody:String=null, msgType:String=null, msgSubject:String=null )
{
// Flash gives a warning if superconstructor is not first, hence the inline id check
var msgId:String = exists( msgID ) ? msgID : generateID("m_");
super( recipient, null, msgType, msgId, "message" );
body = msgBody;
htmlBody = msgHTMLBody;
subject = msgSubject;
}
public static function MessageStaticConstructor():Boolean
{
XHTMLExtension.enable();
return true;
}
/**
* Serializes the Message into XML form for sending to a server.
*
* @return An indication as to whether serialization was successful
*/
override public function serialize( parentNode:XMLNode ):Boolean
{
return super.serialize( parentNode );
}
/**
* Deserializes an XML object and populates the Message instance with its data.
*
* @param xmlNode The XML to deserialize
* @return An indication as to whether deserialization was sucessful
*/
override public function deserialize( xmlNode:XMLNode ):Boolean
{
var isSerialized:Boolean = super.deserialize( xmlNode );
if (isSerialized) {
var children:Array = xmlNode.childNodes;
for( var i:String in children )
{
trace(children[i].nodeName);
switch( children[i].nodeName )
{
// Adding error handler for 404 sent back by server
case "error":
break;
case "body":
myBodyNode = children[i];
break;
case "subject":
mySubjectNode = children[i];
break;
case "thread":
myThreadNode = children[i];
break;
case "x":
if(children[i].attributes.xmlns == "jabber:x:delay")
myTimeStampNode = children[i];
break;
}
}
}
return isSerialized;
}
/**
* The message body in plain-text format. If a client cannot render HTML-formatted
* text, this text is typically used instead.
*/
public function get body():String
{
if (!exists(myBodyNode)){
return null;
}
var value: String = '';
try
{
value = myBodyNode.firstChild.nodeValue;
}
catch (error:Error)
{
trace (error.getStackTrace());
}
return value;
}
/**
* @private
*/
public function set body( bodyText:String ):void
{
myBodyNode = replaceTextNode(getNode(), myBodyNode, "body", bodyText);
}
/**
* The message body in XHTML format. Internally, this uses the XHTML data extension.
*
* @see org.jivesoftware.xiff.data.xhtml.XHTMLExtension
*/
public function get htmlBody():String
{
try
{
var ext:XHTMLExtension = getAllExtensionsByNS(XHTMLExtension.NS)[0];
return ext.body;
}
catch (e:Error)
{
trace("Error : null trapped. Resuming.");
}
return null;
}
/**
* @private
*/
public function set htmlBody( bodyHTML:String ):void
{
// Removes any existing HTML body text first
removeAllExtensions(XHTMLExtension.NS);
if (exists(bodyHTML) && bodyHTML.length > 0) {
var ext:XHTMLExtension = new XHTMLExtension(getNode());
ext.body = bodyHTML;
addExtension(ext);
}
}
/**
* The message subject. Typically chat and groupchat-type messages do not use
* subjects. Rather, this is reserved for normal and headline-type messages.
*/
public function get subject():String
{
if (mySubjectNode == null) return null;
return mySubjectNode.firstChild.nodeValue;
}
/**
* @private
*/
public function set subject( aSubject:String ):void
{
mySubjectNode = replaceTextNode(getNode(), mySubjectNode, "subject", aSubject);
}
/**
* The message thread ID. Threading is used to group messages of the same discussion together.
* The library does not perform message grouping, rather it is up to any client authors to
* properly perform this task.
*/
public function get thread():String
{
if (myThreadNode == null) return null;
return myThreadNode.firstChild.nodeValue;
}
/**
* @private
*/
public function set thread( theThread:String ):void
{
myThreadNode = replaceTextNode(getNode(), myThreadNode, "thread", theThread);
}
public function set time( theTime:Date ): void
{
}
public function get time():Date
{
if(myTimeStampNode == null) return null;
var stamp:String = myTimeStampNode.attributes.stamp;
var t:Date = new Date();
//CCYYMMDDThh:mm:ss
//20020910T23:41:07
t.setUTCFullYear(stamp.slice(0, 4)); //2002
t.setUTCMonth(stamp.slice(4, 6)); //09
t.setUTCDate(stamp.slice(6, 8)); //10
//T
t.setUTCHours(stamp.slice(9, 11)); //23
//:
t.setUTCMinutes(stamp.slice(12, 14)); //41
//:
t.setUTCSeconds(stamp.slice(15, 17)); //07
return t;
}
}
}
|
/*
* Copyright (C) 2003-2007
* Nick Velloff <[email protected]>
* Derrick Grigg <[email protected]>
* Sean Voisen <[email protected]>
* Sean Treadway <[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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package org.jivesoftware.xiff.data
{
import org.jivesoftware.xiff.data.ISerializable;
import org.jivesoftware.xiff.data.XMPPStanza;
import org.jivesoftware.xiff.data.ExtensionClassRegistry;
import org.jivesoftware.xiff.data.xhtml.XHTMLExtension;
import flash.xml.XMLNode;
import org.jivesoftware.xiff.events.XIFFErrorEvent;
/**
* A class for abstraction and encapsulation of message data.
*
* @param recipient The JID of the message recipient
* @param sender The JID of the message sender - the server should report an error if this is falsified
* @param msgID The message ID
* @param msgBody The message body in plain-text format
* @param msgHTMLBody The message body in XHTML format
* @param msgType The message type
* @param msgSubject (Optional) The message subject
*/
public class Message extends XMPPStanza implements ISerializable
{
// Static variables for specific type strings
public static var NORMAL_TYPE:String = "normal";
public static var CHAT_TYPE:String = "chat";
public static var GROUPCHAT_TYPE:String = "groupchat";
public static var HEADLINE_TYPE:String = "headline";
public static var ERROR_TYPE:String = "error";
// Private references to nodes within our XML
private var myBodyNode:XMLNode;
private var mySubjectNode:XMLNode;
private var myThreadNode:XMLNode;
private var myTimeStampNode:XMLNode;
private static var isMessageStaticCalled:Boolean = MessageStaticConstructor();
private static var staticConstructorDependency:Array = [ XMPPStanza, XHTMLExtension, ExtensionClassRegistry ];
public function Message( recipient:String=null, msgID:String=null, msgBody:String=null, msgHTMLBody:String=null, msgType:String=null, msgSubject:String=null )
{
// Flash gives a warning if superconstructor is not first, hence the inline id check
var msgId:String = exists( msgID ) ? msgID : generateID("m_");
super( recipient, null, msgType, msgId, "message" );
body = msgBody;
htmlBody = msgHTMLBody;
subject = msgSubject;
}
public static function MessageStaticConstructor():Boolean
{
XHTMLExtension.enable();
return true;
}
/**
* Serializes the Message into XML form for sending to a server.
*
* @return An indication as to whether serialization was successful
*/
override public function serialize( parentNode:XMLNode ):Boolean
{
return super.serialize( parentNode );
}
/**
* Deserializes an XML object and populates the Message instance with its data.
*
* @param xmlNode The XML to deserialize
* @return An indication as to whether deserialization was sucessful
*/
override public function deserialize( xmlNode:XMLNode ):Boolean
{
var isSerialized:Boolean = super.deserialize( xmlNode );
if (isSerialized) {
var children:Array = xmlNode.childNodes;
for( var i:String in children )
{
trace(children[i].nodeName);
switch( children[i].nodeName )
{
// Adding error handler for 404 sent back by server
case "error":
break;
case "body":
myBodyNode = children[i];
break;
case "subject":
mySubjectNode = children[i];
break;
case "thread":
myThreadNode = children[i];
break;
case "x":
if(children[i].attributes.xmlns == "jabber:x:delay")
myTimeStampNode = children[i];
break;
}
}
}
return isSerialized;
}
/**
* The message body in plain-text format. If a client cannot render HTML-formatted
* text, this text is typically used instead.
*/
public function get body():String
{
if (!exists(myBodyNode)){
return null;
}
var value: String = '';
try
{
value = myBodyNode.firstChild.nodeValue;
}
catch (error:Error)
{
trace (error.getStackTrace());
}
return value;
}
/**
* @private
*/
public function set body( bodyText:String ):void
{
myBodyNode = replaceTextNode(getNode(), myBodyNode, "body", bodyText);
}
/**
* The message body in XHTML format. Internally, this uses the XHTML data extension.
*
* @see org.jivesoftware.xiff.data.xhtml.XHTMLExtension
*/
public function get htmlBody():String
{
try
{
var ext:XHTMLExtension = getAllExtensionsByNS(XHTMLExtension.NS)[0];
return ext.body;
}
catch (e:Error)
{
trace("Error : null trapped. Resuming.");
}
return null;
}
/**
* @private
*/
public function set htmlBody( bodyHTML:String ):void
{
// Removes any existing HTML body text first
removeAllExtensions(XHTMLExtension.NS);
if (exists(bodyHTML) && bodyHTML.length > 0) {
var ext:XHTMLExtension = new XHTMLExtension(getNode());
ext.body = bodyHTML;
addExtension(ext);
}
}
/**
* The message subject. Typically chat and groupchat-type messages do not use
* subjects. Rather, this is reserved for normal and headline-type messages.
*/
public function get subject():String
{
if (mySubjectNode == null) return null;
return mySubjectNode.firstChild.nodeValue;
}
/**
* @private
*/
public function set subject( aSubject:String ):void
{
mySubjectNode = replaceTextNode(getNode(), mySubjectNode, "subject", aSubject);
}
/**
* The message thread ID. Threading is used to group messages of the same discussion together.
* The library does not perform message grouping, rather it is up to any client authors to
* properly perform this task.
*/
public function get thread():String
{
if (myThreadNode == null) return null;
return myThreadNode.firstChild.nodeValue;
}
/**
* @private
*/
public function set thread( theThread:String ):void
{
myThreadNode = replaceTextNode(getNode(), myThreadNode, "thread", theThread);
}
public function set time( theTime:Date ): void
{
}
public function get time():Date
{
if(myTimeStampNode == null) return null;
var stamp:String = myTimeStampNode.attributes.stamp;
var t:Date = new Date();
//CCYYMMDDThh:mm:ss
//20020910T23:41:07
t.setUTCFullYear(stamp.slice(0, 4)); //2002
t.setUTCMonth(Number(stamp.slice(4, 6)) - 1); //09
t.setUTCDate(stamp.slice(6, 8)); //10
//T
t.setUTCHours(stamp.slice(9, 11)); //23
//:
t.setUTCMinutes(stamp.slice(12, 14)); //41
//:
t.setUTCSeconds(stamp.slice(15, 17)); //07
return t;
}
}
}
|
Fix an off-by-one error due to the way flex deals with dates. Thanks to Bill Bailey for pointing this out :)
|
Fix an off-by-one error due to the way flex deals with dates. Thanks to Bill Bailey for pointing this out :)
git-svn-id: c197267f952b24206666de142881703007ca05d5@8984 b35dd754-fafc-0310-a699-88a17e54d16e
|
ActionScript
|
apache-2.0
|
nazoking/xiff
|
5f399ec1005c764c6d95daaa76484f67a906ccf6
|
src/flash/htmlelements/AudioElement.as
|
src/flash/htmlelements/AudioElement.as
|
package htmlelements
{
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.TimerEvent;
import flash.media.ID3Info;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundLoaderContext;
import flash.media.SoundTransform;
import flash.net.URLRequest;
import flash.utils.Timer;
/**
* ...
* @author DefaultUser (Tools -> Custom Arguments...)
*/
public class AudioElement implements IMediaElement
{
private var _sound:Sound;
private var _soundTransform:SoundTransform;
private var _soundChannel:SoundChannel;
private var _soundLoaderContext:SoundLoaderContext;
private var _volume:Number = 1;
private var _preMuteVolume:Number = 0;
private var _isMuted:Boolean = false;
private var _isPaused:Boolean = true;
private var _isEnded:Boolean = false;
private var _isLoaded:Boolean = false;
private var _currentTime:Number = 0;
private var _duration:Number = 0;
private var _bytesLoaded:Number = 0;
private var _bytesTotal:Number = 0;
private var _bufferedTime:Number = 0;
private var _currentUrl:String = "";
private var _autoplay:Boolean = true;
private var _preload:String = "";
private var _element:FlashMediaElement;
private var _timer:Timer;
private var _firedCanPlay:Boolean = false;
public function setSize(width:Number, height:Number):void {
// do nothing!
}
public function duration():Number {
return _duration;
}
public function currentTime():Number {
return _currentTime;
}
public function currentProgress():Number {
return Math.round(_bytesLoaded/_bytesTotal*100);
}
public function AudioElement(element:FlashMediaElement, autoplay:Boolean, preload:String, timerRate:Number, startVolume:Number)
{
_element = element;
_autoplay = autoplay;
_volume = startVolume;
_preload = preload;
_timer = new Timer(timerRate);
_timer.addEventListener(TimerEvent.TIMER, timerEventHandler);
_soundTransform = new SoundTransform(_volume);
_soundLoaderContext = new SoundLoaderContext();
}
// events
function progressHandler(e:ProgressEvent):void {
_bytesLoaded = e.bytesLoaded;
_bytesTotal = e.bytesTotal;
sendEvent(HtmlMediaEvent.PROGRESS);
}
function id3Handler(e:Event):void {
sendEvent(HtmlMediaEvent.LOADEDMETADATA);
try {
var id3:ID3Info = _sound.id3;
var obj = {
type:'id3',
album:id3.album,
artist:id3.artist,
comment:id3.comment,
genre:id3.genre,
songName:id3.songName,
track:id3.track,
year:id3.year
}
} catch (err:Error) {}
}
function timerEventHandler(e:TimerEvent) {
_currentTime = _soundChannel.position/1000;
// calculate duration
var duration = Math.round(_sound.length * _sound.bytesTotal/_sound.bytesLoaded/100) / 10;
// check to see if the estimated duration changed
if (_duration != duration && !isNaN(duration)) {
_duration = duration;
sendEvent(HtmlMediaEvent.LOADEDMETADATA);
}
// send timeupdate
sendEvent(HtmlMediaEvent.TIMEUPDATE);
// sometimes the ended event doesn't fire, here's a fake one
if (_duration > 0 && _currentTime >= _duration-0.2) {
handleEnded();
}
}
function soundCompleteHandler(e:Event) {
handleEnded();
}
function handleEnded():void {
_timer.stop();
_currentTime = 0;
_isEnded = true;
sendEvent(HtmlMediaEvent.ENDED);
}
//events
// METHODS
public function setSrc(url:String):void {
_currentUrl = url;
_isLoaded = false;
}
public function load():void {
if (_currentUrl == "")
return;
_sound = new Sound();
//sound.addEventListener(IOErrorEvent.IO_ERROR,errorHandler);
_sound.addEventListener(ProgressEvent.PROGRESS,progressHandler);
_sound.addEventListener(Event.ID3,id3Handler);
_sound.load(new URLRequest(_currentUrl));
_currentTime = 0;
sendEvent(HtmlMediaEvent.LOADSTART);
_isLoaded = true;
sendEvent(HtmlMediaEvent.LOADEDDATA);
sendEvent(HtmlMediaEvent.CANPLAY);
_firedCanPlay = true;
if (_playAfterLoading) {
_playAfterLoading = false;
play();
}
}
private var _playAfterLoading:Boolean= false;
public function play():void {
if (!_isLoaded) {
_playAfterLoading = true;
load();
return;
}
_timer.stop();
_soundChannel = _sound.play(_currentTime*1000, 0, _soundTransform);
_soundChannel.removeEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);
_soundChannel.addEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);
_timer.start();
didStartPlaying();
}
public function pause():void {
_timer.stop();
if (_soundChannel != null) {
_currentTime = _soundChannel.position/1000;
_soundChannel.stop();
}
_isPaused = true;
sendEvent(HtmlMediaEvent.PAUSE);
}
public function stop():void {
if (_timer != null) {
_timer.stop();
}
if (_soundChannel != null) {
_soundChannel.stop();
_sound.close();
}
unload();
sendEvent(HtmlMediaEvent.STOP);
}
public function setCurrentTime(pos:Number):void {
sendEvent(HtmlMediaEvent.SEEKING);
_timer.stop();
_currentTime = pos;
_soundChannel.stop();
_sound.length
_soundChannel = _sound.play(_currentTime * 1000, 0, _soundTransform);
sendEvent(HtmlMediaEvent.SEEKED);
_timer.start();
didStartPlaying();
}
private function didStartPlaying():void {
_isPaused = false;
sendEvent(HtmlMediaEvent.PLAY);
sendEvent(HtmlMediaEvent.PLAYING);
if (!_firedCanPlay) {
sendEvent(HtmlMediaEvent.LOADEDDATA);
sendEvent(HtmlMediaEvent.CANPLAY);
_firedCanPlay = true;
}
}
public function setVolume(volume:Number):void {
_volume = volume;
_soundTransform.volume = volume;
if (_soundChannel != null) {
_soundChannel.soundTransform = _soundTransform;
}
_isMuted = (_volume == 0);
sendEvent(HtmlMediaEvent.VOLUMECHANGE);
}
public function getVolume():Number {
if(_isMuted) {
return 0;
} else {
return _volume;
}
}
public function setMuted(muted:Boolean):void {
// ignore if already set
if ( (muted && _isMuted) || (!muted && !_isMuted))
return;
if (muted) {
_preMuteVolume = _soundTransform.volume;
setVolume(0);
} else {
setVolume(_preMuteVolume);
}
_isMuted = muted;
}
public function unload():void {
_sound = null;
_isLoaded = false;
}
private function sendEvent(eventName:String) {
// calculate this to mimic HTML5
_bufferedTime = _bytesLoaded / _bytesTotal * _duration;
// build JSON
var values:String = "duration:" + _duration +
",currentTime:" + _currentTime +
",muted:" + _isMuted +
",paused:" + _isPaused +
",ended:" + _isEnded +
",volume:" + _volume +
",src:\"" + _currentUrl + "\"" +
",bytesTotal:" + _bytesTotal +
",bufferedBytes:" + _bytesLoaded +
",bufferedTime:" + _bufferedTime +
"";
_element.sendEvent(eventName, values);
}
}
}
|
package htmlelements
{
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.TimerEvent;
import flash.media.ID3Info;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundLoaderContext;
import flash.media.SoundTransform;
import flash.net.URLRequest;
import flash.utils.Timer;
/**
* ...
* @author DefaultUser (Tools -> Custom Arguments...)
*/
public class AudioElement implements IMediaElement
{
private var _sound:Sound;
private var _soundTransform:SoundTransform;
private var _soundChannel:SoundChannel;
private var _soundLoaderContext:SoundLoaderContext;
private var _volume:Number = 1;
private var _preMuteVolume:Number = 0;
private var _isMuted:Boolean = false;
private var _isPaused:Boolean = true;
private var _isEnded:Boolean = false;
private var _isLoaded:Boolean = false;
private var _currentTime:Number = 0;
private var _duration:Number = 0;
private var _bytesLoaded:Number = 0;
private var _bytesTotal:Number = 0;
private var _bufferedTime:Number = 0;
private var _bufferingChanged:Boolean = false;
private var _currentUrl:String = "";
private var _autoplay:Boolean = true;
private var _preload:String = "";
private var _element:FlashMediaElement;
private var _timer:Timer;
private var _firedCanPlay:Boolean = false;
public function setSize(width:Number, height:Number):void {
// do nothing!
}
public function duration():Number {
return _duration;
}
public function currentTime():Number {
return _currentTime;
}
public function currentProgress():Number {
return Math.round(_bytesLoaded/_bytesTotal*100);
}
public function AudioElement(element:FlashMediaElement, autoplay:Boolean, preload:String, timerRate:Number, startVolume:Number)
{
_element = element;
_autoplay = autoplay;
_volume = startVolume;
_preload = preload;
_timer = new Timer(timerRate);
_timer.addEventListener(TimerEvent.TIMER, timerEventHandler);
_soundTransform = new SoundTransform(_volume);
_soundLoaderContext = new SoundLoaderContext();
}
// events
function progressHandler(e:ProgressEvent):void {
_bytesLoaded = e.bytesLoaded;
_bytesTotal = e.bytesTotal;
// this happens too much to send every time
//sendEvent(HtmlMediaEvent.PROGRESS);
// so now we just trigger a flag and send with the timer
_bufferingChanged = true;
}
function id3Handler(e:Event):void {
sendEvent(HtmlMediaEvent.LOADEDMETADATA);
try {
var id3:ID3Info = _sound.id3;
var obj = {
type:'id3',
album:id3.album,
artist:id3.artist,
comment:id3.comment,
genre:id3.genre,
songName:id3.songName,
track:id3.track,
year:id3.year
}
} catch (err:Error) {}
}
function timerEventHandler(e:TimerEvent) {
_currentTime = _soundChannel.position/1000;
// calculate duration
var duration = Math.round(_sound.length * _sound.bytesTotal/_sound.bytesLoaded/100) / 10;
// check to see if the estimated duration changed
if (_duration != duration && !isNaN(duration)) {
_duration = duration;
sendEvent(HtmlMediaEvent.LOADEDMETADATA);
}
// check for progress
if (_bufferingChanged) {
sendEvent(HtmlMediaEvent.PROGRESS);
_bufferingChanged = false;
}
// send timeupdate
sendEvent(HtmlMediaEvent.TIMEUPDATE);
// sometimes the ended event doesn't fire, here's a fake one
if (_duration > 0 && _currentTime >= _duration-0.2) {
handleEnded();
}
}
function soundCompleteHandler(e:Event) {
handleEnded();
}
function handleEnded():void {
_timer.stop();
_currentTime = 0;
_isEnded = true;
sendEvent(HtmlMediaEvent.ENDED);
}
//events
// METHODS
public function setSrc(url:String):void {
_currentUrl = url;
_isLoaded = false;
}
public function load():void {
if (_currentUrl == "")
return;
_sound = new Sound();
//sound.addEventListener(IOErrorEvent.IO_ERROR,errorHandler);
_sound.addEventListener(ProgressEvent.PROGRESS,progressHandler);
_sound.addEventListener(Event.ID3,id3Handler);
_sound.load(new URLRequest(_currentUrl));
_currentTime = 0;
sendEvent(HtmlMediaEvent.LOADSTART);
_isLoaded = true;
sendEvent(HtmlMediaEvent.LOADEDDATA);
sendEvent(HtmlMediaEvent.CANPLAY);
_firedCanPlay = true;
if (_playAfterLoading) {
_playAfterLoading = false;
play();
}
}
private var _playAfterLoading:Boolean= false;
public function play():void {
if (!_isLoaded) {
_playAfterLoading = true;
load();
return;
}
_timer.stop();
_soundChannel = _sound.play(_currentTime*1000, 0, _soundTransform);
_soundChannel.removeEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);
_soundChannel.addEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);
_timer.start();
didStartPlaying();
}
public function pause():void {
_timer.stop();
if (_soundChannel != null) {
_currentTime = _soundChannel.position/1000;
_soundChannel.stop();
}
_isPaused = true;
sendEvent(HtmlMediaEvent.PAUSE);
}
public function stop():void {
if (_timer != null) {
_timer.stop();
}
if (_soundChannel != null) {
_soundChannel.stop();
_sound.close();
}
unload();
sendEvent(HtmlMediaEvent.STOP);
}
public function setCurrentTime(pos:Number):void {
sendEvent(HtmlMediaEvent.SEEKING);
_timer.stop();
_currentTime = pos;
_soundChannel.stop();
_sound.length
_soundChannel = _sound.play(_currentTime * 1000, 0, _soundTransform);
sendEvent(HtmlMediaEvent.SEEKED);
_timer.start();
didStartPlaying();
}
private function didStartPlaying():void {
_isPaused = false;
sendEvent(HtmlMediaEvent.PLAY);
sendEvent(HtmlMediaEvent.PLAYING);
if (!_firedCanPlay) {
sendEvent(HtmlMediaEvent.LOADEDDATA);
sendEvent(HtmlMediaEvent.CANPLAY);
_firedCanPlay = true;
}
}
public function setVolume(volume:Number):void {
_volume = volume;
_soundTransform.volume = volume;
if (_soundChannel != null) {
_soundChannel.soundTransform = _soundTransform;
}
_isMuted = (_volume == 0);
sendEvent(HtmlMediaEvent.VOLUMECHANGE);
}
public function getVolume():Number {
if(_isMuted) {
return 0;
} else {
return _volume;
}
}
public function setMuted(muted:Boolean):void {
// ignore if already set
if ( (muted && _isMuted) || (!muted && !_isMuted))
return;
if (muted) {
_preMuteVolume = _soundTransform.volume;
setVolume(0);
} else {
setVolume(_preMuteVolume);
}
_isMuted = muted;
}
public function unload():void {
_sound = null;
_isLoaded = false;
}
private function sendEvent(eventName:String) {
// calculate this to mimic HTML5
_bufferedTime = _bytesLoaded / _bytesTotal * _duration;
// build JSON
var values:String = "duration:" + _duration +
",currentTime:" + _currentTime +
",muted:" + _isMuted +
",paused:" + _isPaused +
",ended:" + _isEnded +
",volume:" + _volume +
",src:\"" + _currentUrl + "\"" +
",bytesTotal:" + _bytesTotal +
",bufferedBytes:" + _bytesLoaded +
",bufferedTime:" + _bufferedTime +
"";
_element.sendEvent(eventName, values);
}
}
}
|
fix for too many buffering events by tying it to the timer event
|
fix for too many buffering events by tying it to the timer event
|
ActionScript
|
agpl-3.0
|
libeo/Vibeo,libeo/Vibeo,libeo/Vibeo,libeo/Vibeo
|
573f4f475930dcc1f464b349e6be6ac17282d1f8
|
src/aerys/minko/scene/node/Mesh.as
|
src/aerys/minko/scene/node/Mesh.as
|
package aerys.minko.scene.node
{
import aerys.minko.render.Effect;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.material.Material;
import aerys.minko.render.material.basic.BasicMaterial;
import aerys.minko.render.material.basic.BasicShader;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.controller.mesh.MeshVisibilityController;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.bounding.FrustumCulling;
import aerys.minko.type.enum.DataProviderUsage;
import aerys.minko.type.math.Ray;
/**
* Mesh objects are a visible instance of a Geometry rendered using a specific
* Effect with specific rendering properties.
*
* <p>
* Those rendering properties are stored in a DataBindings object so they can
* be directly used by the shaders in the rendering API.
* </p>
*
* @author Jean-Marc Le Roux
*
*/
public class Mesh extends AbstractSceneNode
{
public static const DEFAULT_MATERIAL : Material = new Material(
new Effect(new BasicShader())
);
private var _geometry : Geometry = null;
private var _properties : DataProvider = null;
private var _material : Material = null;
private var _bindings : DataBindings = null;
private var _visibility : MeshVisibilityController = new MeshVisibilityController();
private var _frame : uint = 0;
private var _cloned : Signal = new Signal('Mesh.clones');
private var _materialChanged : Signal = new Signal('Mesh.materialChanged');
private var _frameChanged : Signal = new Signal('Mesh.frameChanged');
private var _geometryChanged : Signal = new Signal('Mesh.geometryChanged');
/**
* A DataProvider object already bound to the Mesh bindings.
*
* <pre>
* // set the "diffuseColor" property to 0x0000ffff
* mesh.properties.diffuseColor = 0x0000ffff;
*
* // animate the "diffuseColor" property
* mesh.addController(
* new AnimationController(
* new <ITimeline>[new ColorTimeline(
* "dataProvider.diffuseColor",
* 5000,
* new <uint>[0xffffffff, 0xffffff00, 0xffffffff]
* )]
* )
* );
* </pre>
*
* @return
*
*/
public function get properties() : DataProvider
{
return _properties;
}
public function set properties(value : DataProvider) : void
{
if (_properties != value)
{
if (_properties)
_bindings.removeProvider(_properties);
_properties = value;
if (value)
_bindings.addProvider(value);
}
}
public function get material() : Material
{
return _material;
}
public function set material(value : Material) : void
{
if (_material != value)
{
if (_material)
_bindings.removeProvider(_material);
_material = value;
if (value)
_bindings.addProvider(value);
}
}
/**
* The rendering properties provided to the shaders to customize
* how the mesh will appear on screen.
*
* @return
*
*/
public function get bindings() : DataBindings
{
return _bindings;
}
/**
* The Geometry of the mesh.
* @return
*
*/
public function get geometry() : Geometry
{
return _geometry;
}
public function set geometry(value : Geometry) : void
{
if (_geometry != value)
{
var oldGeometry : Geometry = _geometry;
_geometry = value;
_geometryChanged.execute(this, oldGeometry, value);
}
}
/**
* Whether the mesh is visible or not.
*
* @return
*
*/
public function get visible() : Boolean
{
return _visibility.visible;
}
public function set visible(value : Boolean) : void
{
_visibility.visible = value;
}
public function get frustumCulling() : uint
{
return _visibility.frustumCulling;
}
public function set frustumCulling(value : uint) : void
{
_visibility.frustumCulling = value;
}
public function get cloned() : Signal
{
return _cloned;
}
public function get materialChanged() : Signal
{
return _materialChanged;
}
public function get frameChanged() : Signal
{
return _frameChanged;
}
public function get geometryChanged() : Signal
{
return _geometryChanged;
}
public function get frame() : uint
{
return _frame;
}
public function set frame(value : uint) : void
{
if (_frame != value)
{
var oldFrame : uint = _frame;
_frame = value;
_frameChanged.execute(this, oldFrame, value);
}
}
public function Mesh(geometry : Geometry = null,
material : Material = null,
...controllers)
{
super();
initialize(geometry, material, controllers);
}
private function initialize(geometry : Geometry,
material : Material,
controllers : Array) : void
{
_bindings = new DataBindings(this);
this.properties = new DataProvider(properties, 'meshProperties', DataProviderUsage.EXCLUSIVE);
_geometry = geometry;
this.material = material || DEFAULT_MATERIAL;
// _visibility.frustumCulling = FrustumCulling.ENABLED;
addController(_visibility);
while (controllers && !(controllers[0] is AbstractController))
controllers = controllers[0];
if (controllers)
for each (var ctrl : AbstractController in controllers)
addController(ctrl);
}
public function cast(ray : Ray, maxDistance : Number = Number.POSITIVE_INFINITY) : Number
{
return _geometry.boundingBox.testRay(
ray,
worldToLocal,
maxDistance
);
}
override public function clone(cloneControllers : Boolean = false) : ISceneNode
{
var clone : Mesh = new Mesh();
clone.copyFrom(this, true, cloneControllers);
return clone;
}
override protected function addedToSceneHandler(child : ISceneNode, scene : Scene) : void
{
super.addedToSceneHandler(child, scene);
if (child === this)
_bindings.addProvider(transformData);
}
override protected function removedFromSceneHandler(child : ISceneNode, scene : Scene) : void
{
super.removedFromSceneHandler(child, scene);
if (child === this)
_bindings.removeProvider(transformData);
}
protected function copyFrom(source : Mesh,
withBindings : Boolean,
cloneControllers : Boolean) : void
{
var numControllers : uint = source.numControllers;
name = source.name;
geometry = source._geometry;
properties = DataProvider(source._properties.clone());
_bindings.copySharedProvidersFrom(source._bindings);
copyControllersFrom(
source, this, cloneControllers, new <AbstractController>[source._visibility]
);
_visibility = source._visibility.clone() as MeshVisibilityController;
addController(_visibility);
transform.copyFrom(source.transform);
material = source._material;
source.cloned.execute(this, source);
}
}
}
|
package aerys.minko.scene.node
{
import aerys.minko.render.Effect;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.material.Material;
import aerys.minko.render.material.basic.BasicMaterial;
import aerys.minko.render.material.basic.BasicShader;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.controller.mesh.MeshVisibilityController;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.bounding.FrustumCulling;
import aerys.minko.type.enum.DataProviderUsage;
import aerys.minko.type.math.Ray;
/**
* Mesh objects are a visible instance of a Geometry rendered using a specific
* Effect with specific rendering properties.
*
* <p>
* Those rendering properties are stored in a DataBindings object so they can
* be directly used by the shaders in the rendering API.
* </p>
*
* @author Jean-Marc Le Roux
*
*/
public class Mesh extends AbstractSceneNode
{
public static const DEFAULT_MATERIAL : Material = new Material(
new Effect(new BasicShader())
);
private var _geometry : Geometry = null;
private var _properties : DataProvider = null;
private var _material : Material = null;
private var _bindings : DataBindings = null;
private var _visibility : MeshVisibilityController = new MeshVisibilityController();
private var _frame : uint = 0;
private var _cloned : Signal = new Signal('Mesh.clones');
private var _materialChanged : Signal = new Signal('Mesh.materialChanged');
private var _frameChanged : Signal = new Signal('Mesh.frameChanged');
private var _geometryChanged : Signal = new Signal('Mesh.geometryChanged');
/**
* A DataProvider object already bound to the Mesh bindings.
*
* <pre>
* // set the "diffuseColor" property to 0x0000ffff
* mesh.properties.diffuseColor = 0x0000ffff;
*
* // animate the "diffuseColor" property
* mesh.addController(
* new AnimationController(
* new <ITimeline>[new ColorTimeline(
* "dataProvider.diffuseColor",
* 5000,
* new <uint>[0xffffffff, 0xffffff00, 0xffffffff]
* )]
* )
* );
* </pre>
*
* @return
*
*/
public function get properties() : DataProvider
{
return _properties;
}
public function set properties(value : DataProvider) : void
{
if (_properties != value)
{
if (_properties)
_bindings.removeProvider(_properties);
_properties = value;
if (value)
_bindings.addProvider(value);
}
}
public function get material() : Material
{
return _material;
}
public function set material(value : Material) : void
{
if (_material != value)
{
if (_material)
_bindings.removeProvider(_material);
_material = value;
if (value)
_bindings.addProvider(value);
}
}
/**
* The rendering properties provided to the shaders to customize
* how the mesh will appear on screen.
*
* @return
*
*/
public function get bindings() : DataBindings
{
return _bindings;
}
/**
* The Geometry of the mesh.
* @return
*
*/
public function get geometry() : Geometry
{
return _geometry;
}
public function set geometry(value : Geometry) : void
{
if (_geometry != value)
{
var oldGeometry : Geometry = _geometry;
_geometry = value;
_geometryChanged.execute(this, oldGeometry, value);
}
}
/**
* Whether the mesh is visible or not.
*
* @return
*
*/
public function get visible() : Boolean
{
return _visibility.visible;
}
public function set visible(value : Boolean) : void
{
_visibility.visible = value;
}
public function get frustumCulling() : uint
{
return _visibility.frustumCulling;
}
public function set frustumCulling(value : uint) : void
{
_visibility.frustumCulling = value;
}
public function get cloned() : Signal
{
return _cloned;
}
public function get materialChanged() : Signal
{
return _materialChanged;
}
public function get frameChanged() : Signal
{
return _frameChanged;
}
public function get geometryChanged() : Signal
{
return _geometryChanged;
}
public function get frame() : uint
{
return _frame;
}
public function set frame(value : uint) : void
{
if (_frame != value)
{
var oldFrame : uint = _frame;
_frame = value;
_frameChanged.execute(this, oldFrame, value);
}
}
public function Mesh(geometry : Geometry = null,
material : Material = null,
...controllers)
{
super();
initialize(geometry, material, controllers);
}
private function initialize(geometry : Geometry,
material : Material,
controllers : Array) : void
{
_bindings = new DataBindings(this);
this.properties = new DataProvider(properties, 'meshProperties', DataProviderUsage.EXCLUSIVE);
_geometry = geometry;
this.material = material || DEFAULT_MATERIAL;
// _visibility.frustumCulling = FrustumCulling.ENABLED;
addController(_visibility);
while (controllers && !(controllers[0] is AbstractController))
controllers = controllers[0];
if (controllers)
for each (var ctrl : AbstractController in controllers)
addController(ctrl);
}
public function cast(ray : Ray, maxDistance : Number = Number.POSITIVE_INFINITY) : Number
{
return _geometry.boundingBox.testRay(
ray,
worldToLocal,
maxDistance
);
}
override public function clone(cloneControllers : Boolean = false) : ISceneNode
{
var clone : Mesh = new Mesh();
clone.copyFrom(this, true, cloneControllers);
return clone;
}
override protected function addedToSceneHandler(child : ISceneNode, scene : Scene) : void
{
super.addedToSceneHandler(child, scene);
if (child === this)
_bindings.addProvider(transformData);
}
override protected function removedFromSceneHandler(child : ISceneNode, scene : Scene) : void
{
super.removedFromSceneHandler(child, scene);
if (child === this)
_bindings.removeProvider(transformData);
}
protected function copyFrom(source : Mesh,
withBindings : Boolean,
cloneControllers : Boolean) : void
{
var numControllers : uint = source.numControllers;
name = source.name;
geometry = source._geometry;
properties = DataProvider(source._properties.clone());
_bindings.copySharedProvidersFrom(source._bindings);
copyControllersFrom(
source, this, cloneControllers, new <AbstractController>[source._visibility]
);
_visibility = source._visibility.clone() as MeshVisibilityController;
addController(_visibility);
transform.copyFrom(source.transform);
material = source._material;
source.cloned.execute(source, this);
}
}
}
|
Switch arguments in callbacks of the cloned signal
|
Switch arguments in callbacks of the cloned signal
|
ActionScript
|
mit
|
aerys/minko-as3
|
47b6fb1cf01fa23f06132ae01dc8cff04d33b6e1
|
src/ageofai/home/view/HomeView.as
|
src/ageofai/home/view/HomeView.as
|
/**
* Created by newkrok on 08/04/16.
*/
package ageofai.home.view
{
import ageofai.building.base.BaseBuildingView;
<<<<<<< Updated upstream
import ageofai.home.view.event.HomeViewEvent;
import ageofai.villager.event.VillagerEvent;
import ageofai.villager.view.VillagerView;
=======
import ageofai.map.constant.CMap;
>>>>>>> Stashed changes
public class HomeView extends BaseBuildingView
{
public function HomeView()
{
this.createUI( HomeUI );
this.createLifeBar();
this.createProgressBar();
this._graphicUI.x = CMap.TILE_SIZE;
this._graphicUI.y = CMap.TILE_SIZE;
}
public function showProgressValue( value:Number):void
{
this._buildProgressBar.show();
this._buildProgressBar.drawProcessBar( value );
}
public function createVillagerView():void
{
var homeViewEvent:HomeViewEvent = new HomeViewEvent( HomeViewEvent.VILLAGER_VIEW_CREATED );
homeViewEvent.villagerView = new VillagerView( );
this.dispatchEvent( homeViewEvent );
}
}
}
|
/**
* Created by newkrok on 08/04/16.
*/
package ageofai.home.view
{
import ageofai.building.base.BaseBuildingView;
import ageofai.home.view.event.HomeViewEvent;
import ageofai.villager.view.VillagerView;
import ageofai.map.constant.CMap;
public class HomeView extends BaseBuildingView
{
public function HomeView()
{
this.createUI( HomeUI );
this.createLifeBar();
this.createProgressBar();
this._graphicUI.x = CMap.TILE_SIZE;
this._graphicUI.y = CMap.TILE_SIZE;
}
public function showProgressValue( value:Number ):void
{
this._buildProgressBar.show();
this._buildProgressBar.drawProcessBar( value );
}
public function createVillagerView():void
{
var homeViewEvent:HomeViewEvent = new HomeViewEvent( HomeViewEvent.VILLAGER_VIEW_CREATED );
homeViewEvent.villagerView = new VillagerView();
this.dispatchEvent( homeViewEvent );
}
}
}
|
Fix merge problem
|
Fix merge problem
Fix merge problem
|
ActionScript
|
apache-2.0
|
goc-flashplusplus/ageofai
|
06530fa3290e88cf6b48e030181686d9eee79d43
|
WEB-INF/lps/lfc/kernel/swf9/LzTimeKernel.as
|
WEB-INF/lps/lfc/kernel/swf9/LzTimeKernel.as
|
/**
* LzTimeKernel.as
*
* @copyright Copyright 2001-2009 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic Kernel
* @subtopic swf9
*/
// Receives and sends timing events
final class LzTimeKernelClass {
#passthrough (toplevel:true) {
import flash.utils.getTimer;
import flash.events.TimerEvent;
}#
private const MAX_POOL :int = 10;
private var timerPool :Array = [];
private var timers :Object = {};
/**
* Creates a new timer and returns an unique identifier which can be used to remove the timer.
*/
private function createTimer (delay:Number, repeatCount:int, closure:Function, args:Array) :uint {
var timer:LzKernelTimer = this.timerPool.pop() || new LzKernelTimer();
this.timers[timer.timerID] = timer;
timer.delay = delay;
timer.repeatCount = repeatCount;
timer.closure = closure;
timer.arguments = args;
timer.addEventListener(TimerEvent.TIMER, this.timerHandler);
timer.addEventListener(TimerEvent.TIMER_COMPLETE, this.timerCompleteHandler);
timer.start();
return timer.timerID;
}
/**
* Stops and removes the timer with the given id.
*/
private function removeTimer (id:uint) :void {
var timer:LzKernelTimer = this.timers[id];
if (timer) {
timer.closure = null;
timer.arguments = null;
timer.removeEventListener(TimerEvent.TIMER, this.timerHandler);
timer.removeEventListener(TimerEvent.TIMER_COMPLETE, this.timerCompleteHandler);
timer.reset();
delete this.timers[id];
if (this.timerPool.length < this.MAX_POOL) {
this.timerPool.push(timer);
}
}
}
private function timerHandler (event:TimerEvent) :void {
var timer:LzKernelTimer = LzKernelTimer(event.target);
if (timer.closure) {
timer.closure.apply(null, timer.arguments);
}
}
private function timerCompleteHandler (event:TimerEvent) :void {
var timer:LzKernelTimer = LzKernelTimer(event.target);
this.removeTimer(timer.timerID);
}
public const getTimer :Function = flash.utils.getTimer;
// const setTimeout :Function = flash.utils.setTimeout;
public function setTimeout (closure:Function, delay:Number, ...args) :uint {
return this.createTimer(delay, 1, closure, args);
}
// const setInterval :Function = flash.utils.setInterval;
public function setInterval (closure:Function, delay:Number, ...args) :uint {
return this.createTimer(delay, 0, closure, args);
}
// const clearTimeout :Function = flash.utils.clearTimeout;
public function clearTimeout (id:uint) :void {
this.removeTimer(id);
}
// const clearInterval :Function = flash.utils.clearInterval;
public function clearInterval (id:uint) :void {
this.removeTimer(id);
}
function LzTimeKernelClass() {
}
}
var LzTimeKernel = new LzTimeKernelClass();
/**
* This is a helper class for LzTimeKernel. In addition to the flash.utils.Timer
* class, each timer has got an unique id and holds a reference to a function
* and an arguments array.
* @see LzTimeKernelClass#createTimer
* @see LzTimeKernelClass#removeTimer
*/
final class LzKernelTimer extends Timer {
#passthrough (toplevel:true) {
import flash.utils.Timer;
}#
#passthrough {
private static var idCounter :uint = 0;
public function LzKernelTimer () {
super(0);
this._timerID = LzKernelTimer.idCounter++;
}
private var _timerID :uint;
public function get timerID () :uint {
return this._timerID;
}
private var _closure :Function;
public function get closure () :Function {
return this._closure;
}
public function set closure (c:Function) :void {
this._closure = c;
}
private var _arguments :Array;
public function get arguments () :Array {
return this._arguments;
}
public function set arguments (a:Array) :void {
this._arguments = a;
}
}#
}
|
/**
* LzTimeKernel.as
*
* @copyright Copyright 2001-2009 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic Kernel
* @subtopic swf9
*/
// Receives and sends timing events
final class LzTimeKernelClass {
#passthrough (toplevel:true) {
import flash.utils.getTimer;
import flash.events.TimerEvent;
}#
private var timers :Object = {};
/**
* Creates a new timer and returns an unique identifier which can be used to remove the timer.
*/
private function createTimer (delay:Number, repeatCount:int, closure:Function, args:Array) :uint {
var timer:LzKernelTimer = LzKernelTimer.create();
this.timers[timer.timerID] = timer;
timer.delay = delay;
timer.repeatCount = repeatCount;
timer.closure = closure;
timer.arguments = args;
timer.addEventListener(TimerEvent.TIMER, this.timerHandler);
timer.addEventListener(TimerEvent.TIMER_COMPLETE, this.timerCompleteHandler);
timer.start();
return timer.timerID;
}
/**
* Stops and removes the timer with the given id.
*/
private function removeTimer (id:uint) :void {
var timer:LzKernelTimer = this.timers[id];
if (timer) {
timer.closure = null;
timer.arguments = null;
timer.removeEventListener(TimerEvent.TIMER, this.timerHandler);
timer.removeEventListener(TimerEvent.TIMER_COMPLETE, this.timerCompleteHandler);
timer.reset();
delete this.timers[id];
LzKernelTimer.remove(timer);
}
}
private function timerHandler (event:TimerEvent) :void {
var timer:LzKernelTimer = LzKernelTimer(event.target);
if (timer.closure) {
timer.closure.apply(null, timer.arguments);
}
}
private function timerCompleteHandler (event:TimerEvent) :void {
var timer:LzKernelTimer = LzKernelTimer(event.target);
this.removeTimer(timer.timerID);
}
public const getTimer :Function = flash.utils.getTimer;
// const setTimeout :Function = flash.utils.setTimeout;
public function setTimeout (closure:Function, delay:Number, ...args) :uint {
return this.createTimer(delay, 1, closure, args);
}
// const setInterval :Function = flash.utils.setInterval;
public function setInterval (closure:Function, delay:Number, ...args) :uint {
return this.createTimer(delay, 0, closure, args);
}
// const clearTimeout :Function = flash.utils.clearTimeout;
public function clearTimeout (id:uint) :void {
this.removeTimer(id);
}
// const clearInterval :Function = flash.utils.clearInterval;
public function clearInterval (id:uint) :void {
this.removeTimer(id);
}
function LzTimeKernelClass() {
}
}
var LzTimeKernel = new LzTimeKernelClass();
/**
* This is a helper class for LzTimeKernel. In addition to the flash.utils.Timer
* class, each timer has got an unique id and holds a reference to a function
* and an arguments array.
* @see LzTimeKernelClass#createTimer
* @see LzTimeKernelClass#removeTimer
*/
final class LzKernelTimer extends Timer {
#passthrough (toplevel:true) {
import flash.utils.Timer;
}#
#passthrough {
private static var idCounter :uint = 0;
private static const MAX_POOL :int = 10;
private static var timerPool :Array = [];
/**
* Use this method instead of the constructor to create an instance
*/
public static function create () :LzKernelTimer {
var timer:LzKernelTimer = timerPool.pop() || new LzKernelTimer();
timer._timerID = idCounter++;
return timer;
}
/**
* Allow timers to be pooled and reused later
*/
public static function remove (timer:LzKernelTimer) :void {
if (timerPool.length < MAX_POOL) {
timerPool.push(timer);
}
}
public function LzKernelTimer () {
super(0);
}
private var _timerID :uint;
public function get timerID () :uint {
return this._timerID;
}
private var _closure :Function;
public function get closure () :Function {
return this._closure;
}
public function set closure (c:Function) :void {
this._closure = c;
}
private var _arguments :Array;
public function get arguments () :Array {
return this._arguments;
}
public function set arguments (a:Array) :void {
this._arguments = a;
}
}#
}
|
Change 20091010-bargull-uVg by bargull@dell--p4--2-53 on 2009-10-10 17:05:16 in /home/Admin/src/svn/openlaszlo/trunk for http://svn.openlaszlo.org/openlaszlo/trunk
|
Change 20091010-bargull-uVg by bargull@dell--p4--2-53 on 2009-10-10 17:05:16
in /home/Admin/src/svn/openlaszlo/trunk
for http://svn.openlaszlo.org/openlaszlo/trunk
Summary: ensure pooled timers don't reuse UID
New Features:
Bugs Fixed: LPP-8545 (SWF9: Pooled Timer must not reuse UID)
Technical Reviewer: ptw
QA Reviewer: (pending)
Doc Reviewer: (pending)
Documentation:
Release Notes:
Details:
Moved timer pool from LzTimeKernelClass to LzKernelTimer. Timers should now be created to the static function "create()" and later returned to the timer pool through "remove()". "create()" takes care that timers won't reuse an UID.
Tests:
test case from bug report works in swf9+
git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@15012 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
|
ActionScript
|
epl-1.0
|
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
|
130b4d59d7e0d4d4cad416e2eba51ebe7264cda2
|
src/goplayer/ConfigurationParser.as
|
src/goplayer/ConfigurationParser.as
|
package goplayer
{
public class ConfigurationParser
{
public static const DEFAULT_SKIN_URL : String = "goplayer-skin.swf"
public static const DEFAULT_STREAMIO_API_URL : String
= "http://staging.streamio.com/api"
public static const DEFAULT_STREAMIO_TRACKER_ID : String = "global"
public static const VALID_PARAMETERS : Array
= ["skin", "src", "bitrate",
"enablertmp", "autoplay", "loop",
"skin:showchrome", "skin:showtitle",
"streamio:api", "streamio:tracker"]
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.skinURL = getString("skin", DEFAULT_SKIN_URL)
result.movieID = getStreamioVideoID()
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)
result.apiURL = getString
("streamio:api", DEFAULT_STREAMIO_API_URL)
result.trackerID = getString
("streamio:tracker", DEFAULT_STREAMIO_TRACKER_ID)
}
private function getStreamioVideoID() : String
{
if ("src" in parameters)
return $getStreamioVideoID()
else
{
debug("Error: Missing “src” parameter.")
return null
}
}
private function $getStreamioVideoID() : String
{
const src : String = parameters["src"]
const match : Array = src.match(/^streamio:video:(.*)$/)
if (match != null)
return match[1]
else
{
debug("Error: Unrecognized “src” value: “" + src + "”; " +
"must be “streamio:video:foo”.")
return null
}
}
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_SKIN_URL : String = "goplayer-skin.swf"
public static const DEFAULT_STREAMIO_API_URL : String
= "http://streamio.com/api"
public static const DEFAULT_STREAMIO_TRACKER_ID : String = "global"
public static const VALID_PARAMETERS : Array
= ["skin", "src", "bitrate",
"enablertmp", "autoplay", "loop",
"skin:showchrome", "skin:showtitle",
"streamio:api", "streamio:tracker"]
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.skinURL = getString("skin", DEFAULT_SKIN_URL)
result.movieID = getStreamioVideoID()
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)
result.apiURL = getString
("streamio:api", DEFAULT_STREAMIO_API_URL)
result.trackerID = getString
("streamio:tracker", DEFAULT_STREAMIO_TRACKER_ID)
}
private function getStreamioVideoID() : String
{
if ("src" in parameters)
return $getStreamioVideoID()
else
{
debug("Error: Missing “src” parameter.")
return null
}
}
private function $getStreamioVideoID() : String
{
const src : String = parameters["src"]
const match : Array = src.match(/^streamio:video:(.*)$/)
if (match != null)
return match[1]
else
{
debug("Error: Unrecognized “src” value: “" + src + "”; " +
"must be “streamio:video:foo”.")
return null
}
}
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
}
}
}
|
Change default API URL to <http://streamio.com/api>.
|
Change default API URL to <http://streamio.com/api>.
|
ActionScript
|
mit
|
dbrock/goplayer,dbrock/goplayer
|
49b9968026233bdc5a056fc36b0a0e6cff4126f1
|
src/aerys/minko/scene/controller/light/SpotLightController.as
|
src/aerys/minko/scene/controller/light/SpotLightController.as
|
package aerys.minko.scene.controller.light
{
import aerys.minko.scene.data.LightDataProvider;
import aerys.minko.scene.node.Scene;
import aerys.minko.scene.node.light.AbstractLight;
import aerys.minko.scene.node.light.SpotLight;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
/**
*
* @author Jean-Marc Le Roux
*
*/
public final class SpotLightController extends LightController
{
private static const SCREEN_TO_UV : Matrix4x4 = new Matrix4x4(
.5, .0, .0, .0,
.0, -.5, .0, .0,
.0, .0, 1., .0,
.5, .5, .0, 1.
);
private var _worldPosition : Vector4;
private var _worldDirection : Vector4;
private var _projection : Matrix4x4;
private var _worldToScreen : Matrix4x4;
private var _worldToUV : Matrix4x4;
public function SpotLightController()
{
super(SpotLight);
initialize();
}
private function initialize() : void
{
_worldDirection = new Vector4();
_worldPosition = new Vector4();
_projection = new Matrix4x4();
_worldToScreen = new Matrix4x4();
_worldToUV = new Matrix4x4();
}
override protected function lightAddedHandler(ctrl : LightController,
light : AbstractLight) : void
{
super.lightAddedHandler(ctrl, light);
lightData.setLightProperty('worldDirection', _worldDirection);
lightData.setLightProperty('worldPosition', _worldPosition);
lightData.setLightProperty('projection', _projection);
lightData.setLightProperty('worldToScreen', _worldToScreen);
lightData.setLightProperty('worldToUV', _worldToUV);
}
override protected function lightAddedToSceneHandler(light : AbstractLight,
scene : Scene) : void
{
super.lightAddedToSceneHandler(light, scene);
updateProjectionMatrix();
lightLocalToWorldChangedHandler(light.localToWorld);
light.localToWorld.changed.add(lightLocalToWorldChangedHandler);
}
override protected function lightRemovedFromSceneHandler(light : AbstractLight,
scene : Scene) : void
{
super.lightRemovedFromSceneHandler(light, scene);
light.localToWorld.changed.remove(lightLocalToWorldChangedHandler);
}
private function lightLocalToWorldChangedHandler(localToWorld : Matrix4x4) : void
{
_worldPosition = localToWorld.getTranslation(_worldPosition);
_worldDirection.lock();
_worldDirection = localToWorld.deltaTransformVector(Vector4.Z_AXIS, _worldDirection);
_worldDirection.normalize();
_worldDirection.unlock();
_worldToScreen.lock()
.copyFrom(light.worldToLocal)
.append(_projection)
.unlock();
_worldToUV.lock()
.copyFrom(_worldToScreen)
.append(SCREEN_TO_UV)
.unlock();
}
override protected function lightDataChangedHandler(lightData : LightDataProvider,
propertyName : String) : void
{
super.lightDataChangedHandler(lightData, propertyName);
propertyName = LightDataProvider.getPropertyName(propertyName);
if (propertyName == 'shadowZNear' || propertyName == 'shadowZFar'
|| propertyName == 'outerRadius')
updateProjectionMatrix();
}
private function updateProjectionMatrix() : void
{
var zNear : Number = lightData.getLightProperty('shadowZNear');
var zFar : Number = lightData.getLightProperty('shadowZFar');
var outerRadius : Number = lightData.getLightProperty('outerRadius');
var fd : Number = 1. / Math.tan(outerRadius * .5);
var m33 : Number = 1. / (zFar - zNear);
var m43 : Number = -zNear / (zFar - zNear);
_projection.initialize(
fd, 0., 0., 0.,
0., fd, 0., 0.,
0., 0., m33, 1.,
0., 0., m43, 0.
);
_worldToScreen.lock()
.copyFrom(light.worldToLocal)
.append(_projection)
.unlock();
_worldToUV.lock()
.copyFrom(_worldToScreen)
.append(SCREEN_TO_UV)
.unlock();
}
}
}
|
package aerys.minko.scene.controller.light
{
import aerys.minko.scene.data.LightDataProvider;
import aerys.minko.scene.node.Scene;
import aerys.minko.scene.node.light.AbstractLight;
import aerys.minko.scene.node.light.SpotLight;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
/**
*
* @author Jean-Marc Le Roux
*
*/
public final class SpotLightController extends LightController
{
private static const SCREEN_TO_UV : Matrix4x4 = new Matrix4x4(
.5, .0, .0, .0,
.0, -.5, .0, .0,
.0, .0, 1., .0,
.5, .5, .0, 1.
);
private var _worldPosition : Vector4;
private var _worldDirection : Vector4;
private var _projection : Matrix4x4;
private var _worldToScreen : Matrix4x4;
private var _worldToUV : Matrix4x4;
public function SpotLightController()
{
super(SpotLight);
initialize();
}
private function initialize() : void
{
_worldDirection = new Vector4();
_worldPosition = new Vector4();
_projection = new Matrix4x4();
_worldToScreen = new Matrix4x4();
_worldToUV = new Matrix4x4();
}
override protected function lightAddedHandler(ctrl : LightController,
light : AbstractLight) : void
{
super.lightAddedHandler(ctrl, light);
lightData.setLightProperty('worldDirection', _worldDirection);
lightData.setLightProperty('worldPosition', _worldPosition);
lightData.setLightProperty('projection', _projection);
lightData.setLightProperty('worldToScreen', _worldToScreen);
lightData.setLightProperty('worldToUV', _worldToUV);
}
override protected function lightAddedToSceneHandler(light : AbstractLight,
scene : Scene) : void
{
super.lightAddedToSceneHandler(light, scene);
updateProjectionMatrix();
lightLocalToWorldChangedHandler(light.localToWorld);
light.localToWorld.changed.add(lightLocalToWorldChangedHandler);
}
override protected function lightRemovedFromSceneHandler(light : AbstractLight,
scene : Scene) : void
{
super.lightRemovedFromSceneHandler(light, scene);
light.localToWorld.changed.remove(lightLocalToWorldChangedHandler);
}
private function lightLocalToWorldChangedHandler(localToWorld : Matrix4x4) : void
{
_worldPosition = localToWorld.getTranslation(_worldPosition);
_worldDirection.lock();
_worldDirection = localToWorld.deltaTransformVector(Vector4.Z_AXIS, _worldDirection);
_worldDirection.normalize();
_worldDirection.unlock();
_worldToScreen.lock()
.copyFrom(light.worldToLocal)
.append(_projection)
.unlock();
_worldToUV.lock()
.copyFrom(_worldToScreen)
.append(SCREEN_TO_UV)
.unlock();
}
override protected function lightDataChangedHandler(lightData : LightDataProvider,
propertyName : String) : void
{
super.lightDataChangedHandler(lightData, propertyName);
propertyName = LightDataProvider.getPropertyName(propertyName);
if (propertyName == 'shadowZNear' || propertyName == 'shadowZFar'
|| propertyName == 'outerRadius')
updateProjectionMatrix();
}
private function updateProjectionMatrix() : void
{
var zNear : Number = lightData.getLightProperty('shadowZNear');
var zFar : Number = lightData.getLightProperty('shadowZFar');
var outerRadius : Number = lightData.getLightProperty('outerRadius');
var fd : Number = 1. / Math.tan(outerRadius * .5);
var m33 : Number = 1. / (zFar - zNear);
var m43 : Number = -zNear / (zFar - zNear);
_projection.initialize(
fd, 0., 0., 0.,
0., fd, 0., 0.,
0., 0., m33, 1.,
0., 0., m43, 0.
);
_worldToScreen.lock()
.copyFrom(light.worldToLocal)
.append(_projection)
.unlock();
_worldToUV.lock()
.copyFrom(_worldToScreen)
.append(SCREEN_TO_UV)
.unlock();
}
}
}
|
fix coding style
|
fix coding style
|
ActionScript
|
mit
|
aerys/minko-as3
|
88007477c20c8e2b6d5cf391481d836dee30b6fb
|
as3/xobjas3/src/com/rpath/xobj/XObjUtils.as
|
as3/xobjas3/src/com/rpath/xobj/XObjUtils.as
|
/*
#
# Copyright (c) 2008 rPath, Inc.
#
# This program is distributed under the terms of the MIT License as found
# in a file called LICENSE. If it is not present, the license
# is always available at http://www.opensource.org/licenses/mit-license.php.
#
# This program is distributed in the hope that it will be useful, but
# without any waranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the MIT License for full details.
*/
package com.rpath.xobj
{
import mx.collections.ArrayCollection;
import mx.utils.DescribeTypeCache;
import mx.utils.ObjectProxy;
import flash.utils.getQualifiedClassName;
import flash.utils.getDefinitionByName;
import flash.xml.XMLNode;
import mx.utils.object_proxy;
use namespace object_proxy;
public class XObjUtils
{
public static const DEFAULT_NAMESPACE_PREFIX:String = "_default_";
/**
* @private
*/
private static var CLASS_INFO_CACHE:Object = {};
/**
* Returns the local name of an XMLNode.
*
* @return The local name of an XMLNode.
*/
public static function getLocalName(xmlNode:XMLNode):String
{
return getNCName(xmlNode.nodeName);
}
public static function getNCName(name:String):String
{
var myPrefixIndex:int = name.indexOf(":");
if (myPrefixIndex != -1)
{
name = name.substring(myPrefixIndex+1);
}
return name;
}
public static function encodeElementTag(qname:XObjQName, node:XMLNode):String
{
var elementTag:String = XObjUtils.getNCName(qname.localName);
var prefix:String = node.getPrefixForNamespace(qname.uri);
if (prefix)
elementTag = prefix + ":" + elementTag;
return elementTag;
}
/**
* Return a Class instance based on a string class name
* @private
*/
public static function getClassByName(className:String):Class
{
var classReference:Class = null;
try
{
classReference = getDefinitionByName(className) as Class;
}
catch (e:ReferenceError)
{
trace("Request for unknown class "+className);
}
return classReference;
}
private static var typePropertyCache:Object = {};
public static function isTypeArray(type:Class):Boolean
{
if (type == null)
return false;
var foo:* = new type();
return (foo is Array);
}
public static function isTypeArrayCollection(type:Class):Boolean
{
if (type == null)
return false;
var foo:* = new type();
return (foo is ArrayCollection);
}
public static function typeInfoForProperty(object:*, className:String, propName:String):Object
{
var isArray:Boolean = false;
var result:Object = {typeName: null, isArray: false, isArrayCollection: false};
if (propName == "label")
trace("stop");
if (className == "Object" || className == "mx.utils::ObjectProxy")
return result;
var propertyCacheKey:String = className + "." + propName;
var arrayElementType:String;
result = typePropertyCache[propertyCacheKey];
if (result == null)
{
result = {typeName: null, isArray: false, isArrayCollection: false};
// go look it up (expensive)
// very important to use the instance object here, not the classname
// using the classname results in the typeInfo cache
// returning class not instance info later on! Bad cache!
var typeDesc:* = DescribeTypeCache.describeType(object);
var typeInfo:XML = typeDesc.typeDescription;
result.typeName = typeInfo..accessor.(@name == propName)[email protected]().replace( /::/, "." );
if (result.typeName == null || result.typeName == "")
{
result.typeName = typeInfo..variable.(@name == propName)[email protected]().replace( /::/, "." );
arrayElementType = typeInfo..variable.(@name == propName).metadata.(@name == 'ArrayElementType')[email protected]().replace( /::/, "." );
}
else
arrayElementType = typeInfo..accessor.(@name == propName).metadata.(@name == 'ArrayElementType')[email protected]().replace( /::/, "." );
if (result.typeName == "Array")
{
result.isArray = true;
result.typeName = null; // assume generic object unless told otherwise
}
else if (result.typeName == "mx.collections.ArrayCollection")
{
result.isArrayCollection = true;
result.typeName = null; // assume generic object unless told otherwise
}
if (arrayElementType != "")
{
// use type specified
result.typeName = arrayElementType;
}
if (result.typeName == "Object"
|| result.typeName == "mx.utils::ObjectProxy"
|| result.typeName == "Undefined"
|| result.typeName == "*"
|| result.typeName == "")
{
result.typeName = null;
}
// cache the result for next time
typePropertyCache[propertyCacheKey] = result;
}
return result;
}
/**
* Use our own version of getClassInfo to support various metadata
* tags we use. See ObjectUtil.getClassInfo for more info about
* the baisc functionality of this method.
*/
public static function getClassInfo(obj:Object,
excludes:Array = null,
options:Object = null):Object
{
var n:int;
var i:int;
if (obj is ObjectProxy)
obj = ObjectProxy(obj).object_proxy::object;
if (options == null)
options = { includeReadOnly: true, uris: null, includeTransient: true };
var result:Object;
var propertyNames:Array = [];
var cacheKey:String;
var className:String;
var classAlias:String;
var properties:XMLList;
var prop:XML;
var dynamic:Boolean = false;
var metadataInfo:Object;
if (typeof(obj) == "xml")
{
className = "XML";
properties = obj.text();
if (properties.length())
propertyNames.push("*");
properties = obj.attributes();
}
else
{
var classInfo:XML = DescribeTypeCache.describeType(obj).typeDescription;
className = [email protected]();
classAlias = [email protected]();
dynamic = ([email protected]() == "true");
if (options.includeReadOnly)
properties = classInfo..accessor.(@access != "writeonly") + classInfo..variable;
else
properties = classInfo..accessor.(@access == "readwrite") + classInfo..variable;
var numericIndex:Boolean = false;
}
// If type is not dynamic, check our cache for class info...
if (!dynamic)
{
cacheKey = getCacheKey(obj, excludes, options);
result = CLASS_INFO_CACHE[cacheKey];
if (result != null)
return result;
}
result = {};
result["name"] = className;
result["alias"] = classAlias;
result["properties"] = propertyNames;
result["dynamic"] = dynamic;
result["metadata"] = metadataInfo = recordMetadata(properties);
var excludeObject:Object = {};
if (excludes)
{
n = excludes.length;
for (i = 0; i < n; i++)
{
excludeObject[excludes[i]] = 1;
}
}
//TODO this seems slightly fragile, why not use the 'is' operator?
var isArray:Boolean = (className == "Array");
var isDict:Boolean = (className == "flash.utils::Dictionary");
if (isDict)
{
// dictionaries can have multiple keys of the same type,
// (they can index by reference rather than QName, String, or number),
// which cannot be looked up by QName, so use references to the actual key
for (var key:* in obj)
{
propertyNames.push(key);
}
}
else if (dynamic)
{
for (var p:String in obj)
{
if (excludeObject[p] != 1)
{
if (isArray)
{
var pi:Number = parseInt(p);
if (isNaN(pi))
propertyNames.push(new QName("", p));
else
propertyNames.push(pi);
}
else
{
propertyNames.push(new QName("", p));
}
}
}
numericIndex = isArray && !isNaN(Number(p));
}
if (isArray || isDict || className == "Object")
{
// Do nothing since we've already got the dynamic members
}
else if (className == "XML")
{
n = properties.length();
for (i = 0; i < n; i++)
{
p = properties[i].name();
if (excludeObject[p] != 1)
propertyNames.push(new QName("", "@" + p));
}
}
else
{
n = properties.length();
var uris:Array = options.uris;
var uri:String;
var qName:QName;
for (i = 0; i < n; i++)
{
prop = properties[i];
p = [email protected]();
uri = [email protected]();
if (excludeObject[p] == 1)
continue;
if (!options.includeTransient && internalHasMetadata(metadataInfo, p, "Transient"))
continue;
if (internalHasMetadata(metadataInfo, p, "xobjTransient"))
continue;
if (uris != null)
{
if (uris.length == 1 && uris[0] == "*")
{
qName = new QName(uri, p);
try
{
obj[qName]; // access the property to ensure it is supported
propertyNames.push();
}
catch(e:Error)
{
// don't keep property name
}
}
else
{
for (var j:int = 0; j < uris.length; j++)
{
uri = uris[j];
if ([email protected]() == uri)
{
qName = new QName(uri, p);
try
{
obj[qName];
propertyNames.push(qName);
}
catch(e:Error)
{
// don't keep property name
}
}
}
}
}
else if (uri.length == 0)
{
qName = new QName(uri, p);
try
{
obj[qName];
propertyNames.push(qName);
}
catch(e:Error)
{
// don't keep property name
}
}
}
}
propertyNames.sort(Array.CASEINSENSITIVE |
(numericIndex ? Array.NUMERIC : 0));
// dictionary keys can be indexed by an object reference
// there's a possibility that two keys will have the same toString()
// so we don't want to remove dupes
if (!isDict)
{
// for Arrays, etc., on the other hand...
// remove any duplicates, i.e. any items that can't be distingushed by toString()
for (i = 0; i < propertyNames.length - 1; i++)
{
// the list is sorted so any duplicates should be adjacent
// two properties are only equal if both the uri and local name are identical
if (propertyNames[i].toString() == propertyNames[i + 1].toString())
{
propertyNames.splice(i, 1);
i--; // back up
}
}
}
// For normal, non-dynamic classes we cache the class info
if (!dynamic)
{
cacheKey = getCacheKey(obj, excludes, options);
CLASS_INFO_CACHE[cacheKey] = result;
}
return result;
}
/**
* @private
*/
private static function internalHasMetadata(metadataInfo:Object, propName:String, metadataName:String):Boolean
{
if (metadataInfo != null)
{
var metadata:Object = metadataInfo[propName];
if (metadata != null)
{
if (metadata[metadataName] != null)
return true;
}
}
return false;
}
/**
* @private
*/
private static function recordMetadata(properties:XMLList):Object
{
var result:Object = null;
try
{
for each (var prop:XML in properties)
{
var propName:String = prop.attribute("name").toString();
var metadataList:XMLList = prop.metadata;
if (metadataList.length() > 0)
{
if (result == null)
result = {};
var metadata:Object = {};
result[propName] = metadata;
for each (var md:XML in metadataList)
{
var mdName:String = md.attribute("name").toString();
var argsList:XMLList = md.arg;
var value:Object = {};
for each (var arg:XML in argsList)
{
var argKey:String = arg.attribute("key").toString();
if (argKey != null)
{
var argValue:String = arg.attribute("value").toString();
value[argKey] = argValue;
}
}
var existing:Object = metadata[mdName];
if (existing != null)
{
var existingArray:Array;
if (existing is Array)
existingArray = existing as Array;
else
existingArray = [];
existingArray.push(value);
existing = existingArray;
}
else
{
existing = value;
}
metadata[mdName] = existing;
}
}
}
}
catch(e:Error)
{
}
return result;
}
/**
* @private
*/
private static function getCacheKey(o:Object, excludes:Array = null, options:Object = null):String
{
var key:String = getQualifiedClassName(o);
if (excludes != null)
{
for (var i:uint = 0; i < excludes.length; i++)
{
var excl:String = excludes[i] as String;
if (excl != null)
key += excl;
}
}
if (options != null)
{
for (var flag:String in options)
{
key += flag;
var value:String = options[flag] as String;
if (value != null)
key += value;
}
}
return key;
}
}
}
|
/*
#
# Copyright (c) 2008 rPath, Inc.
#
# This program is distributed under the terms of the MIT License as found
# in a file called LICENSE. If it is not present, the license
# is always available at http://www.opensource.org/licenses/mit-license.php.
#
# This program is distributed in the hope that it will be useful, but
# without any waranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the MIT License for full details.
*/
package com.rpath.xobj
{
import mx.collections.ArrayCollection;
import mx.utils.DescribeTypeCache;
import mx.utils.ObjectProxy;
import flash.utils.getQualifiedClassName;
import flash.utils.getDefinitionByName;
import flash.xml.XMLNode;
import mx.utils.object_proxy;
use namespace object_proxy;
public class XObjUtils
{
public static const DEFAULT_NAMESPACE_PREFIX:String = "_default_";
/**
* @private
*/
private static var CLASS_INFO_CACHE:Object = {};
/**
* Returns the local name of an XMLNode.
*
* @return The local name of an XMLNode.
*/
public static function getLocalName(xmlNode:XMLNode):String
{
return getNCName(xmlNode.nodeName);
}
public static function getNCName(name:String):String
{
var myPrefixIndex:int = name.indexOf(":");
if (myPrefixIndex != -1)
{
name = name.substring(myPrefixIndex+1);
}
return name;
}
public static function encodeElementTag(qname:XObjQName, node:XMLNode):String
{
var elementTag:String = XObjUtils.getNCName(qname.localName);
var prefix:String = node.getPrefixForNamespace(qname.uri);
if (prefix)
elementTag = prefix + ":" + elementTag;
return elementTag;
}
/**
* Return a Class instance based on a string class name
* @private
*/
public static function getClassByName(className:String):Class
{
var classReference:Class = null;
try
{
classReference = getDefinitionByName(className) as Class;
}
catch (e:ReferenceError)
{
trace("Request for unknown class "+className);
}
return classReference;
}
private static var typePropertyCache:Object = {};
public static function isTypeArray(type:Class):Boolean
{
if (type == null)
return false;
var foo:* = new type();
return (foo is Array);
}
public static function isTypeArrayCollection(type:Class):Boolean
{
if (type == null)
return false;
var foo:* = new type();
return (foo is ArrayCollection);
}
public static function typeInfoForProperty(object:*, className:String, propName:String):Object
{
var isArray:Boolean = false;
var result:Object = {typeName: null, isArray: false, isArrayCollection: false};
if (className == "Object" || className == "mx.utils::ObjectProxy")
return result;
var propertyCacheKey:String = className + "." + propName;
var arrayElementType:String;
result = typePropertyCache[propertyCacheKey];
if (result == null)
{
result = {typeName: null, isArray: false, isArrayCollection: false};
// go look it up (expensive)
// very important to use the instance object here, not the classname
// using the classname results in the typeInfo cache
// returning class not instance info later on! Bad cache!
var typeDesc:* = DescribeTypeCache.describeType(object);
var typeInfo:XML = typeDesc.typeDescription;
result.typeName = typeInfo..accessor.(@name == propName)[email protected]().replace( /::/, "." );
if (result.typeName == null || result.typeName == "")
{
result.typeName = typeInfo..variable.(@name == propName)[email protected]().replace( /::/, "." );
arrayElementType = typeInfo..variable.(@name == propName).metadata.(@name == 'ArrayElementType')[email protected]().replace( /::/, "." );
}
else
arrayElementType = typeInfo..accessor.(@name == propName).metadata.(@name == 'ArrayElementType')[email protected]().replace( /::/, "." );
if (result.typeName == "Array")
{
result.isArray = true;
result.typeName = null; // assume generic object unless told otherwise
}
else if (result.typeName == "mx.collections.ArrayCollection")
{
result.isArrayCollection = true;
result.typeName = null; // assume generic object unless told otherwise
}
if (arrayElementType != "")
{
// use type specified
result.typeName = arrayElementType;
}
if (result.typeName == "Object"
|| result.typeName == "mx.utils::ObjectProxy"
|| result.typeName == "Undefined"
|| result.typeName == "*"
|| result.typeName == "")
{
result.typeName = null;
}
// cache the result for next time
typePropertyCache[propertyCacheKey] = result;
}
return result;
}
/**
* Use our own version of getClassInfo to support various metadata
* tags we use. See ObjectUtil.getClassInfo for more info about
* the baisc functionality of this method.
*/
public static function getClassInfo(obj:Object,
excludes:Array = null,
options:Object = null):Object
{
var n:int;
var i:int;
if (obj is ObjectProxy)
obj = ObjectProxy(obj).object_proxy::object;
if (options == null)
options = { includeReadOnly: true, uris: null, includeTransient: true };
var result:Object;
var propertyNames:Array = [];
var cacheKey:String;
var className:String;
var classAlias:String;
var properties:XMLList;
var prop:XML;
var dynamic:Boolean = false;
var metadataInfo:Object;
if (typeof(obj) == "xml")
{
className = "XML";
properties = obj.text();
if (properties.length())
propertyNames.push("*");
properties = obj.attributes();
}
else
{
var classInfo:XML = DescribeTypeCache.describeType(obj).typeDescription;
className = [email protected]();
classAlias = [email protected]();
dynamic = ([email protected]() == "true");
if (options.includeReadOnly)
properties = classInfo..accessor.(@access != "writeonly") + classInfo..variable;
else
properties = classInfo..accessor.(@access == "readwrite") + classInfo..variable;
var numericIndex:Boolean = false;
}
// If type is not dynamic, check our cache for class info...
if (!dynamic)
{
cacheKey = getCacheKey(obj, excludes, options);
result = CLASS_INFO_CACHE[cacheKey];
if (result != null)
return result;
}
result = {};
result["name"] = className;
result["alias"] = classAlias;
result["properties"] = propertyNames;
result["dynamic"] = dynamic;
result["metadata"] = metadataInfo = recordMetadata(properties);
var excludeObject:Object = {};
if (excludes)
{
n = excludes.length;
for (i = 0; i < n; i++)
{
excludeObject[excludes[i]] = 1;
}
}
//TODO this seems slightly fragile, why not use the 'is' operator?
var isArray:Boolean = (className == "Array");
var isDict:Boolean = (className == "flash.utils::Dictionary");
if (isDict)
{
// dictionaries can have multiple keys of the same type,
// (they can index by reference rather than QName, String, or number),
// which cannot be looked up by QName, so use references to the actual key
for (var key:* in obj)
{
propertyNames.push(key);
}
}
else if (dynamic)
{
for (var p:String in obj)
{
if (excludeObject[p] != 1)
{
if (isArray)
{
var pi:Number = parseInt(p);
if (isNaN(pi))
propertyNames.push(new QName("", p));
else
propertyNames.push(pi);
}
else
{
propertyNames.push(new QName("", p));
}
}
}
numericIndex = isArray && !isNaN(Number(p));
}
if (isArray || isDict || className == "Object")
{
// Do nothing since we've already got the dynamic members
}
else if (className == "XML")
{
n = properties.length();
for (i = 0; i < n; i++)
{
p = properties[i].name();
if (excludeObject[p] != 1)
propertyNames.push(new QName("", "@" + p));
}
}
else
{
n = properties.length();
var uris:Array = options.uris;
var uri:String;
var qName:QName;
for (i = 0; i < n; i++)
{
prop = properties[i];
p = [email protected]();
uri = [email protected]();
if (excludeObject[p] == 1)
continue;
if (!options.includeTransient && internalHasMetadata(metadataInfo, p, "Transient"))
continue;
if (internalHasMetadata(metadataInfo, p, "xobjTransient"))
continue;
if (uris != null)
{
if (uris.length == 1 && uris[0] == "*")
{
qName = new QName(uri, p);
try
{
obj[qName]; // access the property to ensure it is supported
propertyNames.push();
}
catch(e:Error)
{
// don't keep property name
}
}
else
{
for (var j:int = 0; j < uris.length; j++)
{
uri = uris[j];
if ([email protected]() == uri)
{
qName = new QName(uri, p);
try
{
obj[qName];
propertyNames.push(qName);
}
catch(e:Error)
{
// don't keep property name
}
}
}
}
}
else if (uri.length == 0)
{
qName = new QName(uri, p);
try
{
obj[qName];
propertyNames.push(qName);
}
catch(e:Error)
{
// don't keep property name
}
}
}
}
propertyNames.sort(Array.CASEINSENSITIVE |
(numericIndex ? Array.NUMERIC : 0));
// dictionary keys can be indexed by an object reference
// there's a possibility that two keys will have the same toString()
// so we don't want to remove dupes
if (!isDict)
{
// for Arrays, etc., on the other hand...
// remove any duplicates, i.e. any items that can't be distingushed by toString()
for (i = 0; i < propertyNames.length - 1; i++)
{
// the list is sorted so any duplicates should be adjacent
// two properties are only equal if both the uri and local name are identical
if (propertyNames[i].toString() == propertyNames[i + 1].toString())
{
propertyNames.splice(i, 1);
i--; // back up
}
}
}
// For normal, non-dynamic classes we cache the class info
if (!dynamic)
{
cacheKey = getCacheKey(obj, excludes, options);
CLASS_INFO_CACHE[cacheKey] = result;
}
return result;
}
/**
* @private
*/
private static function internalHasMetadata(metadataInfo:Object, propName:String, metadataName:String):Boolean
{
if (metadataInfo != null)
{
var metadata:Object = metadataInfo[propName];
if (metadata != null)
{
if (metadata[metadataName] != null)
return true;
}
}
return false;
}
/**
* @private
*/
private static function recordMetadata(properties:XMLList):Object
{
var result:Object = null;
try
{
for each (var prop:XML in properties)
{
var propName:String = prop.attribute("name").toString();
var metadataList:XMLList = prop.metadata;
if (metadataList.length() > 0)
{
if (result == null)
result = {};
var metadata:Object = {};
result[propName] = metadata;
for each (var md:XML in metadataList)
{
var mdName:String = md.attribute("name").toString();
var argsList:XMLList = md.arg;
var value:Object = {};
for each (var arg:XML in argsList)
{
var argKey:String = arg.attribute("key").toString();
if (argKey != null)
{
var argValue:String = arg.attribute("value").toString();
value[argKey] = argValue;
}
}
var existing:Object = metadata[mdName];
if (existing != null)
{
var existingArray:Array;
if (existing is Array)
existingArray = existing as Array;
else
existingArray = [];
existingArray.push(value);
existing = existingArray;
}
else
{
existing = value;
}
metadata[mdName] = existing;
}
}
}
}
catch(e:Error)
{
}
return result;
}
/**
* @private
*/
private static function getCacheKey(o:Object, excludes:Array = null, options:Object = null):String
{
var key:String = getQualifiedClassName(o);
if (excludes != null)
{
for (var i:uint = 0; i < excludes.length; i++)
{
var excl:String = excludes[i] as String;
if (excl != null)
key += excl;
}
}
if (options != null)
{
for (var flag:String in options)
{
key += flag;
var value:String = options[flag] as String;
if (value != null)
key += value;
}
}
return key;
}
}
}
|
Remove debug trace
|
Remove debug trace
|
ActionScript
|
apache-2.0
|
sassoftware/xobj,sassoftware/xobj,sassoftware/xobj,sassoftware/xobj
|
e6b11b136abbf18358d112bb6cf7d100b0a6386b
|
src/aerys/minko/type/loader/AssetsLibrary.as
|
src/aerys/minko/type/loader/AssetsLibrary.as
|
package aerys.minko.type.loader
{
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.material.Material;
import aerys.minko.render.material.basic.BasicMaterial;
import aerys.minko.render.resource.texture.TextureResource;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.type.Signal;
public final class AssetsLibrary
{
private var _numGeometries : uint = 0;
private var _numMaterials : uint = 0;
private var _numTextures : uint = 0;
private var _numSymbols : uint = 0;
private var _geometryList : Vector.<Geometry> = new Vector.<Geometry>();
private var _materialList : Vector.<Material> = new Vector.<Material>();
private var _textureList : Vector.<TextureResource> = new Vector.<TextureResource>();
private var _symbolList : Vector.<ISceneNode> = new Vector.<ISceneNode>();
private var _geometries : Object;
private var _symbols : Object;
private var _textures : Object;
private var _materials : Object;
private var _layers : Vector.<String>;
private var _nameToLayer : Object;
private var _geometryAdded : Signal;
private var _symbolAdded : Signal;
private var _textureAdded : Signal;
private var _materialAdded : Signal;
private var _layerAdded : Signal;
public function AssetsLibrary()
{
initialize();
initializeSignals();
}
public function get numSymbols() : uint
{
return _numSymbols;
}
public function get numTextures() : uint
{
return _numTextures;
}
public function get numGeometries() : uint
{
return _numGeometries;
}
public function get numMaterials() : uint
{
return _numMaterials;
}
public function getSymbolAt(index : uint) : ISceneNode
{
return _symbolList[index];
}
public function getMaterialAt(index : uint): Material
{
return _materialList[index];
}
public function getGeometryAt(index : uint): Geometry
{
return _geometryList[index];
}
public function getTextureAt(index : uint): TextureResource
{
return _textureList[index];
}
public function getSymbolByName(name : String) : ISceneNode
{
return _symbols[name];
}
public function getMaterialByName(name : String) : Material
{
return _materials[name];
}
public function getTextureByName(name : String) : TextureResource
{
return _textures[name];
}
public function getGeometryByName(name : String) : Geometry
{
return _geometries[name];
}
private function initialize() : void
{
_geometries = {};
_textures = {};
_materials = {};
_symbols = {};
_layers = new Vector.<String>(32, true);
_layers[0] = 'Default';
for (var i : uint = 1; i < _layers.length; ++i)
_layers[i] = 'Layer_' + i;
_nameToLayer = {};
}
private function initializeSignals() : void
{
_geometryAdded = new Signal('AssetsLibrary.geometryAdded');
_textureAdded = new Signal('AssetsLibrary.textureAdded');
_materialAdded = new Signal('AssetsLibrary.materialAdded');
_layerAdded = new Signal('AssetsLibrary.layerAdded');
_symbolAdded = new Signal('AssetsLibrary.symbolAdded');
}
public function get layerAdded() : Signal
{
return _layerAdded;
}
public function get materialAdded() : Signal
{
return _materialAdded;
}
public function get textureAdded() : Signal
{
return _textureAdded;
}
public function get geometryAdded() : Signal
{
return _geometryAdded;
}
public function get symbolAdded() : Signal
{
return _symbolAdded;
}
public function setSymbol(name : String, node : ISceneNode) : void
{
if (_symbolList.indexOf(node) == -1)
{
++_numSymbols;
_symbolList.push(node);
_symbols[name] = node;
_symbolAdded.execute(this, name, node);
}
}
public function setGeometry(name : String, geometry : Geometry) : void
{
if (_geometryList.indexOf(geometry) == -1)
{
++_numGeometries;
_geometryList.push(geometry);
_geometries[name] = geometry;
_geometryAdded.execute(this, name, geometry);
}
}
public function setTexture(name : String, texture : TextureResource) : void
{
if (_textureList.indexOf(texture) == -1)
{
++_numTextures;
_textureList.push(texture);
_textures[name] = texture;
_textureAdded.execute(this, name, texture);
}
}
public function setMaterial(name : String, material : Material) : void
{
material ||= new BasicMaterial();
name ||= material.name;
if (_materialList.indexOf(material) == -1)
{
++_numMaterials;
_materialList.push(material);
_materials[name] = material;
_materialAdded.execute(this, name, material);
}
}
public function setLayer(name : String, layer : uint) : void
{
name ||= 'Layer_' + layer;
_layers[layer] = name;
_layerAdded.execute(this, name, layer);
}
public function getLayerTag(name : String, ... params) : uint
{
var tag : uint = 0;
if (_nameToLayer[name])
{
tag |= 1 << _nameToLayer[name];
}
for each (name in params)
{
if (_nameToLayer[name])
{
tag |= 1 << _nameToLayer[name];
}
}
return tag;
}
public function getLayerName(tag : uint) : String
{
var names : Vector.<String> = new <String>[];
var name : String = null;
var i : uint = 0;
for (i = 0; i < 32; ++i)
{
if (tag & (1 << i))
names.push(_layers[i]);
}
name = names.join('|');
return name;
}
public function merge(other : AssetsLibrary) : AssetsLibrary
{
var name : String = null;
var i : uint = 0;
for (name in other._geometries)
setGeometry(name, other._geometries[name]);
for (name in other._materials)
setMaterial(name, other._materials[name]);
for (name in other._textures)
setTexture(name, other._textures[name]);
for each (name in other._layers)
setLayer(name, i++);
return this;
}
}
}
|
package aerys.minko.type.loader
{
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.material.Material;
import aerys.minko.render.material.basic.BasicMaterial;
import aerys.minko.render.resource.texture.TextureResource;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.type.Signal;
public final class AssetsLibrary
{
private var _numGeometries : uint = 0;
private var _numMaterials : uint = 0;
private var _numTextures : uint = 0;
private var _numSymbols : uint = 0;
private var _numLayers : uint = 0;
private var _layerList : Vector.<String> = new Vector.<String>();
private var _geometryList : Vector.<Geometry> = new Vector.<Geometry>();
private var _materialList : Vector.<Material> = new Vector.<Material>();
private var _textureList : Vector.<TextureResource> = new Vector.<TextureResource>();
private var _symbolList : Vector.<ISceneNode> = new Vector.<ISceneNode>();
private var _geometries : Object;
private var _symbols : Object;
private var _textures : Object;
private var _materials : Object;
private var _layers : Vector.<String>;
private var _nameToLayer : Object;
private var _geometryAdded : Signal;
private var _symbolAdded : Signal;
private var _textureAdded : Signal;
private var _materialAdded : Signal;
private var _layerAdded : Signal;
public function AssetsLibrary()
{
initialize();
initializeSignals();
}
public function get numLayers() : uint
{
return _numLayers;
}
public function get numSymbols() : uint
{
return _numSymbols;
}
public function get numTextures() : uint
{
return _numTextures;
}
public function get numGeometries() : uint
{
return _numGeometries;
}
public function get numMaterials() : uint
{
return _numMaterials;
}
public function getSymbolAt(index : uint) : ISceneNode
{
return _symbolList[index];
}
public function getMaterialAt(index : uint): Material
{
return _materialList[index];
}
public function getGeometryAt(index : uint): Geometry
{
return _geometryList[index];
}
public function getTextureAt(index : uint): TextureResource
{
return _textureList[index];
}
public function getSymbolByName(name : String) : ISceneNode
{
return _symbols[name];
}
public function getMaterialByName(name : String) : Material
{
return _materials[name];
}
public function getTextureByName(name : String) : TextureResource
{
return _textures[name];
}
public function getGeometryByName(name : String) : Geometry
{
return _geometries[name];
}
private function initialize() : void
{
_geometries = {};
_textures = {};
_materials = {};
_symbols = {};
_layers = new Vector.<String>(32, true);
_layers[0] = 'Default';
for (var i : uint = 1; i < _layers.length; ++i)
_layers[i] = 'Layer_' + i;
_nameToLayer = {};
}
private function initializeSignals() : void
{
_geometryAdded = new Signal('AssetsLibrary.geometryAdded');
_textureAdded = new Signal('AssetsLibrary.textureAdded');
_materialAdded = new Signal('AssetsLibrary.materialAdded');
_layerAdded = new Signal('AssetsLibrary.layerAdded');
_symbolAdded = new Signal('AssetsLibrary.symbolAdded');
}
public function get layerAdded() : Signal
{
return _layerAdded;
}
public function get materialAdded() : Signal
{
return _materialAdded;
}
public function get textureAdded() : Signal
{
return _textureAdded;
}
public function get geometryAdded() : Signal
{
return _geometryAdded;
}
public function get symbolAdded() : Signal
{
return _symbolAdded;
}
public function setSymbol(name : String, node : ISceneNode) : void
{
if (_symbolList.indexOf(node) == -1)
{
++_numSymbols;
_symbolList.push(node);
_symbols[name] = node;
_symbolAdded.execute(this, name, node);
}
}
public function setGeometry(name : String, geometry : Geometry) : void
{
if (_geometryList.indexOf(geometry) == -1)
{
++_numGeometries;
_geometryList.push(geometry);
_geometries[name] = geometry;
_geometryAdded.execute(this, name, geometry);
}
}
public function setTexture(name : String, texture : TextureResource) : void
{
if (_textureList.indexOf(texture) == -1)
{
++_numTextures;
_textureList.push(texture);
_textures[name] = texture;
_textureAdded.execute(this, name, texture);
}
}
public function setMaterial(name : String, material : Material) : void
{
material ||= new BasicMaterial();
name ||= material.name;
if (_materialList.indexOf(material) == -1)
{
++_numMaterials;
_materialList.push(material);
_materials[name] = material;
_materialAdded.execute(this, name, material);
}
}
public function setLayer(name : String, layer : uint) : void
{
name ||= 'Layer_' + layer;
_layers[layer] = name;
_layerAdded.execute(this, name, layer);
}
public function getLayerTag(name : String, ... params) : uint
{
var tag : uint = 0;
if (_nameToLayer[name])
{
tag |= 1 << _nameToLayer[name];
}
for each (name in params)
{
if (_nameToLayer[name])
{
tag |= 1 << _nameToLayer[name];
}
}
return tag;
}
public function getLayerName(tag : uint) : String
{
var names : Vector.<String> = new <String>[];
var name : String = null;
var i : uint = 0;
for (i = 0; i < 32; ++i)
{
if (tag & (1 << i))
names.push(_layers[i]);
}
name = names.join('|');
return name;
}
public function merge(other : AssetsLibrary) : AssetsLibrary
{
var name : String = null;
var i : uint = 0;
for (name in other._geometries)
setGeometry(name, other._geometries[name]);
for (name in other._materials)
setMaterial(name, other._materials[name]);
for (name in other._textures)
setTexture(name, other._textures[name]);
for each (name in other._layers)
setLayer(name, i++);
return this;
}
}
}
|
Add datastructure to store layers
|
Add datastructure to store layers
|
ActionScript
|
mit
|
aerys/minko-as3
|
5652ba775256800c4e0babb4e24d51b0eb8ff09f
|
fp9/src/as3isolib/display/scene/IsoScene.as
|
fp9/src/as3isolib/display/scene/IsoScene.as
|
/*
as3isolib - An open-source ActionScript 3.0 Isometric Library developed to assist
in creating isometrically projected content (such as games and graphics)
targeted for the Flash player platform
http://code.google.com/p/as3isolib/
Copyright (c) 2006 - 2008 J.W.Opitz, All Rights Reserved.
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 as3isolib.display.scene
{
import as3isolib.bounds.IBounds;
import as3isolib.bounds.SceneBounds;
import as3isolib.core.IIsoDisplayObject;
import as3isolib.core.IsoContainer;
import as3isolib.core.as3isolib_internal;
import as3isolib.data.INode;
import as3isolib.display.renderers.DefaultSceneLayoutRenderer;
import as3isolib.display.renderers.ISceneLayoutRenderer;
import as3isolib.display.renderers.ISceneRenderer;
import as3isolib.events.IsoEvent;
import flash.display.DisplayObjectContainer;
import mx.core.ClassFactory;
import mx.core.IFactory;
use namespace as3isolib_internal;
/**
* IsoScene is a base class for grouping and rendering IIsoDisplayObject children according to their isometric position-based depth.
*/
public class IsoScene extends IsoContainer implements IIsoScene
{
///////////////////////////////////////////////////////////////////////////////
// BOUNDS
///////////////////////////////////////////////////////////////////////////////
/**
* @private
*/
private var _isoBounds:IBounds;
/**
* @inheritDoc
*/
public function get isoBounds ():IBounds
{
/* if (!_isoBounds || isInvalidated)
_isoBounds = */
return new SceneBounds(this);
}
///////////////////////////////////////////////////////////////////////////////
// HOST CONTAINER
///////////////////////////////////////////////////////////////////////////////
/**
* @private
*/
protected var host:DisplayObjectContainer;
as3isolib_internal
/**
* @private
*/
public function get hostContainer ():DisplayObjectContainer
{
return host;
}
/**
* @inheritDoc
*/
public function set hostContainer (value:DisplayObjectContainer):void
{
if (value && host != value)
{
if (host && host.contains(container))
{
host.removeChild(container);
ownerObject = null;
}
else if (hasParent)
parent.removeChild(this);
host = value;
if (host)
{
host.addChild(container);
ownerObject = host;
parentNode = null;
}
}
}
///////////////////////////////////////////////////////////////////////////////
// INVALIDATE CHILDREN
///////////////////////////////////////////////////////////////////////////////
/**
* @private
*
* Array of invalidated children. Each child dispatches an IsoEvent.INVALIDATION event which notifies
* the scene that that particular child is invalidated and subsequentally the scene is also invalidated.
*/
protected var invalidatedChildrenArray:Array = [];
/**
* @inheritDoc
*/
public function get invalidatedChildren ():Array
{
return invalidatedChildrenArray;
}
///////////////////////////////////////////////////////////////////////////////
// OVERRIDES
///////////////////////////////////////////////////////////////////////////////
/**
* @inheritDoc
*/
override public function addChildAt (child:INode, index:uint):void
{
if (child is IIsoDisplayObject)
{
super.addChildAt(child, index);
child.addEventListener(IsoEvent.INVALIDATE, child_invalidateHandler);
bIsInvalidated = true; //since the child most likely had fired an invalidation event prior to being added, manually invalidate the scene
}
else
throw new Error ("parameter child is not of type IIsoDisplayObject");
}
/**
* @inheritDoc
*/
override public function setChildIndex (child:INode, index:uint):void
{
super.setChildIndex(child, index);
bIsInvalidated = true;
}
/**
* @inheritDoc
*/
override public function removeChildByID (id:String):INode
{
var child:INode = super.removeChildByID(id);
if (child)
{
child.removeEventListener(IsoEvent.INVALIDATE, child_invalidateHandler);
bIsInvalidated = true;
}
return child;
}
/**
* @inheritDoc
*/
override public function removeAllChildren ():void
{
var child:INode
for each (child in children)
child.removeEventListener(IsoEvent.INVALIDATE, child_invalidateHandler);
super.removeAllChildren();
bIsInvalidated = true;
}
/**
* Renders the scene as invalidated if a child object is invalidated.
*
* @param evt The IsoEvent dispatched from the invalidated child.
*/
protected function child_invalidateHandler (evt:IsoEvent):void
{
var child:Object = evt.target;
if (invalidatedChildrenArray.indexOf(child) == -1)
invalidatedChildrenArray.push(child);
bIsInvalidated = true;
}
///////////////////////////////////////////////////////////////////////////////
// LAYOUT RENDERER
///////////////////////////////////////////////////////////////////////////////
/**
* Flags the scene for possible layout rendering.
* If false, child objects are sorted by the order they were added rather than by their isometric depth.
*/
public var layoutEnabled:Boolean = true;
private var layoutRendererFactory:IFactory;
/**
* @private
*/
public function get layoutRenderer ():IFactory
{
return layoutRendererFactory;
}
/**
* The factory used to create the ISceneLayoutRenderer responsible for the layout of the child objects.
*/
public function set layoutRenderer (value:IFactory):void
{
if (value && layoutRendererFactory != value)
{
layoutRendererFactory = value;
bIsInvalidated = true;
}
}
///////////////////////////////////////////////////////////////////////////////
// STYLE RENDERERS
///////////////////////////////////////////////////////////////////////////////
/**
* Flags the scene for possible style rendering.
*/
public var stylingEnabled:Boolean = true;
private var styleRendererFactories:Array = [];
/**
* @private
*/
public function get styleRenderers ():Array
{
return styleRendererFactories;
}
/**
* An array of IFactories whose class generators are ISceneRenderer.
* If any value contained within the array is not of type IFactory, it will be ignored.
*/
public function set styleRenderers (value:Array):void
{
if (value)
{
var temp:Array = [];
var obj:Object;
for each (obj in value)
{
if (obj is IFactory)
temp.push(obj);
}
styleRendererFactories = temp;
bIsInvalidated = true;
}
}
///////////////////////////////////////////////////////////////////////////////
// INVALIDATION
///////////////////////////////////////////////////////////////////////////////
/**
* Flags the scene as invalidated during the rendering process
*/
public function invalidateScene ():void
{
bIsInvalidated = true;
}
///////////////////////////////////////////////////////////////////////////////
// RENDER
///////////////////////////////////////////////////////////////////////////////
/**
* @inheritDoc
*/
override protected function renderLogic (recursive:Boolean = true):void
{
super.renderLogic(recursive); //push individual changes thru, then sort based on new visible content of each child
if (bIsInvalidated)
{
//render the layout first
var sceneLayoutRenderer:ISceneLayoutRenderer;
if (layoutEnabled)
{
sceneLayoutRenderer = layoutRendererFactory.newInstance();
if (sceneLayoutRenderer)
sceneLayoutRenderer.renderScene(this);
}
//apply styling
mainContainer.graphics.clear(); //should we do this here?
var sceneRenderer:ISceneRenderer;
var factory:IFactory
if (stylingEnabled)
{
for each (factory in styleRendererFactories)
{
sceneRenderer = factory.newInstance();
if (sceneRenderer)
sceneRenderer.renderScene(this);
}
}
bIsInvalidated = false;
}
}
/**
* @inheritDoc
*/
override protected function postRenderLogic ():void
{
invalidatedChildrenArray = [];
super.postRenderLogic();
//should we still call sceneRendered()?
sceneRendered();
}
/**
* This function has been deprecated. Please refer to postRenderLogic.
*/
protected function sceneRendered ():void
{
}
///////////////////////////////////////////////////////////////////////////////
// CONSTRUCTOR
///////////////////////////////////////////////////////////////////////////////
/**
* Constructor
*/
public function IsoScene ()
{
super();
layoutRendererFactory = new ClassFactory(DefaultSceneLayoutRenderer);
}
}
}
|
/*
as3isolib - An open-source ActionScript 3.0 Isometric Library developed to assist
in creating isometrically projected content (such as games and graphics)
targeted for the Flash player platform
http://code.google.com/p/as3isolib/
Copyright (c) 2006 - 2008 J.W.Opitz, All Rights Reserved.
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 as3isolib.display.scene
{
import as3isolib.bounds.IBounds;
import as3isolib.bounds.SceneBounds;
import as3isolib.core.IIsoDisplayObject;
import as3isolib.core.IsoContainer;
import as3isolib.core.as3isolib_internal;
import as3isolib.data.INode;
import as3isolib.display.renderers.DefaultSceneLayoutRenderer;
import as3isolib.display.renderers.ISceneLayoutRenderer;
import as3isolib.display.renderers.ISceneRenderer;
import as3isolib.events.IsoEvent;
import flash.display.DisplayObjectContainer;
import mx.core.ClassFactory;
import mx.core.IFactory;
use namespace as3isolib_internal;
/**
* IsoScene is a base class for grouping and rendering IIsoDisplayObject children according to their isometric position-based depth.
*/
public class IsoScene extends IsoContainer implements IIsoScene
{
///////////////////////////////////////////////////////////////////////////////
// BOUNDS
///////////////////////////////////////////////////////////////////////////////
/**
* @private
*/
private var _isoBounds:IBounds;
/**
* @inheritDoc
*/
public function get isoBounds ():IBounds
{
/* if (!_isoBounds || isInvalidated)
_isoBounds = */
return new SceneBounds(this);
}
///////////////////////////////////////////////////////////////////////////////
// HOST CONTAINER
///////////////////////////////////////////////////////////////////////////////
/**
* @private
*/
protected var host:DisplayObjectContainer;
as3isolib_internal
/**
* @private
*/
public function get hostContainer ():DisplayObjectContainer
{
return host;
}
/**
* @inheritDoc
*/
public function set hostContainer (value:DisplayObjectContainer):void
{
if (value && host != value)
{
if (host && host.contains(container))
{
host.removeChild(container);
ownerObject = null;
}
else if (hasParent)
parent.removeChild(this);
host = value;
if (host)
{
host.addChild(container);
ownerObject = host;
parentNode = null;
}
}
}
///////////////////////////////////////////////////////////////////////////////
// INVALIDATE CHILDREN
///////////////////////////////////////////////////////////////////////////////
/**
* @private
*
* Array of invalidated children. Each child dispatches an IsoEvent.INVALIDATION event which notifies
* the scene that that particular child is invalidated and subsequentally the scene is also invalidated.
*/
protected var invalidatedChildrenArray:Array = [];
/**
* @inheritDoc
*/
public function get invalidatedChildren ():Array
{
return invalidatedChildrenArray;
}
///////////////////////////////////////////////////////////////////////////////
// OVERRIDES
///////////////////////////////////////////////////////////////////////////////
/**
* @inheritDoc
*/
override public function addChildAt (child:INode, index:uint):void
{
if (child is IIsoDisplayObject)
{
super.addChildAt(child, index);
child.addEventListener(IsoEvent.INVALIDATE, child_invalidateHandler);
bIsInvalidated = true; //since the child most likely had fired an invalidation event prior to being added, manually invalidate the scene
}
else
throw new Error ("parameter child is not of type IIsoDisplayObject");
}
/**
* @inheritDoc
*/
override public function setChildIndex (child:INode, index:uint):void
{
super.setChildIndex(child, index);
bIsInvalidated = true;
}
/**
* @inheritDoc
*/
override public function removeChildByID (id:String):INode
{
var child:INode = super.removeChildByID(id);
if (child)
{
child.removeEventListener(IsoEvent.INVALIDATE, child_invalidateHandler);
bIsInvalidated = true;
}
return child;
}
/**
* @inheritDoc
*/
override public function removeAllChildren ():void
{
var child:INode
for each (child in children)
child.removeEventListener(IsoEvent.INVALIDATE, child_invalidateHandler);
super.removeAllChildren();
bIsInvalidated = true;
}
/**
* Renders the scene as invalidated if a child object is invalidated.
*
* @param evt The IsoEvent dispatched from the invalidated child.
*/
protected function child_invalidateHandler (evt:IsoEvent):void
{
var child:Object = evt.target;
if (invalidatedChildrenArray.indexOf(child) == -1)
invalidatedChildrenArray.push(child);
bIsInvalidated = true;
}
///////////////////////////////////////////////////////////////////////////////
// LAYOUT RENDERER
///////////////////////////////////////////////////////////////////////////////
/**
* Flags the scene for possible layout rendering.
* If false, child objects are sorted by the order they were added rather than by their isometric depth.
*/
public var layoutEnabled:Boolean = true;
private var layoutRendererFactory:IFactory;
/**
* @private
*/
public function get layoutRenderer ():IFactory
{
return layoutRendererFactory;
}
/**
* The factory used to create the ISceneLayoutRenderer responsible for the layout of the child objects.
*/
public function set layoutRenderer (value:IFactory):void
{
if (value && layoutRendererFactory != value)
{
layoutRendererFactory = value;
bIsInvalidated = true;
}
}
///////////////////////////////////////////////////////////////////////////////
// STYLE RENDERERS
///////////////////////////////////////////////////////////////////////////////
/**
* Flags the scene for possible style rendering.
*/
public var stylingEnabled:Boolean = true;
private var styleRendererFactories:Array = [];
/**
* @private
*/
public function get styleRenderers ():Array
{
return styleRendererFactories;
}
/**
* An array of IFactories whose class generators are ISceneRenderer.
* If any value contained within the array is not of type IFactory, it will be ignored.
*/
public function set styleRenderers (value:Array):void
{
if (value)
{
var temp:Array = [];
var obj:Object;
for each (obj in value)
{
if (obj is IFactory)
temp.push(obj);
}
styleRendererFactories = temp;
bIsInvalidated = true;
}
}
///////////////////////////////////////////////////////////////////////////////
// INVALIDATION
///////////////////////////////////////////////////////////////////////////////
/**
* Flags the scene as invalidated during the rendering process
*/
public function invalidateScene ():void
{
bIsInvalidated = true;
}
///////////////////////////////////////////////////////////////////////////////
// RENDER
///////////////////////////////////////////////////////////////////////////////
/**
* @inheritDoc
*/
override protected function renderLogic (recursive:Boolean = true):void
{
super.renderLogic(recursive); //push individual changes thru, then sort based on new visible content of each child
if (bIsInvalidated)
{
//render the layout first
var sceneLayoutRenderer:ISceneLayoutRenderer;
if (layoutEnabled)
{
sceneLayoutRenderer = layoutRendererFactory.newInstance();
if (sceneLayoutRenderer)
sceneLayoutRenderer.renderScene(this);
}
//fix for bug #20 - http://code.google.com/p/as3isolib/issues/detail?id=20
var sceneRenderer:ISceneRenderer;
var factory:IFactory
if (stylingEnabled && styleRendererFactories.length > 0)
{
mainContainer.graphics.clear();
for each (factory in styleRendererFactories)
{
sceneRenderer = factory.newInstance();
if (sceneRenderer)
sceneRenderer.renderScene(this);
}
}
bIsInvalidated = false;
}
}
/**
* @inheritDoc
*/
override protected function postRenderLogic ():void
{
invalidatedChildrenArray = [];
super.postRenderLogic();
//should we still call sceneRendered()?
sceneRendered();
}
/**
* This function has been deprecated. Please refer to postRenderLogic.
*/
protected function sceneRendered ():void
{
}
///////////////////////////////////////////////////////////////////////////////
// CONSTRUCTOR
///////////////////////////////////////////////////////////////////////////////
/**
* Constructor
*/
public function IsoScene ()
{
super();
layoutRendererFactory = new ClassFactory(DefaultSceneLayoutRenderer);
}
}
}
|
fix for bug #20 - http://code.google.com/p/as3isolib/issues/detail?id=20
|
fix for bug #20 - http://code.google.com/p/as3isolib/issues/detail?id=20
|
ActionScript
|
mit
|
as3isolib/as3isolib.v1,liuju/as3isolib.v1,dreamsxin/as3isolib.v1,as3isolib/as3isolib.v1,liuju/as3isolib.v1,dreamsxin/as3isolib.v1
|
79761189cc01d3d37f4ec770636ccd9be5724ced
|
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.data.LocalData;
import aerys.minko.scene.data.RenderingData;
import aerys.minko.scene.data.ViewportData;
import aerys.minko.scene.node.IScene;
import aerys.minko.scene.visitor.ISceneVisitor;
import aerys.minko.scene.visitor.PostprocessVisitor;
import aerys.minko.scene.visitor.RenderingVisitor;
import aerys.minko.scene.visitor.WorldDataVisitor;
import aerys.minko.type.Factory;
import aerys.minko.type.IVersionnable;
import flash.display.DisplayObject;
import flash.display.Sprite;
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.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 _postProcessEffect : IEffect = null;
private var _postProcessVisitor : ISceneVisitor = new PostprocessVisitor();
private var _viewportData : ViewportData = null;
private var _logoIsHidden : Boolean = false;
public function get postProcessEffect() : IEffect
{
return _postProcessEffect;
}
public function set postProcessEffect(value : IEffect):void
{
_postProcessEffect = value;
}
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,
autoResize : Boolean = true,
antiAliasing : int = 0,
rendererType : Class = null)
{
this.width = width;
this.height = height;
_autoResize = autoResize;
_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 (!_logoIsHidden)
showLogo();
}
private function removedFromStage(event : Event) : void
{
_stage3d.removeEventListener(Event.CONTEXT3D_CREATE, resetStage3D);
_stage3d.context3D.dispose();
_stage3d = null;
}
private function addedHandler(event : Event) : void
{
if (_autoResize)
{
parent.addEventListener(Event.RESIZE, resizeHandler);
if (parent == stage)
{
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
}
}
updateRectangle();
}
private function resizeHandler(event : Event = null) : void
{
if (parent == stage)
{
width = stage.stageWidth;
height = stage.stageHeight;
}
else
{
var p : DisplayObject = parent;
while (p && (p.width == 0 || p.height == 0))
p = p.parent;
if (p)
{
width = p.width;
height = p.height;
}
}
resetStage3D();
if (!_logoIsHidden)
showLogo();
}
private function resetStage3D(event : Event = null) : void
{
if (_stage3d && _stage3d.context3D && _width && _height)
{
updateRectangle();
_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.x = origin.x;
_stage3d.y = origin.y;
if (_stage3d.context3D)
{
_stage3d.context3D.configureBackBuffer(
Math.min(2048, _width),
Math.min(2048, _height),
_antiAliasing,
true
);
}
}
}
/**
* Render the specified scene.
* @param scene
*/
public function render(scene : IScene) : void
{
if (!_logoIsHidden)
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);
_drawTime = _renderer.drawingTime;
// execute postprocessing
if (_postProcessEffect != null)
{
renderingData.effect = _postProcessEffect;
_postProcessVisitor.processSceneGraph(scene, localData, worldData, renderingData, _renderer);
}
_renderer.present();
_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;
}
public function hideLogo() : void
{
_logoIsHidden = true;
if (contains(Minko.logo))
removeChild(Minko.logo);
}
}
}
|
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.data.LocalData;
import aerys.minko.scene.data.RenderingData;
import aerys.minko.scene.data.ViewportData;
import aerys.minko.scene.node.IScene;
import aerys.minko.scene.visitor.ISceneVisitor;
import aerys.minko.scene.visitor.PostprocessVisitor;
import aerys.minko.scene.visitor.RenderingVisitor;
import aerys.minko.scene.visitor.WorldDataVisitor;
import aerys.minko.type.Factory;
import aerys.minko.type.IVersionnable;
import flash.display.DisplayObject;
import flash.display.Sprite;
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.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 _postProcessEffect : IEffect = null;
private var _postProcessVisitor : ISceneVisitor = new PostprocessVisitor();
private var _viewportData : ViewportData = null;
private var _logoIsHidden : Boolean = false;
public function get postProcessEffect() : IEffect
{
return _postProcessEffect;
}
public function set postProcessEffect(value : IEffect):void
{
_postProcessEffect = value;
}
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 frameId() : uint
{
return _renderer.frameId;
}
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,
autoResize : Boolean = true,
antiAliasing : int = 0,
rendererType : Class = null)
{
this.width = width;
this.height = height;
_autoResize = autoResize;
_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 (!_logoIsHidden)
showLogo();
}
private function removedFromStage(event : Event) : void
{
_stage3d.removeEventListener(Event.CONTEXT3D_CREATE, resetStage3D);
_stage3d.context3D.dispose();
_stage3d = null;
}
private function addedHandler(event : Event) : void
{
if (_autoResize)
{
parent.addEventListener(Event.RESIZE, resizeHandler);
if (parent == stage)
{
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
}
}
updateRectangle();
}
private function resizeHandler(event : Event = null) : void
{
if (parent == stage)
{
width = stage.stageWidth;
height = stage.stageHeight;
}
else
{
var p : DisplayObject = parent;
while (p && (p.width == 0 || p.height == 0))
p = p.parent;
if (p)
{
width = p.width;
height = p.height;
}
}
resetStage3D();
if (!_logoIsHidden)
showLogo();
}
private function resetStage3D(event : Event = null) : void
{
if (_stage3d && _stage3d.context3D && _width && _height)
{
updateRectangle();
_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.x = origin.x;
_stage3d.y = origin.y;
if (_stage3d.context3D)
{
_stage3d.context3D.configureBackBuffer(
Math.min(2048, _width),
Math.min(2048, _height),
_antiAliasing,
true
);
}
}
}
/**
* Render the specified scene.
* @param scene
*/
public function render(scene : IScene) : void
{
if (!_logoIsHidden)
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);
_drawTime = _renderer.drawingTime;
// execute postprocessing
if (_postProcessEffect != null)
{
renderingData.effect = _postProcessEffect;
_postProcessVisitor.processSceneGraph(scene, localData, worldData, renderingData, _renderer);
}
_renderer.present();
_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;
}
public function hideLogo() : void
{
_logoIsHidden = true;
if (contains(Minko.logo))
removeChild(Minko.logo);
}
}
}
|
Add a getter to get the frameId from the viewport
|
Add a getter to get the frameId from the viewport
|
ActionScript
|
mit
|
aerys/minko-as3
|
eaf875209dd9ecde954095ad63b559583062e154
|
exporter/src/test/as/flump/test/TestRunner.as
|
exporter/src/test/as/flump/test/TestRunner.as
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.test {
import flash.desktop.NativeApplication;
import flash.filesystem.File;
import flump.executor.Executor;
import flump.executor.Finisher;
import flump.executor.Future;
import starling.display.Sprite;
import com.threerings.util.Log;
import com.threerings.util.Map;
import com.threerings.util.Maps;
public class TestRunner extends Sprite
{
public static const root :File = new File(File.applicationDirectory.nativePath);
public static const resources :File = root.resolvePath('../src/test/resources');
public static const dist :File = root.resolvePath('../dist');
public function TestRunner () {
Log.setLevel("", Log.INFO);
_exec.completed.add(onCompletion);
_exec.terminated.add(function (..._) :void {
if (_passed.length > 0) {
trace("Passed:");
for each (var name :String in _passed) trace(" " + name);
}
if (_failed.length > 0) {
trace("Failed:");
for each (name in _failed) trace(" " + name);
}
NativeApplication.nativeApplication.exit(_failed.length == 0 ? 0 : 1);
});
new XflParseTest(this);
}
public function run (name :String, f :Function) :void {
runAsync(name, function (finisher :Finisher) :void { finisher.succeedAfter(f); });
}
public function runAsync (name :String, f :Function) :void { _runs.put(_exec.submit(f), name); }
protected function onCompletion (f :Future) :void {
const name :String = _runs.remove(f);
if (name == null) {
log.error("Unknown test completed", "future", f, "result", f.result);
return;
}
if (f.isSuccessful) {
log.info("Passed", "test", name);
_passed.push(name);
} else {
_failed.push(name)
if (f.result is Error) log.error("Failed", "test", name, f.result);
else log.error("Failed", "test", name, "reason", f.result);
}
if (_exec.isIdle) _exec.shutdown();
}
protected const _exec :Executor = new Executor(/*maxSimultaneous=*/1);
protected const _runs :Map = Maps.newMapOf(Future);//String name
protected const _passed :Vector.<String> = new Vector.<String>();
protected const _failed :Vector.<String> = new Vector.<String>();
private static const log :Log = Log.getLog(TestRunner);
}
}
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.test {
import flash.desktop.NativeApplication;
import flash.filesystem.File;
import flump.executor.Executor;
import flump.executor.Finisher;
import flump.executor.Future;
import starling.display.Sprite;
import com.threerings.util.Log;
import com.threerings.util.Map;
import com.threerings.util.Maps;
public class TestRunner extends Sprite
{
public static const root :File = new File(File.applicationDirectory.nativePath);
public static const resources :File = root.resolvePath('../src/test/resources');
public static const dist :File = root.resolvePath('../dist');
public function TestRunner () {
Log.setLevel("", Log.INFO);
_exec.completed.add(onCompletion);
_exec.terminated.add(function (..._) :void {
if (_passed.length > 0) {
trace("Passed:");
for each (var name :String in _passed) trace(" " + name);
}
if (_failed.length > 0) {
trace("Failed:");
for each (name in _failed) trace(" " + name);
}
NativeApplication.nativeApplication.exit(_failed.length == 0 ? 0 : 1);
});
new XflParseTest(this);
}
public function run (name :String, f :Function) :void {
runAsync(name, function (finisher :Finisher) :void { finisher.succeedAfter(f); });
}
public function runAsync (name :String, f :Function) :void { _runs.put(_exec.submit(f), name); }
protected function onCompletion (f :Future) :void {
const name :String = _runs.remove(f);
if (name == null) {
log.error("Unknown test completed", "future", f, "result", f.result);
return;
}
if (f.isSuccessful) {
log.info("Passed", "test", name);
_passed.push(name);
} else {
_failed.push(name)
if (f.result is Error) log.error("Failed", "test", name, f.result);
else log.error("Failed", "test", name, "reason", f.result);
_exec.shutdownNow();
}
if (_exec.isIdle) _exec.shutdown();
}
protected const _exec :Executor = new Executor(/*maxSimultaneous=*/1);
protected const _runs :Map = Maps.newMapOf(Future);//String name
protected const _passed :Vector.<String> = new Vector.<String>();
protected const _failed :Vector.<String> = new Vector.<String>();
private static const log :Log = Log.getLog(TestRunner);
}
}
|
Halt tests after a failure
|
Halt tests after a failure
|
ActionScript
|
mit
|
funkypandagame/flump,funkypandagame/flump,tconkling/flump,mathieuanthoine/flump,tconkling/flump,mathieuanthoine/flump,mathieuanthoine/flump
|
562e0ca3a34148bd90569dfab0f5d7218f9a7830
|
runtime/src/main/as/flump/display/Movie.as
|
runtime/src/main/as/flump/display/Movie.as
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.display {
import flump.mold.MovieMold;
import org.osflash.signals.Signal;
import starling.core.Starling;
import starling.display.DisplayObject;
import starling.display.Sprite;
import starling.events.Event;
public class Movie extends Sprite
{
public static const FIRST_FRAME :String = "flump.movie.FIRST_FRAME";
public static const LAST_FRAME :String = "flump.movie.LAST_FRAME";
public const labelPassed :Signal = new Signal(String);
public function Movie (src :MovieMold, frameRate :Number, idToDisplayObject :Function) {
name = src.libraryItem;
_labels = src.labels;
_frameRate = frameRate;
_ticker = new Ticker(advanceTime);
const flipbook :Boolean = src.flipbook;
if (src.flipbook) {
_layers = new Vector.<Layer>(1, true);
_layers[0] = new Layer(this, src.layers[0], idToDisplayObject, /*flipbook=*/true);
_frames = src.layers[0].frames;
} else {
_layers = new Vector.<Layer>(src.layers.length, true);
for (var ii :int = 0; ii < _layers.length; ii++) {
_layers[ii] = new Layer(this, src.layers[ii], idToDisplayObject, /*flipbook=*/false);
_frames = Math.max(src.layers[ii].frames, _frames);
}
}
_duration = _frames / _frameRate;
goto(0, true, false);
addEventListener(Event.ADDED_TO_STAGE, addedToStage);
addEventListener(Event.REMOVED_FROM_STAGE, removedFromStage);
}
public function get frame () :int { return _frame; }
public function get frames () :int { return _frames; }
protected function advanceTime (dt :Number) :void {
if (!_playing) return;
_playTime += dt;
var actualPlaytime :Number = _playTime;
if (_playTime > _duration) _playTime = _playTime % _duration;
var newFrame :int = int(_playTime * _frameRate);
const overDuration :Boolean = dt >= _duration;
// If the update crosses or goes to the stopFrame, go to the stop frame, stop the movie and
// clear it
if (_stopFrame != NO_FRAME) {
// how many frames remain to the stopframe?
var framesRemaining :int =
(_frame <= _stopFrame ? _stopFrame - _frame : _frames - _frame + _stopFrame);
var framesElapsed :int = int(actualPlaytime * _frameRate) - _frame;
if (framesElapsed >= framesRemaining) {
_playing = false;
newFrame = _stopFrame;
_stopFrame = NO_FRAME;
}
}
goto(newFrame, false, overDuration);
}
protected function goto (newFrame :int, fromSkip :Boolean, overDuration :Boolean) :void {
if (_goingToFrame) {
_pendingFrame = newFrame;
return;
}
_goingToFrame = true;
const differentFrame :Boolean = newFrame != _frame;
const wrapped :Boolean = newFrame < _frame;
if (differentFrame) {
if (wrapped) {
for each (var layer :Layer in _layers) {
layer.changedKeyframe = true;
layer.keyframeIdx = 0;
}
}
for each (layer in _layers) layer.drawFrame(newFrame);
}
// Update the frame before firing, so if firing changes the frame, it sticks.
const oldFrame :int = _frame;
_frame = newFrame;
if (fromSkip) {
fireLabels(newFrame, newFrame);
_playTime = newFrame/_frameRate;
} else if (overDuration) {
fireLabels(oldFrame + 1, _frames - 1);
fireLabels(0, _frame);
} else if (differentFrame) {
if (wrapped) {
fireLabels(oldFrame + 1, _frames - 1);
fireLabels(0, _frame);
} else {
fireLabels(oldFrame + 1, _frame);
}
}
_goingToFrame = false;
if (_pendingFrame != NO_FRAME) {
newFrame = _pendingFrame;
_pendingFrame = NO_FRAME;
goto(newFrame, true, false);
}
}
protected function fireLabels (startFrame :int, endFrame :int) :void {
for (var ii :int = startFrame; ii <= endFrame; ii++) {
if (_labels[ii] == null) continue;
for each (var label :String in _labels[ii]) labelPassed.dispatch(label);
}
}
protected function addedToStage (..._) :void { Starling.juggler.add(_ticker); }
protected function removedFromStage (..._) :void { Starling.juggler.add(_ticker); }
protected var _goingToFrame :Boolean;
protected var _pendingFrame :int = NO_FRAME;
protected var _frame :int = NO_FRAME, _stopFrame :int = NO_FRAME;
protected var _playing :Boolean = true;
protected var _playTime :Number, _duration :Number;
protected var _layers :Vector.<Layer>;
protected var _ticker :Ticker;
protected var _frames :int;
protected var _frameRate :Number;
protected var _labels :Vector.<Vector.<String>>;
private static const NO_FRAME :int = -1;
}
}
import flump.display.Movie;
import flump.mold.KeyframeMold;
import flump.mold.LayerMold;
import starling.display.DisplayObject;
import starling.display.Sprite;
class Layer {
public var keyframeIdx :int ;// The index of the last keyframe drawn in drawFrame
public var layerIdx :int;// This layer's index in the movie
public var keyframes :Vector.<KeyframeMold>;
// Only created if there are multiple items on this layer. If it does exist, the appropriate display is swapped in at keyframe changes. If it doesn't, the display is only added to the parent on layer creation
public var displays :Vector.<DisplayObject>;// <SPDisplayObject*>
public var movie :Movie; // The movie this layer belongs to
// If the keyframe has changed since the last drawFrame
public var changedKeyframe :Boolean;
public function Layer (movie :Movie, src :LayerMold, idToDisplayObject :Function,
flipbook :Boolean) {
keyframes = src.keyframes;
this.movie = movie;
var lastItem :String;
for (var ii :int = 0; ii < keyframes.length && lastItem == null; ii++) {
lastItem = keyframes[ii].id;
}
if (!flipbook && lastItem == null) movie.addChild(new Sprite());// Label only layer
else {
var multipleItems :Boolean = flipbook;
for (ii = 0; ii < keyframes.length && !multipleItems; ii++) {
multipleItems = keyframes[ii].id != lastItem;
}
if (!multipleItems) movie.addChild(idToDisplayObject(lastItem));
else {
displays = new Vector.<DisplayObject>();
for each (var kf :KeyframeMold in keyframes) {
var display :DisplayObject = kf.id == null ? new Sprite() : idToDisplayObject(kf.id);
displays.push(display);
display.name = src.name;
}
movie.addChild(displays[0]);
}
}
layerIdx = movie.numChildren - 1;
movie.getChildAt(layerIdx).name = src.name;
}
public function drawFrame (frame :int) :void {
while (keyframeIdx < keyframes.length - 1 && keyframes[keyframeIdx + 1].index <= frame) {
keyframeIdx++;
changedKeyframe = true;
}
// We've got multiple items. Swap in the one for this kf
if (changedKeyframe && displays != null) {
movie.removeChildAt(layerIdx);
movie.addChildAt(displays[keyframeIdx], layerIdx);
}
changedKeyframe = false;
const kf :KeyframeMold = keyframes[keyframeIdx];
const layer :DisplayObject = movie.getChildAt(layerIdx);
if (keyframeIdx == keyframes.length - 1 || kf.index == frame) {
layer.x = kf.x;
layer.y = kf.y;
layer.scaleX = kf.scaleX;
layer.scaleY = kf.scaleY;
layer.rotation = kf.rotation;
layer.alpha = kf.alpha;
} else {
var interped :Number = (frame - kf.index)/kf.duration;
var ease :Number = kf.ease;
if (ease != 0) {
var t :Number;
if (ease < 0) {
// Ease in
var inv :Number = 1 - interped;
t = 1 - inv*inv;
ease = -ease;
} else {
// Ease out
t = interped*interped;
}
interped = ease*t + (1 - ease)*interped;
}
const nextKf :KeyframeMold = keyframes[keyframeIdx + 1];
layer.x = kf.x + (nextKf.x - kf.x) * interped;
layer.y = kf.y + (nextKf.y - kf.y) * interped;
layer.scaleX = kf.scaleX + (nextKf.scaleX - kf.scaleX) * interped;
layer.scaleY = kf.scaleY + (nextKf.scaleY - kf.scaleY) * interped;
layer.rotation = kf.rotation + (nextKf.rotation - kf.rotation) * interped;
layer.alpha = kf.alpha + (nextKf.alpha - kf.alpha) * interped;
}
layer.pivotX = kf.pivotX;
layer.pivotY = kf.pivotY;
layer.visible = kf.visible;
}
}
import starling.animation.IAnimatable;
class Ticker implements IAnimatable {
public function Ticker (callback :Function) {
_callback = callback;
}
public function get isComplete () :Boolean { return false; }
public function advanceTime (time :Number) :void { _callback(time); }
protected var _callback :Function;
}
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.display {
import flump.mold.MovieMold;
import org.osflash.signals.Signal;
import starling.core.Starling;
import starling.display.DisplayObject;
import starling.display.Sprite;
import starling.events.Event;
public class Movie extends Sprite
{
public static const FIRST_FRAME :String = "flump.movie.FIRST_FRAME";
public static const LAST_FRAME :String = "flump.movie.LAST_FRAME";
public const labelPassed :Signal = new Signal(String);
public function Movie (src :MovieMold, frameRate :Number, idToDisplayObject :Function) {
name = src.libraryItem;
_labels = src.labels;
_frameRate = frameRate;
_ticker = new Ticker(advanceTime);
const flipbook :Boolean = src.flipbook;
if (src.flipbook) {
_layers = new Vector.<Layer>(1, true);
_layers[0] = new Layer(this, src.layers[0], idToDisplayObject, /*flipbook=*/true);
_frames = src.layers[0].frames;
} else {
_layers = new Vector.<Layer>(src.layers.length, true);
for (var ii :int = 0; ii < _layers.length; ii++) {
_layers[ii] = new Layer(this, src.layers[ii], idToDisplayObject, /*flipbook=*/false);
_frames = Math.max(src.layers[ii].frames, _frames);
}
}
_duration = _frames / _frameRate;
goto(0, true, false);
addEventListener(Event.ADDED_TO_STAGE, addedToStage);
addEventListener(Event.REMOVED_FROM_STAGE, removedFromStage);
}
public function get frame () :int { return _frame; }
public function get frames () :int { return _frames; }
protected function advanceTime (dt :Number) :void {
if (!_playing) return;
_playTime += dt;
var actualPlaytime :Number = _playTime;
if (_playTime > _duration) _playTime = _playTime % _duration;
var newFrame :int = int(_playTime * _frameRate);
const overDuration :Boolean = dt >= _duration;
// If the update crosses or goes to the stopFrame, go to the stop frame, stop the movie and
// clear it
if (_stopFrame != NO_FRAME) {
// how many frames remain to the stopframe?
var framesRemaining :int =
(_frame <= _stopFrame ? _stopFrame - _frame : _frames - _frame + _stopFrame);
var framesElapsed :int = int(actualPlaytime * _frameRate) - _frame;
if (framesElapsed >= framesRemaining) {
_playing = false;
newFrame = _stopFrame;
_stopFrame = NO_FRAME;
}
}
goto(newFrame, false, overDuration);
}
protected function goto (newFrame :int, fromSkip :Boolean, overDuration :Boolean) :void {
if (_goingToFrame) {
_pendingFrame = newFrame;
return;
}
_goingToFrame = true;
const differentFrame :Boolean = newFrame != _frame;
const wrapped :Boolean = newFrame < _frame;
if (differentFrame) {
if (wrapped) {
for each (var layer :Layer in _layers) {
layer.changedKeyframe = true;
layer.keyframeIdx = 0;
}
}
for each (layer in _layers) layer.drawFrame(newFrame);
}
// Update the frame before firing, so if firing changes the frame, it sticks.
const oldFrame :int = _frame;
_frame = newFrame;
if (fromSkip) {
fireLabels(newFrame, newFrame);
_playTime = newFrame/_frameRate;
} else if (overDuration) {
fireLabels(oldFrame + 1, _frames - 1);
fireLabels(0, _frame);
} else if (differentFrame) {
if (wrapped) {
fireLabels(oldFrame + 1, _frames - 1);
fireLabels(0, _frame);
} else {
fireLabels(oldFrame + 1, _frame);
}
}
_goingToFrame = false;
if (_pendingFrame != NO_FRAME) {
newFrame = _pendingFrame;
_pendingFrame = NO_FRAME;
goto(newFrame, true, false);
}
}
protected function fireLabels (startFrame :int, endFrame :int) :void {
for (var ii :int = startFrame; ii <= endFrame; ii++) {
if (_labels[ii] == null) continue;
for each (var label :String in _labels[ii]) labelPassed.dispatch(label);
}
}
protected function addedToStage (..._) :void { Starling.juggler.add(_ticker); }
protected function removedFromStage (..._) :void { Starling.juggler.remove(_ticker); }
protected var _goingToFrame :Boolean;
protected var _pendingFrame :int = NO_FRAME;
protected var _frame :int = NO_FRAME, _stopFrame :int = NO_FRAME;
protected var _playing :Boolean = true;
protected var _playTime :Number, _duration :Number;
protected var _layers :Vector.<Layer>;
protected var _ticker :Ticker;
protected var _frames :int;
protected var _frameRate :Number;
protected var _labels :Vector.<Vector.<String>>;
private static const NO_FRAME :int = -1;
}
}
import flump.display.Movie;
import flump.mold.KeyframeMold;
import flump.mold.LayerMold;
import starling.display.DisplayObject;
import starling.display.Sprite;
class Layer {
public var keyframeIdx :int ;// The index of the last keyframe drawn in drawFrame
public var layerIdx :int;// This layer's index in the movie
public var keyframes :Vector.<KeyframeMold>;
// Only created if there are multiple items on this layer. If it does exist, the appropriate display is swapped in at keyframe changes. If it doesn't, the display is only added to the parent on layer creation
public var displays :Vector.<DisplayObject>;// <SPDisplayObject*>
public var movie :Movie; // The movie this layer belongs to
// If the keyframe has changed since the last drawFrame
public var changedKeyframe :Boolean;
public function Layer (movie :Movie, src :LayerMold, idToDisplayObject :Function,
flipbook :Boolean) {
keyframes = src.keyframes;
this.movie = movie;
var lastItem :String;
for (var ii :int = 0; ii < keyframes.length && lastItem == null; ii++) {
lastItem = keyframes[ii].id;
}
if (!flipbook && lastItem == null) movie.addChild(new Sprite());// Label only layer
else {
var multipleItems :Boolean = flipbook;
for (ii = 0; ii < keyframes.length && !multipleItems; ii++) {
multipleItems = keyframes[ii].id != lastItem;
}
if (!multipleItems) movie.addChild(idToDisplayObject(lastItem));
else {
displays = new Vector.<DisplayObject>();
for each (var kf :KeyframeMold in keyframes) {
var display :DisplayObject = kf.id == null ? new Sprite() : idToDisplayObject(kf.id);
displays.push(display);
display.name = src.name;
}
movie.addChild(displays[0]);
}
}
layerIdx = movie.numChildren - 1;
movie.getChildAt(layerIdx).name = src.name;
}
public function drawFrame (frame :int) :void {
while (keyframeIdx < keyframes.length - 1 && keyframes[keyframeIdx + 1].index <= frame) {
keyframeIdx++;
changedKeyframe = true;
}
// We've got multiple items. Swap in the one for this kf
if (changedKeyframe && displays != null) {
movie.removeChildAt(layerIdx);
movie.addChildAt(displays[keyframeIdx], layerIdx);
}
changedKeyframe = false;
const kf :KeyframeMold = keyframes[keyframeIdx];
const layer :DisplayObject = movie.getChildAt(layerIdx);
if (keyframeIdx == keyframes.length - 1 || kf.index == frame) {
layer.x = kf.x;
layer.y = kf.y;
layer.scaleX = kf.scaleX;
layer.scaleY = kf.scaleY;
layer.rotation = kf.rotation;
layer.alpha = kf.alpha;
} else {
var interped :Number = (frame - kf.index)/kf.duration;
var ease :Number = kf.ease;
if (ease != 0) {
var t :Number;
if (ease < 0) {
// Ease in
var inv :Number = 1 - interped;
t = 1 - inv*inv;
ease = -ease;
} else {
// Ease out
t = interped*interped;
}
interped = ease*t + (1 - ease)*interped;
}
const nextKf :KeyframeMold = keyframes[keyframeIdx + 1];
layer.x = kf.x + (nextKf.x - kf.x) * interped;
layer.y = kf.y + (nextKf.y - kf.y) * interped;
layer.scaleX = kf.scaleX + (nextKf.scaleX - kf.scaleX) * interped;
layer.scaleY = kf.scaleY + (nextKf.scaleY - kf.scaleY) * interped;
layer.rotation = kf.rotation + (nextKf.rotation - kf.rotation) * interped;
layer.alpha = kf.alpha + (nextKf.alpha - kf.alpha) * interped;
}
layer.pivotX = kf.pivotX;
layer.pivotY = kf.pivotY;
layer.visible = kf.visible;
}
}
import starling.animation.IAnimatable;
class Ticker implements IAnimatable {
public function Ticker (callback :Function) {
_callback = callback;
}
public function get isComplete () :Boolean { return false; }
public function advanceTime (time :Number) :void { _callback(time); }
protected var _callback :Function;
}
|
Remove the juggler when removed
|
Remove the juggler when removed
|
ActionScript
|
mit
|
mathieuanthoine/flump,funkypandagame/flump,tconkling/flump,mathieuanthoine/flump,funkypandagame/flump,mathieuanthoine/flump,tconkling/flump
|
d58eaedee98ff229bf8f908fdc1e655379739d01
|
src/milkshape/media/flash/src/Main.as
|
src/milkshape/media/flash/src/Main.as
|
package
{
import cc.milkshape.framework.Application;
import cc.milkshape.main.*;
import cc.milkshape.preloader.PreloaderKb;
import cc.milkshape.preloader.events.PreloaderEvent;
import cc.milkshape.register.Register;
import cc.milkshape.user.Login;
import cc.milkshape.utils.Constance;
import cc.milkshape.utils.MilkshapeMenu;
import cc.milkshape.utils.TableLine;
import flash.display.Shape;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.ColorTransform;
import nl.demonsters.debugger.MonsterDebugger;
[SWF(width='1430', height='680', frameRate='31', backgroundColor='#191919')]
public class Main extends Application
{
private static var _instance:Main = null;
private const DEFAULT_CONTAINER_POSX:int = 20;
private const DEFAULT_CONTAINER_POSY:int = 100;
private const BAR_BG_COLOR:int = 0x0a0a0a;
private var _equalizer:Equalizer;
private var _menu:Menu;
private var _subMenu:SubMenu;
private var _login:Login;
private var _logo:Logo;
private var _fullscreen:Fullscreen;
private var _pageContainer:PreloaderKb;
private var _bottomBar:Shape;
private var _topBar:Shape;
private var _background:TableLine;
private var _register:Register;
public function Main():void {
if(_instance != null)
throw new Error("Cannot instance this class a second time, use getInstance instead.");
_instance = this;
var debugger:MonsterDebugger = new MonsterDebugger(this);
addEventListener(Event.ADDED_TO_STAGE, _handlerAddedToStage);
}
public static function getInstance():Main {
if(_instance == null)
new Main();
return _instance;
}
private function _handlerAddedToStage(e:Event):void
{
var mct:MilkshapeMenu = new MilkshapeMenu();// Menu contextuel personnalisé
contextMenu = mct.cm;
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.addEventListener(Event.RESIZE, _resize);
_menu = new Menu(new Array(
{label: 'home', slug: 'home', url: Constance.HOME_SWF, posX:0, posY:60},
{label: 'about', slug: 'about', url: Constance.ABOUT_SWF},
{label: 'issues', slug: 'issues', url: Constance.ISSUES_SWF, posX:0},
{label: 'artists', slug: 'artists', url: Constance.ARTISTS_SWF},
{label: 'contact', slug: 'contact', url: Constance.CONTACT_SWF}
));
_menu.addEventListener(PreloaderEvent.LOAD, loadSwf);
_subMenu = new SubMenu();
_subMenu.addEventListener(PreloaderEvent.LOAD, loadSwf);
_fullscreen = new Fullscreen();
_equalizer = new Equalizer();
_login = new Login();
_logo = new Logo();
_logo.addEventListener(MouseEvent.CLICK, _showRegister);
_bottomBar = new Shape();
_bottomBar.graphics.beginFill(BAR_BG_COLOR);
_bottomBar.graphics.drawRect(0, 0, stage.stageWidth, 33);
_bottomBar.graphics.endFill();
_topBar = new Shape();
_topBar.graphics.beginFill(BAR_BG_COLOR);
_topBar.graphics.drawRect(0, 0, stage.stageWidth, 60);
_topBar.graphics.endFill();
var errorArea:ErrorArea = new ErrorArea();
_pageContainer = new PreloaderKb();
_background = new TableLine(stage.stageWidth*2, stage.stageHeight*2, 100, 100, 0x202020);
// On colore les éléments du main
var mainColorTransform:ColorTransform = new ColorTransform();
mainColorTransform.color = 0xffdd00;
_logo.transform.colorTransform = mainColorTransform;
mainColorTransform.color = 0x999999;
_fullscreen.transform.colorTransform = mainColorTransform;
_equalizer.transform.colorTransform = mainColorTransform;
addChild(_pageContainer);
addChild(_bottomBar);
addChild(_topBar);
addChild(_menu);
addChild(_subMenu);
addChild(_login);
addChild(_logo);
addChild(_fullscreen);
addChild(_equalizer);
addChild(errorArea);
_itemsDisposition();
loadSwf(new PreloaderEvent(PreloaderEvent.LOAD, _menu.getMenuButton('home').option));
}
private function _showRegister(e:Event):void
{
_register = new Register();
_register.addEventListener('CLOSE_REGISTER', _closeRegister);
addChild(_register);
removeChild(_login);
}
private function _closeRegister(e:Event):void
{
_register.removeEventListener('CLOSE_REGISTER', _closeRegister);
if(contains(_register))
{
removeChild(_register);
addChild(_login);
}
}
public function loadSwf(e:PreloaderEvent):void
{
if((e.option.background != null) ? e.option.background : true)
addChildAt(_background, 0);
else if(contains(_background))
removeChild(_background);
_pageContainer.x = (e.option.posX != null) ? e.option.posX : DEFAULT_CONTAINER_POSX;
_pageContainer.y = (e.option.posY != null) ? e.option.posY : DEFAULT_CONTAINER_POSY;
trace(_pageContainer.y);
try {
_pageContainer.unloadMedia();
} catch(e:Error) {
trace(e.message);
}
try {
_pageContainer.params = e.option.params;
_pageContainer.loadMedia(e.option.url);
} catch(e:Error){
trace(e.message);
}
}
private function _itemsDisposition():void
{
ErrorArea.getInstance().x = 610;
ErrorArea.getInstance().y = 24;
_pageContainer.y = 60;
_background.x = -50;
_menu.x = 37;
_logo.x = 37;
_logo.y = 12;
_login.x = 275;
_login.y = 24;
_fullscreen.y = 12;
_equalizer.y = _fullscreen.y + 20;
_resize();
}
private function _resize(e:Event = null):void
{
_topBar.width = stage.stageWidth;
_bottomBar.y = stage.stageHeight - 33;
_bottomBar.width = stage.stageWidth;
_fullscreen.x = stage.stageWidth - 27;
_equalizer.x = _fullscreen.x;
_menu.y = stage.stageHeight - 21;
_subMenu.y = stage.stageHeight - 23;
_subMenu.x = stage.stageWidth - 70;
}
}
}
|
package
{
import cc.milkshape.main.*;
import cc.milkshape.preloader.PreloaderKb;
import cc.milkshape.preloader.events.PreloaderEvent;
import cc.milkshape.register.Register;
import cc.milkshape.user.Login;
import cc.milkshape.utils.Constance;
import cc.milkshape.utils.MilkshapeMenu;
import cc.milkshape.utils.TableLine;
import flash.display.Shape;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.ColorTransform;
import nl.demonsters.debugger.MonsterDebugger;
[SWF(width='1430', height='680', frameRate='31', backgroundColor='#191919')]
public class Main extends Sprite
{
private static var _instance:Main = null;
private const DEFAULT_CONTAINER_POSX:int = 20;
private const DEFAULT_CONTAINER_POSY:int = 100;
private const BAR_BG_COLOR:int = 0x0a0a0a;
private var _equalizer:Equalizer;
private var _menu:Menu;
private var _subMenu:SubMenu;
private var _login:Login;
private var _logo:Logo;
private var _fullscreen:Fullscreen;
private var _pageContainer:PreloaderKb;
private var _bottomBar:Shape;
private var _topBar:Shape;
private var _background:TableLine;
private var _register:Register;
public function Main():void {
if(_instance != null)
throw new Error("Cannot instance this class a second time, use getInstance instead.");
_instance = this;
var debugger:MonsterDebugger = new MonsterDebugger(this);
addEventListener(Event.ADDED_TO_STAGE, _handlerAddedToStage);
}
public static function getInstance():Main {
if(_instance == null)
new Main();
return _instance;
}
private function _handlerAddedToStage(e:Event):void
{
var mct:MilkshapeMenu = new MilkshapeMenu();// Menu contextuel personnalisé
contextMenu = mct.cm;
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.addEventListener(Event.RESIZE, _resize);
_menu = new Menu(new Array(
{label: 'home', slug: 'home', url: Constance.HOME_SWF, posX:0, posY:60},
{label: 'about', slug: 'about', url: Constance.ABOUT_SWF},
{label: 'issues', slug: 'issues', url: Constance.ISSUES_SWF, posX:0},
{label: 'artists', slug: 'artists', url: Constance.ARTISTS_SWF},
{label: 'contact', slug: 'contact', url: Constance.CONTACT_SWF}
));
_menu.addEventListener(PreloaderEvent.LOAD, loadSwf);
_subMenu = new SubMenu();
_subMenu.addEventListener(PreloaderEvent.LOAD, loadSwf);
_fullscreen = new Fullscreen();
_equalizer = new Equalizer();
_login = new Login();
_logo = new Logo();
_logo.addEventListener(MouseEvent.CLICK, _showRegister);
_bottomBar = new Shape();
_bottomBar.graphics.beginFill(BAR_BG_COLOR);
_bottomBar.graphics.drawRect(0, 0, stage.stageWidth, 33);
_bottomBar.graphics.endFill();
_topBar = new Shape();
_topBar.graphics.beginFill(BAR_BG_COLOR);
_topBar.graphics.drawRect(0, 0, stage.stageWidth, 60);
_topBar.graphics.endFill();
var errorArea:ErrorArea = new ErrorArea();
_pageContainer = new PreloaderKb();
_background = new TableLine(stage.stageWidth*2, stage.stageHeight*2, 100, 100, 0x202020);
// On colore les éléments du main
var mainColorTransform:ColorTransform = new ColorTransform();
mainColorTransform.color = 0xffdd00;
_logo.transform.colorTransform = mainColorTransform;
mainColorTransform.color = 0x999999;
_fullscreen.transform.colorTransform = mainColorTransform;
_equalizer.transform.colorTransform = mainColorTransform;
addChild(_pageContainer);
addChild(_bottomBar);
addChild(_topBar);
addChild(_menu);
addChild(_subMenu);
addChild(_login);
addChild(_logo);
addChild(_fullscreen);
addChild(_equalizer);
addChild(errorArea);
_itemsDisposition();
loadSwf(new PreloaderEvent(PreloaderEvent.LOAD, _menu.getMenuButton('home').option));
}
private function _showRegister(e:Event):void
{
_register = new Register();
_register.addEventListener('CLOSE_REGISTER', _closeRegister);
addChild(_register);
removeChild(_login);
}
private function _closeRegister(e:Event):void
{
_register.removeEventListener('CLOSE_REGISTER', _closeRegister);
if(contains(_register))
{
removeChild(_register);
addChild(_login);
}
}
public function loadSwf(e:PreloaderEvent):void
{
if((e.option.background != null) ? e.option.background : true)
addChildAt(_background, 0);
else if(contains(_background))
removeChild(_background);
_pageContainer.x = (e.option.posX != null) ? e.option.posX : DEFAULT_CONTAINER_POSX;
_pageContainer.y = (e.option.posY != null) ? e.option.posY : DEFAULT_CONTAINER_POSY;
trace(_pageContainer.y);
try {
_pageContainer.unloadMedia();
} catch(e:Error) {
trace(e.message);
}
try {
_pageContainer.params = e.option.params;
_pageContainer.loadMedia(e.option.url);
} catch(e:Error){
trace(e.message);
}
}
private function _itemsDisposition():void
{
ErrorArea.getInstance().x = 610;
ErrorArea.getInstance().y = 24;
_pageContainer.y = 60;
_background.x = -50;
_menu.x = 37;
_logo.x = 37;
_logo.y = 12;
_login.x = 275;
_login.y = 24;
_fullscreen.y = 12;
_equalizer.y = _fullscreen.y + 20;
_resize();
}
private function _resize(e:Event = null):void
{
_topBar.width = stage.stageWidth;
_bottomBar.y = stage.stageHeight - 33;
_bottomBar.width = stage.stageWidth;
_fullscreen.x = stage.stageWidth - 27;
_equalizer.x = _fullscreen.x;
_menu.y = stage.stageHeight - 21;
_subMenu.y = stage.stageHeight - 23;
_subMenu.x = stage.stageWidth - 70;
}
}
}
|
fix Main
|
fix Main
|
ActionScript
|
mit
|
thoas/i386,thoas/i386,thoas/i386,thoas/i386
|
500239366c01a3158e1e36101ff6cdb9aae42e17
|
src/avm2/tests/regress/correctness/prot-2.as
|
src/avm2/tests/regress/correctness/prot-2.as
|
class A {
static protected function get staticGetA() {
return 10;
}
protected function get getA() {
return 0;
}
static protected function set staticSetA(v) {
trace ("staticSetA " + v);
}
}
class B extends A {
static protected function get staticGetB() {
return 11;
}
protected function get getB() {
return 1;
}
static protected function set staticSetB(v) {
trace ("staticSetB " + v);
}
}
class C extends B {
static protected function get staticGetC() {
return 12;
}
protected function get getC() {
return 2;
}
static protected function set staticSetC(v) {
trace ("staticSetC " + v);
}
public function foo() {
trace(getA + getB + getC);
trace(staticGetA + staticGetB + staticGetC);
staticSetA = "A";
staticSetB = "B";
staticSetC = "C";
}
}
var c = new C();
c.foo();
trace("--");
|
class A {
static protected function get staticGetA() {
return 10;
}
protected function get getA() {
return 0;
}
protected function set setA(v) {
trace ("setA " + v);
}
static protected function set staticSetA(v) {
trace ("staticSetA " + v);
}
}
class B extends A {
static protected function get staticGetB() {
return 11;
}
protected function get getB() {
return 1;
}
protected function set setB(v) {
trace ("setB " + v);
}
static protected function set staticSetB(v) {
trace ("staticSetB " + v);
}
}
class C extends B {
static protected function get staticGetC() {
return 12;
}
protected function get getC() {
return 2;
}
protected function set setC(v) {
trace ("setC " + v);
}
static protected function set staticSetC(v) {
trace ("staticSetC " + v);
}
public function foo() {
trace(getA + getB + getC);
setA = "A";
setB = "B";
setC = "C";
trace(staticGetA + staticGetB + staticGetC);
staticSetA = "A";
staticSetB = "B";
staticSetC = "C";
}
}
var c = new C();
c.foo();
trace("--");
|
Update test case.
|
Update test case.
|
ActionScript
|
apache-2.0
|
mozilla/shumway,mozilla/shumway,tschneidereit/shumway,yurydelendik/shumway,tschneidereit/shumway,mbebenita/shumway,yurydelendik/shumway,mbebenita/shumway,mbebenita/shumway,mozilla/shumway,mbebenita/shumway,yurydelendik/shumway,mozilla/shumway,tschneidereit/shumway,yurydelendik/shumway,mozilla/shumway,tschneidereit/shumway,tschneidereit/shumway,mbebenita/shumway,tschneidereit/shumway,mbebenita/shumway,mozilla/shumway,yurydelendik/shumway,mbebenita/shumway,yurydelendik/shumway,yurydelendik/shumway,yurydelendik/shumway,mozilla/shumway,tschneidereit/shumway,tschneidereit/shumway,mbebenita/shumway,mozilla/shumway
|
0fe8c0473ebe3e07a5dbf661e996a353fd7898e4
|
KalturaHLSPlugin/src/KalturaHLSPlugin.as
|
KalturaHLSPlugin/src/KalturaHLSPlugin.as
|
package
{
import com.kaltura.hls.HLSPluginInfo;
import com.kaltura.kdpfl.model.MediaProxy;
import com.kaltura.kdpfl.plugin.IPlugin;
import com.kaltura.kdpfl.plugin.IPluginFactory;
import flash.utils.getDefinitionByName;
import org.osmf.events.MediaFactoryEvent;
import org.osmf.media.MediaFactory;
import org.osmf.media.MediaResourceBase;
import org.osmf.media.PluginInfoResource;
import org.puremvc.as3.interfaces.IFacade;
import com.kaltura.kdpfl.plugin.KPluginEvent;
import flash.display.Sprite;
import org.osmf.media.PluginInfo;
import flash.system.Security;
public class KalturaHLSPlugin extends Sprite implements IPluginFactory, IPlugin
{
private var _pluginInfo:HLSPluginInfo;
private static const HLS_PLUGIN_INFO:String = "com.kaltura.hls.HLSPluginInfo";
public function KalturaHLSPlugin()
{
Security.allowDomain("*");
_pluginInfo = new HLSPluginInfo();
}
public function create (pluginName : String =null) : IPlugin
{
return this;
}
public function initializePlugin(facade:IFacade):void
{
//Getting Static reference to Plugin.
var pluginInfoRef:Class = getDefinitionByName(HLS_PLUGIN_INFO) as Class;
var pluginResource:MediaResourceBase = new PluginInfoResource(new pluginInfoRef);
var mediaFactory:MediaFactory = (facade.retrieveProxy(MediaProxy.NAME) as MediaProxy).vo.mediaFactory;
mediaFactory.addEventListener(MediaFactoryEvent.PLUGIN_LOAD, onOSMFPluginLoaded);
mediaFactory.addEventListener(MediaFactoryEvent.PLUGIN_LOAD_ERROR, onOSMFPluginLoadError);
mediaFactory.loadPlugin(pluginResource);
}
/**
* Listener for the LOAD_COMPLETE event.
* @param e - MediaFactoryEvent
*
*/
protected function onOSMFPluginLoaded (e : MediaFactoryEvent) : void
{
e.target.removeEventListener(MediaFactoryEvent.PLUGIN_LOAD, onOSMFPluginLoaded);
dispatchEvent( new KPluginEvent (KPluginEvent.KPLUGIN_INIT_COMPLETE) );
}
/**
* Listener for the LOAD_ERROR event.
* @param e - MediaFactoryEvent
*
*/
protected function onOSMFPluginLoadError (e : MediaFactoryEvent) : void
{
e.target.removeEventListener(MediaFactoryEvent.PLUGIN_LOAD_ERROR, onOSMFPluginLoadError);
dispatchEvent( new KPluginEvent (KPluginEvent.KPLUGIN_INIT_FAILED) );
}
public function setSkin(styleName:String, setSkinSize:Boolean=false):void
{
// Do nothing here
}
public function get pluginInfo():PluginInfo
{
return _pluginInfo;
}
}
}
|
package
{
import com.kaltura.hls.HLSPluginInfo;
import com.kaltura.kdpfl.model.MediaProxy;
import com.kaltura.kdpfl.plugin.IPlugin;
import com.kaltura.kdpfl.plugin.IPluginFactory;
import flash.utils.getDefinitionByName;
import org.osmf.events.MediaFactoryEvent;
import org.osmf.media.MediaFactory;
import org.osmf.media.MediaResourceBase;
import org.osmf.media.PluginInfoResource;
import org.puremvc.as3.interfaces.IFacade;
import com.kaltura.kdpfl.plugin.KPluginEvent;
import flash.display.Sprite;
import org.osmf.media.PluginInfo;
import flash.system.Security;
public class KalturaHLSPlugin extends Sprite implements IPluginFactory, IPlugin
{
private var _pluginInfo:HLSPluginInfo;
private static const HLS_PLUGIN_INFO:String = "com.kaltura.hls.HLSPluginInfo";
private var _pluginResource:MediaResourceBase;
public function KalturaHLSPlugin()
{
Security.allowDomain("*");
_pluginInfo = new HLSPluginInfo();
}
public function create (pluginName : String =null) : IPlugin
{
return this;
}
public function initializePlugin(facade:IFacade):void
{
//Getting Static reference to Plugin.
var pluginInfoRef:Class = getDefinitionByName(HLS_PLUGIN_INFO) as Class;
_pluginResource = new PluginInfoResource(new pluginInfoRef);
var mediaFactory:MediaFactory = (facade.retrieveProxy(MediaProxy.NAME) as MediaProxy).vo.mediaFactory;
mediaFactory.addEventListener(MediaFactoryEvent.PLUGIN_LOAD, onOSMFPluginLoaded);
mediaFactory.addEventListener(MediaFactoryEvent.PLUGIN_LOAD_ERROR, onOSMFPluginLoadError);
mediaFactory.loadPlugin(_pluginResource);
}
/**
* Listener for the LOAD_COMPLETE event.
* @param e - MediaFactoryEvent
*
*/
protected function onOSMFPluginLoaded (e : MediaFactoryEvent) : void
{
if ( e.resource && e.resource == _pluginResource ) {
e.target.removeEventListener(MediaFactoryEvent.PLUGIN_LOAD, onOSMFPluginLoaded);
dispatchEvent( new KPluginEvent (KPluginEvent.KPLUGIN_INIT_COMPLETE) );
}
}
/**
* Listener for the LOAD_ERROR event.
* @param e - MediaFactoryEvent
*
*/
protected function onOSMFPluginLoadError (e : MediaFactoryEvent) : void
{
if ( e.resource && e.resource == _pluginResource ) {
e.target.removeEventListener(MediaFactoryEvent.PLUGIN_LOAD_ERROR, onOSMFPluginLoadError);
dispatchEvent( new KPluginEvent (KPluginEvent.KPLUGIN_INIT_FAILED) );
}
}
public function setSkin(styleName:String, setSkinSize:Boolean=false):void
{
// Do nothing here
}
public function get pluginInfo():PluginInfo
{
return _pluginInfo;
}
}
}
|
Fix plugin loaded events
|
Fix plugin loaded events
|
ActionScript
|
agpl-3.0
|
kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF
|
0358d0bc14c1a6318854e6003fdf81cdcb2728b7
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/SimpleCSSValuesImpl.as
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/SimpleCSSValuesImpl.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 flash.system.ApplicationDomain;
import flash.utils.getDefinitionByName;
import flash.utils.getQualifiedClassName;
import flash.utils.getQualifiedSuperclassName;
import org.apache.flex.events.EventDispatcher;
import org.apache.flex.events.ValueChangeEvent;
/**
* The SimpleCSSValuesImpl class implements a minimal set of
* CSS lookup rules that is sufficient for most applications.
* It does not support attribute selectors or descendant selectors
* or id selectors. It will filter on a custom -flex-flash
* media query but not other media queries. It can be
* replaced with other implementations that handle more complex
* selector lookups.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class SimpleCSSValuesImpl extends EventDispatcher implements IValuesImpl
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function SimpleCSSValuesImpl()
{
super();
}
private var mainClass:Object;
private var conditionCombiners:Object;
/**
* @copy org.apache.flex.core.IValuesImpl#init()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function init(mainClass:Object):void
{
var styleClassName:String;
var c:Class;
if (!values)
{
values = {};
this.mainClass = mainClass;
var mainClassName:String = getQualifiedClassName(mainClass);
styleClassName = "_" + mainClassName + "_Styles";
c = ApplicationDomain.currentDomain.getDefinition(styleClassName) as Class;
}
else
{
c = mainClass.constructor as Class;
}
generateCSSStyleDeclarations(c["factoryFunctions"], c["data"]);
}
/**
* Process the encoded CSS data into data structures. Usually not called
* directly by application developers.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function generateCSSStyleDeclarations(factoryFunctions:Object, arr:Array):void
{
if (factoryFunctions == null)
return;
if (arr == null)
return;
var declarationName:String = "";
var segmentName:String = "";
var n:int = arr.length;
for (var i:int = 0; i < n; i++)
{
var className:int = arr[i];
if (className == CSSClass.CSSSelector)
{
var selectorName:String = arr[++i];
segmentName = selectorName + segmentName;
if (declarationName != "")
declarationName += " ";
declarationName += segmentName;
segmentName = "";
}
else if (className == CSSClass.CSSCondition)
{
if (!conditionCombiners)
{
conditionCombiners = {};
conditionCombiners["class"] = ".";
conditionCombiners["id"] = "#";
conditionCombiners["pseudo"] = ':';
}
var conditionType:String = arr[++i];
var conditionName:String = arr[++i];
segmentName = segmentName + conditionCombiners[conditionType] + conditionName;
}
else if (className == CSSClass.CSSStyleDeclaration)
{
var factoryName:int = arr[++i]; // defaultFactory or factory
var defaultFactory:Boolean = factoryName == CSSFactory.DefaultFactory;
/*
if (defaultFactory)
{
mergedStyle = styleManager.getMergedStyleDeclaration(declarationName);
style = new CSSStyleDeclaration(selector, styleManager, mergedStyle == null);
}
else
{
style = styleManager.getStyleDeclaration(declarationName);
if (!style)
{
style = new CSSStyleDeclaration(selector, styleManager, mergedStyle == null);
if (factoryName == CSSFactory.Override)
newSelectors.push(style);
}
}
*/
var mq:String = null;
var o:Object;
if (i < n - 2)
{
// peek ahead to see if there is a media query
if (arr[i + 1] == CSSClass.CSSMediaQuery)
{
mq = arr[i + 2];
i += 2;
declarationName = mq + "_" + declarationName;
}
}
var finalName:String;
var valuesFunction:Function;
var valuesObject:Object;
if (defaultFactory)
{
valuesFunction = factoryFunctions[declarationName];
valuesObject = new valuesFunction();
}
else
{
valuesFunction = factoryFunctions[declarationName];
valuesObject = new valuesFunction();
}
if (isValidStaticMediaQuery(mq))
{
finalName = fixNames(declarationName, mq);
o = values[finalName];
if (o == null)
values[finalName] = valuesObject;
else
{
valuesFunction.prototype = o;
values[finalName] = new valuesFunction();
}
}
declarationName = "";
}
}
}
private function isValidStaticMediaQuery(mq:String):Boolean
{
if (mq == null)
return true;
if (mq == "-flex-flash")
return true;
// TODO: (aharui) other media query
return false;
}
private function fixNames(s:String, mq:String):String
{
if (mq != null)
s = s.substr(mq.length + 1); // 1 more for the hyphen
if (s == "")
return "*";
var arr:Array = s.split(" ");
var n:int = arr.length;
for (var i:int = 0; i < n; i++)
{
var segmentName:String = arr[i];
if (segmentName.charAt(0) == "#" || segmentName.charAt(0) == ".")
continue;
var c:int = segmentName.lastIndexOf(".");
if (c > -1) // it is 0 for class selectors
{
segmentName = segmentName.substr(0, c) + "::" + segmentName.substr(c + 1);
arr[i] = segmentName;
}
}
return arr.join(" ");
}
/**
* The map of values. The format is not documented and it is not recommended
* to manipulate this structure directly.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var values:Object;
/**
* @copy org.apache.flex.core.IValuesImpl#getValue()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function getValue(thisObject:Object, valueName:String, state:String = null, attrs:Object = null):*
{
var c:int = valueName.indexOf("-");
while (c != -1)
{
valueName = valueName.substr(0, c) +
valueName.charAt(c + 1).toUpperCase() +
valueName.substr(c + 2);
c = valueName.indexOf("-");
}
var value:*;
var o:Object;
var className:String;
var selectorName:String;
if ("className" in thisObject)
{
className = thisObject.className;
if (state)
{
selectorName = className + ":" + state;
o = values["." + selectorName];
if (o)
{
value = o[valueName];
if (value !== undefined)
return value;
}
}
o = values["." + className];
if (o)
{
value = o[valueName];
if (value !== undefined)
return value;
}
}
className = getQualifiedClassName(thisObject);
var thisInstance:Object = thisObject;
while (className != "Object")
{
if (state)
{
selectorName = className + ":" + state;
o = values[selectorName];
if (o)
{
value = o[valueName];
if (value !== undefined)
return value;
}
}
o = values[className];
if (o)
{
value = o[valueName];
if (value !== undefined)
return value;
}
className = getQualifiedSuperclassName(thisInstance);
thisInstance = getDefinitionByName(className);
}
if (inheritingStyles[valueName] != null &&
thisObject is IChild)
{
var parentObject:Object = IChild(thisObject).parent;
if (parentObject)
return getValue(parentObject, valueName, state, attrs);
}
o = values["global"];
if (o)
{
value = o[valueName];
if (value !== undefined)
return value;
}
o = values["*"];
if(o)
{
return o[valueName];
}
return null;
}
/**
* A method that stores a value to be shared with other objects.
* It is global, not per instance. Fancier implementations
* may store shared values per-instance.
*
* @param thisObject An object associated with this value. Thiis
* parameter is ignored.
* @param valueName The name or key of the value being stored.
* @param The value to be stored.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function setValue(thisObject:Object, valueName:String, value:*):void
{
var c:int = valueName.indexOf("-");
while (c != -1)
{
valueName = valueName.substr(0, c) +
valueName.charAt(c + 1).toUpperCase() +
valueName..substr(c + 2);
c = valueName.indexOf("-");
}
var oldValue:Object = values[valueName];
if (oldValue != value)
{
values[valueName] = value;
dispatchEvent(new ValueChangeEvent(ValueChangeEvent.VALUE_CHANGE, false, false, oldValue, value));
}
}
/**
* @copy org.apache.flex.core.IValuesImpl#newInstance()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function newInstance(thisObject:Object, valueName:String, state:String = null, attrs:Object = null):*
{
var c:Class = getValue(thisObject, valueName, state, attrs);
if (c)
return new c();
return null;
}
/**
* @copy org.apache.flex.core.IValuesImpl#getInstance()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function getInstance(valueName:String):Object
{
var o:Object = values["global"];
if (o is Class)
{
o[valueName] = new o[valueName]();
if (o[valueName] is IDocument)
o[valueName].setDocument(mainClass);
}
return o[valueName];
}
/**
* @copy org.apache.flex.core.IValuesImpl#convertColor()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function convertColor(value:Object):uint
{
if (!(value is String))
return uint(value);
var stringValue:String = value as String;
if (stringValue.charAt(0) == '#')
return uint(stringValue.substr(1));
return uint(stringValue);
}
/**
* A map of inheriting styles
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public static var inheritingStyles:Object = {
"color" : 1,
"fontFamily" : 1,
"fontSize" : 1,
"fontStyle" : 1
}
}
}
class CSSClass
{
public static const CSSSelector:int = 0;
public static const CSSCondition:int = 1;
public static const CSSStyleDeclaration:int = 2;
public static const CSSMediaQuery:int = 3;
}
class CSSFactory
{
public static const DefaultFactory:int = 0;
public static const Factory:int = 1;
public static const Override:int = 2;
}
class CSSDataType
{
public static const Native:int = 0;
public static const Definition:int = 1;
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 flash.system.ApplicationDomain;
import flash.utils.getDefinitionByName;
import flash.utils.getQualifiedClassName;
import flash.utils.getQualifiedSuperclassName;
import org.apache.flex.events.EventDispatcher;
import org.apache.flex.events.ValueChangeEvent;
/**
* The SimpleCSSValuesImpl class implements a minimal set of
* CSS lookup rules that is sufficient for most applications.
* It does not support attribute selectors or descendant selectors
* or id selectors. It will filter on a custom -flex-flash
* media query but not other media queries. It can be
* replaced with other implementations that handle more complex
* selector lookups.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class SimpleCSSValuesImpl extends EventDispatcher implements IValuesImpl
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function SimpleCSSValuesImpl()
{
super();
}
private var mainClass:Object;
private var conditionCombiners:Object;
/**
* @copy org.apache.flex.core.IValuesImpl#init()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function init(mainClass:Object):void
{
var styleClassName:String;
var c:Class;
if (!values)
{
values = {};
this.mainClass = mainClass;
var mainClassName:String = getQualifiedClassName(mainClass);
styleClassName = "_" + mainClassName + "_Styles";
c = ApplicationDomain.currentDomain.getDefinition(styleClassName) as Class;
}
else
{
c = mainClass.constructor as Class;
}
generateCSSStyleDeclarations(c["factoryFunctions"], c["data"]);
}
/**
* Process the encoded CSS data into data structures. Usually not called
* directly by application developers.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function generateCSSStyleDeclarations(factoryFunctions:Object, arr:Array):void
{
if (factoryFunctions == null)
return;
if (arr == null)
return;
var declarationName:String = "";
var segmentName:String = "";
var n:int = arr.length;
for (var i:int = 0; i < n; i++)
{
var className:int = arr[i];
if (className == CSSClass.CSSSelector)
{
var selectorName:String = arr[++i];
segmentName = selectorName + segmentName;
if (declarationName != "")
declarationName += " ";
declarationName += segmentName;
segmentName = "";
}
else if (className == CSSClass.CSSCondition)
{
if (!conditionCombiners)
{
conditionCombiners = {};
conditionCombiners["class"] = ".";
conditionCombiners["id"] = "#";
conditionCombiners["pseudo"] = ':';
}
var conditionType:String = arr[++i];
var conditionName:String = arr[++i];
segmentName = segmentName + conditionCombiners[conditionType] + conditionName;
}
else if (className == CSSClass.CSSStyleDeclaration)
{
var factoryName:int = arr[++i]; // defaultFactory or factory
var defaultFactory:Boolean = factoryName == CSSFactory.DefaultFactory;
/*
if (defaultFactory)
{
mergedStyle = styleManager.getMergedStyleDeclaration(declarationName);
style = new CSSStyleDeclaration(selector, styleManager, mergedStyle == null);
}
else
{
style = styleManager.getStyleDeclaration(declarationName);
if (!style)
{
style = new CSSStyleDeclaration(selector, styleManager, mergedStyle == null);
if (factoryName == CSSFactory.Override)
newSelectors.push(style);
}
}
*/
var mq:String = null;
var o:Object;
if (i < n - 2)
{
// peek ahead to see if there is a media query
if (arr[i + 1] == CSSClass.CSSMediaQuery)
{
mq = arr[i + 2];
i += 2;
declarationName = mq + "_" + declarationName;
}
}
var finalName:String;
var valuesFunction:Function;
var valuesObject:Object;
if (defaultFactory)
{
valuesFunction = factoryFunctions[declarationName];
valuesObject = new valuesFunction();
}
else
{
valuesFunction = factoryFunctions[declarationName];
valuesObject = new valuesFunction();
}
if (isValidStaticMediaQuery(mq))
{
finalName = fixNames(declarationName, mq);
o = values[finalName];
if (o == null)
values[finalName] = valuesObject;
else
{
valuesFunction.prototype = o;
values[finalName] = new valuesFunction();
}
}
declarationName = "";
}
}
}
private function isValidStaticMediaQuery(mq:String):Boolean
{
if (mq == null)
return true;
if (mq == "-flex-flash")
return true;
// TODO: (aharui) other media query
return false;
}
private function fixNames(s:String, mq:String):String
{
if (mq != null)
s = s.substr(mq.length + 1); // 1 more for the hyphen
if (s == "")
return "*";
var arr:Array = s.split(" ");
var n:int = arr.length;
for (var i:int = 0; i < n; i++)
{
var segmentName:String = arr[i];
if (segmentName.charAt(0) == "#" || segmentName.charAt(0) == ".")
continue;
var c:int = segmentName.lastIndexOf(".");
if (c > -1) // it is 0 for class selectors
{
segmentName = segmentName.substr(0, c) + "::" + segmentName.substr(c + 1);
arr[i] = segmentName;
}
}
return arr.join(" ");
}
/**
* The map of values. The format is not documented and it is not recommended
* to manipulate this structure directly.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var values:Object;
/**
* @copy org.apache.flex.core.IValuesImpl#getValue()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function getValue(thisObject:Object, valueName:String, state:String = null, attrs:Object = null):*
{
var c:int = valueName.indexOf("-");
while (c != -1)
{
valueName = valueName.substr(0, c) +
valueName.charAt(c + 1).toUpperCase() +
valueName.substr(c + 2);
c = valueName.indexOf("-");
}
var value:*;
var o:Object;
var className:String;
var selectorName:String;
if (thisObject is IStyleableObject)
{
var styleable:IStyleableObject = IStyleableObject(thisObject);
if (styleable.style != null)
{
try {
value = styleable.style[valueName];
}
catch (e:Error) {
value = undefined;
}
if (value == "inherit")
return getInheritingValue(thisObject, valueName, state, attrs);
if (value !== undefined)
return value;
}
className = styleable.className;
if (state)
{
selectorName = className + ":" + state;
o = values["." + selectorName];
if (o)
{
value = o[valueName];
if (value == "inherit")
return getInheritingValue(thisObject, valueName, state, attrs);
if (value !== undefined)
return value;
}
}
o = values["." + className];
if (o)
{
value = o[valueName];
if (value == "inherit")
return getInheritingValue(thisObject, valueName, state, attrs);
if (value !== undefined)
return value;
}
}
className = getQualifiedClassName(thisObject);
var thisInstance:Object = thisObject;
while (className != "Object")
{
if (state)
{
selectorName = className + ":" + state;
o = values[selectorName];
if (o)
{
value = o[valueName];
if (value == "inherit")
return getInheritingValue(thisObject, valueName, state, attrs);
if (value !== undefined)
return value;
}
}
o = values[className];
if (o)
{
value = o[valueName];
if (value == "inherit")
return getInheritingValue(thisObject, valueName, state, attrs);
if (value !== undefined)
return value;
}
className = getQualifiedSuperclassName(thisInstance);
thisInstance = getDefinitionByName(className);
}
if (inheritingStyles[valueName] != null &&
thisObject is IChild)
{
var parentObject:Object = IChild(thisObject).parent;
if (parentObject)
return getValue(parentObject, valueName, state, attrs);
}
o = values["global"];
if (o)
{
value = o[valueName];
if (value !== undefined)
return value;
}
o = values["*"];
if(o)
{
return o[valueName];
}
return undefined;
}
private function getInheritingValue(thisObject:Object, valueName:String, state:String = null, attrs:Object = null):*
{
var value:*;
if (thisObject is IChild)
{
var parentObject:Object = IChild(thisObject).parent;
if (parentObject)
{
value = getValue(parentObject, valueName, state, attrs);
if (value == "inherit" || value === undefined)
return getInheritingValue(parentObject, valueName, state, attrs);
if (value !== undefined)
return value;
}
}
return "inherit";
}
/**
* A method that stores a value to be shared with other objects.
* It is global, not per instance. Fancier implementations
* may store shared values per-instance.
*
* @param thisObject An object associated with this value. Thiis
* parameter is ignored.
* @param valueName The name or key of the value being stored.
* @param The value to be stored.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function setValue(thisObject:Object, valueName:String, value:*):void
{
var c:int = valueName.indexOf("-");
while (c != -1)
{
valueName = valueName.substr(0, c) +
valueName.charAt(c + 1).toUpperCase() +
valueName..substr(c + 2);
c = valueName.indexOf("-");
}
var oldValue:Object = values[valueName];
if (oldValue != value)
{
values[valueName] = value;
dispatchEvent(new ValueChangeEvent(ValueChangeEvent.VALUE_CHANGE, false, false, oldValue, value));
}
}
/**
* @copy org.apache.flex.core.IValuesImpl#newInstance()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function newInstance(thisObject:Object, valueName:String, state:String = null, attrs:Object = null):*
{
var c:Class = getValue(thisObject, valueName, state, attrs);
if (c)
return new c();
return null;
}
/**
* @copy org.apache.flex.core.IValuesImpl#getInstance()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function getInstance(valueName:String):Object
{
var o:Object = values["global"];
if (o is Class)
{
o[valueName] = new o[valueName]();
if (o[valueName] is IDocument)
o[valueName].setDocument(mainClass);
}
return o[valueName];
}
/**
* @copy org.apache.flex.core.IValuesImpl#convertColor()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function convertColor(value:Object):uint
{
if (!(value is String))
return uint(value);
var stringValue:String = value as String;
if (stringValue.charAt(0) == '#')
return uint(stringValue.substr(1));
return uint(stringValue);
}
/**
* A map of inheriting styles
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public static var inheritingStyles:Object = {
"color" : 1,
"fontFamily" : 1,
"fontSize" : 1,
"fontStyle" : 1
}
}
}
class CSSClass
{
public static const CSSSelector:int = 0;
public static const CSSCondition:int = 1;
public static const CSSStyleDeclaration:int = 2;
public static const CSSMediaQuery:int = 3;
}
class CSSFactory
{
public static const DefaultFactory:int = 0;
public static const Factory:int = 1;
public static const Override:int = 2;
}
class CSSDataType
{
public static const Native:int = 0;
public static const Definition:int = 1;
}
|
support inline styles
|
support inline styles
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
cf2fb19a5aa7663f02f1503379dfe3a73cb57c9b
|
src/com/mangui/HLS/streaming/Buffer.as
|
src/com/mangui/HLS/streaming/Buffer.as
|
package com.mangui.HLS.streaming {
import com.mangui.HLS.*;
import com.mangui.HLS.muxing.*;
import com.mangui.HLS.streaming.*;
import com.mangui.HLS.parsing.*;
import com.mangui.HLS.utils.*;
import flash.media.*;
import flash.net.*;
import flash.utils.*;
/** Class that keeps the buffer filled. **/
public class Buffer {
/** Reference to the framework controller. **/
private var _hls:HLS;
/** The buffer with video tags. **/
private var _buffer:Vector.<Tag>;
/** The fragment loader. **/
private var _loader:FragmentLoader;
/** Store that a fragment load is in progress. **/
private var _loading:Boolean;
/** means that last fragment of a VOD playlist has been loaded */
private var _reached_vod_end:Boolean;
/** Interval for checking buffer and position. **/
private var _interval:Number;
/** Next loading fragment sequence number. **/
/** The start position of the stream. **/
public var PlaybackStartPosition:Number = 0;
/** start playback position in second, retrieved from first fragment **/
private var _playback_start_position:Number;
/** playback start PTS. **/
private var _playback_start_pts:Number;
/** playlist start PTS when playback started. **/
private var _playlist_start_pts:Number;
/** Current play position (relative position from beginning of sliding window) **/
private var _playback_current_position:Number;
/** buffer last PTS. **/
private var _buffer_last_pts:Number;
/** next buffer time. **/
private var _buffer_next_time:Number;
/** previous buffer time. **/
private var _last_buffer:Number;
/** Current playback state. **/
private var _state:String;
/** Netstream instance used for playing the stream. **/
private var _stream:NetStream;
/** The last tag that was appended to the buffer. **/
private var _buffer_current_index:Number;
/** soundtransform object. **/
private var _transform:SoundTransform;
private var _was_playing:Boolean = false;
/** Create the buffer. **/
public function Buffer(hls:HLS, loader:FragmentLoader, stream:NetStream):void {
_hls = hls;
_loader = loader;
_stream = stream;
_stream.inBufferSeek = true;
_hls.addEventListener(HLSEvent.MANIFEST,_manifestHandler);
_transform = new SoundTransform();
_transform.volume = 0.9;
_setState(HLSStates.IDLE);
};
/** Check the bufferlength. **/
private function _checkBuffer():void {
//Log.txt("checkBuffer");
var buffer:Number = 0;
// Calculate the buffer and position.
if(_buffer.length) {
buffer = (_buffer_last_pts - _playback_start_pts)/1000 - _stream.time;
/** Current play time (time since beginning of playback) **/
var playback_current_time:Number = (Math.round(_stream.time*100 + _playback_start_position*100)/100);
var current_playlist_start_pts:Number = _loader.getPlayListStartPTS();
var play_position:Number;
if(current_playlist_start_pts ==Number.NEGATIVE_INFINITY) {
play_position = 0;
} else {
play_position = playback_current_time -(current_playlist_start_pts-_playlist_start_pts)/1000;
}
if(play_position != _playback_current_position || buffer !=_last_buffer) {
if (play_position <0) {
play_position = 0;
}
_playback_current_position = play_position;
_last_buffer = buffer;
_hls.dispatchEvent(new HLSEvent(HLSEvent.MEDIA_TIME,{ position:_playback_current_position, buffer:buffer, duration:_loader.getPlayListDuration()}));
}
}
// Load new tags from fragment.
if(_reached_vod_end == false && buffer < _loader.getBufferLength() && ((!_loading) || _loader.needReload() == true)) {
var loadstatus:Number = _loader.loadfragment(_buffer_next_time,_buffer_last_pts,buffer,_loaderCallback,(_buffer.length == 0));
if (loadstatus == 0) {
// good, new fragment being loaded
_loading = true;
} else if (loadstatus < 0) {
/* it means PTS requested is smaller than playlist start PTS.
it could happen on live playlist :
- if bandwidth available is lower than lowest quality needed bandwidth
- after long pause
seek to offset 0 to force a restart of the playback session */
Log.txt("long pause on live stream or bad network quality");
seek(0);
return;
} else if(loadstatus > 0) {
_loading = false;
//seqnum not available in playlist
if (_hls.getType() == HLSTypes.VOD) {
// if VOD playlist, it means we reached the end, on live playlist do nothing and wait ...
_reached_vod_end = true;
}
}
}
if((_state == HLSStates.PLAYING) ||
(_state == HLSStates.BUFFERING && buffer > _loader.getSegmentAverageDuration()))
{
//Log.txt("appending data into NetStream");
while(_buffer_current_index < _buffer.length && _stream.bufferLength < 2*_loader.getSegmentAverageDuration()) {
try {
_stream.appendBytes(_buffer[_buffer_current_index].data);
} catch (error:Error) {
_errorHandler(new Error(_buffer[_buffer_current_index].type+": "+ error.message));
}
// Last tag done? Then append sequence end.
if (_reached_vod_end ==true && _buffer_current_index == _buffer.length - 1) {
_stream.appendBytesAction(NetStreamAppendBytesAction.END_SEQUENCE);
_stream.appendBytes(new ByteArray());
}
_buffer_current_index++;
}
}
// Set playback state and complete.
if(_stream.bufferLength < 3) {
if(_stream.bufferLength == 0 && _reached_vod_end ==true) {
clearInterval(_interval);
_hls.dispatchEvent(new HLSEvent(HLSEvent.COMPLETE));
_setState(HLSStates.IDLE);
} else if(_state == HLSStates.PLAYING) {
!_reached_vod_end && _setState(HLSStates.BUFFERING);
}
} else if (_state == HLSStates.BUFFERING) {
if(_was_playing)
_setState(HLSStates.PLAYING);
else
pause();
}
};
/** Dispatch an error to the controller. **/
private function _errorHandler(error:Error):void {
_hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR,error.toString()));
};
/** Return the current playback state. **/
public function getPosition():Number {
return _playback_current_position;
};
/** Return the current playback state. **/
public function getState():String {
return _state;
};
/** Add a fragment to the buffer. **/
private function _loaderCallback(tags:Vector.<Tag>,min_pts:Number,max_pts:Number, hasDiscontinuity:Boolean, start_offset:Number):void {
// flush already injected Tags and restart index from 0
_buffer = _buffer.slice(_buffer_current_index);
_buffer_current_index = 0;
var seek_pts:Number = min_pts + (PlaybackStartPosition-start_offset)*1000;
if (_playback_start_pts == Number.NEGATIVE_INFINITY) {
_playback_start_pts = seek_pts;
_playlist_start_pts = _loader.getPlayListStartPTS();
_playback_start_position = (_playback_start_pts-_playlist_start_pts)/1000;
}
_buffer_last_pts = max_pts;
tags.sort(_sortTagsbyDTS);
for each (var t:Tag in tags) {
_filterTag(t,seek_pts) && _buffer.push(t);
}
_buffer_next_time=_playback_start_position+(_buffer_last_pts-_playback_start_pts)/1000;
Log.txt("_loaderCallback,_buffer_next_time:"+ _buffer_next_time);
_loading = false;
};
/** Start streaming on manifest load. **/
private function _manifestHandler(event:HLSEvent):void {
if(_state == HLSStates.IDLE) {
_stream.close();
_stream.play(null);
_stream.soundTransform = _transform;
_stream.appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN);
_stream.appendBytes(FLV.getHeader());
seek(PlaybackStartPosition);
}
};
/** Pause playback. **/
public function pause():void {
if(_state == HLSStates.PLAYING || _state == HLSStates.BUFFERING) {
clearInterval(_interval);
_setState(HLSStates.PAUSED);
_stream.pause();
}
};
/** Resume playback. **/
public function resume():void {
if(_state == HLSStates.PAUSED) {
clearInterval(_interval);
_setState(HLSStates.PLAYING);
_stream.resume();
_interval = setInterval(_checkBuffer,100);
}
};
/** Change playback state. **/
private function _setState(state:String):void {
if(state != _state) {
_state = state;
_hls.dispatchEvent(new HLSEvent(HLSEvent.STATE,_state));
}
};
/** Sort the buffer by tag. **/
private function _sortTagsbyDTS(x:Tag,y:Tag):Number {
if(x.dts < y.dts) {
return -1;
} else if (x.dts > y.dts) {
return 1;
} else {
if(x.type == Tag.AVC_HEADER || x.type == Tag.AAC_HEADER) {
return -1;
} else if (y.type == Tag.AVC_HEADER || y.type == Tag.AAC_HEADER) {
return 1;
} else {
if(x.type == Tag.AVC_NALU) {
return -1;
} else if (y.type == Tag.AVC_NALU) {
return 1;
} else {
return 0;
}
}
}
};
/**
*
* Filter tag by type and pts for accurate seeking.
*
* @param tag
* @param pts Destination pts
* @return
*/
private function _filterTag(tag:Tag,pts:Number = 0):Boolean{
if(tag.type == Tag.AAC_HEADER || tag.type == Tag.AVC_HEADER || tag.type == Tag.AVC_NALU){
if(tag.pts < pts)
tag.pts = tag.dts = pts;
return true;
}
return tag.pts >= pts;
}
/** Start playing data in the buffer. **/
public function seek(position:Number):void {
_buffer = new Vector.<Tag>();
_loader.clearLoader();
_loading = false;
_buffer_current_index = 0;
PlaybackStartPosition = position;
_stream.seek(0);
_stream.appendBytesAction(NetStreamAppendBytesAction.RESET_SEEK);
_reached_vod_end = false;
_playback_start_pts = Number.NEGATIVE_INFINITY;
_buffer_next_time = position;
_buffer_last_pts = 0;
_last_buffer = 0;
_was_playing = (_state == HLSStates.PLAYING) || (_state == HLSStates.IDLE);
_setState(HLSStates.BUFFERING);
clearInterval(_interval);
_interval = setInterval(_checkBuffer,100);
};
/** Stop playback. **/
public function stop():void {
if(_stream) {
_stream.pause();
}
_loading = false;
clearInterval(_interval);
_setState(HLSStates.IDLE);
};
/** Change the volume (set in the NetStream). **/
public function volume(percent:Number):void {
_transform.volume = percent/100;
if(_stream) {
_stream.soundTransform = _transform;
}
};
}
}
|
package com.mangui.HLS.streaming {
import com.mangui.HLS.*;
import com.mangui.HLS.muxing.*;
import com.mangui.HLS.streaming.*;
import com.mangui.HLS.parsing.*;
import com.mangui.HLS.utils.*;
import flash.media.*;
import flash.net.*;
import flash.utils.*;
/** Class that keeps the buffer filled. **/
public class Buffer {
/** Reference to the framework controller. **/
private var _hls:HLS;
/** The buffer with video tags. **/
private var _buffer:Vector.<Tag>;
/** The fragment loader. **/
private var _loader:FragmentLoader;
/** Store that a fragment load is in progress. **/
private var _loading:Boolean;
/** means that last fragment of a VOD playlist has been loaded */
private var _reached_vod_end:Boolean;
/** Interval for checking buffer and position. **/
private var _interval:Number;
/** Next loading fragment sequence number. **/
/** The start position of the stream. **/
public var PlaybackStartPosition:Number = 0;
/** start playback position in second, retrieved from first fragment **/
private var _playback_start_position:Number;
/** playback start PTS. **/
private var _playback_start_pts:Number;
/** playlist start PTS when playback started. **/
private var _playlist_start_pts:Number;
/** Current play position (relative position from beginning of sliding window) **/
private var _playback_current_position:Number;
/** buffer last PTS. **/
private var _buffer_last_pts:Number;
/** next buffer time. **/
private var _buffer_next_time:Number;
/** previous buffer time. **/
private var _last_buffer:Number;
/** Current playback state. **/
private var _state:String;
/** Netstream instance used for playing the stream. **/
private var _stream:NetStream;
/** The last tag that was appended to the buffer. **/
private var _buffer_current_index:Number;
/** soundtransform object. **/
private var _transform:SoundTransform;
private var _was_playing:Boolean = false;
/** Create the buffer. **/
public function Buffer(hls:HLS, loader:FragmentLoader, stream:NetStream):void {
_hls = hls;
_loader = loader;
_stream = stream;
_stream.inBufferSeek = true;
_hls.addEventListener(HLSEvent.MANIFEST,_manifestHandler);
_transform = new SoundTransform();
_transform.volume = 0.9;
_setState(HLSStates.IDLE);
};
/** Check the bufferlength. **/
private function _checkBuffer():void {
//Log.txt("checkBuffer");
var buffer:Number = 0;
// Calculate the buffer and position.
if(_buffer.length) {
buffer = (_buffer_last_pts - _playback_start_pts)/1000 - _stream.time;
/** Current play time (time since beginning of playback) **/
var playback_current_time:Number = (Math.round(_stream.time*100 + _playback_start_position*100)/100);
var current_playlist_start_pts:Number = _loader.getPlayListStartPTS();
var play_position:Number;
if(current_playlist_start_pts ==Number.NEGATIVE_INFINITY) {
play_position = 0;
} else {
play_position = playback_current_time -(current_playlist_start_pts-_playlist_start_pts)/1000;
}
if(play_position != _playback_current_position || buffer !=_last_buffer) {
if (play_position <0) {
play_position = 0;
}
_playback_current_position = play_position;
_last_buffer = buffer;
_hls.dispatchEvent(new HLSEvent(HLSEvent.MEDIA_TIME,{ position:_playback_current_position, buffer:buffer, duration:_loader.getPlayListDuration()}));
}
}
// Load new tags from fragment.
if(_reached_vod_end == false && buffer < _loader.getBufferLength() && ((!_loading) || _loader.needReload() == true)) {
var loadstatus:Number = _loader.loadfragment(_buffer_next_time,_buffer_last_pts,buffer,_loaderCallback,(_buffer.length == 0));
if (loadstatus == 0) {
// good, new fragment being loaded
_loading = true;
} else if (loadstatus < 0) {
/* it means PTS requested is smaller than playlist start PTS.
it could happen on live playlist :
- if bandwidth available is lower than lowest quality needed bandwidth
- after long pause
seek to offset 0 to force a restart of the playback session */
Log.txt("long pause on live stream or bad network quality");
seek(0);
return;
} else if(loadstatus > 0) {
_loading = false;
//seqnum not available in playlist
if (_hls.getType() == HLSTypes.VOD) {
// if VOD playlist, it means we reached the end, on live playlist do nothing and wait ...
_reached_vod_end = true;
}
}
}
if((_state == HLSStates.PLAYING) ||
(_state == HLSStates.BUFFERING && (buffer > _loader.getSegmentAverageDuration() || _reached_vod_end)))
{
//Log.txt("appending data into NetStream");
while(_buffer_current_index < _buffer.length && _stream.bufferLength < 2*_loader.getSegmentAverageDuration()) {
try {
_stream.appendBytes(_buffer[_buffer_current_index].data);
} catch (error:Error) {
_errorHandler(new Error(_buffer[_buffer_current_index].type+": "+ error.message));
}
// Last tag done? Then append sequence end.
if (_reached_vod_end ==true && _buffer_current_index == _buffer.length - 1) {
_stream.appendBytesAction(NetStreamAppendBytesAction.END_SEQUENCE);
_stream.appendBytes(new ByteArray());
}
_buffer_current_index++;
}
}
// Set playback state and complete.
if(_stream.bufferLength < 3) {
if(_stream.bufferLength == 0 && _reached_vod_end ==true) {
clearInterval(_interval);
_hls.dispatchEvent(new HLSEvent(HLSEvent.COMPLETE));
_setState(HLSStates.IDLE);
} else if(_state == HLSStates.PLAYING) {
!_reached_vod_end && _setState(HLSStates.BUFFERING);
}
} else if (_state == HLSStates.BUFFERING) {
if(_was_playing)
_setState(HLSStates.PLAYING);
else
pause();
}
};
/** Dispatch an error to the controller. **/
private function _errorHandler(error:Error):void {
_hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR,error.toString()));
};
/** Return the current playback state. **/
public function getPosition():Number {
return _playback_current_position;
};
/** Return the current playback state. **/
public function getState():String {
return _state;
};
/** Add a fragment to the buffer. **/
private function _loaderCallback(tags:Vector.<Tag>,min_pts:Number,max_pts:Number, hasDiscontinuity:Boolean, start_offset:Number):void {
// flush already injected Tags and restart index from 0
_buffer = _buffer.slice(_buffer_current_index);
_buffer_current_index = 0;
var seek_pts:Number = min_pts + (PlaybackStartPosition-start_offset)*1000;
if (_playback_start_pts == Number.NEGATIVE_INFINITY) {
_playback_start_pts = seek_pts;
_playlist_start_pts = _loader.getPlayListStartPTS();
_playback_start_position = (_playback_start_pts-_playlist_start_pts)/1000;
}
_buffer_last_pts = max_pts;
tags.sort(_sortTagsbyDTS);
for each (var t:Tag in tags) {
_filterTag(t,seek_pts) && _buffer.push(t);
}
_buffer_next_time=_playback_start_position+(_buffer_last_pts-_playback_start_pts)/1000;
Log.txt("_loaderCallback,_buffer_next_time:"+ _buffer_next_time);
_loading = false;
};
/** Start streaming on manifest load. **/
private function _manifestHandler(event:HLSEvent):void {
if(_state == HLSStates.IDLE) {
_stream.close();
_stream.play(null);
_stream.soundTransform = _transform;
_stream.appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN);
_stream.appendBytes(FLV.getHeader());
seek(PlaybackStartPosition);
}
};
/** Pause playback. **/
public function pause():void {
if(_state == HLSStates.PLAYING || _state == HLSStates.BUFFERING) {
clearInterval(_interval);
_stream.pause();
_setState(HLSStates.PAUSED);
}
};
/** Resume playback. **/
public function resume():void {
if(_state == HLSStates.PAUSED) {
clearInterval(_interval);
_stream.resume();
_interval = setInterval(_checkBuffer,100);
_setState(HLSStates.PLAYING);
}
};
/** Change playback state. **/
private function _setState(state:String):void {
if(state != _state) {
_state = state;
_hls.dispatchEvent(new HLSEvent(HLSEvent.STATE,_state));
}
};
/** Sort the buffer by tag. **/
private function _sortTagsbyDTS(x:Tag,y:Tag):Number {
if(x.dts < y.dts) {
return -1;
} else if (x.dts > y.dts) {
return 1;
} else {
if(x.type == Tag.AVC_HEADER || x.type == Tag.AAC_HEADER) {
return -1;
} else if (y.type == Tag.AVC_HEADER || y.type == Tag.AAC_HEADER) {
return 1;
} else {
if(x.type == Tag.AVC_NALU) {
return -1;
} else if (y.type == Tag.AVC_NALU) {
return 1;
} else {
return 0;
}
}
}
};
/**
*
* Filter tag by type and pts for accurate seeking.
*
* @param tag
* @param pts Destination pts
* @return
*/
private function _filterTag(tag:Tag,pts:Number = 0):Boolean{
if(tag.type == Tag.AAC_HEADER || tag.type == Tag.AVC_HEADER || tag.type == Tag.AVC_NALU){
if(tag.pts < pts)
tag.pts = tag.dts = pts;
return true;
}
return tag.pts >= pts;
}
/** Start playing data in the buffer. **/
public function seek(position:Number):void {
_buffer = new Vector.<Tag>();
_loader.clearLoader();
_loading = false;
_buffer_current_index = 0;
PlaybackStartPosition = position;
_stream.seek(0);
_stream.appendBytesAction(NetStreamAppendBytesAction.RESET_SEEK);
_reached_vod_end = false;
_playback_start_pts = Number.NEGATIVE_INFINITY;
_buffer_next_time = position;
_buffer_last_pts = 0;
_last_buffer = 0;
_was_playing = (_state == HLSStates.PLAYING) || (_state == HLSStates.IDLE);
_setState(HLSStates.BUFFERING);
clearInterval(_interval);
_interval = setInterval(_checkBuffer,100);
};
/** Stop playback. **/
public function stop():void {
if(_stream) {
_stream.pause();
}
_loading = false;
clearInterval(_interval);
_setState(HLSStates.IDLE);
};
/** Change the volume (set in the NetStream). **/
public function volume(percent:Number):void {
_transform.volume = percent/100;
if(_stream) {
_stream.soundTransform = _transform;
}
};
}
}
|
put state update after stream action in resume/pause, also deal with last fragment duration that can be smaller than average duration.
|
put state update after stream action in resume/pause, also deal with last fragment duration that can be smaller than average duration.
State update event must occur after real state update (otherwise, e.g. if I want prevent hls from pausing I can't do that: I receive event, call resume, but than _stream.pause() is executed.
|
ActionScript
|
mpl-2.0
|
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
|
57dbe161efc9dd46021ccf7bae5e8f98fe35c4d0
|
frameworks/projects/HTML/as/src/org/apache/flex/html/beads/DownArrowButtonView.as
|
frameworks/projects/HTML/as/src/org/apache/flex/html/beads/DownArrowButtonView.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 flash.display.Shape;
import flash.display.SimpleButton;
import org.apache.flex.core.BeadViewBase;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IBeadView;
import org.apache.flex.events.Event;
/**
* The DownArrowButtonView class is the view for
* the down arrow button in a ScrollBar and other controls.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class DownArrowButtonView extends BeadViewBase implements IBeadView
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function DownArrowButtonView()
{
upView = new Shape();
downView = new Shape();
overView = new Shape();
drawView(upView.graphics, 0xf8f8f8);
drawView(downView.graphics, 0xd8d8d8);
drawView(overView.graphics, 0xe8e8e8);
}
private function drawView(g:Graphics, bgColor:uint):void
{
g.lineStyle(1, 0x808080);
g.beginFill(bgColor);
g.drawRoundRect(0, 0, ScrollBarView.FullSize, ScrollBarView.FullSize, ScrollBarView.ThirdSize);
g.endFill();
g.lineStyle(0);
g.beginFill(0);
g.moveTo(ScrollBarView.QuarterSize, ScrollBarView.QuarterSize);
g.lineTo(ScrollBarView.ThreeQuarterSize, ScrollBarView.QuarterSize);
g.lineTo(ScrollBarView.HalfSize, ScrollBarView.ThreeQuarterSize);
g.lineTo(ScrollBarView.QuarterSize, ScrollBarView.QuarterSize);
g.endFill();
}
private var shape:Shape;
/**
* @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;
shape = new Shape();
shape.graphics.beginFill(0xCCCCCC);
shape.graphics.drawRect(0, 0, ScrollBarView.FullSize, ScrollBarView.FullSize);
shape.graphics.endFill();
SimpleButton(value).upState = upView;
SimpleButton(value).downState = downView;
SimpleButton(value).overState = overView;
SimpleButton(value).hitTestState = shape;
SimpleButton(_strand).addEventListener("widthChanged",sizeChangeHandler);
SimpleButton(_strand).addEventListener("heightChanged",sizeChangeHandler);
}
private var upView:Shape;
private var downView:Shape;
private var overView:Shape;
private function sizeChangeHandler(event:Event):void
{
SimpleButton(_strand).scaleX = SimpleButton(_strand).width / ScrollBarView.FullSize;
SimpleButton(_strand).scaleY = SimpleButton(_strand).height / ScrollBarView.FullSize;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 flash.display.Shape;
import flash.display.SimpleButton;
import org.apache.flex.core.BeadViewBase;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IBeadView;
import org.apache.flex.events.Event;
/**
* The DownArrowButtonView class is the view for
* the down arrow button in a ScrollBar and other controls.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class DownArrowButtonView extends BeadViewBase implements IBeadView
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function DownArrowButtonView()
{
upView = new Shape();
downView = new Shape();
overView = new Shape();
drawView(upView.graphics, 0xf8f8f8);
drawView(downView.graphics, 0xd8d8d8);
drawView(overView.graphics, 0xe8e8e8);
}
private function drawView(g:Graphics, bgColor:uint):void
{
g.lineStyle(1);
g.beginFill(bgColor);
g.drawRoundRect(0, 0, ScrollBarView.FullSize, ScrollBarView.FullSize, ScrollBarView.ThirdSize);
g.endFill();
g.lineStyle(0);
g.beginFill(0);
g.moveTo(ScrollBarView.QuarterSize, ScrollBarView.QuarterSize);
g.lineTo(ScrollBarView.ThreeQuarterSize, ScrollBarView.QuarterSize);
g.lineTo(ScrollBarView.HalfSize, ScrollBarView.ThreeQuarterSize);
g.lineTo(ScrollBarView.QuarterSize, ScrollBarView.QuarterSize);
g.endFill();
}
private var shape:Shape;
/**
* @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;
shape = new Shape();
shape.graphics.beginFill(0xCCCCCC);
shape.graphics.drawRect(0, 0, ScrollBarView.FullSize, ScrollBarView.FullSize);
shape.graphics.endFill();
SimpleButton(value).upState = upView;
SimpleButton(value).downState = downView;
SimpleButton(value).overState = overView;
SimpleButton(value).hitTestState = shape;
SimpleButton(_strand).addEventListener("widthChanged",sizeChangeHandler);
SimpleButton(_strand).addEventListener("heightChanged",sizeChangeHandler);
}
private var upView:Shape;
private var downView:Shape;
private var overView:Shape;
private function sizeChangeHandler(event:Event):void
{
SimpleButton(_strand).scaleX = SimpleButton(_strand).width / ScrollBarView.FullSize;
SimpleButton(_strand).scaleY = SimpleButton(_strand).height / ScrollBarView.FullSize;
}
}
}
|
use black like up button
|
use black like up button
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
f1e92f36969cb1f9c0bfff60cfcab18d30300759
|
src/aerys/minko/type/clone/CloneOptions.as
|
src/aerys/minko/type/clone/CloneOptions.as
|
package aerys.minko.type.clone
{
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.controller.AnimationController;
import aerys.minko.scene.controller.TransformController;
import aerys.minko.scene.controller.camera.CameraController;
import aerys.minko.scene.controller.light.DirectionalLightController;
import aerys.minko.scene.controller.light.LightController;
import aerys.minko.scene.controller.light.PointLightController;
import aerys.minko.scene.controller.light.SpotLightController;
import aerys.minko.scene.controller.mesh.MeshController;
import aerys.minko.scene.controller.mesh.MeshVisibilityController;
import aerys.minko.scene.controller.mesh.skinning.SkinningController;
public final class CloneOptions
{
private var _clonedControllerTypes : Vector.<Class>;
private var _ignoredControllerTypes : Vector.<Class>;
private var _reassignedControllerTypes : Vector.<Class>;
private var _defaultControllerAction : uint;
public function get defaultControllerAction() : uint
{
return _defaultControllerAction;
}
public function set defaultControllerAction(v : uint) : void
{
if (v != ControllerCloneAction.CLONE
&& v != ControllerCloneAction.IGNORE
&& v != ControllerCloneAction.REASSIGN)
throw new Error('Unknown action type.');
_defaultControllerAction = v;
}
public function CloneOptions()
{
initialize();
}
private function initialize() : void
{
_clonedControllerTypes = new <Class>[];
_ignoredControllerTypes = new <Class>[];
_reassignedControllerTypes = new <Class>[];
_defaultControllerAction = ControllerCloneAction.REASSIGN;
}
public static function get defaultOptions() : CloneOptions
{
var cloneOptions : CloneOptions = new CloneOptions();
cloneOptions._clonedControllerTypes.push(
AnimationController,
SkinningController
);
cloneOptions._ignoredControllerTypes.push(
MeshController,
MeshVisibilityController,
CameraController,
TransformController,
LightController,
DirectionalLightController,
SpotLightController,
PointLightController,
);
cloneOptions._defaultControllerAction = ControllerCloneAction.REASSIGN;
return cloneOptions;
}
public static function get cloneAllOptions() : CloneOptions
{
var cloneOptions : CloneOptions = new CloneOptions();
cloneOptions._ignoredControllerTypes.push(
MeshController,
MeshVisibilityController,
CameraController,
TransformController,
LightController,
DirectionalLightController,
SpotLightController,
PointLightController
);
cloneOptions._defaultControllerAction = ControllerCloneAction.CLONE;
return cloneOptions;
}
public function addControllerAction(controllerClass : Class, action : uint) : CloneOptions
{
switch (action)
{
case ControllerCloneAction.CLONE:
_clonedControllerTypes.push(controllerClass);
break;
case ControllerCloneAction.IGNORE:
_ignoredControllerTypes.push(controllerClass);
break;
case ControllerCloneAction.REASSIGN:
_reassignedControllerTypes.push(controllerClass);
break;
default:
throw new Error('Unknown action type.');
}
return this;
}
public function removeControllerAction(controllerClass : Class) : void
{
throw new Error('Implement me.');
}
public function getActionForController(controller : AbstractController) : uint
{
var numControllersToClone : uint = _clonedControllerTypes.length;
var numControllersToIgnore : uint = _ignoredControllerTypes.length;
var numControllersToReassign : uint = _reassignedControllerTypes.length;
var controllerId : uint;
for (controllerId = 0; controllerId < numControllersToClone; ++controllerId)
if (controller is _clonedControllerTypes[controllerId])
return ControllerCloneAction.CLONE;
for (controllerId = 0; controllerId < numControllersToIgnore; ++controllerId)
if (controller is _ignoredControllerTypes[controllerId])
return ControllerCloneAction.IGNORE;
for (controllerId = 0; controllerId < numControllersToReassign; ++controllerId)
if (controller is _reassignedControllerTypes[controllerId])
return ControllerCloneAction.REASSIGN;
return _defaultControllerAction;
}
}
}
|
package aerys.minko.type.clone
{
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.controller.AnimationController;
import aerys.minko.scene.controller.TransformController;
import aerys.minko.scene.controller.camera.CameraController;
import aerys.minko.scene.controller.light.DirectionalLightController;
import aerys.minko.scene.controller.light.LightController;
import aerys.minko.scene.controller.light.PointLightController;
import aerys.minko.scene.controller.light.SpotLightController;
import aerys.minko.scene.controller.mesh.MeshController;
import aerys.minko.scene.controller.mesh.MeshVisibilityController;
import aerys.minko.scene.controller.mesh.skinning.SkinningController;
public final class CloneOptions
{
private var _clonedControllerTypes : Vector.<Class>;
private var _ignoredControllerTypes : Vector.<Class>;
private var _reassignedControllerTypes : Vector.<Class>;
private var _defaultControllerAction : uint;
public function get defaultControllerAction() : uint
{
return _defaultControllerAction;
}
public function set defaultControllerAction(v : uint) : void
{
if (v != ControllerCloneAction.CLONE
&& v != ControllerCloneAction.IGNORE
&& v != ControllerCloneAction.REASSIGN)
throw new Error('Unknown action type.');
_defaultControllerAction = v;
}
public function CloneOptions()
{
initialize();
}
private function initialize() : void
{
_clonedControllerTypes = new <Class>[];
_ignoredControllerTypes = new <Class>[];
_reassignedControllerTypes = new <Class>[];
_defaultControllerAction = ControllerCloneAction.REASSIGN;
}
public static function get defaultOptions() : CloneOptions
{
var cloneOptions : CloneOptions = new CloneOptions();
cloneOptions._clonedControllerTypes.push(
AnimationController,
SkinningController
);
cloneOptions._ignoredControllerTypes.push(
MeshController,
MeshVisibilityController,
CameraController,
TransformController,
LightController,
DirectionalLightController,
SpotLightController,
PointLightController
);
cloneOptions._defaultControllerAction = ControllerCloneAction.REASSIGN;
return cloneOptions;
}
public static function get cloneAllOptions() : CloneOptions
{
var cloneOptions : CloneOptions = new CloneOptions();
cloneOptions._ignoredControllerTypes.push(
MeshController,
MeshVisibilityController,
CameraController,
TransformController,
LightController,
DirectionalLightController,
SpotLightController,
PointLightController
);
cloneOptions._defaultControllerAction = ControllerCloneAction.CLONE;
return cloneOptions;
}
public function addControllerAction(controllerClass : Class, action : uint) : CloneOptions
{
switch (action)
{
case ControllerCloneAction.CLONE:
_clonedControllerTypes.push(controllerClass);
break;
case ControllerCloneAction.IGNORE:
_ignoredControllerTypes.push(controllerClass);
break;
case ControllerCloneAction.REASSIGN:
_reassignedControllerTypes.push(controllerClass);
break;
default:
throw new Error('Unknown action type.');
}
return this;
}
public function removeControllerAction(controllerClass : Class) : void
{
throw new Error('Implement me.');
}
public function getActionForController(controller : AbstractController) : uint
{
var numControllersToClone : uint = _clonedControllerTypes.length;
var numControllersToIgnore : uint = _ignoredControllerTypes.length;
var numControllersToReassign : uint = _reassignedControllerTypes.length;
var controllerId : uint;
for (controllerId = 0; controllerId < numControllersToClone; ++controllerId)
if (controller is _clonedControllerTypes[controllerId])
return ControllerCloneAction.CLONE;
for (controllerId = 0; controllerId < numControllersToIgnore; ++controllerId)
if (controller is _ignoredControllerTypes[controllerId])
return ControllerCloneAction.IGNORE;
for (controllerId = 0; controllerId < numControllersToReassign; ++controllerId)
if (controller is _reassignedControllerTypes[controllerId])
return ControllerCloneAction.REASSIGN;
return _defaultControllerAction;
}
}
}
|
fix typo
|
fix typo
|
ActionScript
|
mit
|
aerys/minko-as3
|
3eb7ac3d5d2bb04dfc2fdbfa5dc29b403c8413ad
|
src/aerys/minko/type/math/HLSAMatrix4x4.as
|
src/aerys/minko/type/math/HLSAMatrix4x4.as
|
package aerys.minko.type.math
{
public class HLSAMatrix4x4 extends Matrix4x4
{
private static const TMP_NUMBERS : Vector.<Number> = new Vector.<Number>(16, true);
private static const TMP_MATRIX : Matrix4x4 = new Matrix4x4();
private static const TMP_VECTOR4 : Vector4 = new Vector4();
private static const RWGT : Number = 0.3086;
private static const GWGT : Number = 0.6094;
private static const BWGT : Number = 0.0820;
private static const SQRT2 : Number = Math.sqrt(2.0);
private static const SQRT3 : Number = Math.sqrt(3.0);
private static const INV_SQRT2 : Number = 1.0 / SQRT2;
private var _hue : Number = 0;
private var _saturation : Number = 1;
private var _luminance : Number = 1;
private var _alpha : Number = 1;
private var _hueMatrix : Matrix4x4 = new Matrix4x4();
private var _saturationMatrix : Matrix4x4 = new Matrix4x4();
private var _luminanceMatrix : Matrix4x4 = new Matrix4x4();
private var _luminancePlane : Vector4 = new Vector4(RWGT, GWGT, BWGT, 0);
/**
* Alpha multiplier, from 0 to 1, default is 1.
*/
public function get alpha() : Number
{
return _alpha
}
public function set alpha(value : Number) : void
{
_alpha = value;
updateDiffuseColorMatrix();
}
/**
* Hue correction, from -2PI to 2PI, default is 0.
*/
public function get hue() : Number
{
return _hue;
}
public function set hue(value : Number) : void
{
_hue = value;
// First we make an identity matrix
_hueMatrix.identity();
// Rotate the grey vector into positive Z
TMP_MATRIX.initialize(
1, 0, 0, 0,
0, INV_SQRT2, INV_SQRT2, 0,
0, -INV_SQRT2, INV_SQRT2, 0,
0, 0, 0, 1
);
_hueMatrix.append(TMP_MATRIX);
var mag : Number = SQRT3;
var yrs : Number = -1.0 / mag;
var yrc : Number = SQRT2 / mag;
TMP_MATRIX.initialize(
yrc, 0, -yrs, 0,
0, 1, 0, 0,
yrs, 0, yrc, 0,
0, 0, 0, 1
);
_hueMatrix.append(TMP_MATRIX);
// Shear the space to make the luminance plane horizontal
var l : Vector4 = _hueMatrix.transformVector(_luminancePlane, TMP_VECTOR4);
var zsx : Number = l.x / l.z;
var zsy : Number = l.y / l.z;
TMP_MATRIX.initialize(
1, 0, zsx, 0,
0, 1, zsy, 0,
0, 0, 1, 0,
0, 0, 0, 1
);
_hueMatrix.append(TMP_MATRIX);
// Rotate the hue
var zrs : Number = Math.sin(value);
var zrc : Number = Math.cos(value);
TMP_MATRIX.initialize(
zrc, zrs, 0, 0,
-zrs, zrc, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
);
_hueMatrix.append(TMP_MATRIX);
// Unshear the space to put the luminance plane back
TMP_MATRIX.initialize(
1, 0, -zsx, 0,
0, 1, -zsy, 0,
0, 0, 1, 0,
0, 0, 0, 1
);
_hueMatrix.append(TMP_MATRIX);
// Rotate the grey vector back into place
TMP_MATRIX.initialize(
yrc, 0, yrs, 0,
0, 1, 0, 0,
-yrs, 0, yrc, 0,
0, 0, 0, 1
);
_hueMatrix.append(TMP_MATRIX);
TMP_MATRIX.initialize(
1, 0, 0, 0,
0, INV_SQRT2, -INV_SQRT2, 0,
0, INV_SQRT2, INV_SQRT2, 0,
0, 0, 0, 1
);
_hueMatrix.append(TMP_MATRIX);
updateDiffuseColorMatrix();
}
/**
* Saturation multiplier, default is 1.
*/
public function get saturation() : Number
{
return _saturation;
}
public function set saturation(s : Number):void
{
_saturation = s;
var s1 : Number = 1.0 - s;
var a : Number = s1 * RWGT + s;
var b : Number = s1 * RWGT;
var c : Number = s1 * RWGT;
var d : Number = s1 * GWGT;
var e : Number = s1 * GWGT + s;
var f : Number = s1 * GWGT;
var g : Number = s1 * BWGT;
var h : Number = s1 * BWGT;
var i : Number = s1 * BWGT + s;
_saturationMatrix.initialize(
a, b, c, 0,
d, e, f, 0,
g, h, i, 0,
0, 0, 0, 1
);
updateDiffuseColorMatrix();
}
/**
* Luminance multiplier, default is 1.
*/
public function get luminance() : Number
{
return _luminance;
}
public function set luminance(l : Number) : void
{
_luminance = l;
_luminanceMatrix
.lock()
.identity()
.appendUniformScale(l)
.unlock();
updateDiffuseColorMatrix();
}
public function HLSAMatrix4x4(hue : Number, luminance : Number, saturation : Number, alpha : Number)
{
super();
this.hue = hue;
this.luminance = luminance;
this.saturation = saturation;
this.alpha = alpha;
updateDiffuseColorMatrix();
}
private function updateDiffuseColorMatrix() : void
{
lock();
identity();
append(_hueMatrix);
append(_saturationMatrix);
append(_luminanceMatrix);
appendTranslation(0, 0, _alpha);
unlock();
}
}
}
|
package aerys.minko.type.math
{
public class HLSAMatrix4x4 extends Matrix4x4
{
private static const TMP_NUMBERS : Vector.<Number> = new Vector.<Number>(16, true);
private static const TMP_MATRIX : Matrix4x4 = new Matrix4x4();
private static const TMP_VECTOR4 : Vector4 = new Vector4();
private static const RWGT : Number = 0.3086;
private static const GWGT : Number = 0.6094;
private static const BWGT : Number = 0.0820;
private static const SQRT2 : Number = Math.sqrt(2.0);
private static const SQRT3 : Number = Math.sqrt(3.0);
private static const INV_SQRT2 : Number = 1. / SQRT2;
private var _hue : Number = 0;
private var _saturation : Number = 1;
private var _luminance : Number = 1;
private var _alpha : Number = 1;
private var _hueMatrix : Matrix4x4 = new Matrix4x4();
private var _saturationMatrix : Matrix4x4 = new Matrix4x4();
private var _luminanceMatrix : Matrix4x4 = new Matrix4x4();
private var _luminancePlane : Vector4 = new Vector4(RWGT, GWGT, BWGT, 0);
/**
* Alpha multiplier, from 0 to 1, default is 1.
*/
public function get alpha() : Number
{
return _alpha
}
public function set alpha(value : Number) : void
{
_alpha = value;
updateDiffuseColorMatrix();
}
/**
* Hue correction, from -2PI to 2PI, default is 0.
*/
public function get hue() : Number
{
return _hue;
}
public function set hue(value : Number) : void
{
_hue = value;
// First we make an identity matrix
_hueMatrix.identity();
// Rotate the grey vector into positive Z
TMP_MATRIX.initialize(
1, 0, 0, 0,
0, INV_SQRT2, INV_SQRT2, 0,
0, -INV_SQRT2, INV_SQRT2, 0,
0, 0, 0, 1
);
_hueMatrix.append(TMP_MATRIX);
var mag : Number = SQRT3;
var yrs : Number = -1.0 / mag;
var yrc : Number = SQRT2 / mag;
TMP_MATRIX.initialize(
yrc, 0, -yrs, 0,
0, 1, 0, 0,
yrs, 0, yrc, 0,
0, 0, 0, 1
);
_hueMatrix.append(TMP_MATRIX);
// Shear the space to make the luminance plane horizontal
var l : Vector4 = _hueMatrix.transformVector(_luminancePlane, TMP_VECTOR4);
var zsx : Number = l.x / l.z;
var zsy : Number = l.y / l.z;
TMP_MATRIX.initialize(
1, 0, zsx, 0,
0, 1, zsy, 0,
0, 0, 1, 0,
0, 0, 0, 1
);
_hueMatrix.append(TMP_MATRIX);
// Rotate the hue
var zrs : Number = Math.sin(value);
var zrc : Number = Math.cos(value);
TMP_MATRIX.initialize(
zrc, zrs, 0, 0,
-zrs, zrc, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
);
_hueMatrix.append(TMP_MATRIX);
// Unshear the space to put the luminance plane back
TMP_MATRIX.initialize(
1, 0, -zsx, 0,
0, 1, -zsy, 0,
0, 0, 1, 0,
0, 0, 0, 1
);
_hueMatrix.append(TMP_MATRIX);
// Rotate the grey vector back into place
TMP_MATRIX.initialize(
yrc, 0, yrs, 0,
0, 1, 0, 0,
-yrs, 0, yrc, 0,
0, 0, 0, 1
);
_hueMatrix.append(TMP_MATRIX);
TMP_MATRIX.initialize(
1, 0, 0, 0,
0, INV_SQRT2, -INV_SQRT2, 0,
0, INV_SQRT2, INV_SQRT2, 0,
0, 0, 0, 1
);
_hueMatrix.append(TMP_MATRIX);
updateDiffuseColorMatrix();
}
/**
* Saturation multiplier, default is 1.
*/
public function get saturation() : Number
{
return _saturation;
}
public function set saturation(s : Number):void
{
_saturation = s;
var s1 : Number = 1.0 - s;
var a : Number = s1 * RWGT + s;
var b : Number = s1 * RWGT;
var c : Number = s1 * RWGT;
var d : Number = s1 * GWGT;
var e : Number = s1 * GWGT + s;
var f : Number = s1 * GWGT;
var g : Number = s1 * BWGT;
var h : Number = s1 * BWGT;
var i : Number = s1 * BWGT + s;
_saturationMatrix.initialize(
a, b, c, 0,
d, e, f, 0,
g, h, i, 0,
0, 0, 0, 1
);
updateDiffuseColorMatrix();
}
/**
* Luminance multiplier, default is 1.
*/
public function get luminance() : Number
{
return _luminance;
}
public function set luminance(l : Number) : void
{
_luminance = l;
_luminanceMatrix
.lock()
.identity()
.appendUniformScale(l)
.unlock();
updateDiffuseColorMatrix();
}
public function HLSAMatrix4x4(hue : Number = 0.,
luminance : Number = 1.,
saturation : Number = 1.,
alpha : Number = 1.)
{
super();
this.hue = hue;
this.luminance = luminance;
this.saturation = saturation;
this.alpha = alpha;
updateDiffuseColorMatrix();
}
private function updateDiffuseColorMatrix() : void
{
lock();
identity();
append(_hueMatrix);
append(_saturationMatrix);
append(_luminanceMatrix);
setColumn(3, new Vector4(0, 0, 0, _alpha));
unlock();
}
override public function clone() : Matrix4x4
{
return new HLSAMatrix4x4(_hue, _luminance, _saturation, _alpha);
}
}
}
|
fix HLSAMatrix4x4.updateDiffuseColorMatrix() to use Matrix4x4.setColumn() instead of Matrix4x4.appendTranslation() to handle alpha and override HLSAMatrix4x4.clone() to return an HLSAMatrix4x4 instance
|
fix HLSAMatrix4x4.updateDiffuseColorMatrix() to use Matrix4x4.setColumn() instead of Matrix4x4.appendTranslation() to handle alpha and override HLSAMatrix4x4.clone() to return an HLSAMatrix4x4 instance
|
ActionScript
|
mit
|
aerys/minko-as3
|
1ef811ce32b00e36994297c7114bef70ae46030d
|
src/com/esri/builder/controllers/supportClasses/StartupWidgetTypeLoader.as
|
src/com/esri/builder/controllers/supportClasses/StartupWidgetTypeLoader.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.supportClasses
{
import com.esri.builder.model.WidgetType;
import com.esri.builder.model.WidgetTypeRegistryModel;
import com.esri.builder.supportClasses.FileUtil;
import com.esri.builder.supportClasses.LogUtil;
import com.esri.builder.views.BuilderAlert;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.filesystem.File;
import flash.utils.Dictionary;
import mx.logging.ILogger;
import mx.logging.Log;
import mx.resources.ResourceManager;
public class StartupWidgetTypeLoader extends EventDispatcher
{
private static const LOG:ILogger = LogUtil.createLogger(StartupWidgetTypeLoader);
private var widgetTypeArr:Array = [];
private var pendingLoaders:Array;
public function loadWidgetTypes():void
{
if (Log.isInfo())
{
LOG.info('Loading modules...');
}
var moduleFiles:Array = getModuleFiles(WellKnownDirectories.getInstance().bundledModules)
.concat(getModuleFiles(WellKnownDirectories.getInstance().customModules));
var swfFileAndXMLFileMaps:Array = mapFilenameToModuleSWFAndXMLFiles(moduleFiles);
var processedFileNames:Array = [];
var loaders:Array = [];
for each (var moduleFile:File in moduleFiles)
{
var fileName:String = FileUtil.getFileName(moduleFile);
if (Log.isDebug())
{
LOG.debug('loading module {0}', fileName);
}
if (processedFileNames.indexOf(fileName) == -1)
{
processedFileNames.push(fileName);
loaders.push(new WidgetTypeLoader(swfFileAndXMLFileMaps[0][fileName],
swfFileAndXMLFileMaps[1][fileName]));
}
}
pendingLoaders = loaders;
for each (var loader:WidgetTypeLoader in loaders)
{
loader.addEventListener(WidgetTypeLoaderEvent.LOAD_COMPLETE, loader_loadCompleteHandler);
loader.addEventListener(WidgetTypeLoaderEvent.LOAD_ERROR, loader_loadErrorHandler);
loader.load();
}
checkIfWidgetTypeLoadersComplete();
}
private function mapFilenameToModuleSWFAndXMLFiles(moduleFiles:Array):Array
{
var uniqueFileNameToSWF:Dictionary = new Dictionary();
var uniqueFileNameToXML:Dictionary = new Dictionary();
for each (var file:File in moduleFiles)
{
if (file.extension == "swf")
{
uniqueFileNameToSWF[FileUtil.getFileName(file)] = file;
}
else if (file.extension == "xml")
{
uniqueFileNameToXML[FileUtil.getFileName(file)] = file;
}
}
return [ uniqueFileNameToSWF, uniqueFileNameToXML ];
}
private function getModuleFiles(directory:File):Array
{
const moduleFileName:RegExp = /^.*Module\.(swf|xml)$/;
return FileUtil.findMatchingFiles(directory, moduleFileName);
}
private function checkIfWidgetTypeLoadersComplete():void
{
if (pendingLoaders.length === 0)
{
sortAndAssignWidgetTypes();
}
}
private function markModuleAsLoaded(loader:WidgetTypeLoader):void
{
var loaderIndex:int = pendingLoaders.indexOf(loader);
if (loaderIndex > -1)
{
pendingLoaders.splice(loaderIndex, 1);
}
}
private function sortAndAssignWidgetTypes():void
{
if (Log.isInfo())
{
LOG.info('All modules resolved');
}
for each (var widgetType:WidgetType in widgetTypeArr)
{
if (widgetType.isManaged)
{
WidgetTypeRegistryModel.getInstance().widgetTypeRegistry.addWidgetType(widgetType);
}
else
{
WidgetTypeRegistryModel.getInstance().layoutWidgetTypeRegistry.addWidgetType(widgetType);
}
}
WidgetTypeRegistryModel.getInstance().widgetTypeRegistry.sort();
WidgetTypeRegistryModel.getInstance().layoutWidgetTypeRegistry.sort();
dispatchEvent(new Event(Event.COMPLETE));
}
private function loader_loadCompleteHandler(event:WidgetTypeLoaderEvent):void
{
var loader:WidgetTypeLoader = event.currentTarget as WidgetTypeLoader;
loader.removeEventListener(WidgetTypeLoaderEvent.LOAD_COMPLETE, loader_loadCompleteHandler);
loader.removeEventListener(WidgetTypeLoaderEvent.LOAD_ERROR, loader_loadErrorHandler);
var widgetType:WidgetType = event.widgetType;
if (Log.isDebug())
{
LOG.debug('Module {0} is resolved', widgetType.name);
}
widgetTypeArr.push(widgetType);
markModuleAsLoaded(loader);
checkIfWidgetTypeLoadersComplete();
}
private function loader_loadErrorHandler(event:WidgetTypeLoaderEvent):void
{
var loader:WidgetTypeLoader = event.currentTarget as WidgetTypeLoader;
loader.removeEventListener(WidgetTypeLoaderEvent.LOAD_COMPLETE, loader_loadCompleteHandler);
loader.removeEventListener(WidgetTypeLoaderEvent.LOAD_ERROR, loader_loadErrorHandler);
var errorMessage:String = ResourceManager.getInstance().getString('BuilderStrings',
'importWidgetProcess.couldNotLoadCustomWidgets',
[ loader.name ]);
if (Log.isDebug())
{
LOG.debug(errorMessage);
}
BuilderAlert.show(errorMessage,
ResourceManager.getInstance().getString('BuilderStrings', 'error'));
markModuleAsLoaded(loader);
checkIfWidgetTypeLoadersComplete();
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
// 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.supportClasses
{
import com.esri.builder.model.WidgetType;
import com.esri.builder.model.WidgetTypeRegistryModel;
import com.esri.builder.supportClasses.FileUtil;
import com.esri.builder.supportClasses.LogUtil;
import com.esri.builder.views.BuilderAlert;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.filesystem.File;
import flash.utils.Dictionary;
import mx.logging.ILogger;
import mx.logging.Log;
import mx.resources.ResourceManager;
public class StartupWidgetTypeLoader extends EventDispatcher
{
private static const LOG:ILogger = LogUtil.createLogger(StartupWidgetTypeLoader);
private var widgetTypeArr:Array = [];
private var pendingLoaders:Array;
public function loadWidgetTypes():void
{
if (Log.isInfo())
{
LOG.info('Loading modules...');
}
var moduleFiles:Array = getModuleFiles(WellKnownDirectories.getInstance().bundledModules)
.concat(getModuleFiles(WellKnownDirectories.getInstance().customModules));
var swfFileAndXMLFileMaps:Array = mapFilenameToModuleSWFAndXMLFiles(moduleFiles);
var processedFileNames:Array = [];
var loaders:Array = [];
for each (var moduleFile:File in moduleFiles)
{
var fileName:String = FileUtil.getFileName(moduleFile);
if (Log.isDebug())
{
LOG.debug('loading module {0}', fileName);
}
if (processedFileNames.indexOf(fileName) == -1)
{
processedFileNames.push(fileName);
loaders.push(new WidgetTypeLoader(swfFileAndXMLFileMaps[0][fileName],
swfFileAndXMLFileMaps[1][fileName]));
}
}
pendingLoaders = loaders.concat();
for each (var loader:WidgetTypeLoader in loaders)
{
loader.addEventListener(WidgetTypeLoaderEvent.LOAD_COMPLETE, loader_loadCompleteHandler);
loader.addEventListener(WidgetTypeLoaderEvent.LOAD_ERROR, loader_loadErrorHandler);
loader.load();
}
checkIfWidgetTypeLoadersComplete();
}
private function mapFilenameToModuleSWFAndXMLFiles(moduleFiles:Array):Array
{
var uniqueFileNameToSWF:Dictionary = new Dictionary();
var uniqueFileNameToXML:Dictionary = new Dictionary();
for each (var file:File in moduleFiles)
{
if (file.extension == "swf")
{
uniqueFileNameToSWF[FileUtil.getFileName(file)] = file;
}
else if (file.extension == "xml")
{
uniqueFileNameToXML[FileUtil.getFileName(file)] = file;
}
}
return [ uniqueFileNameToSWF, uniqueFileNameToXML ];
}
private function getModuleFiles(directory:File):Array
{
const moduleFileName:RegExp = /^.*Module\.(swf|xml)$/;
return FileUtil.findMatchingFiles(directory, moduleFileName);
}
private function checkIfWidgetTypeLoadersComplete():void
{
if (pendingLoaders.length === 0)
{
sortAndAssignWidgetTypes();
}
}
private function markModuleAsLoaded(loader:WidgetTypeLoader):void
{
var loaderIndex:int = pendingLoaders.indexOf(loader);
if (loaderIndex > -1)
{
pendingLoaders.splice(loaderIndex, 1);
}
}
private function sortAndAssignWidgetTypes():void
{
if (Log.isInfo())
{
LOG.info('All modules resolved');
}
for each (var widgetType:WidgetType in widgetTypeArr)
{
if (widgetType.isManaged)
{
WidgetTypeRegistryModel.getInstance().widgetTypeRegistry.addWidgetType(widgetType);
}
else
{
WidgetTypeRegistryModel.getInstance().layoutWidgetTypeRegistry.addWidgetType(widgetType);
}
}
WidgetTypeRegistryModel.getInstance().widgetTypeRegistry.sort();
WidgetTypeRegistryModel.getInstance().layoutWidgetTypeRegistry.sort();
dispatchEvent(new Event(Event.COMPLETE));
}
private function loader_loadCompleteHandler(event:WidgetTypeLoaderEvent):void
{
var loader:WidgetTypeLoader = event.currentTarget as WidgetTypeLoader;
loader.removeEventListener(WidgetTypeLoaderEvent.LOAD_COMPLETE, loader_loadCompleteHandler);
loader.removeEventListener(WidgetTypeLoaderEvent.LOAD_ERROR, loader_loadErrorHandler);
var widgetType:WidgetType = event.widgetType;
if (Log.isDebug())
{
LOG.debug('Module {0} is resolved', widgetType.name);
}
widgetTypeArr.push(widgetType);
markModuleAsLoaded(loader);
checkIfWidgetTypeLoadersComplete();
}
private function loader_loadErrorHandler(event:WidgetTypeLoaderEvent):void
{
var loader:WidgetTypeLoader = event.currentTarget as WidgetTypeLoader;
loader.removeEventListener(WidgetTypeLoaderEvent.LOAD_COMPLETE, loader_loadCompleteHandler);
loader.removeEventListener(WidgetTypeLoaderEvent.LOAD_ERROR, loader_loadErrorHandler);
var errorMessage:String = ResourceManager.getInstance().getString('BuilderStrings',
'importWidgetProcess.couldNotLoadCustomWidgets',
[ loader.name ]);
if (Log.isDebug())
{
LOG.debug(errorMessage);
}
BuilderAlert.show(errorMessage,
ResourceManager.getInstance().getString('BuilderStrings', 'error'));
markModuleAsLoaded(loader);
checkIfWidgetTypeLoadersComplete();
}
}
}
|
Store pending widget type loaders separately to avoid messing load order.
|
Store pending widget type loaders separately to avoid messing load order.
|
ActionScript
|
apache-2.0
|
Esri/arcgis-viewer-builder-flex
|
c9519feec79d53ad3f7cc903cf47bd214cc47b88
|
frameworks/projects/HTML/as/src/org/apache/flex/html/beads/TextInputView.as
|
frameworks/projects/HTML/as/src/org/apache/flex/html/beads/TextInputView.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.DisplayObject;
import flash.text.TextFieldType;
import org.apache.flex.core.ILayoutChild;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.UIMetrics;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
import org.apache.flex.utils.BeadMetrics;
/**
* The TextInputView class is the view for
* the org.apache.flex.html.TextInput in
* a ComboBox and other controls
* because it does not display a border.
* It displays text using a TextField, so there is no
* right-to-left text support in this view.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class TextInputView extends TextFieldViewBase
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function TextInputView()
{
super();
textField.selectable = true;
textField.type = TextFieldType.INPUT;
textField.mouseEnabled = true;
textField.multiline = false;
textField.wordWrap = false;
}
/**
* @private
*/
override public function set strand(value:IStrand):void
{
super.strand = value;
var w:Number;
var h:Number;
var ilc:ILayoutChild = host as ILayoutChild;
if (ilc.isWidthSizedToContent())
{
// use default width of 20
var s:String = textField.text;
textField.text = "0";
w = textField.textWidth * 20;
h = textField.textHeight;
textField.text = s;
ilc.setWidth(w, true);
}
if (ilc.isHeightSizedToContent())
{
var uiMetrics:UIMetrics = BeadMetrics.getMetrics(host);
if (isNaN(h))
{
s = textField.text;
textField.text = "0";
h = textField.textHeight;
textField.text = s;
}
ilc.setHeight(h + uiMetrics.top + uiMetrics.bottom, true);
}
IEventDispatcher(host).addEventListener("widthChanged", sizeChangedHandler);
IEventDispatcher(host).addEventListener("heightChanged", sizeChangedHandler);
sizeChangedHandler(null);
}
private function sizeChangedHandler(event:Event):void
{
var ww:Number = host.width;
if( !isNaN(ww) && ww > 0 ) textField.width = ww;
var hh:Number = host.height;
if( !isNaN(hh) && hh > 0 )
{
textField.height = textField.textHeight + 5;
}
textField.y = ((hh - textField.height) / 2);
}
}
}
|
//
// 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.DisplayObject;
import flash.text.TextFieldType;
import org.apache.flex.core.ILayoutChild;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.UIMetrics;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
import org.apache.flex.utils.BeadMetrics;
/**
* The TextInputView class is the view for
* the org.apache.flex.html.TextInput in
* a ComboBox and other controls
* because it does not display a border.
* It displays text using a TextField, so there is no
* right-to-left text support in this view.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class TextInputView extends TextFieldViewBase
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function TextInputView()
{
super();
textField.selectable = true;
textField.type = TextFieldType.INPUT;
textField.mouseEnabled = true;
textField.multiline = false;
textField.wordWrap = false;
}
/**
* @private
*/
override public function set strand(value:IStrand):void
{
super.strand = value;
var w:Number;
var h:Number;
var uiMetrics:UIMetrics;
var ilc:ILayoutChild = host as ILayoutChild;
if (ilc.isWidthSizedToContent())
{
uiMetrics = BeadMetrics.getMetrics(host);
// use default width of 20
var s:String = textField.text;
textField.text = "0";
w = textField.textWidth * 20;
h = textField.textHeight;
textField.text = s;
ilc.setWidth(w + uiMetrics.left + uiMetrics.right, true);
}
if (ilc.isHeightSizedToContent())
{
if (!uiMetrics)
uiMetrics = BeadMetrics.getMetrics(host);
if (isNaN(h))
{
s = textField.text;
textField.text = "0";
h = textField.textHeight;
textField.text = s;
}
ilc.setHeight(h + uiMetrics.top + uiMetrics.bottom, true);
}
IEventDispatcher(host).addEventListener("widthChanged", sizeChangedHandler);
IEventDispatcher(host).addEventListener("heightChanged", sizeChangedHandler);
sizeChangedHandler(null);
}
private function sizeChangedHandler(event:Event):void
{
var ww:Number = host.width;
if( !isNaN(ww) && ww > 0 ) textField.width = ww;
var hh:Number = host.height;
if( !isNaN(hh) && hh > 0 )
{
textField.height = textField.textHeight + 5;
}
textField.y = ((hh - textField.height) / 2);
}
}
}
|
adjust default TextInput width
|
adjust default TextInput width
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
2b87aa9028c193fdf0723a13e7d0713cdbdd9ea4
|
src/aerys/minko/type/stream/iterator/VertexIterator.as
|
src/aerys/minko/type/stream/iterator/VertexIterator.as
|
package aerys.minko.type.stream.iterator
{
import aerys.minko.ns.minko_stream;
import aerys.minko.type.stream.IVertexStream;
import aerys.minko.type.stream.IndexStream;
import aerys.minko.type.stream.format.VertexComponent;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
/**
* VertexIterator allow per-vertex access on VertexStream objects.
*
* The class overrides the "[]" and "delete" operators and is iterable
* using "for" and "for each" loops. It enable an higher level and easier
* traversal and manipulation of the underlaying data stream while
* minimizing the memory footprint.
*
* <pre>
* public function tracePositions(mesh : IMesh) : void
* {
* var vertices : VertexIterator = new VertexIterator(mesh.vertexStream);
*
* for each (var vertex : VertexReference in vertices)
* trace(vertex.x, vertex.y, vertex.z);
* }
* </pre>
*
* @author Jean-Marc Le Roux
*
*/
public class VertexIterator extends Proxy
{
use namespace minko_stream;
private var _index : int = 0;
private var _offset : int = 0;
private var _singleReference : Boolean = true;
private var _vertex : VertexReference = null;
private var _vstream : IVertexStream = null;
private var _istream : IndexStream = null;
private var _propertyToStream : Object = new Object();
public function get length() : int
{
return _istream ? _istream.length : _vstream.length;
}
/**
* Create a new VertexIterator instance.
*
* If the "singleReference" argument is true, only one VertexReference
* will be created during a "for each" loop on the iterator. This
* VertexReference will be updated at each iteration to provide
* the data of the current vertex. Otherwise, a dedicated
* VertexReference will be provided at each iteration. Using the
* "single reference" mode is nicer on the memory footprint, but makes
* it impossible to keep a VertexReference object and re-use it later
* as it will be automatically updated at each iteration.
*
* @param vertexStream The VertexStream to use.
*
* @param indexStream The IndexStream to use. If none is
* provided, the iterator will iterate on each vertex of the
* VertexStream. Otherwise, the iterator will iterate
* on vertices as provided by the indices in the IndexStream.
*
* @param shallow Whether to use the "single reference" mode.
*
* @return
*
*/
public function VertexIterator(vertexStream : IVertexStream,
indexStream : IndexStream = null,
singleReference : Boolean = true)
{
super();
/*if (!vertexStream.dynamic)
throw new Error("Unable to work on static VertexStream.");
if (!indexStream.dynamic)
throw new Error("Unable to work on static IndexStream.");*/
_vstream = vertexStream;
_istream = indexStream;
_singleReference = singleReference;
initialize();
}
private function initialize() : void
{
var components : Object = _vstream.format.components;
for each (var component : VertexComponent in components)
for each (var field : String in component.fields)
_propertyToStream[field] = _vstream.getSubStreamByComponent(component);
}
override flash_proxy function getProperty(name : *) : *
{
var index : int = int(name);
if (_istream)
index = _istream._data[index];
var vertex : VertexReference = new VertexReference(_vstream, index);
vertex._propertyToStream = _propertyToStream;
return vertex;
}
override flash_proxy function deleteProperty(name : *) : Boolean
{
var index : int = int(name);
if (_vstream.deleteVertexByIndex(index))
{
if (index <= _index)
++_offset;
return true;
}
return false;
}
override flash_proxy function hasProperty(name : *) : Boolean
{
var index : int = int(name);
return _istream
? index < _istream.length
: index < _vstream.length;
}
override flash_proxy function nextNameIndex(index : int) : int
{
index -= _offset;
_offset = 0;
return _istream
? index < _istream.length ? index + 1 : 0
: index < _vstream.length ? index + 1 : 0;
}
override flash_proxy function nextName(index : int) : String
{
return String(index - 1);
}
override flash_proxy function nextValue(index : int) : *
{
_index = index - 1;
index = _istream ? _istream._data[_index] : _index;
if (!_singleReference || !_vertex)
{
_vertex = new VertexReference(_vstream, index);
_vertex._propertyToStream = _propertyToStream;
}
if (_singleReference)
_vertex._index = -_offset + index;
return _vertex;
}
}
}
|
package aerys.minko.type.stream.iterator
{
import aerys.minko.ns.minko_stream;
import aerys.minko.type.stream.IVertexStream;
import aerys.minko.type.stream.IndexStream;
import aerys.minko.type.stream.format.VertexComponent;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
/**
* VertexIterator allow per-vertex access on VertexStream objects.
*
* The class overrides the "[]" and "delete" operators and is iterable
* using "for" and "for each" loops. It enable an higher level and easier
* traversal and manipulation of the underlaying data stream while
* minimizing the memory footprint.
*
* <pre>
* public function tracePositions(mesh : IMesh) : void
* {
* var vertices : VertexIterator = new VertexIterator(mesh.vertexStream);
*
* for each (var vertex : VertexReference in vertices)
* trace(vertex.x, vertex.y, vertex.z);
* }
* </pre>
*
* @author Jean-Marc Le Roux
*
*/
public class VertexIterator extends Proxy
{
use namespace minko_stream;
private var _index : int = 0;
private var _offset : int = 0;
private var _singleReference : Boolean = true;
private var _vertex : VertexReference = null;
private var _vstream : IVertexStream = null;
private var _istream : IndexStream = null;
private var _propertyToStream : Object = new Object();
public function get length() : int
{
return _istream ? _istream.length : _vstream.length;
}
/**
* Create a new VertexIterator instance.
*
* If the "singleReference" argument is true, only one VertexReference
* will be created during a "for each" loop on the iterator. This
* VertexReference will be updated at each iteration to provide
* the data of the current vertex. Otherwise, a dedicated
* VertexReference will be provided at each iteration. Using the
* "single reference" mode is nicer on the memory footprint, but makes
* it impossible to keep a VertexReference object and re-use it later
* as it will be automatically updated at each iteration.
*
* @param vertexStream The VertexStream to use.
*
* @param indexStream The IndexStream to use. If none is
* provided, the iterator will iterate on each vertex of the
* VertexStream. Otherwise, the iterator will iterate
* on vertices as provided by the indices in the IndexStream.
*
* @param shallow Whether to use the "single reference" mode.
*
* @return
*
*/
public function VertexIterator(vertexStream : IVertexStream,
indexStream : IndexStream = null,
singleReference : Boolean = true)
{
super();
// if (!vertexStream.dynamic)
// throw new Error("Unable to work on static VertexStream.");
// if (!indexStream.dynamic)
// throw new Error("Unable to work on static IndexStream.");
_vstream = vertexStream;
_istream = indexStream;
_singleReference = singleReference;
initialize();
}
private function initialize() : void
{
var components : Object = _vstream.format.components;
for each (var component : VertexComponent in components)
for each (var field : String in component.fields)
_propertyToStream[field] = _vstream.getSubStreamByComponent(component);
}
override flash_proxy function getProperty(name : *) : *
{
var index : int = int(name);
if (_istream)
index = _istream._data[index];
var vertex : VertexReference = new VertexReference(_vstream, index);
vertex._propertyToStream = _propertyToStream;
return vertex;
}
override flash_proxy function deleteProperty(name : *) : Boolean
{
var index : int = int(name);
if (_vstream.deleteVertexByIndex(index))
{
if (index <= _index)
++_offset;
return true;
}
return false;
}
override flash_proxy function hasProperty(name : *) : Boolean
{
var index : int = int(name);
return _istream
? index < _istream.length
: index < _vstream.length;
}
override flash_proxy function nextNameIndex(index : int) : int
{
index -= _offset;
_offset = 0;
return _istream
? index < _istream.length ? index + 1 : 0
: index < _vstream.length ? index + 1 : 0;
}
override flash_proxy function nextName(index : int) : String
{
return String(index - 1);
}
override flash_proxy function nextValue(index : int) : *
{
_index = index - 1;
index = _istream ? _istream._data[_index] : _index;
if (!_singleReference || !_vertex)
{
_vertex = new VertexReference(_vstream, index);
_vertex._propertyToStream = _propertyToStream;
}
if (_singleReference)
_vertex._index = -_offset + index;
return _vertex;
}
}
}
|
Resolve conflict
|
Resolve conflict
|
ActionScript
|
mit
|
aerys/minko-as3
|
edfe538571ecf69b070a89b1696d0ded9d6b6a90
|
frameworks/as/projects/FlexJSJX/src/org/apache/flex/html/accessories/CurrencyFormatter.as
|
frameworks/as/projects/FlexJSJX/src/org/apache/flex/html/accessories/CurrencyFormatter.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.accessories
{
import org.apache.flex.core.IBeadModel;
import org.apache.flex.core.IFormatBead;
import org.apache.flex.core.IStrand;
import org.apache.flex.events.Event;
import org.apache.flex.events.EventDispatcher;
import org.apache.flex.events.IEventDispatcher;
/**
* The CurrencyFormatter class formats a value in separated groups. The formatter listens
* to a property on a model and when the property changes, formats it and dispatches a
* formatChanged event.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class CurrencyFormatter extends EventDispatcher implements IFormatBead
{
/**
* constructor
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function CurrencyFormatter()
{
super();
}
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;
// Listen for the beadsAdded event which signals when all of a strand's
// beads have been added.
IEventDispatcher(value).addEventListener("beadsAdded",handleBeadsAdded);
}
/**
* @private
*/
private function handleBeadsAdded(event:Event):void
{
// Listen for the change in the model
var model:IBeadModel = _strand.getBeadByType(IBeadModel) as IBeadModel;
model.addEventListener(eventName,propertyChangeHandler);
model.addEventListener(propertyName+"Change",propertyChangeHandler);
// format the current value of that property
propertyChangeHandler(null);
}
private var _propertyName:String;
private var _eventName:String;
private var _formattedResult:String;
private var _fractionalDigits:Number = 2;
private var _currencySymbol:String = "$";
/**
* The name of the property on the model to format.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get propertyName():String
{
if (_propertyName == null) {
return "text";
}
return _propertyName;
}
public function set propertyName(value:String):void
{
_propertyName = value;
}
/**
* The event dispatched by the model when the property changes. The
* default is propertyName+"Changed".
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get eventName():String
{
if (_eventName == null) {
return _propertyName+"Changed";
}
return _eventName;
}
public function set eventName(value:String):void
{
_eventName = value;
}
/**
* Number of digits after the decimal separator
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get fractionalDigits():int
{
return _fractionalDigits;
}
public function set fractionalDigits(value:int):void
{
_fractionalDigits = value;
}
/**
* The currency symbol, such as "$"
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get currencySymbol():String
{
return _currencySymbol;
}
public function set currencySymbol(value:String):void
{
_currencySymbol = value;
}
/**
* The formatted string.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get formattedString():String
{
return _formattedResult;
}
/**
* @private
*/
private function propertyChangeHandler(event:Event):void
{
// When the property changes, fetch it from the model and
// format it, storing the result in _formattedResult.
var model:IBeadModel = _strand.getBeadByType(IBeadModel) as IBeadModel;
var value:Object = model[propertyName];
_formattedResult = format(value);
// Dispatch the formatChanged event so any bead that's interested in
// the formatted string knows to use it.
var newEvent:Event = new Event("formatChanged");
this.dispatchEvent(newEvent);
}
/**
* Computes the formatted string.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function format(value:Object):String
{
if (value == null) return "";
var num:Number = Number(value);
var source:String = num.toPrecision(fractionalDigits);
return currencySymbol + source;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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.accessories
{
import org.apache.flex.core.IBeadModel;
import org.apache.flex.core.IFormatBead;
import org.apache.flex.core.IStrand;
import org.apache.flex.events.Event;
import org.apache.flex.events.EventDispatcher;
import org.apache.flex.events.IEventDispatcher;
/**
* The CurrencyFormatter class formats a value in separated groups. The formatter listens
* to a property on a model and when the property changes, formats it and dispatches a
* formatChanged event.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class CurrencyFormatter extends EventDispatcher implements IFormatBead
{
/**
* constructor
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function CurrencyFormatter()
{
super();
}
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;
// Listen for the beadsAdded event which signals when all of a strand's
// beads have been added.
IEventDispatcher(value).addEventListener("beadsAdded",handleBeadsAdded);
}
/**
* @private
*/
private function handleBeadsAdded(event:Event):void
{
// Listen for the change in the model
var model:IBeadModel = _strand.getBeadByType(IBeadModel) as IBeadModel;
model.addEventListener(eventName,propertyChangeHandler);
model.addEventListener(propertyName+"Change",propertyChangeHandler);
// format the current value of that property
propertyChangeHandler(null);
}
private var _propertyName:String;
private var _eventName:String;
private var _formattedResult:String;
private var _fractionalDigits:Number = 2;
private var _currencySymbol:String = "$";
/**
* The name of the property on the model to format.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get propertyName():String
{
if (_propertyName == null) {
return "text";
}
return _propertyName;
}
public function set propertyName(value:String):void
{
_propertyName = value;
}
/**
* The event dispatched by the model when the property changes. The
* default is propertyName+"Changed".
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get eventName():String
{
if (_eventName == null) {
return _propertyName+"Changed";
}
return _eventName;
}
public function set eventName(value:String):void
{
_eventName = value;
}
/**
* Number of digits after the decimal separator
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get fractionalDigits():int
{
return _fractionalDigits;
}
public function set fractionalDigits(value:int):void
{
_fractionalDigits = value;
}
/**
* The currency symbol, such as "$"
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get currencySymbol():String
{
return _currencySymbol;
}
public function set currencySymbol(value:String):void
{
_currencySymbol = value;
}
/**
* The formatted string.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get formattedString():String
{
return _formattedResult;
}
/**
* @private
*/
private function propertyChangeHandler(event:Event):void
{
// When the property changes, fetch it from the model and
// format it, storing the result in _formattedResult.
var model:IBeadModel = _strand.getBeadByType(IBeadModel) as IBeadModel;
var value:Object = model[propertyName];
_formattedResult = format(value);
// Dispatch the formatChanged event so any bead that's interested in
// the formatted string knows to use it.
var newEvent:Event = new Event("formatChanged");
this.dispatchEvent(newEvent);
}
/**
* Computes the formatted string.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function format(value:Object):String
{
if (value == null) return "";
var num:Number = Number(value);
var source:String = num.toFixed(fractionalDigits);
return currencySymbol + source;
}
}
}
|
fix currencyformatter
|
fix currencyformatter
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
1f8f164a5da1b709ed44c2247481ca969f17c8ba
|
software/sasFlex/src/gov/nih/nci/cbiit/casas/components/FormulaEditor.as
|
software/sasFlex/src/gov/nih/nci/cbiit/casas/components/FormulaEditor.as
|
package gov.nih.nci.cbiit.casas.components
{
import fl.core.UIComponent;
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.utils.Timer;
import learnmath.mathml.components.MathMLEditor;
import learnmath.mathml.formula.Constants;
import learnmath.windows.ConfigManager;
import mx.controls.Alert;
import mx.core.IUIComponent;
import flash.events.TimerEvent;
public class FormulaEditor extends MathMLEditor
{
public function FormulaEditor()
{
//duplicate MathMLEditor Constructor
ConfigManager.urlFonts="./";
Constants.setUrlFonts("./");
// ConfigManager.setConfig("disableSave","false");
// ConfigManager.setConfig("disableOpen","false");
ConfigManager.disableOpen=new Boolean(false);
ConfigManager.disableSave=new Boolean(false);
addEventListener(KeyboardEvent.KEY_DOWN, processKey);
// mainPannel.name= "<a href=\'http://ncicb.nci.nih.gov/\'>NCI Center for Biomedical Informatics & Information Technology - Scientific Algorithm Service</a>";
// mainPannel.draw();
return;
}
// override protected function createChildren():void
// {
// Alert.show("before created by super", mainPannel+"");
// super.createChildren();
// Alert.show("created by super", mainPannel+"");
// mainPannel=null;
// while (this.numChildren>0)
// {
// this.removeChildAt(0);
// }
// var _loc_1:*=new MovieClip();
// var editorW:Number=800;
// var editorH:Number=500;
//
// mainPannel = new FormulaPanel(_loc_1, 0,0,editorW, editorH, returnFocus);
// mainPannel.draw();
// mainPannel.setMathML("..xx");
// Alert.show(mainPannel+"", mainPannel.getMathML());
// var _loc_2:*=new UIComponent();
// addChild(_loc_2);
//
// var _loc_3:*=new Timer(100,1);
// _loc_3.addEventListenr(TimerEvent.TIMER, redrawEditor);
// _loc_3.start();
// return;
// }
//override private method
private function redrawEditor(event:TimerEvent):void
{
mainPannel.draw();
if (focusManager!=null)
{
focusManager.setFocus(this);
}
return;
}
}
}
|
package gov.nih.nci.cbiit.casas.components
{
import fl.core.UIComponent;
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import learnmath.mathml.components.MathMLEditor;
import learnmath.mathml.formula.Constants;
import learnmath.windows.ConfigManager;
import learnmath.windows.apps.EditorApp;
import mx.containers.Canvas;
import mx.controls.Alert;
import mx.controls.listClasses.BaseListData;
import mx.controls.listClasses.IDropInListItemRenderer;
import mx.controls.listClasses.IListItemRenderer;
import mx.core.IDataRenderer;
import mx.core.IFlexModuleFactory;
import mx.core.IFontContextComponent;
import mx.core.IUIComponent;
import mx.managers.IFocusManagerComponent;
import mx.events.FlexEvent;
public class FormulaEditor extends MathMLEditor
//extends Canvas implements IDataRenderer, IDropInListItemRenderer, IListItemRenderer, IFontContextComponent, IFocusManagerComponent
{
private var _mathML:String = "";
var _editorHeight:Number = 500;
// private var _listData:BaseListData;
var _editorWidth:Number = 800;
// public var mainPannel:EditorApp;
public function FormulaEditor()
{
//duplicate MathMLEditor Constructor
ConfigManager.urlFonts="./";
Constants.setUrlFonts("./");
// ConfigManager.setConfig("disableSave","false");
// ConfigManager.setConfig("disableOpen","false");
ConfigManager.disableOpen=new Boolean(false);
ConfigManager.disableSave=new Boolean(false);
addEventListener(KeyboardEvent.KEY_DOWN, processKey);
addEventListener(FlexEvent.CREATION_COMPLETE,onCreationComplete) ;
return;
}
private function onCreationComplete(event : FlexEvent):void
{
// this.removeAllCh ildren();
// this.invalidateDisplayList();
// createCustomButtons();
mainPannel.name= "<a href=\'http://ncicb.nci.nih.gov/\'>NCI Center for Biomedical Informatics & Information Technology - Scientific Algorithm Service</a>";
var p1:XML =new XML("<math><mrow><mtext>default</mtext><mo selected='true'>×</mo><mtext>0123456789</mtext></mrow>" + "</math>")
mainPannel.setMathML(p1);
}
// private function createCustomButtons() : void
// {
// super.createChildren();
// mainPannel = null;
// while (this.numChildren > 0)
// {
//
// this.removeChildAt(0);
// }
// var _loc_1:* = new MovieClip();
// mainPannel = new EditorApp(_loc_1, 0, 0, _editorWidth, _editorHeight, returnFocus);
// mainPannel.draw();
// mainPannel.setMathML(_mathML);
// var _loc_2:* = new UIComponent();
// addChild(_loc_2);
// _loc_2.addChild(_loc_1);
// var _loc_3:* = new Timer(100, 1);
// _loc_3.addEventListener(TimerEvent.TIMER, redrawEditor);
// _loc_3.start();
// return;
// }// end function
/**
override protected function measure() : void
{
measuredHeight = editorHeight;
measuredMinHeight = editorHeight;
measuredWidth = editorWidth;
measuredMinWidth = editorWidth;
return;
}// end function
public function get fontContext() : IFlexModuleFactory
{
return moduleFactory;
}
public function set fontContext(moduleFactory:IFlexModuleFactory) : void
{
this.moduleFactory = moduleFactory;
return;
}// end function
public function get listData() : BaseListData
{
return _listData;
}// end function
public function set listData(value:BaseListData) : void
{
_listData = value;
return;
}// end function
public function get mathML() : String
{
_mathML = mainPannel.getMathML();
return _mathML;
}// end function
public function set mathML(mathML:String) : void
{
_mathML = mathML;
if (mainPannel != null)
{
mainPannel.setMathML(_mathML);
}
return;
}// end function
public function get editorHeight() : Number
{
return _editorHeight;
}// end function
public function get editorWidth() : Number
{
return _editorWidth;
}// end function
public function set editorWidth(w:Number) : void
{
this._editorWidth = w;
width = w;
invalidateProperties();
invalidateSize();
invalidateDisplayList();
return;
}// end function
public function set editorHeight(h:Number) : void
{
this._editorHeight = h;
height = h;
invalidateProperties();
invalidateSize();
invalidateDisplayList();
return;
}
*/
//override private method
private function redrawEditor(event:TimerEvent):void
{
mainPannel.draw();
if (focusManager!=null)
{
focusManager.setFocus(this);
}
return;
}
/**
public function saveImageOnServer(type:String, compression:int, callbackName:Function) : void
{
mainPannel.saveImageOnServer(type, compression, callbackName);
return;
}// end function
public function setConfiguration(key:String, value:String) : void
{
ConfigManager.setConfig(key, value);
return;
}// end function
public function viewImageInBrowser(type:String, compression:int) : void
{
mainPannel.viewImageInBrowser(type, compression);
return;
}// end function
public function processKey(event:KeyboardEvent) : void
{
if (mainPannel == null)
{
return;
}
mainPannel.processKey(event);
return;
}// end function
public function returnFocus() : void
{
if (focusManager != null)
{
focusManager.setFocus(this);
}
return;
}// end function
public function getBase64Image(type:String, precission:int = 100) : String
{
return mainPannel.getBase64Image(type, precission);
}// end function
*/
}
}
|
use creationCompletion event
|
use creationCompletion event
SVN-Revision: 3128
|
ActionScript
|
bsd-3-clause
|
NCIP/caadapter,NCIP/caadapter,NCIP/caadapter
|
133d83ab5e0f012bdd44c2d772e166b29b93ee1f
|
src/org/mangui/hls/HLS.as
|
src/org/mangui/hls/HLS.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 {
import flash.display.Stage;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.net.URLLoader;
import flash.net.URLStream;
import org.mangui.hls.constant.HLSSeekStates;
import org.mangui.hls.controller.AudioTrackController;
import org.mangui.hls.controller.LevelController;
import org.mangui.hls.event.HLSEvent;
import org.mangui.hls.loader.AltAudioLevelLoader;
import org.mangui.hls.loader.LevelLoader;
import org.mangui.hls.model.AudioTrack;
import org.mangui.hls.model.Level;
import org.mangui.hls.playlist.AltAudioTrack;
import org.mangui.hls.stream.HLSNetStream;
import org.mangui.hls.stream.StreamBuffer;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
/** Class that manages the streaming process. **/
public class HLS extends EventDispatcher {
private var _levelLoader : LevelLoader;
private var _altAudioLevelLoader : AltAudioLevelLoader;
private var _audioTrackController : AudioTrackController;
private var _levelController : LevelController;
private var _streamBuffer : StreamBuffer;
/** HLS NetStream **/
private var _hlsNetStream : HLSNetStream;
/** HLS URLStream/URLLoader **/
private var _hlsURLStream : Class;
private var _hlsURLLoader : Class;
private var _client : Object = {};
private var _stage : Stage;
/* level handling */
private var _level : int;
/* overrided quality_manual_level level */
private var _manual_level : int = -1;
/** Create and connect all components. **/
public function HLS() {
_levelLoader = new LevelLoader(this);
_altAudioLevelLoader = new AltAudioLevelLoader(this);
_audioTrackController = new AudioTrackController(this);
_levelController = new LevelController(this);
_streamBuffer = new StreamBuffer(this, _audioTrackController, _levelController);
_hlsURLStream = URLStream as Class;
_hlsURLLoader = URLLoader as Class;
// default loader
var connection : NetConnection = new NetConnection();
connection.connect(null);
_hlsNetStream = new HLSNetStream(connection, this, _streamBuffer);
this.addEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler);
};
/** Forward internal errors. **/
override public function dispatchEvent(event : Event) : Boolean {
if (event.type == HLSEvent.ERROR) {
CONFIG::LOGGING {
Log.error((event as HLSEvent).error);
}
_hlsNetStream.close();
}
if (hasEventListener(event.type)) {
return super.dispatchEvent(event);
}
return false;
}
private function _levelSwitchHandler(event : HLSEvent) : void {
_level = event.level;
};
public function dispose() : void {
this.removeEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler);
_levelLoader.dispose();
_altAudioLevelLoader.dispose();
_audioTrackController.dispose();
_levelController.dispose();
_hlsNetStream.dispose_();
_streamBuffer.dispose();
_levelLoader = null;
_altAudioLevelLoader = null;
_audioTrackController = null;
_levelController = null;
_hlsNetStream = null;
_client = null;
_stage = null;
_hlsNetStream = null;
}
/** Return index of first quality level referenced in Manifest **/
public function get firstLevel() : int {
return _levelController.firstLevel;
};
/** Return the quality level used when starting a fresh playback **/
public function get startLevel() : int {
return _levelController.startLevel;
};
/* set the quality level used when starting a fresh playback */
public function set startLevel(level : int) : void {
_levelController.startLevel = level;
};
/** Return the quality level used after a seek operation **/
public function get seekLevel() : int {
return _levelController.seekLevel;
};
/** Return the quality level of the currently played fragment **/
public function get currentLevel() : int {
return _hlsNetStream.currentLevel;
};
/** Return the quality level of the next played fragment **/
public function get nextLevel() : int {
return _streamBuffer.nextLevel;
};
/** Return the quality level of last loaded fragment **/
public function get loadLevel() : int {
return _level;
};
/* instant quality level switch (-1 for automatic level selection) */
public function set currentLevel(level : int) : void {
_manual_level = level;
// don't flush and seek if never seeked or if end of stream
if(seekState != HLSSeekStates.IDLE) {
_streamBuffer.flushBuffer();
_hlsNetStream.seek(position);
}
};
/* set quality level for next loaded fragment (-1 for automatic level selection) */
public function set nextLevel(level : int) : void {
_manual_level = level;
_streamBuffer.nextLevel = level;
};
/* set quality level for last loaded fragment (-1 for automatic level selection) */
public function set loadLevel(level : int) : void {
_manual_level = level;
};
/* check if we are in automatic level selection mode */
public function get autoLevel() : Boolean {
return (_manual_level == -1);
};
/* return manual level */
public function get manualLevel() : int {
return _manual_level;
};
/** Return the capping/max level value that could be used by automatic level selection algorithm **/
public function get autoLevelCapping() : int {
return _levelController.autoLevelCapping;
}
/** set the capping/max level value that could be used by automatic level selection algorithm **/
public function set autoLevelCapping(newLevel : int) : void {
_levelController.autoLevelCapping = newLevel;
}
/** Return a Vector of quality level **/
public function get levels() : Vector.<Level> {
return _levelLoader.levels;
};
/** Return the current playback position. **/
public function get position() : Number {
return _streamBuffer.position;
};
/** Return the live main playlist sliding in seconds since previous out of buffer seek(). **/
public function get liveSlidingMain() : Number {
return _streamBuffer.liveSlidingMain;
}
/** Return the live altaudio playlist sliding in seconds since previous out of buffer seek(). **/
public function get liveSlidingAltAudio() : Number {
return _streamBuffer.liveSlidingAltAudio;
}
/** Return the current playback state. **/
public function get playbackState() : String {
return _hlsNetStream.playbackState;
};
/** Return the current seek state. **/
public function get seekState() : String {
return _hlsNetStream.seekState;
};
/** Return the current watched time **/
public function get watched() : Number {
return _hlsNetStream.watched;
};
/** Return the total nb of dropped video frames since last call to hls.load() **/
public function get droppedFrames() : Number {
return _hlsNetStream.droppedFrames;
};
/** Return the type of stream (VOD/LIVE). **/
public function get type() : String {
return _levelLoader.type;
};
/** Load and parse a new HLS URL **/
public function load(url : String) : void {
_level = 0;
_hlsNetStream.close();
_levelLoader.load(url);
};
/** return HLS NetStream **/
public function get stream() : NetStream {
return _hlsNetStream;
}
public function get client() : Object {
return _client;
}
public function set client(value : Object) : void {
_client = value;
}
/** get audio tracks list**/
public function get audioTracks() : Vector.<AudioTrack> {
return _audioTrackController.audioTracks;
};
/** get alternate audio tracks list from playlist **/
public function get altAudioTracks() : Vector.<AltAudioTrack> {
return _levelLoader.altAudioTracks;
};
/** get index of the selected audio track (index in audio track lists) **/
public function get audioTrack() : int {
return _audioTrackController.audioTrack;
};
/** select an audio track, based on its index in audio track lists**/
public function set audioTrack(val : int) : void {
_audioTrackController.audioTrack = val;
}
/* set stage */
public function set stage(stage : Stage) : void {
_stage = stage;
this.dispatchEvent(new HLSEvent(HLSEvent.STAGE_SET));
}
/* get stage */
public function get stage() : Stage {
return _stage;
}
/* set URL stream loader */
public function set URLstream(urlstream : Class) : void {
_hlsURLStream = urlstream;
}
/* retrieve URL stream loader */
public function get URLstream() : Class {
return _hlsURLStream;
}
/* set URL stream loader */
public function set URLloader(urlloader : Class) : void {
_hlsURLLoader = urlloader;
}
/* retrieve URL stream loader */
public function get URLloader() : Class {
return _hlsURLLoader;
}
/* start/restart playlist/fragment loading.
this is only effective if MANIFEST_PARSED event has been triggered already */
public function startLoad() : void {
if(levels && levels.length) {
this.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_SWITCH, startLevel));
}
}
}
}
|
/* 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 {
import flash.display.Stage;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.net.URLLoader;
import flash.net.URLStream;
import org.mangui.hls.constant.HLSSeekStates;
import org.mangui.hls.controller.AudioTrackController;
import org.mangui.hls.controller.LevelController;
import org.mangui.hls.event.HLSEvent;
import org.mangui.hls.loader.AltAudioLevelLoader;
import org.mangui.hls.loader.LevelLoader;
import org.mangui.hls.model.AudioTrack;
import org.mangui.hls.model.Level;
import org.mangui.hls.playlist.AltAudioTrack;
import org.mangui.hls.stream.HLSNetStream;
import org.mangui.hls.stream.StreamBuffer;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
/** Class that manages the streaming process. **/
public class HLS extends EventDispatcher {
private var _levelLoader : LevelLoader;
private var _altAudioLevelLoader : AltAudioLevelLoader;
private var _audioTrackController : AudioTrackController;
private var _levelController : LevelController;
private var _streamBuffer : StreamBuffer;
/** HLS NetStream **/
private var _hlsNetStream : HLSNetStream;
/** HLS URLStream/URLLoader **/
private var _hlsURLStream : Class;
private var _hlsURLLoader : Class;
private var _client : Object = {};
private var _stage : Stage;
/* level handling */
private var _level : int;
/* overrided quality_manual_level level */
private var _manual_level : int = -1;
/** Create and connect all components. **/
public function HLS() {
_levelLoader = new LevelLoader(this);
_altAudioLevelLoader = new AltAudioLevelLoader(this);
_audioTrackController = new AudioTrackController(this);
_levelController = new LevelController(this);
_streamBuffer = new StreamBuffer(this, _audioTrackController, _levelController);
_hlsURLStream = URLStream as Class;
_hlsURLLoader = URLLoader as Class;
// default loader
var connection : NetConnection = new NetConnection();
connection.connect(null);
_hlsNetStream = new HLSNetStream(connection, this, _streamBuffer);
this.addEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler);
};
/** Forward internal errors. **/
override public function dispatchEvent(event : Event) : Boolean {
if (event.type == HLSEvent.ERROR) {
CONFIG::LOGGING {
Log.error((event as HLSEvent).error);
}
_hlsNetStream.close();
}
if (hasEventListener(event.type)) {
return super.dispatchEvent(event);
}
return false;
}
private function _levelSwitchHandler(event : HLSEvent) : void {
_level = event.level;
};
public function dispose() : void {
this.removeEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler);
_levelLoader.dispose();
_altAudioLevelLoader.dispose();
_audioTrackController.dispose();
_levelController.dispose();
_hlsNetStream.dispose_();
_streamBuffer.dispose();
_levelLoader = null;
_altAudioLevelLoader = null;
_audioTrackController = null;
_levelController = null;
_hlsNetStream = null;
_client = null;
_stage = null;
_hlsNetStream = null;
}
/** Return index of first quality level referenced in Manifest **/
public function get firstLevel() : int {
return _levelController.firstLevel;
};
/** Return the quality level used when starting a fresh playback **/
public function get startLevel() : int {
return _levelController.startLevel;
};
/* set the quality level used when starting a fresh playback */
public function set startLevel(level : int) : void {
_levelController.startLevel = level;
};
/** Return the quality level used after a seek operation **/
public function get seekLevel() : int {
return _levelController.seekLevel;
};
/** Return the quality level of the currently played fragment **/
public function get currentLevel() : int {
return _hlsNetStream.currentLevel;
};
/** Return the quality level of the next played fragment **/
public function get nextLevel() : int {
return _streamBuffer.nextLevel;
};
/** Return the quality level of last loaded fragment **/
public function get loadLevel() : int {
return _level;
};
/* instant quality level switch (-1 for automatic level selection) */
public function set currentLevel(level : int) : void {
_manual_level = level;
// don't flush and seek if never seeked or if end of stream
if(seekState != HLSSeekStates.IDLE) {
_streamBuffer.flushBuffer();
_hlsNetStream.seek(position);
}
};
/* set quality level for next loaded fragment (-1 for automatic level selection) */
public function set nextLevel(level : int) : void {
_manual_level = level;
_streamBuffer.nextLevel = level;
};
/* set quality level for next loaded fragment (-1 for automatic level selection) */
public function set loadLevel(level : int) : void {
_manual_level = level;
};
/* check if we are in automatic level selection mode */
public function get autoLevel() : Boolean {
return (_manual_level == -1);
};
/* return manual level */
public function get manualLevel() : int {
return _manual_level;
};
/** Return the capping/max level value that could be used by automatic level selection algorithm **/
public function get autoLevelCapping() : int {
return _levelController.autoLevelCapping;
}
/** set the capping/max level value that could be used by automatic level selection algorithm **/
public function set autoLevelCapping(newLevel : int) : void {
_levelController.autoLevelCapping = newLevel;
}
/** Return a Vector of quality level **/
public function get levels() : Vector.<Level> {
return _levelLoader.levels;
};
/** Return the current playback position. **/
public function get position() : Number {
return _streamBuffer.position;
};
/** Return the live main playlist sliding in seconds since previous out of buffer seek(). **/
public function get liveSlidingMain() : Number {
return _streamBuffer.liveSlidingMain;
}
/** Return the live altaudio playlist sliding in seconds since previous out of buffer seek(). **/
public function get liveSlidingAltAudio() : Number {
return _streamBuffer.liveSlidingAltAudio;
}
/** Return the current playback state. **/
public function get playbackState() : String {
return _hlsNetStream.playbackState;
};
/** Return the current seek state. **/
public function get seekState() : String {
return _hlsNetStream.seekState;
};
/** Return the current watched time **/
public function get watched() : Number {
return _hlsNetStream.watched;
};
/** Return the total nb of dropped video frames since last call to hls.load() **/
public function get droppedFrames() : Number {
return _hlsNetStream.droppedFrames;
};
/** Return the type of stream (VOD/LIVE). **/
public function get type() : String {
return _levelLoader.type;
};
/** Load and parse a new HLS URL **/
public function load(url : String) : void {
_level = 0;
_hlsNetStream.close();
_levelLoader.load(url);
};
/** return HLS NetStream **/
public function get stream() : NetStream {
return _hlsNetStream;
}
public function get client() : Object {
return _client;
}
public function set client(value : Object) : void {
_client = value;
}
/** get audio tracks list**/
public function get audioTracks() : Vector.<AudioTrack> {
return _audioTrackController.audioTracks;
};
/** get alternate audio tracks list from playlist **/
public function get altAudioTracks() : Vector.<AltAudioTrack> {
return _levelLoader.altAudioTracks;
};
/** get index of the selected audio track (index in audio track lists) **/
public function get audioTrack() : int {
return _audioTrackController.audioTrack;
};
/** select an audio track, based on its index in audio track lists**/
public function set audioTrack(val : int) : void {
_audioTrackController.audioTrack = val;
}
/* set stage */
public function set stage(stage : Stage) : void {
_stage = stage;
this.dispatchEvent(new HLSEvent(HLSEvent.STAGE_SET));
}
/* get stage */
public function get stage() : Stage {
return _stage;
}
/* set URL stream loader */
public function set URLstream(urlstream : Class) : void {
_hlsURLStream = urlstream;
}
/* retrieve URL stream loader */
public function get URLstream() : Class {
return _hlsURLStream;
}
/* set URL stream loader */
public function set URLloader(urlloader : Class) : void {
_hlsURLLoader = urlloader;
}
/* retrieve URL stream loader */
public function get URLloader() : Class {
return _hlsURLLoader;
}
/* start/restart playlist/fragment loading.
this is only effective if MANIFEST_PARSED event has been triggered already */
public function startLoad() : void {
if(levels && levels.length) {
this.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_SWITCH, startLevel));
}
}
}
}
|
fix typo
|
fix typo
|
ActionScript
|
mpl-2.0
|
hola/flashls,hola/flashls,NicolasSiver/flashls,vidible/vdb-flashls,mangui/flashls,clappr/flashls,mangui/flashls,neilrackett/flashls,tedconf/flashls,NicolasSiver/flashls,vidible/vdb-flashls,fixedmachine/flashls,fixedmachine/flashls,neilrackett/flashls,jlacivita/flashls,codex-corp/flashls,tedconf/flashls,codex-corp/flashls,jlacivita/flashls,clappr/flashls
|
7f96dcd37dc4f9c39cc515ebdcefc86b509b4665
|
as3/com/netease/protobuf/ReadUtils.as
|
as3/com/netease/protobuf/ReadUtils.as
|
// vim: tabstop=4 shiftwidth=4
// Copyright (c) 2010 , NetEase.com,Inc. All rights reserved.
// Copyright (c) 2012 , Yang Bo. 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.errors.*
import flash.utils.*
/**
* @private
*/
public final class ReadUtils {
public static function skip(input:IDataInput, wireType:uint):void {
switch (wireType) {
case WireType.VARINT:
while (input.readUnsignedByte() > 0x80) {}
break
case WireType.FIXED_64_BIT:
input.readInt()
input.readInt()
break
case WireType.LENGTH_DELIMITED:
for (var i:uint = read$TYPE_UINT32(input); i != 0; i--) {
input.readByte()
}
break
case WireType.FIXED_32_BIT:
input.readInt()
break
default:
throw new IOError("Invalid wire type: " + wireType)
}
}
public static function read$TYPE_DOUBLE(input:IDataInput):Number {
return input.readDouble()
}
public static function read$TYPE_FLOAT(input:IDataInput):Number {
return input.readFloat()
}
public static function read$TYPE_INT64(input:IDataInput):Int64 {
const result:Int64 = new Int64
var b:uint
var i:uint = 0
for (;; i += 7) {
b = input.readUnsignedByte()
if (i == 28) {
break
} else {
if (b >= 0x80) {
result.low |= ((b & 0x7f) << i)
} else {
result.low |= (b << i)
return result
}
}
}
if (b >= 0x80) {
b &= 0x7f
result.low |= (b << i)
result.high = b >>> 4
} else {
result.low |= (b << i)
result.high = b >>> 4
return result
}
for (i = 3;; i += 7) {
b = input.readUnsignedByte()
if (i < 32) {
if (b >= 0x80) {
result.high |= ((b & 0x7f) << i)
} else {
result.high |= (b << i)
break
}
}
}
return result
}
public static function read$TYPE_UINT64(input:IDataInput):UInt64 {
const result:UInt64 = new UInt64
var b:uint
var i:uint = 0
for (;; i += 7) {
b = input.readUnsignedByte()
if (i == 28) {
break
} else {
if (b >= 0x80) {
result.low |= ((b & 0x7f) << i)
} else {
result.low |= (b << i)
return result
}
}
}
if (b >= 0x80) {
b &= 0x7f
result.low |= (b << i)
result.high = b >>> 4
} else {
result.low |= (b << i)
result.high = b >>> 4
return result
}
for (i = 3;; i += 7) {
b = input.readUnsignedByte()
if (i < 32) {
if (b >= 0x80) {
result.high |= ((b & 0x7f) << i)
} else {
result.high |= (b << i)
break
}
}
}
return result
}
public static function read$TYPE_INT32(input:IDataInput):int {
return int(read$TYPE_UINT32(input))
}
public static function read$TYPE_FIXED64(input:IDataInput):UInt64 {
const result:UInt64 = new UInt64
result.low = input.readUnsignedInt()
result.high = input.readUnsignedInt()
return result
}
public static function read$TYPE_FIXED32(input:IDataInput):uint {
return input.readUnsignedInt()
}
public static function read$TYPE_BOOL(input:IDataInput):Boolean {
return read$TYPE_UINT32(input) != 0
}
public static function read$TYPE_STRING(input:IDataInput):String {
const length:uint = read$TYPE_UINT32(input)
return input.readUTFBytes(length)
}
public static function read$TYPE_BYTES(input:IDataInput):ByteArray {
const result:ByteArray = new ByteArray
const length:uint = read$TYPE_UINT32(input)
if (length > 0) {
input.readBytes(result, 0, length)
}
return result
}
public static function read$TYPE_UINT32(input:IDataInput):uint {
var result:uint = 0
for (var i:uint = 0;; i += 7) {
const b:uint = input.readUnsignedByte()
if (i < 32) {
if (b >= 0x80) {
result |= ((b & 0x7f) << i)
} else {
result |= (b << i)
break
}
} else {
while (input.readUnsignedByte() >= 0x80) {}
break
}
}
return result
}
public static function read$TYPE_ENUM(input:IDataInput):int {
return read$TYPE_INT32(input)
}
public static function read$TYPE_SFIXED32(input:IDataInput):int {
return input.readInt()
}
public static function read$TYPE_SFIXED64(input:IDataInput):Int64 {
const result:Int64 = new Int64
result.low = input.readUnsignedInt()
result.high = input.readInt()
return result
}
public static function read$TYPE_SINT32(input:IDataInput):int {
return ZigZag.decode32(read$TYPE_UINT32(input))
}
public static function read$TYPE_SINT64(input:IDataInput):Int64 {
const result:Int64 = read$TYPE_INT64(input)
const low:uint = result.low
const high:uint = result.high
result.low = ZigZag.decode64low(low, high)
result.high = ZigZag.decode64high(low, high)
return result
}
public static function read$TYPE_MESSAGE(input:IDataInput,
message:Message):Message {
const length:uint = read$TYPE_UINT32(input)
if (input.bytesAvailable < length) {
throw new IOError("Invalid message length: " + length)
}
const bytesAfterSlice:uint = input.bytesAvailable - length
message.used_by_generated_code::readFromSlice(input, bytesAfterSlice)
if (input.bytesAvailable != bytesAfterSlice) {
throw new IOError("Invalid nested message")
}
return message
}
public static function readPackedRepeated(input:IDataInput,
readFuntion:Function, value:Array):void {
const length:uint = read$TYPE_UINT32(input)
if (input.bytesAvailable < length) {
throw new IOError("Invalid message length: " + length)
}
const bytesAfterSlice:uint = input.bytesAvailable - length
while (input.bytesAvailable > bytesAfterSlice) {
value.push(readFuntion(input))
}
if (input.bytesAvailable != bytesAfterSlice) {
throw new IOError("Invalid packed repeated data")
}
}
}
}
|
// vim: tabstop=4 shiftwidth=4
// Copyright (c) 2010 , NetEase.com,Inc. All rights reserved.
// Copyright (c) 2012 , Yang Bo. 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.errors.*
import flash.utils.*
/**
* @private
*/
public final class ReadUtils {
public static function skip(input:IDataInput, wireType:uint):void {
switch (wireType) {
case WireType.VARINT:
while (input.readUnsignedByte() >= 0x80) {}
break
case WireType.FIXED_64_BIT:
input.readInt()
input.readInt()
break
case WireType.LENGTH_DELIMITED:
for (var i:uint = read$TYPE_UINT32(input); i != 0; i--) {
input.readByte()
}
break
case WireType.FIXED_32_BIT:
input.readInt()
break
default:
throw new IOError("Invalid wire type: " + wireType)
}
}
public static function read$TYPE_DOUBLE(input:IDataInput):Number {
return input.readDouble()
}
public static function read$TYPE_FLOAT(input:IDataInput):Number {
return input.readFloat()
}
public static function read$TYPE_INT64(input:IDataInput):Int64 {
const result:Int64 = new Int64
var b:uint
var i:uint = 0
for (;; i += 7) {
b = input.readUnsignedByte()
if (i == 28) {
break
} else {
if (b >= 0x80) {
result.low |= ((b & 0x7f) << i)
} else {
result.low |= (b << i)
return result
}
}
}
if (b >= 0x80) {
b &= 0x7f
result.low |= (b << i)
result.high = b >>> 4
} else {
result.low |= (b << i)
result.high = b >>> 4
return result
}
for (i = 3;; i += 7) {
b = input.readUnsignedByte()
if (i < 32) {
if (b >= 0x80) {
result.high |= ((b & 0x7f) << i)
} else {
result.high |= (b << i)
break
}
}
}
return result
}
public static function read$TYPE_UINT64(input:IDataInput):UInt64 {
const result:UInt64 = new UInt64
var b:uint
var i:uint = 0
for (;; i += 7) {
b = input.readUnsignedByte()
if (i == 28) {
break
} else {
if (b >= 0x80) {
result.low |= ((b & 0x7f) << i)
} else {
result.low |= (b << i)
return result
}
}
}
if (b >= 0x80) {
b &= 0x7f
result.low |= (b << i)
result.high = b >>> 4
} else {
result.low |= (b << i)
result.high = b >>> 4
return result
}
for (i = 3;; i += 7) {
b = input.readUnsignedByte()
if (i < 32) {
if (b >= 0x80) {
result.high |= ((b & 0x7f) << i)
} else {
result.high |= (b << i)
break
}
}
}
return result
}
public static function read$TYPE_INT32(input:IDataInput):int {
return int(read$TYPE_UINT32(input))
}
public static function read$TYPE_FIXED64(input:IDataInput):UInt64 {
const result:UInt64 = new UInt64
result.low = input.readUnsignedInt()
result.high = input.readUnsignedInt()
return result
}
public static function read$TYPE_FIXED32(input:IDataInput):uint {
return input.readUnsignedInt()
}
public static function read$TYPE_BOOL(input:IDataInput):Boolean {
return read$TYPE_UINT32(input) != 0
}
public static function read$TYPE_STRING(input:IDataInput):String {
const length:uint = read$TYPE_UINT32(input)
return input.readUTFBytes(length)
}
public static function read$TYPE_BYTES(input:IDataInput):ByteArray {
const result:ByteArray = new ByteArray
const length:uint = read$TYPE_UINT32(input)
if (length > 0) {
input.readBytes(result, 0, length)
}
return result
}
public static function read$TYPE_UINT32(input:IDataInput):uint {
var result:uint = 0
for (var i:uint = 0;; i += 7) {
const b:uint = input.readUnsignedByte()
if (i < 32) {
if (b >= 0x80) {
result |= ((b & 0x7f) << i)
} else {
result |= (b << i)
break
}
} else {
while (input.readUnsignedByte() >= 0x80) {}
break
}
}
return result
}
public static function read$TYPE_ENUM(input:IDataInput):int {
return read$TYPE_INT32(input)
}
public static function read$TYPE_SFIXED32(input:IDataInput):int {
return input.readInt()
}
public static function read$TYPE_SFIXED64(input:IDataInput):Int64 {
const result:Int64 = new Int64
result.low = input.readUnsignedInt()
result.high = input.readInt()
return result
}
public static function read$TYPE_SINT32(input:IDataInput):int {
return ZigZag.decode32(read$TYPE_UINT32(input))
}
public static function read$TYPE_SINT64(input:IDataInput):Int64 {
const result:Int64 = read$TYPE_INT64(input)
const low:uint = result.low
const high:uint = result.high
result.low = ZigZag.decode64low(low, high)
result.high = ZigZag.decode64high(low, high)
return result
}
public static function read$TYPE_MESSAGE(input:IDataInput,
message:Message):Message {
const length:uint = read$TYPE_UINT32(input)
if (input.bytesAvailable < length) {
throw new IOError("Invalid message length: " + length)
}
const bytesAfterSlice:uint = input.bytesAvailable - length
message.used_by_generated_code::readFromSlice(input, bytesAfterSlice)
if (input.bytesAvailable != bytesAfterSlice) {
throw new IOError("Invalid nested message")
}
return message
}
public static function readPackedRepeated(input:IDataInput,
readFuntion:Function, value:Array):void {
const length:uint = read$TYPE_UINT32(input)
if (input.bytesAvailable < length) {
throw new IOError("Invalid message length: " + length)
}
const bytesAfterSlice:uint = input.bytesAvailable - length
while (input.bytesAvailable > bytesAfterSlice) {
value.push(readFuntion(input))
}
if (input.bytesAvailable != bytesAfterSlice) {
throw new IOError("Invalid packed repeated data")
}
}
}
}
|
Fix #35
|
Fix #35
|
ActionScript
|
bsd-2-clause
|
tconkling/protoc-gen-as3
|
33d86e27c5c3b8bc377f32b387eb546482d8c0bd
|
src/ageofai/unit/base/BaseUnitView.as
|
src/ageofai/unit/base/BaseUnitView.as
|
package ageofai.unit.base
{
import ageofai.map.constant.CMap;
import ageofai.unit.view.LifeBarView;
import ageofai.unit.vo.UnitVO;
import caurina.transitions.Tweener;
import common.mvc.view.base.ABaseView;
import common.utils.MathUtil;
import flash.display.DisplayObject;
import flash.geom.Point;
/**
* ...
* @author Tibor Túri
*/
public class BaseUnitView extends ABaseView implements IUnitView
{
public var speed:Number;
private var _graphicUI:DisplayObject;
public var lifebar:LifeBarView;
public var unitVO:UnitVO;
public function BaseUnitView()
{
}
protected function createUI( uiClass:Class ):void
{
this._graphicUI = new uiClass;
this.addChild( this._graphicUI );
this._graphicUI.x = CMap.TILE_SIZE / 2;
this._graphicUI.y = CMap.TILE_SIZE / 2;
}
public function createLifeBar():void
{
this.lifebar = new LifeBarView();
this.addChild( this.lifebar );
this.lifebar.x = ( CMap.TILE_SIZE - this.lifebar.barWidth ) / 2;
this.lifebar.y = -30;
this.lifebar.drawProcessBar( 1 );
}
public function moveTo( villagerVO:UnitVO ):void
{
if ( this == villagerVO.view )
{
var movingTime:Number = this.calculateMovingTime( new Point( villagerVO.position.x, villagerVO.position.y ) );
Tweener.addTween( this, {
x: villagerVO.position.x,
y: villagerVO.position.y,
time: movingTime,
transition: "linear"
} )
this.calculateDirection( new Point( villagerVO.position.x, villagerVO.position.y ) );
}
}
private function calculateDirection( targetPoint:Point ):void
{
var direction:Number = targetPoint.x > this.x ? 1 : -1;
this.scaleX = direction;
}
public function calculateMovingTime( point:Point ):Number
{
var distance:Number;
var movingTime:Number;
var currentPosition:Point = this.getCurrentPosition();
distance = MathUtil.distance( currentPosition.x, currentPosition.y, point.x, point.y );
movingTime = Math.abs( distance ) / CMap.TILE_SIZE * this.speed;
return movingTime;
}
private function getCurrentPosition():Point
{
return new Point( this.x, this.y );
}
public function get graphicUI():DisplayObject
{
return _graphicUI;
}
}
}
|
package ageofai.unit.base
{
import ageofai.map.constant.CMap;
import ageofai.unit.view.LifeBarView;
import ageofai.unit.vo.UnitVO;
import caurina.transitions.Tweener;
import common.mvc.view.base.ABaseView;
import common.utils.MathUtil;
import flash.display.DisplayObject;
import flash.geom.Point;
/**
* ...
* @author Tibor Túri
*/
public class BaseUnitView extends ABaseView implements IUnitView
{
public var speed:Number;
private var _graphicUI:DisplayObject;
public var lifebar:LifeBarView;
public var unitVO:UnitVO;
public function BaseUnitView()
{
}
protected function createUI( uiClass:Class ):void
{
this._graphicUI = new uiClass;
this.addChild( this._graphicUI );
this._graphicUI.x = CMap.TILE_SIZE / 2;
this._graphicUI.y = CMap.TILE_SIZE / 2;
}
public function createLifeBar():void
{
this.lifebar = new LifeBarView();
this.addChild( this.lifebar );
this.lifebar.x = ( CMap.TILE_SIZE - this.lifebar.barWidth ) / 2;
this.lifebar.y = -30;
this.lifebar.drawProcessBar( 1 );
}
public function moveTo( villagerVO:UnitVO ):void
{
if ( this == villagerVO.view )
{
var movingTime:Number = this.calculateMovingTime( new Point( villagerVO.position.x, villagerVO.position.y ) );
Tweener.addTween( this, {
x: villagerVO.position.x,
y: villagerVO.position.y,
time: movingTime,
transition: "linear"
} )
this.calculateDirection( new Point( villagerVO.position.x, villagerVO.position.y ) );
}
}
private function calculateDirection( targetPoint:Point ):void
{
var direction:Number = targetPoint.x > this.x ? 1 : -1;
this._graphicUI.scaleX = direction;
}
public function calculateMovingTime( point:Point ):Number
{
var distance:Number;
var movingTime:Number;
var currentPosition:Point = this.getCurrentPosition();
distance = MathUtil.distance( currentPosition.x, currentPosition.y, point.x, point.y );
movingTime = Math.abs( distance ) / CMap.TILE_SIZE * this.speed;
return movingTime;
}
private function getCurrentPosition():Point
{
return new Point( this.x, this.y );
}
public function get graphicUI():DisplayObject
{
return _graphicUI;
}
}
}
|
scale fix
|
scale fix
scale fix
ó
|
ActionScript
|
apache-2.0
|
goc-flashplusplus/ageofai
|
6aecd6f28adf454e2c649b773b2b30fbbd0e0af9
|
src/aerys/minko/scene/node/Mesh.as
|
src/aerys/minko/scene/node/Mesh.as
|
package aerys.minko.scene.node
{
import aerys.minko.ns.minko_scene;
import aerys.minko.render.Effect;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.material.Material;
import aerys.minko.render.material.basic.BasicMaterial;
import aerys.minko.render.material.basic.BasicShader;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.controller.mesh.MeshVisibilityController;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.enum.DataProviderUsage;
import aerys.minko.type.math.Ray;
use namespace minko_scene;
/**
* Mesh objects are a visible instance of a Geometry rendered using a specific
* Effect with specific rendering properties.
*
* <p>
* Those rendering properties are stored in a DataBindings object so they can
* be directly used by the shaders in the rendering API.
* </p>
*
* @author Jean-Marc Le Roux
*
*/
public class Mesh extends AbstractSceneNode
{
public static const DEFAULT_MATERIAL : Material = new BasicMaterial();
private var _geometry : Geometry = null;
private var _properties : DataProvider = null;
private var _material : Material = null;
private var _bindings : DataBindings = null;
private var _visibility : MeshVisibilityController = new MeshVisibilityController();
private var _frame : uint = 0;
private var _cloned : Signal = new Signal('Mesh.clones');
private var _materialChanged : Signal = new Signal('Mesh.materialChanged');
private var _frameChanged : Signal = new Signal('Mesh.frameChanged');
private var _geometryChanged : Signal = new Signal('Mesh.geometryChanged');
/**
* A DataProvider object already bound to the Mesh bindings.
*
* <pre>
* // set the "diffuseColor" property to 0x0000ffff
* mesh.properties.diffuseColor = 0x0000ffff;
*
* // animate the "diffuseColor" property
* mesh.addController(
* new AnimationController(
* new <ITimeline>[new ColorTimeline(
* "dataProvider.diffuseColor",
* 5000,
* new <uint>[0xffffffff, 0xffffff00, 0xffffffff]
* )]
* )
* );
* </pre>
*
* @return
*
*/
public function get properties() : DataProvider
{
return _properties;
}
public function set properties(value : DataProvider) : void
{
if (_properties != value)
{
if (_properties)
_bindings.removeProvider(_properties);
_properties = value;
if (value)
_bindings.addProvider(value);
}
}
public function get material() : Material
{
return _material;
}
public function set material(value : Material) : void
{
if (_material != value)
{
if (_material)
_bindings.removeProvider(_material);
_material = value;
if (value)
_bindings.addProvider(value);
}
}
/**
* The rendering properties provided to the shaders to customize
* how the mesh will appear on screen.
*
* @return
*
*/
public function get bindings() : DataBindings
{
return _bindings;
}
/**
* The Geometry of the mesh.
* @return
*
*/
public function get geometry() : Geometry
{
return _geometry;
}
public function set geometry(value : Geometry) : void
{
if (_geometry != value)
{
var oldGeometry : Geometry = _geometry;
_geometry = value;
_geometryChanged.execute(this, oldGeometry, value);
}
}
/**
* Whether the mesh is visible or not.
*
* @return
*
*/
public function get visible() : Boolean
{
return _visibility.visible;
}
public function set visible(value : Boolean) : void
{
_visibility.visible = value;
}
public function get frustumCulling() : uint
{
return _visibility.frustumCulling;
}
public function set frustumCulling(value : uint) : void
{
_visibility.frustumCulling = value;
}
public function get cloned() : Signal
{
return _cloned;
}
public function get materialChanged() : Signal
{
return _materialChanged;
}
public function get frameChanged() : Signal
{
return _frameChanged;
}
public function get geometryChanged() : Signal
{
return _geometryChanged;
}
public function get frame() : uint
{
return _frame;
}
public function set frame(value : uint) : void
{
if (_frame != value)
{
var oldFrame : uint = _frame;
_frame = value;
_frameChanged.execute(this, oldFrame, value);
}
}
public function Mesh(geometry : Geometry = null,
material : Material = null,
...controllers)
{
super();
initialize(geometry, material, controllers);
}
private function initialize(geometry : Geometry,
material : Material,
controllers : Array) : void
{
_bindings = new DataBindings(this);
this.properties = new DataProvider(properties, 'meshProperties', DataProviderUsage.EXCLUSIVE);
_geometry = geometry;
this.material = material || DEFAULT_MATERIAL;
// _visibility.frustumCulling = FrustumCulling.BOX ^ FrustumCulling.TOP_BOX;
addController(_visibility);
while (controllers && !(controllers[0] is AbstractController))
controllers = controllers[0];
if (controllers)
for each (var ctrl : AbstractController in controllers)
addController(ctrl);
}
public function cast(ray : Ray, maxDistance : Number = Number.POSITIVE_INFINITY) : Number
{
return _geometry.boundingBox.testRay(
ray,
worldToLocal,
maxDistance
);
}
override minko_scene function cloneNode() : AbstractSceneNode
{
var clone : Mesh = new Mesh();
clone.name = name;
clone.geometry = _geometry;
clone.properties = DataProvider(_properties.clone());
clone._bindings.copySharedProvidersFrom(_bindings);
clone.transform.copyFrom(transform);
clone.material = _material;
this.cloned.execute(this, clone);
return clone;
}
override protected function addedToSceneHandler(child : ISceneNode, scene : Scene) : void
{
super.addedToSceneHandler(child, scene);
if (child === this)
_bindings.addProvider(transformData);
}
override protected function removedFromSceneHandler(child : ISceneNode, scene : Scene) : void
{
super.removedFromSceneHandler(child, scene);
if (child === this)
_bindings.removeProvider(transformData);
}
}
}
|
package aerys.minko.scene.node
{
import aerys.minko.ns.minko_scene;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.material.Material;
import aerys.minko.render.material.basic.BasicMaterial;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.controller.mesh.MeshVisibilityController;
import aerys.minko.scene.controller.mesh.VisibilityController;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.enum.DataProviderUsage;
import aerys.minko.type.math.Ray;
use namespace minko_scene;
/**
* Mesh objects are a visible instance of a Geometry rendered using a specific
* Effect with specific rendering properties.
*
* <p>
* Those rendering properties are stored in a DataBindings object so they can
* be directly used by the shaders in the rendering API.
* </p>
*
* @author Jean-Marc Le Roux
*
*/
public class Mesh extends AbstractSceneNode
{
public static const DEFAULT_MATERIAL : Material = new BasicMaterial();
private var _geometry : Geometry;
private var _properties : DataProvider;
private var _material : Material;
private var _bindings : DataBindings;
private var _visibility : VisibilityController;
private var _frame : uint;
private var _cloned : Signal;
private var _materialChanged : Signal;
private var _frameChanged : Signal;
private var _geometryChanged : Signal;
/**
* A DataProvider object already bound to the Mesh bindings.
*
* <pre>
* // set the "diffuseColor" property to 0x0000ffff
* mesh.properties.diffuseColor = 0x0000ffff;
*
* // animate the "diffuseColor" property
* mesh.addController(
* new AnimationController(
* new <ITimeline>[new ColorTimeline(
* "dataProvider.diffuseColor",
* 5000,
* new <uint>[0xffffffff, 0xffffff00, 0xffffffff]
* )]
* )
* );
* </pre>
*
* @return
*
*/
public function get properties() : DataProvider
{
return _properties;
}
public function set properties(value : DataProvider) : void
{
if (_properties != value)
{
if (_properties)
_bindings.removeProvider(_properties);
_properties = value;
if (value)
_bindings.addProvider(value);
}
}
public function get material() : Material
{
return _material;
}
public function set material(value : Material) : void
{
if (_material != value)
{
if (_material)
_bindings.removeProvider(_material);
_material = value;
if (value)
_bindings.addProvider(value);
}
}
/**
* The rendering properties provided to the shaders to customize
* how the mesh will appear on screen.
*
* @return
*
*/
public function get bindings() : DataBindings
{
return _bindings;
}
/**
* The Geometry of the mesh.
* @return
*
*/
public function get geometry() : Geometry
{
return _geometry;
}
public function set geometry(value : Geometry) : void
{
if (_geometry != value)
{
var oldGeometry : Geometry = _geometry;
_geometry = value;
_geometryChanged.execute(this, oldGeometry, value);
}
}
/**
* Whether the mesh is visible or not.
*
* @return
*
*/
public function get visible() : Boolean
{
return _visibility.visible;
}
public function set visible(value : Boolean) : void
{
_visibility.visible = value;
}
public function get frustumCulling() : uint
{
return _visibility.frustumCulling;
}
public function set frustumCulling(value : uint) : void
{
_visibility.frustumCulling = value;
}
public function get cloned() : Signal
{
return _cloned;
}
public function get materialChanged() : Signal
{
return _materialChanged;
}
public function get frameChanged() : Signal
{
return _frameChanged;
}
public function get geometryChanged() : Signal
{
return _geometryChanged;
}
public function get frame() : uint
{
return _frame;
}
public function set frame(value : uint) : void
{
if (_frame != value)
{
var oldFrame : uint = _frame;
_frame = value;
_frameChanged.execute(this, oldFrame, value);
}
}
public function Mesh(geometry : Geometry = null,
material : Material = null,
name : String = null)
{
super();
initialize(geometry, material, name);
}
private function initialize(geometry : Geometry,
material : Material,
name : String) : void
{
if (name)
this.name = name;
_cloned = new Signal('Mesh.clones');
_materialChanged = new Signal('Mesh.materialChanged');
_frameChanged = new Signal('Mesh.frameChanged');
_geometryChanged = new Signal('Mesh.geometryChanged');
_bindings = new DataBindings(this);
this.properties = new DataProvider(properties, 'meshProperties', DataProviderUsage.EXCLUSIVE);
_geometry = geometry;
this.material = material || DEFAULT_MATERIAL;
_visibility = new VisibilityController();
// _visibility.frustumCulling = FrustumCulling.BOX ^ FrustumCulling.TOP_BOX;
addController(_visibility);
}
public function cast(ray : Ray, maxDistance : Number = Number.POSITIVE_INFINITY) : Number
{
return _geometry.boundingBox.testRay(
ray,
worldToLocal,
maxDistance
);
}
override minko_scene function cloneNode() : AbstractSceneNode
{
var clone : Mesh = new Mesh();
clone.name = name;
clone.geometry = _geometry;
clone.properties = DataProvider(_properties.clone());
clone._bindings.copySharedProvidersFrom(_bindings);
clone.transform.copyFrom(transform);
clone.material = _material;
this.cloned.execute(this, clone);
return clone;
}
override protected function addedToSceneHandler(child : ISceneNode, scene : Scene) : void
{
super.addedToSceneHandler(child, scene);
if (child === this)
_bindings.addProvider(transformData);
}
override protected function removedFromSceneHandler(child : ISceneNode, scene : Scene) : void
{
super.removedFromSceneHandler(child, scene);
if (child === this)
_bindings.removeProvider(transformData);
}
}
}
|
remove controllers from Mesh variadic constructor and replace them with a name : String optional argument
|
remove controllers from Mesh variadic constructor and replace them with a name : String optional argument
|
ActionScript
|
mit
|
aerys/minko-as3
|
a30ece9065274bfbfe6220bae13199851a6d3f45
|
actionscript-cafe/src/main/flex/org/servebox/cafe/core/signal/SignalAggregator.as
|
actionscript-cafe/src/main/flex/org/servebox/cafe/core/signal/SignalAggregator.as
|
/*
* actionscript-cafe SignalAggregator 18 avr. 2011 adesmarais
*
* Created by Servebox
* Copyright 2010 Servebox (c) All rights reserved. You may not use, distribute
* or modify this code under its source or binary form
* without the express authorization of ServeBox. Contact : [email protected]
*/
package org.servebox.cafe.core.signal
{
import org.servebox.cafe.core.observer.AbstractObservable;
import org.servebox.cafe.core.observer.IObservable;
import org.servebox.cafe.core.observer.IObserver;
import org.servebox.cafe.core.observer.Notification;
public class SignalAggregator extends AbstractObservable
{
public function SignalAggregator()
{
}
override public function registerObserver(o:IObserver, notificationFilters:Array=null):void
{
if ( !(o is ISignalObserver ) )
{
throw new Error("Observer of SignalAggregator should be ISignalObserver");
}
super.registerObserver( ISignalObserver( o ), notificationFilters );
}
override public function unregisterObserver(o:IObserver):void
{
if ( !(o is ISignalObserver ) )
{
throw new Error("Observer of SignalAggregator should be ISignalObserver");
}
super.unregisterObserver( ISignalObserver( o ) );
}
public function signal( type : String, ... cargo) : void
{
if( cargo.length > 0 )
{
var signal : Signal = new Signal(type);
signal.setCargoList(cargo);
super.signalObservers( signal );
}
else
{
super.signalObservers( new Signal(type) );
}
}
override protected function handleFilters(o : IObserver, notificationFilters : Array = null) : void
{
// Label label_filters
for each( var notificationFilter : String in notificationFilters )
{
addObserver(o,notificationFilter);
}
}
}
}
|
/*
* actionscript-cafe SignalAggregator 18 avr. 2011 adesmarais
*
* Created by Servebox
* Copyright 2010 Servebox (c) All rights reserved. You may not use, distribute
* or modify this code under its source or binary form
* without the express authorization of ServeBox. Contact : [email protected]
*/
package org.servebox.cafe.core.signal
{
import mx.logging.ILogger;
import mx.logging.Log;
import org.servebox.cafe.core.observer.AbstractObservable;
import org.servebox.cafe.core.observer.IObservable;
import org.servebox.cafe.core.observer.IObserver;
import org.servebox.cafe.core.observer.Notification;
public class SignalAggregator extends AbstractObservable
{
public var log : ILogger = Log.getLogger("SignalAggregator");
override public function registerObserver(o:IObserver, notificationFilters:Array=null):void
{
if ( !(o is ISignalObserver ) )
{
throw new Error("Observer of SignalAggregator should be ISignalObserver");
}
super.registerObserver( ISignalObserver( o ), notificationFilters );
}
override public function unregisterObserver(o:IObserver):void
{
if ( !(o is ISignalObserver ) )
{
throw new Error("Observer of SignalAggregator should be ISignalObserver");
}
super.unregisterObserver( ISignalObserver( o ) );
}
public function signal( type : String, ... cargo) : void
{
log.info("SignalAggregator runs " + type );
if( cargo.length > 0 )
{
var signal : Signal = new Signal(type);
signal.setCargoList(cargo);
super.signalObservers( signal );
}
else
{
super.signalObservers( new Signal(type) );
}
}
override protected function handleFilters(o : IObserver, notificationFilters : Array = null) : void
{
// Label label_filters
for each( var notificationFilter : String in notificationFilters )
{
addObserver(o,notificationFilter);
}
}
}
}
|
add lOgger.
|
add lOgger.
|
ActionScript
|
mit
|
servebox/as-cafe
|
c04048c677a1b703b3ec2d80921eeeb86561db60
|
krew-framework/krewfw/core_internal/KrewResourceManager.as
|
krew-framework/krewfw/core_internal/KrewResourceManager.as
|
package krewfw.core_internal {
import flash.media.Sound;
import starling.display.Image;
import starling.textures.Texture;
import starling.utils.AssetManager;
import krewfw.KrewConfig;
import krewfw.utils.krew;
//------------------------------------------------------------
public class KrewResourceManager {
private var _urlScheme:String;
private var _globalScopeAssets:AssetManager;
private var _sceneScopeAssets :AssetManager;
//------------------------------------------------------------
public function KrewResourceManager() {
_urlScheme = KrewConfig.ASSET_URL_SCHEME;
_globalScopeAssets = new KrewConfig.ASSET_MANAGER_CLASS;
_sceneScopeAssets = new KrewConfig.ASSET_MANAGER_CLASS;
_globalScopeAssets.verbose = KrewConfig.ASSET_MANAGER_VERBOSE;
_sceneScopeAssets .verbose = KrewConfig.ASSET_MANAGER_VERBOSE;
}
//------------------------------------------------------------
// accessor
//------------------------------------------------------------
public function get globalAssetManager():AssetManager {
return _globalScopeAssets;
}
public function get sceneAssetManager():AssetManager {
return _sceneScopeAssets;
}
//------------------------------------------------------------
/**
* シーン単位で使いたいリソースのロード.
* 基本的に starling.utils.AssetManager をラップしているだけなので
* そちらのドキュメントを見よ。
*
* <ul>
* <li> テクスチャアトラスを読み込む場合は単純に png と xml の 2 つを指定すればよい。
* getImage("拡張子を除くファイル名") で取得できる。
* 画像はファイル名で引くため、全アトラスでソース画像のファイル名(というか xml 内の識別子)
* がユニークになっている必要がある
* </li>
* <li> mp3 はロード後 getSound() で取得できる </li>
* <li> json も読める。 getObject() で取得できる </li>
* <li> xml も読める。 getXml() で取得できる </li>
*
* <li> ビットマップフォントは png と fnt を読み込み後、自動的に
* starling.text.TextField で使用可能になる
* </li>
* </ul>
*/
public function loadResources(fileNameList:Array, onLoadProgress:Function,
onLoadComplete:Function):void
{
var suitablePathList:Array = _mapToSuitablePath(fileNameList);
_sceneScopeAssets.enqueue(suitablePathList);
_sceneScopeAssets.loadQueue(function(loadRatio:Number):void {
if (onLoadProgress != null) {
onLoadProgress(loadRatio);
}
if (loadRatio == 1) {
onLoadComplete();
}
});
}
/**
* シーン遷移時にこれを呼んでメモリ解放(テクスチャの dispose を呼ぶ)
*/
public function purgeSceneScopeResources():void {
_sceneScopeAssets.purge();
}
/**
* ゲームを通してずっとメモリに保持しておくリソースのロード.
* (Loading 画面のアセットなど)
* 使い方は loadResources と同じ。
* ロードしたものの取得は getGlobalImage() などと Global がついたメソッドで。
*
* 現状はゲームの起動時に 1 回実行することを想定。
*/
public function loadGlobalResources(fileNameList:Array, onLoadProgress:Function,
onLoadComplete:Function):void
{
var suitablePathList:Array = _mapToSuitablePath(fileNameList);
_globalScopeAssets.enqueue(suitablePathList);
_globalScopeAssets.loadQueue(function(loadRatio:Number):void {
if (onLoadProgress != null) {
onLoadProgress(loadRatio);
}
if (loadRatio == 1) {
onLoadComplete();
}
});
}
//------------------------------------------------------------
// getters for game resources
//------------------------------------------------------------
/**
* 拡張子無しのファイル名を指定。シーンスコープのアセットから検索し、
* 見つからなければグローバルスコープのアセットから検索して返す。
* (他の getter でも同様)
*/
public function getImage(fileName:String):Image {
var texture:Texture = getTexture(fileName);
if (texture) { return new Image(texture); }
krew.fwlog('[Error] [KRM] Image not found: ' + fileName);
return null;
}
public function getTexture(fileName:String):Texture {
var texture:Texture = _sceneScopeAssets.getTexture(fileName);
if (texture) { return texture; }
texture = _globalScopeAssets.getTexture(fileName);
if (texture) { return texture; }
krew.fwlog('[Error] [KRM] Texture not found: ' + fileName);
return null;
}
public function getSound(fileName:String):Sound {
var sound:Sound = _sceneScopeAssets.getSound(fileName);
if (sound) { return sound; }
sound = _globalScopeAssets.getSound(fileName);
if (sound) { return sound; }
krew.fwlog('[Error] [KRM] Sound not found: ' + fileName);
return null;
}
public function getXml(fileName:String):XML {
var xml:XML = _sceneScopeAssets.getXml(fileName);
if (xml) { return xml; }
xml = _globalScopeAssets.getXml(fileName);
if (xml) { return xml; }
krew.fwlog('[Error] [KRM] XML not found: ' + fileName);
return null;
}
public function getObject(fileName:String):Object {
var obj:Object = _sceneScopeAssets.getObject(fileName);
if (obj) { return obj; }
obj = _globalScopeAssets.getObject(fileName);
if (obj) { return obj; }
krew.fwlog('[Error] [KRM] Object not found: ' + fileName);
return null;
return _sceneScopeAssets.getObject(fileName);
}
//------------------------------------------------------------
// private
//------------------------------------------------------------
private function _mapToSuitablePath(fileNameList:Array):Array {
var suitablePathList:Array = [];
for each (var fileName:String in fileNameList) {
suitablePathList.push(
_urlScheme + KrewConfig.ASSET_BASE_PATH + fileName
);
}
return suitablePathList;
}
}
}
|
package krewfw.core_internal {
import flash.media.Sound;
import starling.display.Image;
import starling.textures.Texture;
import starling.utils.AssetManager;
import krewfw.KrewConfig;
import krewfw.utils.krew;
//------------------------------------------------------------
public class KrewResourceManager {
private var _globalScopeAssets:AssetManager;
private var _sceneScopeAssets :AssetManager;
//------------------------------------------------------------
public function KrewResourceManager() {
_globalScopeAssets = new KrewConfig.ASSET_MANAGER_CLASS;
_sceneScopeAssets = new KrewConfig.ASSET_MANAGER_CLASS;
_globalScopeAssets.verbose = KrewConfig.ASSET_MANAGER_VERBOSE;
_sceneScopeAssets .verbose = KrewConfig.ASSET_MANAGER_VERBOSE;
}
//------------------------------------------------------------
// accessor
//------------------------------------------------------------
public function get globalAssetManager():AssetManager {
return _globalScopeAssets;
}
public function get sceneAssetManager():AssetManager {
return _sceneScopeAssets;
}
//------------------------------------------------------------
/**
* シーン単位で使いたいリソースのロード.
* 基本的に starling.utils.AssetManager をラップしているだけなので
* そちらのドキュメントを見よ。
*
* <ul>
* <li> テクスチャアトラスを読み込む場合は単純に png と xml の 2 つを指定すればよい。
* getImage("拡張子を除くファイル名") で取得できる。
* 画像はファイル名で引くため、全アトラスでソース画像のファイル名(というか xml 内の識別子)
* がユニークになっている必要がある
* </li>
* <li> mp3 はロード後 getSound() で取得できる </li>
* <li> json も読める。 getObject() で取得できる </li>
* <li> xml も読める。 getXml() で取得できる </li>
*
* <li> ビットマップフォントは png と fnt を読み込み後、自動的に
* starling.text.TextField で使用可能になる
* </li>
* </ul>
*/
public function loadResources(fileNameList:Array, onLoadProgress:Function,
onLoadComplete:Function):void
{
var suitablePathList:Array = _mapToSuitablePath(fileNameList);
_sceneScopeAssets.enqueue(suitablePathList);
_sceneScopeAssets.loadQueue(function(loadRatio:Number):void {
if (onLoadProgress != null) {
onLoadProgress(loadRatio);
}
if (loadRatio == 1) {
onLoadComplete();
}
});
}
/**
* シーン遷移時にこれを呼んでメモリ解放(テクスチャの dispose を呼ぶ)
*/
public function purgeSceneScopeResources():void {
_sceneScopeAssets.purge();
}
/**
* ゲームを通してずっとメモリに保持しておくリソースのロード.
* (Loading 画面のアセットなど)
* 使い方は loadResources と同じ。
* ロードしたものの取得は getGlobalImage() などと Global がついたメソッドで。
*
* 現状はゲームの起動時に 1 回実行することを想定。
*/
public function loadGlobalResources(fileNameList:Array, onLoadProgress:Function,
onLoadComplete:Function):void
{
var suitablePathList:Array = _mapToSuitablePath(fileNameList);
_globalScopeAssets.enqueue(suitablePathList);
_globalScopeAssets.loadQueue(function(loadRatio:Number):void {
if (onLoadProgress != null) {
onLoadProgress(loadRatio);
}
if (loadRatio == 1) {
onLoadComplete();
}
});
}
//------------------------------------------------------------
// getters for game resources
//------------------------------------------------------------
/**
* 拡張子無しのファイル名を指定。シーンスコープのアセットから検索し、
* 見つからなければグローバルスコープのアセットから検索して返す。
* (他の getter でも同様)
*/
public function getImage(fileName:String):Image {
var texture:Texture = getTexture(fileName);
if (texture) { return new Image(texture); }
krew.fwlog('[Error] [KRM] Image not found: ' + fileName);
return null;
}
public function getTexture(fileName:String):Texture {
var texture:Texture = _sceneScopeAssets.getTexture(fileName);
if (texture) { return texture; }
texture = _globalScopeAssets.getTexture(fileName);
if (texture) { return texture; }
krew.fwlog('[Error] [KRM] Texture not found: ' + fileName);
return null;
}
public function getSound(fileName:String):Sound {
var sound:Sound = _sceneScopeAssets.getSound(fileName);
if (sound) { return sound; }
sound = _globalScopeAssets.getSound(fileName);
if (sound) { return sound; }
krew.fwlog('[Error] [KRM] Sound not found: ' + fileName);
return null;
}
public function getXml(fileName:String):XML {
var xml:XML = _sceneScopeAssets.getXml(fileName);
if (xml) { return xml; }
xml = _globalScopeAssets.getXml(fileName);
if (xml) { return xml; }
krew.fwlog('[Error] [KRM] XML not found: ' + fileName);
return null;
}
public function getObject(fileName:String):Object {
var obj:Object = _sceneScopeAssets.getObject(fileName);
if (obj) { return obj; }
obj = _globalScopeAssets.getObject(fileName);
if (obj) { return obj; }
krew.fwlog('[Error] [KRM] Object not found: ' + fileName);
return null;
return _sceneScopeAssets.getObject(fileName);
}
/**
* 現環境におけるアセットファイルの URL を取得する
*/
public function getURL(fileName:String):String {
return KrewConfig.ASSET_URL_SCHEME + KrewConfig.ASSET_BASE_PATH + fileName;
}
//------------------------------------------------------------
// private
//------------------------------------------------------------
private function _mapToSuitablePath(fileNameList:Array):Array {
var suitablePathList:Array = [];
for each (var fileName:String in fileNameList) {
suitablePathList.push(getURL(fileName));
}
return suitablePathList;
}
}
}
|
Modify resource manager
|
Modify resource manager
|
ActionScript
|
mit
|
tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework
|
ff7e1131567519b6412f197d01fc74566274c70a
|
frameworks/projects/mobiletheme/src/spark/skins/ios7/BusyIndicatorSkin.as
|
frameworks/projects/mobiletheme/src/spark/skins/ios7/BusyIndicatorSkin.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 flash.events.TimerEvent;
import flash.geom.Matrix;
import flash.utils.Timer;
import mx.core.DPIClassification;
import spark.components.BusyIndicator;
import spark.skins.ios7.assets.BusyIndicator;
import spark.skins.mobile.supportClasses.MobileSkin;
public class BusyIndicatorSkin extends MobileSkin
{
static private const DEFAULT_ROTATION_INTERVAL:Number = 30;
private var busyIndicatorClass:Class;
private var busyIndicator:DisplayObject;
private var busyIndicatorBackground:DisplayObject;
private var busyIndicatorDiameter:Number;
private var rotationTimer:Timer;
private var rotationInterval:Number;
private var rotationSpeed:Number;
/**
* @private
*
* Current rotation of this component in degrees.
*/
private var currentRotation:Number = 0;
private var symbolColor:uint;
private var symbolColorChanged:Boolean = false;
public function BusyIndicatorSkin()
{
super();
busyIndicatorClass = spark.skins.ios7.assets.BusyIndicator;
rotationInterval = getStyle("rotationInterval");
if (isNaN(rotationInterval))
rotationInterval = DEFAULT_ROTATION_INTERVAL;
if (rotationInterval < 30) //Spokes are at 30 degree angle to each other.
rotationInterval = 30;
rotationSpeed = 60;
switch(applicationDPI)
{
case DPIClassification.DPI_640:
{
busyIndicatorDiameter = 144;
break;
}
case DPIClassification.DPI_480:
{
busyIndicatorDiameter = 108;
break;
}
case DPIClassification.DPI_320:
{
busyIndicatorDiameter = 72;
break;
}
case DPIClassification.DPI_240:
{
busyIndicatorDiameter = 54;
break;
}
case DPIClassification.DPI_120:
{
busyIndicatorDiameter = 27;
break;
}
default://160 DPI
{
busyIndicatorDiameter = 36;
break;
}
}
}
private var _hostComponent:spark.components.BusyIndicator;
public function get hostComponent():spark.components.BusyIndicator
{
return _hostComponent;
}
public function set hostComponent(value:spark.components.BusyIndicator):void
{
_hostComponent = value;
}
override protected function createChildren():void
{
//This layer stays still in the background
busyIndicatorBackground = new busyIndicatorClass();
busyIndicatorBackground.width = busyIndicatorBackground.height = busyIndicatorDiameter;
addChild(busyIndicatorBackground);
//This layer rotates in the foreground to give the required effect
busyIndicator = new busyIndicatorClass();
busyIndicator.alpha = 0.3;
busyIndicator.width = busyIndicator.height = busyIndicatorDiameter;
addChild(busyIndicator);
}
override protected function measure():void
{
measuredWidth = busyIndicatorDiameter;
measuredHeight = busyIndicatorDiameter;
measuredMinHeight = busyIndicatorDiameter;
measuredMinWidth = busyIndicatorDiameter
}
override protected function commitCurrentState():void
{
super.commitCurrentState();
if(currentState == "rotatingState")
{
startRotation();
}
else
{
stopRotation();
}
}
override public function styleChanged(styleProp:String):void
{
var allStyles:Boolean = !styleProp || styleProp == "styleName";
if (allStyles || styleProp == "symbolColor")
{
symbolColor = getStyle("symbolColor");
symbolColorChanged = true;
invalidateDisplayList();
}
super.styleChanged(styleProp);
}
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
{
super.updateDisplayList(unscaledWidth,unscaledHeight);
if(symbolColorChanged)
{
colorizeSymbol();
symbolColorChanged = false;
}
}
private function colorizeSymbol():void
{
super.applyColorTransform(this.busyIndicator, 0x000000, symbolColor);
}
private function startRotation():void
{
rotationTimer = new Timer(rotationSpeed);
if (!rotationTimer.hasEventListener(TimerEvent.TIMER))
{
rotationTimer.addEventListener(TimerEvent.TIMER, timerHandler);
rotationTimer.start();
}
}
private function stopRotation():void
{
if (rotationTimer)
{
rotationTimer.removeEventListener(TimerEvent.TIMER, timerHandler);
rotationTimer.stop();
rotationTimer = null;
}
}
/**
* @private
*
* Rotate the spinner once for each timer event.
*/
private function timerHandler(event:TimerEvent):void
{
currentRotation += rotationInterval;
if (currentRotation >= 360)
currentRotation = 0;
rotate(busyIndicator,currentRotation,measuredWidth/2,measuredHeight/2);
event.updateAfterEvent();
}
private var rotationMatrix:Matrix;
private function rotate(obj:DisplayObject, angle:Number, aroundX:Number, aroundY:Number):void
{
rotationMatrix = new Matrix();
rotationMatrix.translate(-aroundX,-aroundY);
rotationMatrix.rotate(Math.PI*angle/180);
rotationMatrix.translate(aroundX,aroundY);
obj.transform.matrix = rotationMatrix;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 flash.events.TimerEvent;
import flash.geom.Matrix;
import flash.utils.Timer;
import mx.core.DPIClassification;
import spark.components.BusyIndicator;
import spark.skins.ios7.assets.BusyIndicator;
import spark.skins.mobile.supportClasses.MobileSkin;
public class BusyIndicatorSkin extends MobileSkin
{
static private const DEFAULT_ROTATION_INTERVAL:Number = 30;
private var busyIndicatorClass:Class;
private var busyIndicator:DisplayObject;
private var busyIndicatorBackground:DisplayObject;
private var busyIndicatorDiameter:Number;
private var rotationTimer:Timer;
private var rotationInterval:Number;
private var rotationSpeed:Number;
/**
* @private
*
* Current rotation of this component in degrees.
*/
private var currentRotation:Number = 0;
private var symbolColor:uint;
private var symbolColorChanged:Boolean = false;
public function BusyIndicatorSkin()
{
super();
busyIndicatorClass = spark.skins.ios7.assets.BusyIndicator;
rotationInterval = getStyle("rotationInterval");
if (isNaN(rotationInterval))
rotationInterval = DEFAULT_ROTATION_INTERVAL;
if (rotationInterval < 30) //Spokes are at 30 degree angle to each other.
rotationInterval = 30;
rotationSpeed = 60;
switch(applicationDPI)
{
case DPIClassification.DPI_640:
{
busyIndicatorDiameter = 104;
break;
}
case DPIClassification.DPI_480:
{
busyIndicatorDiameter = 80;
break;
}
case DPIClassification.DPI_320:
{
busyIndicatorDiameter = 52;
break;
}
case DPIClassification.DPI_240:
{
busyIndicatorDiameter = 40;
break;
}
case DPIClassification.DPI_120:
{
busyIndicatorDiameter = 20;
break;
}
default://160 DPI
{
busyIndicatorDiameter = 20;
break;
}
}
}
private var _hostComponent:spark.components.BusyIndicator;
public function get hostComponent():spark.components.BusyIndicator
{
return _hostComponent;
}
public function set hostComponent(value:spark.components.BusyIndicator):void
{
_hostComponent = value;
}
override protected function createChildren():void
{
//This layer stays still in the background
busyIndicatorBackground = new busyIndicatorClass();
busyIndicatorBackground.width = busyIndicatorBackground.height = busyIndicatorDiameter;
addChild(busyIndicatorBackground);
//This layer rotates in the foreground to give the required effect
busyIndicator = new busyIndicatorClass();
busyIndicator.alpha = 0.3;
busyIndicator.width = busyIndicator.height = busyIndicatorDiameter;
addChild(busyIndicator);
}
override protected function measure():void
{
measuredWidth = busyIndicatorDiameter;
measuredHeight = busyIndicatorDiameter;
measuredMinHeight = busyIndicatorDiameter;
measuredMinWidth = busyIndicatorDiameter
}
override protected function commitCurrentState():void
{
super.commitCurrentState();
if(currentState == "rotatingState")
{
startRotation();
}
else
{
stopRotation();
}
}
override public function styleChanged(styleProp:String):void
{
var allStyles:Boolean = !styleProp || styleProp == "styleName";
if (allStyles || styleProp == "symbolColor")
{
symbolColor = getStyle("symbolColor");
symbolColorChanged = true;
invalidateDisplayList();
}
super.styleChanged(styleProp);
}
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
{
super.updateDisplayList(unscaledWidth,unscaledHeight);
if(symbolColorChanged)
{
colorizeSymbol();
symbolColorChanged = false;
}
}
private function colorizeSymbol():void
{
super.applyColorTransform(this.busyIndicator, 0x000000, symbolColor);
}
private function startRotation():void
{
rotationTimer = new Timer(rotationSpeed);
if (!rotationTimer.hasEventListener(TimerEvent.TIMER))
{
rotationTimer.addEventListener(TimerEvent.TIMER, timerHandler);
rotationTimer.start();
}
}
private function stopRotation():void
{
if (rotationTimer)
{
rotationTimer.removeEventListener(TimerEvent.TIMER, timerHandler);
rotationTimer.stop();
rotationTimer = null;
}
}
/**
* @private
*
* Rotate the spinner once for each timer event.
*/
private function timerHandler(event:TimerEvent):void
{
currentRotation += rotationInterval;
if (currentRotation >= 360)
currentRotation = 0;
rotate(busyIndicator,currentRotation,measuredWidth/2,measuredHeight/2);
event.updateAfterEvent();
}
private var rotationMatrix:Matrix;
private function rotate(obj:DisplayObject, angle:Number, aroundX:Number, aroundY:Number):void
{
rotationMatrix = new Matrix();
rotationMatrix.translate(-aroundX,-aroundY);
rotationMatrix.rotate(Math.PI*angle/180);
rotationMatrix.translate(aroundX,aroundY);
obj.transform.matrix = rotationMatrix;
}
}
}
|
Use legacy BusyIndicator default sizes (new sizes were breaking Mustella tests)
|
Use legacy BusyIndicator default sizes (new sizes were breaking Mustella tests)
|
ActionScript
|
apache-2.0
|
SlavaRa/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk
|
7c7b4fdd105a5ee5e18cf65dc81a4fc01bc65d27
|
src/as/com/threerings/flex/PlayerList.as
|
src/as/com/threerings/flex/PlayerList.as
|
//
// $Id$
//
// Nenya library - tools for developing networked games
// Copyright (C) 2002-2007 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.flex {
import flash.utils.Dictionary;
import mx.collections.ArrayCollection;
import mx.collections.Sort;
import mx.containers.VBox;
import mx.core.ClassFactory;
import mx.core.ScrollPolicy;
import com.threerings.util.Comparable;
public class PlayerList extends VBox
{
/**
* Create a new player list.
*
* @param labelCreator If null, will use a default implementation that does nothing special
* with text formatting or click behavior.
*/
public function PlayerList (labelCreator :NameLabelCreator = null) :void
{
_labelCreator = labelCreator;
if (_labelCreator == null) {
_labelCreator = new DefaultNameLabelCreator();
}
// set up the UI
width = 280;
height = 125;
_list = new AmbidextrousList();
_list.verticalScrollPolicy = ScrollPolicy.ON;
_list.selectable = false;
_list.percentWidth = 100;
_list.percentHeight = 100;
_list.itemRenderer = new ClassFactory(getRenderingClass());
_list.dataProvider = _players;
addChild(_list);
// set up the sort for the collection
var sort :Sort = new Sort();
sort.compareFunction = sortFunction;
_players.sort = sort;
}
/**
* The PlayerList is meant to include data that is at least as complicated as a Name, so to
* keep things simple and extendable, we require Comparable. This allows the issue of passing
* the NameLabelCreator into the player renderer to be kept simple and straightforward and still
* allow efficient item updating.
*/
public function addItem (value :Comparable) :void
{
var currentValue :Array = _values[value] as Array;
if (currentValue != null) {
currentValue[1] = value;
// this is the same array already contained in the list, so the proper renderer should
// be notified of the new value.
_players.itemUpdated(currentValue);
} else {
currentValue = [_labelCreator, value];
_values[value] = currentValue;
_players.addItem(currentValue);
}
}
public function removeItem (value :Comparable) :void
{
var currentValue :Array = _values[value] as Array;
if (currentValue != null) {
_players.removeItemAt(_players.getItemIndex(currentValue));
}
delete _values[value];
}
/**
* Notify the list that this value has changed internally, and the renderer should be told to
* redraw its contents.
*/
public function itemUpdated (value :Comparable) :void
{
var currentValue :Array = _values[value] as Array;
if (currentValue != null) {
currentValue[1] = value;
_players.itemUpdated(currentValue);
}
}
protected function getRenderingClass () :Class
{
return PlayerRenderer;
}
protected function sortFunction (o1 :Object, o2 :Object, fields :Array = null) :int
{
if (!(o1 is Array) || !(o2 is Array)) {
return 0;
}
var data1 :Object = (o1 as Array)[1];
var data2 :Object = (o2 as Array)[1];
if (data1 is Comparable && data2 is Comparable) {
return (data1 as Comparable).compareTo(data2);
} else {
// default to actionscript's magical great than or less than operators
return data1 > data2 ? -1 : (data1 < data2 ? 1 : 0);
}
}
protected var _labelCreator :NameLabelCreator;
protected var _list :AmbidextrousList;
protected var _players :ArrayCollection = new ArrayCollection();
protected var _values :Dictionary = new Dictionary();
}
}
import mx.containers.HBox;
import mx.controls.Label;
import mx.core.ScrollPolicy;
import mx.core.UIComponent;
import com.threerings.flex.NameLabelCreator;
import com.threerings.util.Name;
class DefaultNameLabelCreator implements NameLabelCreator
{
public function createLabel (name :Name) :UIComponent
{
var label :Label = new Label();
label.text = "" + name;
return label;
}
}
/**
* A renederer for lists that contain Names.
*/
class PlayerRenderer extends HBox
{
public function PlayerRenderer ()
{
super();
verticalScrollPolicy = ScrollPolicy.OFF;
horizontalScrollPolicy = ScrollPolicy.OFF;
// the horizontalGap should be 8...
}
override public function set data (value :Object) :void
{
super.data = value;
if (processedDescriptors) {
configureUI();
}
}
override protected function createChildren () :void
{
super.createChildren();
configureUI();
}
/**
* Update the UI elements with the data we're displaying.
*/
protected function configureUI () :void
{
removeAllChildren();
if (this.data != null && (this.data is Array) && (this.data as Array).length == 2) {
var dataArray :Array = this.data as Array;
var creator :NameLabelCreator = dataArray[0] as NameLabelCreator;
var name :Name = dataArray[1] as Name;
if (creator != null && name != null) {
addChild(creator.createLabel(name));
}
}
}
}
|
//
// $Id$
//
// Nenya library - tools for developing networked games
// Copyright (C) 2002-2007 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.flex {
import flash.utils.Dictionary;
import mx.collections.ArrayCollection;
import mx.collections.Sort;
import mx.containers.VBox;
import mx.core.ClassFactory;
import mx.core.ScrollPolicy;
import com.threerings.util.Comparable;
public class PlayerList extends VBox
{
/**
* Create a new player list.
*
* @param labelCreator If null, will use a default implementation that does nothing special
* with text formatting or click behavior.
*/
public function PlayerList (labelCreator :NameLabelCreator = null) :void
{
_labelCreator = labelCreator;
if (_labelCreator == null) {
_labelCreator = new DefaultNameLabelCreator();
}
// set up the UI
width = 280;
height = 125;
_list = new AmbidextrousList();
_list.verticalScrollPolicy = ScrollPolicy.ON;
_list.selectable = false;
_list.percentWidth = 100;
_list.percentHeight = 100;
_list.itemRenderer = new ClassFactory(getRenderingClass());
_list.dataProvider = _players;
addChild(_list);
// set up the sort for the collection
var sort :Sort = new Sort();
sort.compareFunction = sortFunction;
_players.sort = sort;
}
public function clear () :void
{
_values = new Dictionary();
_players.removeAll();
}
/**
* The PlayerList is meant to include data that is at least as complicated as a Name, so to
* keep things simple and extendable, we require Comparable. This allows the issue of passing
* the NameLabelCreator into the player renderer to be kept simple and straightforward and still
* allow efficient item updating.
*/
public function addItem (value :Comparable) :void
{
var currentValue :Array = _values[value] as Array;
if (currentValue != null) {
currentValue[1] = value;
// this is the same array already contained in the list, so the proper renderer should
// be notified of the new value.
_players.itemUpdated(currentValue);
} else {
currentValue = [_labelCreator, value];
_values[value] = currentValue;
_players.addItem(currentValue);
}
}
public function removeItem (value :Comparable) :void
{
var currentValue :Array = _values[value] as Array;
if (currentValue != null) {
_players.removeItemAt(_players.getItemIndex(currentValue));
}
delete _values[value];
}
/**
* Notify the list that this value has changed internally, and the renderer should be told to
* redraw its contents.
*/
public function itemUpdated (value :Comparable) :void
{
var currentValue :Array = _values[value] as Array;
if (currentValue != null) {
currentValue[1] = value;
_players.itemUpdated(currentValue);
}
}
protected function getRenderingClass () :Class
{
return PlayerRenderer;
}
protected function sortFunction (o1 :Object, o2 :Object, fields :Array = null) :int
{
if (!(o1 is Array) || !(o2 is Array)) {
return 0;
}
var data1 :Object = (o1 as Array)[1];
var data2 :Object = (o2 as Array)[1];
if (data1 is Comparable && data2 is Comparable) {
return (data1 as Comparable).compareTo(data2);
} else {
// default to actionscript's magical great than or less than operators
return data1 > data2 ? -1 : (data1 < data2 ? 1 : 0);
}
}
protected var _labelCreator :NameLabelCreator;
protected var _list :AmbidextrousList;
protected var _players :ArrayCollection = new ArrayCollection();
protected var _values :Dictionary = new Dictionary();
}
}
import mx.containers.HBox;
import mx.controls.Label;
import mx.core.ScrollPolicy;
import mx.core.UIComponent;
import com.threerings.flex.NameLabelCreator;
import com.threerings.util.Name;
class DefaultNameLabelCreator implements NameLabelCreator
{
public function createLabel (name :Name) :UIComponent
{
var label :Label = new Label();
label.text = "" + name;
return label;
}
}
/**
* A renederer for lists that contain Names.
*/
class PlayerRenderer extends HBox
{
public function PlayerRenderer ()
{
super();
verticalScrollPolicy = ScrollPolicy.OFF;
horizontalScrollPolicy = ScrollPolicy.OFF;
// the horizontalGap should be 8...
}
override public function set data (value :Object) :void
{
super.data = value;
if (processedDescriptors) {
configureUI();
}
}
override protected function createChildren () :void
{
super.createChildren();
configureUI();
}
/**
* Update the UI elements with the data we're displaying.
*/
protected function configureUI () :void
{
removeAllChildren();
if (this.data != null && (this.data is Array) && (this.data as Array).length == 2) {
var dataArray :Array = this.data as Array;
var creator :NameLabelCreator = dataArray[0] as NameLabelCreator;
var name :Name = dataArray[1] as Name;
if (creator != null && name != null) {
addChild(creator.createLabel(name));
}
}
}
}
|
Add clear() functionality
|
Add clear() functionality
git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@482 ed5b42cb-e716-0410-a449-f6a68f950b19
|
ActionScript
|
lgpl-2.1
|
threerings/nenya,threerings/nenya
|
213ed4ac1c267f053ce209e210c693ac7e973d9f
|
src/org/mangui/osmf/plugins/HLSPlugin.as
|
src/org/mangui/osmf/plugins/HLSPlugin.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.osmf.plugins {
import org.mangui.hls.utils.Params2Settings;
import org.mangui.osmf.plugins.loader.HLSLoaderBase;
import org.mangui.osmf.plugins.loader.HLSLoadFromDocumentElement;
import org.osmf.media.MediaElement;
import org.osmf.media.MediaFactoryItem;
import org.osmf.media.MediaFactoryItemType;
import org.osmf.media.MediaResourceBase;
import org.osmf.media.PluginInfo;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
public class HLSPlugin extends PluginInfo {
public function HLSPlugin(items : Vector.<MediaFactoryItem>=null, elementCreatedNotification : Function = null) {
items = new Vector.<MediaFactoryItem>();
items.push(new MediaFactoryItem('org.mangui.osmf.plugins.HLSPlugin', canHandleResource, createMediaElement, MediaFactoryItemType.STANDARD));
super(items, elementCreatedNotification);
}
/**
* Called from super class when plugin has been initialized with the MediaFactory from which it was loaded.
* Used for customize HLSSettings with values provided in resource metadata (that was set eg. in flash vars)
*
* @param resource Provides acces to the resource used to load the plugin and any associated metadata
*
*/
override public function initializePlugin(resource : MediaResourceBase) : void {
CONFIG::LOGGING {
Log.debug("OSMF HLSPlugin init");
}
metadataParamsToHLSSettings(resource);
}
private function canHandleResource(resource : MediaResourceBase) : Boolean {
return HLSLoaderBase.canHandle(resource);
}
private function createMediaElement() : MediaElement {
return new HLSLoadFromDocumentElement(null, new HLSLoaderBase());
}
private function metadataParamsToHLSSettings(resource : MediaResourceBase) : void {
if (resource == null) {
return;
}
var metadataNamespaceURLs : Vector.<String> = resource.metadataNamespaceURLs;
// set all legal params values to HLSSetings properties
for each (var key : String in metadataNamespaceURLs) {
Params2Settings.set(key, resource.getMetadataValue(key));
}
}
}
}
|
/* 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.osmf.plugins {
import org.mangui.hls.utils.Params2Settings;
import org.mangui.osmf.plugins.loader.HLSLoaderBase;
import org.mangui.osmf.plugins.loader.HLSLoadFromDocumentElement;
import org.osmf.media.MediaElement;
import org.osmf.media.MediaFactoryItem;
import org.osmf.media.MediaFactoryItemType;
import org.osmf.media.MediaResourceBase;
import org.osmf.media.PluginInfo;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
public class HLSPlugin extends PluginInfo {
public function HLSPlugin(items : Vector.<MediaFactoryItem>=null, elementCreatedNotification : Function = null) {
items = new Vector.<MediaFactoryItem>();
items.push(new MediaFactoryItem('org.mangui.osmf.plugins.HLSPlugin', canHandleResource, createMediaElement, MediaFactoryItemType.STANDARD));
super(items, elementCreatedNotification);
}
/**
* Called from super class when plugin has been initialized with the MediaFactory from which it was loaded.
* Used for customize HLSSettings with values provided in resource metadata (that was set eg. in flash vars)
*
* @param resource Provides access to the resource used to load the plugin and any associated metadata
*
*/
override public function initializePlugin(resource : MediaResourceBase) : void {
CONFIG::LOGGING {
Log.debug("OSMF HLSPlugin init");
}
metadataParamsToHLSSettings(resource);
}
private function canHandleResource(resource : MediaResourceBase) : Boolean {
return HLSLoaderBase.canHandle(resource);
}
private function createMediaElement() : MediaElement {
return new HLSLoadFromDocumentElement(null, new HLSLoaderBase());
}
private function metadataParamsToHLSSettings(resource : MediaResourceBase) : void {
if (resource == null) {
return;
}
var metadataNamespaceURLs : Vector.<String> = resource.metadataNamespaceURLs;
// set all legal params values to HLSSettings properties
for each (var key : String in metadataNamespaceURLs) {
Params2Settings.set(key, resource.getMetadataValue(key));
}
}
}
}
|
Fix a couple of typos in comments.
|
Fix a couple of typos in comments.
|
ActionScript
|
mpl-2.0
|
neilrackett/flashls,neilrackett/flashls,clappr/flashls,clappr/flashls,mangui/flashls,mangui/flashls
|
552c5b4edf92101086d57f548e7e5a65b1a36e1a
|
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 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;
}
}
}
}
}
|
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);
encoder.dispose(0);
}
[After(ui)]
public function finalize():void {
UIImpersonator.removeAllChildren();
container = null;
trace("");
trace("test::complete " + new Date().toLocaleString());
trace("=======================================================");
sleep(1000);
}
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
|
6fe7c695c0e4f40202095dd4b4724fa7cebb865d
|
src/aerys/minko/render/geometry/primitive/QuadGeometry.as
|
src/aerys/minko/render/geometry/primitive/QuadGeometry.as
|
package aerys.minko.render.geometry.primitive
{
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.geometry.stream.IVertexStream;
import aerys.minko.render.geometry.stream.IndexStream;
import aerys.minko.render.geometry.stream.VertexStream;
import aerys.minko.render.geometry.stream.format.VertexFormat;
public class QuadGeometry extends Geometry
{
private static var _instance : QuadGeometry = null;
public static function get quadGeometry() : QuadGeometry
{
return _instance || (_instance = new QuadGeometry());
}
public function QuadGeometry(doubleSided : Boolean = false,
numColumns : uint = 1,
numRows : uint = 0,
streamsUsage : uint = 0)
{
var vertices : Vector.<Number> = new Vector.<Number>();
var indices : Vector.<uint> = new Vector.<uint>();
numRows ||= numColumns;
for (var y : int = 0; y <= numRows; y++)
{
for (var x : int = 0; x <= numColumns; x++)
{
vertices.push(
x / numColumns - .5, y / numRows - .5, 0.,
x / numColumns, 1. - y / numRows
);
}
}
for (y = 0; y < numRows; y++)
{
for (x = 0; x < numColumns; x++)
{
indices.push(
x + (numColumns + 1) * y,
x + 1 + y * (numColumns + 1),
(y + 1) * (numColumns + 1) + x,
x + 1 + y * (numColumns + 1),
(y + 1) * (numColumns + 1) + x + 1,
(y + 1) * (numColumns + 1) + x
);
}
}
if (doubleSided)
indices = indices.concat(indices.concat().reverse());
var vstream : VertexStream = new VertexStream(
streamsUsage,
VertexFormat.XYZ_UV,
vertices
);
super(
new <IVertexStream>[vstream],
new IndexStream(streamsUsage, indices)
);
}
}
}
|
package aerys.minko.render.geometry.primitive
{
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.geometry.stream.IVertexStream;
import aerys.minko.render.geometry.stream.IndexStream;
import aerys.minko.render.geometry.stream.VertexStream;
import aerys.minko.render.geometry.stream.format.VertexFormat;
public class QuadGeometry extends Geometry
{
private static var _instance : QuadGeometry = null;
private static var _instanceDoubleSided : QuadGeometry = null;
public static function get quadGeometry() : QuadGeometry
{
return _instance || (_instance = new QuadGeometry());
}
public static function get doubleSidedQuadGeometry() : QuadGeometry
{
return _instanceDoubleSided || (_instanceDoubleSided = new QuadGeometry(true));
}
public function QuadGeometry(doubleSided : Boolean = false,
numColumns : uint = 1,
numRows : uint = 0,
streamsUsage : uint = 0)
{
var vertices : Vector.<Number> = new Vector.<Number>();
var indices : Vector.<uint> = new Vector.<uint>();
numRows ||= numColumns;
for (var y : int = 0; y <= numRows; y++)
{
for (var x : int = 0; x <= numColumns; x++)
{
vertices.push(
x / numColumns - .5, y / numRows - .5, 0.,
x / numColumns, 1. - y / numRows
);
}
}
for (y = 0; y < numRows; y++)
{
for (x = 0; x < numColumns; x++)
{
indices.push(
x + (numColumns + 1) * y,
x + 1 + y * (numColumns + 1),
(y + 1) * (numColumns + 1) + x,
x + 1 + y * (numColumns + 1),
(y + 1) * (numColumns + 1) + x + 1,
(y + 1) * (numColumns + 1) + x
);
}
}
if (doubleSided)
indices = indices.concat(indices.concat().reverse());
var vstream : VertexStream = new VertexStream(
streamsUsage,
VertexFormat.XYZ_UV,
vertices
);
super(
new <IVertexStream>[vstream],
new IndexStream(streamsUsage, indices)
);
}
}
}
|
add QuadGeometry.doubleSidedQuadGeometry
|
add QuadGeometry.doubleSidedQuadGeometry
|
ActionScript
|
mit
|
aerys/minko-as3
|
6f358a82c44fd7f7c52f8d09f209396d682f16bd
|
src/com/esri/builder/views/supportClasses/TextFlowUtil.as
|
src/com/esri/builder/views/supportClasses/TextFlowUtil.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.views.supportClasses
{
import com.esri.builder.supportClasses.URLUtil;
import flashx.textLayout.conversion.TextConverter;
import flashx.textLayout.elements.Configuration;
import flashx.textLayout.elements.IConfiguration;
import flashx.textLayout.elements.TextFlow;
import flashx.textLayout.formats.TextDecoration;
import flashx.textLayout.formats.TextLayoutFormat;
import mx.utils.StringUtil;
public class TextFlowUtil
{
public static function toURLFlow(url:String, label:String = null):TextFlow
{
if (!label)
{
label = url;
}
var urlSource:String =
StringUtil.substitute("<a href='{0}'>{1}</a>", URLUtil.encode(url), label);
return TextConverter.importToFlow(urlSource,
TextConverter.TEXT_FIELD_HTML_FORMAT,
getURLConfig());
}
private static function getURLConfig():IConfiguration
{
var config:Configuration = TextFlow.defaultConfiguration;
var activeFormat:TextLayoutFormat = new TextLayoutFormat(config.defaultLinkActiveFormat);
activeFormat.color = 0x000000;
activeFormat.textDecoration = TextDecoration.UNDERLINE;
var hoverFormat:TextLayoutFormat = new TextLayoutFormat(config.defaultLinkHoverFormat);
hoverFormat.color = 0x000000;
hoverFormat.textDecoration = TextDecoration.UNDERLINE;
var normalFormat:TextLayoutFormat = new TextLayoutFormat(config.defaultLinkNormalFormat);
normalFormat.color = 0x007AC2;
normalFormat.textDecoration = TextDecoration.UNDERLINE;
config.defaultLinkActiveFormat = activeFormat;
config.defaultLinkHoverFormat = hoverFormat;
config.defaultLinkNormalFormat = normalFormat;
return config;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
// 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.views.supportClasses
{
import com.esri.builder.supportClasses.URLUtil;
import flashx.textLayout.conversion.TextConverter;
import flashx.textLayout.elements.Configuration;
import flashx.textLayout.elements.IConfiguration;
import flashx.textLayout.elements.TextFlow;
import flashx.textLayout.formats.TextDecoration;
import flashx.textLayout.formats.TextLayoutFormat;
import mx.utils.StringUtil;
public class TextFlowUtil
{
public static function toURLFlow(url:String, label:String = null):TextFlow
{
if (!label)
{
label = url;
}
var urlSource:String =
StringUtil.substitute("<a href='{0}'>{1}</a>", URLUtil.decode(url), label);
return TextConverter.importToFlow(urlSource,
TextConverter.TEXT_FIELD_HTML_FORMAT,
getURLConfig());
}
private static function getURLConfig():IConfiguration
{
var config:Configuration = TextFlow.defaultConfiguration;
var activeFormat:TextLayoutFormat = new TextLayoutFormat(config.defaultLinkActiveFormat);
activeFormat.color = 0x000000;
activeFormat.textDecoration = TextDecoration.UNDERLINE;
var hoverFormat:TextLayoutFormat = new TextLayoutFormat(config.defaultLinkHoverFormat);
hoverFormat.color = 0x000000;
hoverFormat.textDecoration = TextDecoration.UNDERLINE;
var normalFormat:TextLayoutFormat = new TextLayoutFormat(config.defaultLinkNormalFormat);
normalFormat.color = 0x007AC2;
normalFormat.textDecoration = TextDecoration.UNDERLINE;
config.defaultLinkActiveFormat = activeFormat;
config.defaultLinkHoverFormat = hoverFormat;
config.defaultLinkNormalFormat = normalFormat;
return config;
}
}
}
|
Fix double-encoding caused by encoding URL TextFlow.
|
Fix double-encoding caused by encoding URL TextFlow.
|
ActionScript
|
apache-2.0
|
Esri/arcgis-viewer-builder-flex
|
a2e4a47eff38fbf70e659dc39acb94334b6bca25
|
HLSPlugin/src/org/denivip/osmf/elements/m3u8Classes/M3U8PlaylistParser.as
|
HLSPlugin/src/org/denivip/osmf/elements/m3u8Classes/M3U8PlaylistParser.as
|
package org.denivip.osmf.elements.m3u8Classes
{
import flash.events.EventDispatcher;
import org.denivip.osmf.net.HLSDynamicStreamingResource;
import org.osmf.events.ParseEvent;
import org.osmf.logging.Log;
import org.osmf.logging.Logger;
import org.osmf.media.MediaResourceBase;
import org.osmf.media.MediaType;
import org.osmf.media.URLResource;
import org.osmf.metadata.Metadata;
import org.osmf.metadata.MetadataNamespaces;
import org.osmf.net.DynamicStreamingItem;
import org.osmf.net.DynamicStreamingResource;
import org.osmf.net.StreamType;
import org.osmf.net.StreamingItem;
import org.osmf.net.StreamingURLResource;
[Event(name="parseComplete", type="org.osmf.events.ParseEvent")]
[Event(name="parseError", type="org.osmf.events.ParseEvent")]
/**
* You will not belive, but this class parses *.m3u8 playlist
*/
public class M3U8PlaylistParser extends EventDispatcher
{
public function M3U8PlaylistParser(){
// nothing todo here...
}
public function parse(value:String, baseResource:URLResource):void{
if(!value || value == ''){
throw new ArgumentError("Parsed value is missing =(");
}
var lines:Array = value.split(/\r?\n/);
if(lines[0] != '#EXTM3U'){
;
CONFIG::LOGGING
{
logger.warn('Incorrect header! {0}', lines[0]);
}
}
var result:MediaResourceBase;
var isLive:Boolean = true;
var streamItems:Vector.<DynamicStreamingItem>;
var tempStreamingRes:StreamingURLResource = null;
var tempDynamicRes:DynamicStreamingResource = null;
var alternateStreams:Vector.<StreamingItem> = null;
for(var i:int = 1; i < lines.length; i++){
var line:String = String(lines[i]).replace(/^([\s|\t|\n]+)?(.*)([\s|\t|\n]+)?$/gm, "$2");
if(line.indexOf("#EXTINF:") == 0){
result = baseResource;
tempStreamingRes = result as StreamingURLResource;
if(tempStreamingRes && tempStreamingRes.streamType == StreamType.LIVE_OR_RECORDED){
for(var j:int = i+1; j < lines.length; j++){
if(String(lines[j]).indexOf('#EXT-X-ENDLIST') == 0){
isLive = false;
break;
}
}
if(isLive)
tempStreamingRes.streamType = StreamType.LIVE;
}
break;
}
if(line.indexOf("#EXT-X-STREAM-INF:") == 0){
if(!result){
result = new HLSDynamicStreamingResource(baseResource.url);
tempDynamicRes = result as DynamicStreamingResource;
tempStreamingRes = baseResource as StreamingURLResource;
if(tempStreamingRes){
tempDynamicRes.streamType = tempStreamingRes.streamType;
tempDynamicRes.clipStartTime = tempStreamingRes.clipStartTime;
tempDynamicRes.clipEndTime = tempStreamingRes.clipEndTime;
}
streamItems = new Vector.<DynamicStreamingItem>();
}
var bw:Number;
if(line.search(/BANDWIDTH=(\d+)/) > 0)
bw = parseFloat(line.match(/BANDWIDTH=(\d+)/)[1])/1000;
var width:int = -1;
var height:int = -1;
if(line.search(/RESOLUTION=(\d+)x(\d+)/) > 0){
width = parseInt(line.match(/RESOLUTION=(\d+)x(\d+)/)[1]);
height = parseInt(line.match(/RESOLUTION=(\d+)x(\d+)/)[2]);
}
var name:String = lines[i+1];
streamItems.push(new DynamicStreamingItem(name, bw, width, height));
DynamicStreamingResource(result).streamItems = streamItems;
}
if(line.indexOf("#EXT-X-MEDIA:") == 0){
if(line.search(/TYPE=(.*?)\W/) > 0 && line.match(/TYPE=(.*?)\W/)[1] == 'AUDIO'){
var stUrl:String;
var lang:String;
var stName:String;
if(line.search(/URI="(.*?)"/) > 0){
stUrl = line.match(/URI="(.*?)"/)[1];
if(stUrl.search(/(file|https?):\/\//) != 0){
stUrl = baseResource.url.substr(0, baseResource.url.lastIndexOf('/')+1) + stUrl;
}
}
if(line.search(/LANGUAGE="(.*?)"/) > 0){
lang = line.match(/LANGUAGE="(.*?)"/)[1]
}
if(line.search(/NAME="(.*?)"/) > 0){
stName = line.match(/NAME="(.*?)"/)[1];
}
if(!alternateStreams)
alternateStreams = new Vector.<StreamingItem>();
alternateStreams.push(
new StreamingItem(MediaType.AUDIO, stUrl, 0, {label:stName, language:lang})
);
}
}
}
if(tempDynamicRes && tempDynamicRes.streamItems){
if(tempDynamicRes.streamItems.length == 1){
tempStreamingRes = baseResource as StreamingURLResource;
if(tempStreamingRes){
var url:String = tempDynamicRes.host.substr(0, tempDynamicRes.host.lastIndexOf('/')+1) + tempDynamicRes.streamItems[0].streamName;
result = new StreamingURLResource(
url,
tempStreamingRes.streamType,
tempStreamingRes.clipStartTime,
tempStreamingRes.clipEndTime,
tempStreamingRes.connectionArguments,
tempStreamingRes.urlIncludesFMSApplicationInstance,
tempStreamingRes.drmContentData
);
}
}else if(baseResource.getMetadataValue(MetadataNamespaces.RESOURCE_INITIAL_INDEX) != null){
var initialIndex:int = baseResource.getMetadataValue(MetadataNamespaces.RESOURCE_INITIAL_INDEX) as int;
tempDynamicRes.initialIndex = initialIndex < 0 ? 0 : (initialIndex >= tempDynamicRes.streamItems.length) ? (tempDynamicRes.streamItems.length-1) : initialIndex;
}
}
baseResource.addMetadataValue("HLS_METADATA", new Metadata()); // fix for multistreaming resources
result.addMetadataValue("HLS_METADATA", new Metadata());
var httpMetadata:Metadata = new Metadata();
result.addMetadataValue(MetadataNamespaces.HTTP_STREAMING_METADATA, httpMetadata);
if(alternateStreams && result is StreamingURLResource){
(result as StreamingURLResource).alternativeAudioStreamItems = alternateStreams;
}
if(result is StreamingURLResource && StreamingURLResource(result).streamType == StreamType.DVR){
var dvrMetadata:Metadata = new Metadata();
result.addMetadataValue(MetadataNamespaces.DVR_METADATA, dvrMetadata);
}
dispatchEvent(new ParseEvent(ParseEvent.PARSE_COMPLETE, false, false, result));
}
/*
private function addDVRInfo():void{
CONFIG::LOGGING
{
logger.info('DVR!!! \\o/'); // we happy!
}
// black magic...
var dvrInfo:DVRInfo = new DVRInfo();
dvrInfo.id = dvrInfo.url = '';
dvrInfo.isRecording = true; // if live then in process
//dvrInfo.startTime = 0.0;
// attach info into playlist
}
*/
CONFIG::LOGGING
{
private var logger:Logger = Log.getLogger("org.denivip.osmf.elements.m3u8Classes.M3U8PlaylistParser");
}
}
}
|
package org.denivip.osmf.elements.m3u8Classes
{
import flash.events.EventDispatcher;
import org.denivip.osmf.net.HLSDynamicStreamingResource;
import org.osmf.events.ParseEvent;
import org.osmf.logging.Log;
import org.osmf.logging.Logger;
import org.osmf.media.MediaResourceBase;
import org.osmf.media.MediaType;
import org.osmf.media.URLResource;
import org.osmf.metadata.Metadata;
import org.osmf.metadata.MetadataNamespaces;
import org.osmf.net.DynamicStreamingItem;
import org.osmf.net.DynamicStreamingResource;
import org.osmf.net.StreamType;
import org.osmf.net.StreamingItem;
import org.osmf.net.StreamingURLResource;
[Event(name="parseComplete", type="org.osmf.events.ParseEvent")]
[Event(name="parseError", type="org.osmf.events.ParseEvent")]
/**
* You will not belive, but this class parses *.m3u8 playlist
*/
public class M3U8PlaylistParser extends EventDispatcher
{
public function M3U8PlaylistParser(){
// nothing todo here...
}
public function parse(value:String, baseResource:URLResource):void{
if(!value || value == ''){
throw new ArgumentError("Parsed value is missing =(");
}
var lines:Array = value.split(/\r?\n/);
if(lines[0] != '#EXTM3U'){
;
CONFIG::LOGGING
{
logger.warn('Incorrect header! {0}', lines[0]);
}
}
var result:MediaResourceBase;
var isLive:Boolean = true;
var streamItems:Vector.<DynamicStreamingItem>;
var tempStreamingRes:StreamingURLResource = null;
var tempDynamicRes:DynamicStreamingResource = null;
var alternateStreams:Vector.<StreamingItem> = null;
var initialStreamName:String = '';
for(var i:int = 1; i < lines.length; i++){
var line:String = String(lines[i]).replace(/^([\s|\t|\n]+)?(.*)([\s|\t|\n]+)?$/gm, "$2");
if(line.indexOf("#EXTINF:") == 0){
result = baseResource;
tempStreamingRes = result as StreamingURLResource;
if(tempStreamingRes && tempStreamingRes.streamType == StreamType.LIVE_OR_RECORDED){
for(var j:int = i+1; j < lines.length; j++){
if(String(lines[j]).indexOf('#EXT-X-ENDLIST') == 0){
isLive = false;
break;
}
}
if(isLive)
tempStreamingRes.streamType = StreamType.LIVE;
}
break;
}
if(line.indexOf("#EXT-X-STREAM-INF:") == 0){
if(!result){
result = new HLSDynamicStreamingResource(baseResource.url);
tempDynamicRes = result as DynamicStreamingResource;
tempStreamingRes = baseResource as StreamingURLResource;
if(tempStreamingRes){
tempDynamicRes.streamType = tempStreamingRes.streamType;
tempDynamicRes.clipStartTime = tempStreamingRes.clipStartTime;
tempDynamicRes.clipEndTime = tempStreamingRes.clipEndTime;
}
streamItems = new Vector.<DynamicStreamingItem>();
}
var bw:Number;
if(line.search(/BANDWIDTH=(\d+)/) > 0)
bw = parseFloat(line.match(/BANDWIDTH=(\d+)/)[1])/1000;
var width:int = -1;
var height:int = -1;
if(line.search(/RESOLUTION=(\d+)x(\d+)/) > 0){
width = parseInt(line.match(/RESOLUTION=(\d+)x(\d+)/)[1]);
height = parseInt(line.match(/RESOLUTION=(\d+)x(\d+)/)[2]);
}
var name:String = lines[i+1];
streamItems.push(new DynamicStreamingItem(name, bw, width, height));
// store stream name of first stream encountered
if(initialStreamName == ''){
initialStreamName = name;
}
DynamicStreamingResource(result).streamItems = streamItems;
}
if(line.indexOf("#EXT-X-MEDIA:") == 0){
if(line.search(/TYPE=(.*?)\W/) > 0 && line.match(/TYPE=(.*?)\W/)[1] == 'AUDIO'){
var stUrl:String;
var lang:String;
var stName:String;
if(line.search(/URI="(.*?)"/) > 0){
stUrl = line.match(/URI="(.*?)"/)[1];
if(stUrl.search(/(file|https?):\/\//) != 0){
stUrl = baseResource.url.substr(0, baseResource.url.lastIndexOf('/')+1) + stUrl;
}
}
if(line.search(/LANGUAGE="(.*?)"/) > 0){
lang = line.match(/LANGUAGE="(.*?)"/)[1]
}
if(line.search(/NAME="(.*?)"/) > 0){
stName = line.match(/NAME="(.*?)"/)[1];
}
if(!alternateStreams)
alternateStreams = new Vector.<StreamingItem>();
alternateStreams.push(
new StreamingItem(MediaType.AUDIO, stUrl, 0, {label:stName, language:lang})
);
}
}
}
if(tempDynamicRes && tempDynamicRes.streamItems){
if(tempDynamicRes.streamItems.length == 1){
tempStreamingRes = baseResource as StreamingURLResource;
if(tempStreamingRes){
var url:String = tempDynamicRes.host.substr(0, tempDynamicRes.host.lastIndexOf('/')+1) + tempDynamicRes.streamItems[0].streamName;
result = new StreamingURLResource(
url,
tempStreamingRes.streamType,
tempStreamingRes.clipStartTime,
tempStreamingRes.clipEndTime,
tempStreamingRes.connectionArguments,
tempStreamingRes.urlIncludesFMSApplicationInstance,
tempStreamingRes.drmContentData
);
}
}else{
if(baseResource.getMetadataValue(MetadataNamespaces.RESOURCE_INITIAL_INDEX) != null){
var initialIndex:int = baseResource.getMetadataValue(MetadataNamespaces.RESOURCE_INITIAL_INDEX) as int;
tempDynamicRes.initialIndex = initialIndex < 0 ? 0 : (initialIndex >= tempDynamicRes.streamItems.length) ? (tempDynamicRes.streamItems.length-1) : initialIndex;
}else{
// set initialIndex to index of first stream name encountered
tempDynamicRes.initialIndex = tempDynamicRes.indexFromName(initialStreamName);
}
}
}
baseResource.addMetadataValue("HLS_METADATA", new Metadata()); // fix for multistreaming resources
result.addMetadataValue("HLS_METADATA", new Metadata());
var httpMetadata:Metadata = new Metadata();
result.addMetadataValue(MetadataNamespaces.HTTP_STREAMING_METADATA, httpMetadata);
if(alternateStreams && result is StreamingURLResource){
(result as StreamingURLResource).alternativeAudioStreamItems = alternateStreams;
}
if(result is StreamingURLResource && StreamingURLResource(result).streamType == StreamType.DVR){
var dvrMetadata:Metadata = new Metadata();
result.addMetadataValue(MetadataNamespaces.DVR_METADATA, dvrMetadata);
}
dispatchEvent(new ParseEvent(ParseEvent.PARSE_COMPLETE, false, false, result));
}
/*
private function addDVRInfo():void{
CONFIG::LOGGING
{
logger.info('DVR!!! \\o/'); // we happy!
}
// black magic...
var dvrInfo:DVRInfo = new DVRInfo();
dvrInfo.id = dvrInfo.url = '';
dvrInfo.isRecording = true; // if live then in process
//dvrInfo.startTime = 0.0;
// attach info into playlist
}
*/
CONFIG::LOGGING
{
private var logger:Logger = Log.getLogger("org.denivip.osmf.elements.m3u8Classes.M3U8PlaylistParser");
}
}
}
|
Set initial stream to be played to first entry in M3U8 playlist
|
Set initial stream to be played to first entry in M3U8 playlist
According to HLS especficiation we should play initially the first item
in the m3u8 playlist:
"The first entry in the variant playlist is played when a user joins
the stream and is used as part of a test to determine which stream is
most appropriate. The order of the other entries is irrelevant."
from:
https://developer.apple.com/library/mac/documentation/networkinginternet
/conceptual/streamingmediaguide/UsingHTTPLiveStreaming/UsingHTTPLiveStre
aming.html#//apple_ref/doc/uid/TP40008332-CH102-SW18
|
ActionScript
|
isc
|
mruse/osmf-hls-plugin,denivip/osmf-hls-plugin,mruse/osmf-hls-plugin,denivip/osmf-hls-plugin
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.