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
|
---|---|---|---|---|---|---|---|---|---|
ac2108704aefa713573fc381f9d8db52853a4e5c
|
src/aerys/minko/scene/node/Group.as
|
src/aerys/minko/scene/node/Group.as
|
package aerys.minko.scene.node
{
import aerys.minko.ns.minko_scene;
import aerys.minko.scene.SceneIterator;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.type.Signal;
import aerys.minko.type.Sort;
import aerys.minko.type.loader.ILoader;
import aerys.minko.type.loader.SceneLoader;
import aerys.minko.type.loader.parser.ParserOptions;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Ray;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
import flash.utils.getQualifiedClassName;
use namespace minko_scene;
/**
* Group objects can contain other scene nodes and applies a 3D
* transformation to its descendants.
*
* @author Jean-Marc Le Roux
*/
public class Group extends AbstractSceneNode
{
minko_scene var _children : Vector.<ISceneNode> = null;
minko_scene var _numChildren : uint = 0;
private var _numDescendants : uint = 0;
private var _descendantAdded : Signal = new Signal('Group.descendantAdded');
private var _descendantRemoved : Signal = new Signal('Group.descendantRemoved');
/**
* The number of children of the Group.
*/
public function get numChildren() : uint
{
return _numChildren;
}
/**
* The number of descendants of the Group.
*
* @return
*
*/
public function get numDescendants() : uint
{
return _numDescendants;
}
/**
* The signal executed when a descendant is added to the Group.
* Callbacks for this signal must accept the following arguments:
* <ul>
* <li>newParent : Group, the Group the descendant was actually added to</li>
* <li>descendant : ISceneNode, the descendant that was just added</li>
* </ul>
*
* @return
*
*/
public function get descendantAdded() : Signal
{
return _descendantAdded
}
/**
* The signal executed when a descendant is removed from the Group.
* Callbacks for this signal must accept the following arguments:
* <ul>
* <li>oldParent : Group, the Group the descendant was actually removed from</li>
* <li>descendant : ISceneNode, the descendant that was just removed</li>
* </ul>
*
* @return
*
*/
public function get descendantRemoved() : Signal
{
return _descendantRemoved;
}
public function Group(...children)
{
super();
initialize();
initializeChildren(children);
}
private function initialize() : void
{
_children = new <ISceneNode>[];
descendantAdded.add(descendantAddedHandler);
descendantRemoved.add(descendantRemovedHandler);
}
protected function initializeChildren(children : Array) : void
{
while (children.length == 1 && children[0] is Array)
children = children[0];
var childrenNum : uint = children.length;
for (var childrenIndex : uint = 0; childrenIndex < childrenNum; ++childrenIndex)
addChild(ISceneNode(children[childrenIndex]));
}
// override protected function addedHandler(child : ISceneNode, parent : Group) : void
// {
// super.addedHandler(child, parent);
//
// for (var childIndex : int = 0; childIndex < _numChildren; ++childIndex)
// _children[childIndex].added.execute(child, parent);
// }
//
// override protected function removedHandler(child : ISceneNode, parent : Group) : void
// {
// super.removedHandler(child, parent);
//
// for (var childIndex : int = 0; childIndex < _numChildren; ++childIndex)
// _children[childIndex].removed.execute(child, parent);
// }
private function descendantAddedHandler(group : Group, child : ISceneNode) : void
{
if (group == this)
{
var childGroup : Group = child as Group;
if (childGroup)
{
childGroup.descendantAdded.add(_descendantAdded.execute);
childGroup.descendantRemoved.add(_descendantRemoved.execute);
}
}
_numDescendants += (child is Group) ? (child as Group)._numDescendants + 1 : 1;
}
private function descendantRemovedHandler(group : Group, child : ISceneNode) : void
{
if (group == this)
{
var childGroup : Group = child as Group;
if (childGroup)
{
childGroup.descendantAdded.remove(_descendantAdded.execute);
childGroup.descendantRemoved.remove(_descendantRemoved.execute);
}
}
_numDescendants -= (child is Group) ? (child as Group)._numDescendants + 1 : 1;
}
/**
* Return true if the specified scene node is a child of the Group, false otherwise.
*
* @param scene
* @return
*
*/
public function contains(scene : ISceneNode) : Boolean
{
return getChildIndex(scene) >= 0;
}
/**
* Return the index of the speficied scene node or -1 if it is not in the Group.
*
* @param child
* @return
*
*/
public function getChildIndex(child : ISceneNode) : int
{
if (child == null)
throw new Error('The \'child\' parameter cannot be null.');
for (var i : int = 0; i < _numChildren; i++)
if (_children[i] === child)
return i;
return -1;
}
public function getChildByName(name : String) : ISceneNode
{
for (var i : int = 0; i < _numChildren; i++)
if (_children[i].name === name)
return _children[i];
return null;
}
/**
* Add a child to the group.
*
* @param scene The child to add.
*/
public function addChild(node : ISceneNode) : Group
{
return addChildAt(node, _numChildren);
}
/**
* Add a child to the group at the specified position.
*
* @param node
* @param position
* @return
*
*/
public function addChildAt(node : ISceneNode, position : uint) : Group
{
if (!node)
throw new Error('Parameter \'scene\' must not be null.');
node.parent = this;
for (var i : int = _numChildren - 1; i > position; --i)
_children[i] = _children[int(i - 1)];
_children[position] = node;
return this;
}
/**
* Remove a child from the container.
*
* @param myChild The child to remove.
* @return Whether the child was actually removed or not.
*/
public function removeChild(child : ISceneNode) : Group
{
return removeChildAt(getChildIndex(child));
}
public function removeChildAt(position : uint) : Group
{
if (position >= _numChildren || position < 0)
throw new Error('The scene node is not a child of the caller.');
(_children[position] as ISceneNode).parent = null;
return this;
}
/**
* Remove all the children.
*
* @return
*
*/
public function removeAllChildren() : Group
{
while (_numChildren)
removeChildAt(0);
return this;
}
/**
* Return the child at the specified position.
*
* @param position
* @return
*
*/
public function getChildAt(position : uint) : ISceneNode
{
return position < _numChildren ? _children[position] : null;
}
/**
* Returns the list of descendant scene nodes that have the specified type.
*
* @param type
* @param descendants
* @return
*
*/
public function getDescendantsByType(type : Class,
descendants : Vector.<ISceneNode> = null) : Vector.<ISceneNode>
{
descendants ||= new Vector.<ISceneNode>();
for (var i : int = 0; i < _numChildren; ++i)
{
var child : ISceneNode = _children[i];
var group : Group = child as Group;
if (child is type)
descendants.push(child);
if (group)
group.getDescendantsByType(type, descendants);
}
return descendants;
}
public function toString() : String
{
return '[' + getQualifiedClassName(this) + ' ' + name + ']';
}
/**
* Load the 3D scene corresponding to the specified URLRequest object
* and add it directly to the group.
*
* @param request
* @param options
* @return
*
*/
public function load(request : URLRequest,
options : ParserOptions = null) : ILoader
{
var loader : SceneLoader = new SceneLoader(options);
loader.complete.add(loaderCompleteHandler);
loader.load(request);
return loader;
}
/**
* Load the 3D scene corresponding to the specified Class object
* and add it directly to the group.
*
* @param classObject
* @param options
* @return
*/
public function loadClass(classObject : Class,
options : ParserOptions = null) : SceneLoader
{
var loader : SceneLoader = new SceneLoader(options);
loader.complete.add(loaderCompleteHandler);
loader.loadClass(classObject);
return loader;
}
/**
* Load the 3D scene corresponding to the specified ByteArray object
* and add it directly to the group.
*
* @param bytes
* @param options
* @return
*
*/
public function loadBytes(bytes : ByteArray,
options : ParserOptions = null) : ILoader
{
var loader : SceneLoader = new SceneLoader(options);
loader.complete.add(loaderCompleteHandler);
loader.loadBytes(bytes);
return loader;
}
/**
* Return the set of nodes matching the specified XPath query.
*
* @param xpath
* @return
*
*/
public function get(xpath : String) : SceneIterator
{
return new SceneIterator(xpath, new <ISceneNode>[this]);
}
private function loaderCompleteHandler(loader : ILoader,
scene : ISceneNode) : void
{
addChild(scene);
}
/**
* Return all the Mesh objects hit by the specified ray.
*
* @param ray
* @param maxDistance
* @return
*
*/
public function cast(ray : Ray, maxDistance : Number = Number.POSITIVE_INFINITY) : SceneIterator
{
var meshes : Vector.<ISceneNode> = getDescendantsByType(Mesh);
var numMeshes : uint = meshes.length;
var hit : Array = [];
var depth : Vector.<Number> = new <Number>[];
var numItems : uint = 0;
for (var i : uint = 0; i < numMeshes; ++i)
{
var mesh : Mesh = meshes[i] as Mesh;
var hitDepth : Number = mesh.cast(ray, maxDistance);
if (hitDepth >= 0.0)
{
hit[numItems] = mesh;
depth[numItems] = hitDepth;
++numItems;
}
}
if (numItems > 1)
Sort.flashSort(depth, hit, numItems);
return new SceneIterator(null, Vector.<ISceneNode>(hit));
}
override minko_scene function cloneNode() : AbstractSceneNode
{
var clone : Group = new Group();
clone.name = name;
clone.transform.copyFrom(transform);
for (var childId : uint = 0; childId < _numChildren; ++childId)
{
var child : AbstractSceneNode = AbstractSceneNode(_children[childId]);
var clonedChild : AbstractSceneNode = AbstractSceneNode(child.cloneNode());
clone.addChild(clonedChild);
}
return clone;
}
}
}
|
package aerys.minko.scene.node
{
import aerys.minko.ns.minko_scene;
import aerys.minko.scene.SceneIterator;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.type.Signal;
import aerys.minko.type.Sort;
import aerys.minko.type.loader.ILoader;
import aerys.minko.type.loader.SceneLoader;
import aerys.minko.type.loader.parser.ParserOptions;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Ray;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
import flash.utils.getQualifiedClassName;
use namespace minko_scene;
/**
* Group objects can contain other scene nodes and applies a 3D
* transformation to its descendants.
*
* @author Jean-Marc Le Roux
*/
public class Group extends AbstractSceneNode
{
minko_scene var _children : Vector.<ISceneNode> = null;
minko_scene var _numChildren : uint = 0;
private var _numDescendants : uint = 0;
private var _descendantAdded : Signal = new Signal('Group.descendantAdded');
private var _descendantRemoved : Signal = new Signal('Group.descendantRemoved');
/**
* The number of children of the Group.
*/
public function get numChildren() : uint
{
return _numChildren;
}
/**
* The number of descendants of the Group.
*
* @return
*
*/
public function get numDescendants() : uint
{
return _numDescendants;
}
/**
* The signal executed when a descendant is added to the Group.
* Callbacks for this signal must accept the following arguments:
* <ul>
* <li>newParent : Group, the Group the descendant was actually added to</li>
* <li>descendant : ISceneNode, the descendant that was just added</li>
* </ul>
*
* @return
*
*/
public function get descendantAdded() : Signal
{
return _descendantAdded
}
/**
* The signal executed when a descendant is removed from the Group.
* Callbacks for this signal must accept the following arguments:
* <ul>
* <li>oldParent : Group, the Group the descendant was actually removed from</li>
* <li>descendant : ISceneNode, the descendant that was just removed</li>
* </ul>
*
* @return
*
*/
public function get descendantRemoved() : Signal
{
return _descendantRemoved;
}
public function Group(...children)
{
super();
initialize();
initializeChildren(children);
}
private function initialize() : void
{
_children = new <ISceneNode>[];
descendantAdded.add(descendantAddedHandler);
descendantRemoved.add(descendantRemovedHandler);
}
protected function initializeChildren(children : Array) : void
{
while (children.length == 1 && children[0] is Array)
children = children[0];
var childrenNum : uint = children.length;
for (var childrenIndex : uint = 0; childrenIndex < childrenNum; ++childrenIndex)
addChild(ISceneNode(children[childrenIndex]));
}
private function descendantAddedHandler(group : Group, child : ISceneNode) : void
{
if (group == this)
{
var childGroup : Group = child as Group;
if (childGroup)
{
childGroup.descendantAdded.add(_descendantAdded.execute);
childGroup.descendantRemoved.add(_descendantRemoved.execute);
}
}
_numDescendants += (child is Group) ? (child as Group)._numDescendants + 1 : 1;
}
private function descendantRemovedHandler(group : Group, child : ISceneNode) : void
{
if (group == this)
{
var childGroup : Group = child as Group;
if (childGroup)
{
childGroup.descendantAdded.remove(_descendantAdded.execute);
childGroup.descendantRemoved.remove(_descendantRemoved.execute);
}
}
_numDescendants -= (child is Group) ? (child as Group)._numDescendants + 1 : 1;
}
/**
* Return true if the specified scene node is a child of the Group, false otherwise.
*
* @param scene
* @return
*
*/
public function contains(scene : ISceneNode) : Boolean
{
return getChildIndex(scene) >= 0;
}
/**
* Return the index of the speficied scene node or -1 if it is not in the Group.
*
* @param child
* @return
*
*/
public function getChildIndex(child : ISceneNode) : int
{
if (child == null)
throw new Error('The \'child\' parameter cannot be null.');
for (var i : int = 0; i < _numChildren; i++)
if (_children[i] === child)
return i;
return -1;
}
public function getChildByName(name : String) : ISceneNode
{
for (var i : int = 0; i < _numChildren; i++)
if (_children[i].name === name)
return _children[i];
return null;
}
/**
* Add a child to the group.
*
* @param scene The child to add.
*/
public function addChild(node : ISceneNode) : Group
{
return addChildAt(node, _numChildren);
}
/**
* Add a child to the group at the specified position.
*
* @param node
* @param position
* @return
*
*/
public function addChildAt(node : ISceneNode, position : uint) : Group
{
if (!node)
throw new Error('Parameter \'scene\' must not be null.');
node.parent = this;
for (var i : int = _numChildren - 1; i > position; --i)
_children[i] = _children[int(i - 1)];
_children[position] = node;
return this;
}
/**
* Remove a child from the container.
*
* @param myChild The child to remove.
* @return Whether the child was actually removed or not.
*/
public function removeChild(child : ISceneNode) : Group
{
return removeChildAt(getChildIndex(child));
}
public function removeChildAt(position : uint) : Group
{
if (position >= _numChildren || position < 0)
throw new Error('The scene node is not a child of the caller.');
(_children[position] as ISceneNode).parent = null;
return this;
}
/**
* Remove all the children.
*
* @return
*
*/
public function removeAllChildren() : Group
{
while (_numChildren)
removeChildAt(0);
return this;
}
/**
* Return the child at the specified position.
*
* @param position
* @return
*
*/
public function getChildAt(position : uint) : ISceneNode
{
return position < _numChildren ? _children[position] : null;
}
/**
* Returns the list of descendant scene nodes that have the specified type.
*
* @param type
* @param descendants
* @return
*
*/
public function getDescendantsByType(type : Class,
descendants : Vector.<ISceneNode> = null) : Vector.<ISceneNode>
{
descendants ||= new Vector.<ISceneNode>();
for (var i : int = 0; i < _numChildren; ++i)
{
var child : ISceneNode = _children[i];
var group : Group = child as Group;
if (child is type)
descendants.push(child);
if (group)
group.getDescendantsByType(type, descendants);
}
return descendants;
}
public function toString() : String
{
return '[' + getQualifiedClassName(this) + ' ' + name + ']';
}
/**
* Load the 3D scene corresponding to the specified URLRequest object
* and add it directly to the group.
*
* @param request
* @param options
* @return
*
*/
public function load(request : URLRequest,
options : ParserOptions = null) : ILoader
{
var loader : SceneLoader = new SceneLoader(options);
loader.complete.add(loaderCompleteHandler);
loader.load(request);
return loader;
}
/**
* Load the 3D scene corresponding to the specified Class object
* and add it directly to the group.
*
* @param classObject
* @param options
* @return
*/
public function loadClass(classObject : Class,
options : ParserOptions = null) : SceneLoader
{
var loader : SceneLoader = new SceneLoader(options);
loader.complete.add(loaderCompleteHandler);
loader.loadClass(classObject);
return loader;
}
/**
* Load the 3D scene corresponding to the specified ByteArray object
* and add it directly to the group.
*
* @param bytes
* @param options
* @return
*
*/
public function loadBytes(bytes : ByteArray,
options : ParserOptions = null) : ILoader
{
var loader : SceneLoader = new SceneLoader(options);
loader.complete.add(loaderCompleteHandler);
loader.loadBytes(bytes);
return loader;
}
/**
* Return the set of nodes matching the specified XPath query.
*
* @param xpath
* @return
*
*/
public function get(xpath : String) : SceneIterator
{
return new SceneIterator(xpath, new <ISceneNode>[this]);
}
private function loaderCompleteHandler(loader : ILoader,
scene : ISceneNode) : void
{
addChild(scene);
}
/**
* Return all the Mesh objects hit by the specified ray.
*
* @param ray
* @param maxDistance
* @return
*
*/
public function cast(ray : Ray, maxDistance : Number = Number.POSITIVE_INFINITY) : SceneIterator
{
var meshes : Vector.<ISceneNode> = getDescendantsByType(Mesh);
var numMeshes : uint = meshes.length;
var hit : Array = [];
var depth : Vector.<Number> = new <Number>[];
var numItems : uint = 0;
for (var i : uint = 0; i < numMeshes; ++i)
{
var mesh : Mesh = meshes[i] as Mesh;
var hitDepth : Number = mesh.cast(ray, maxDistance);
if (hitDepth >= 0.0)
{
hit[numItems] = mesh;
depth[numItems] = hitDepth;
++numItems;
}
}
if (numItems > 1)
Sort.flashSort(depth, hit, numItems);
return new SceneIterator(null, Vector.<ISceneNode>(hit));
}
override minko_scene function cloneNode() : AbstractSceneNode
{
var clone : Group = new Group();
clone.name = name;
clone.transform.copyFrom(transform);
for (var childId : uint = 0; childId < _numChildren; ++childId)
{
var child : AbstractSceneNode = AbstractSceneNode(_children[childId]);
var clonedChild : AbstractSceneNode = AbstractSceneNode(child.cloneNode());
clone.addChild(clonedChild);
}
return clone;
}
}
}
|
remove dead/commented code
|
remove dead/commented code
|
ActionScript
|
mit
|
aerys/minko-as3
|
4fe22770a2c4be443f4dfdda60b4f4638bfa63ba
|
Impetus.swf/ImpetusSound.as
|
Impetus.swf/ImpetusSound.as
|
package
{
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.net.URLRequest;
public class ImpetusSound
{
private var url:String;
private var sound:Sound;
private var channel:SoundChannel;
private var volume:int;
public function ImpetusSound(url:String, defaultVolume:int):void
{
this.url = url;
this.sound = new Sound();
this.sound.load(new URLRequest(url));
this.channel = null;
this.volume = defaultVolume;
}
public function getUrl():String
{
return this.url
}
public function play(pos:int):void
{
if(this.channel != null)
{
this.channel.stop();
}
this.channel = sound.play(pos);
this.channel.soundTransform = new SoundTransform(this.volume, 0);
}
public function stop():void
{
this.channel.stop();
this.channel = null;
}
public function getPos():int
{
return (this.channel != null)? channel.position : -1;
}
public function setVolume(volume:int):void
{
this.volume = volume;
this.channel.soundTransform = new SoundTransform(this.volume, 0);
}
public function getVolume():int
{
return this.volume;
}
}
}
|
package
{
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.net.URLRequest;
public class ImpetusSound
{
private var url:String;
private var sound:Sound;
private var channel:SoundChannel;
private var volume:int;
private var balance:int;
public function ImpetusSound(url:String, defaultVolume:int):void
{
this.url = url;
this.sound = new Sound();
this.sound.load(new URLRequest(url));
this.channel = null;
this.volume = defaultVolume;
}
public function getUrl():String
{
return this.url
}
public function play(pos:int):void
{
if(this.channel != null)
{
this.channel.stop();
}
this.channel = sound.play(pos);
this.updateTransform();
}
public function stop():void
{
this.channel.stop();
this.channel = null;
}
public function getPos():int
{
return (this.channel != null)? channel.position : -1;
}
public function setVolume(volume:int):void
{
this.volume = volume;
this.updateTransform();
}
public function getVolume():int
{
return this.volume;
}
public function setBalance(balance:int):void
{
this.balance = balance;
this.updateTransform();
}
public function getBalance():int
{
return this.balance;
}
private function updateTransform():void
{
this.channel.soundTransform = new SoundTransform(this.volume, this.balance);
}
}
}
|
Add balance system
|
Add balance system
|
ActionScript
|
mit
|
Julow/Impetus
|
99a16145993037bef4b84ee36b4e9bac7208a813
|
src/org/mangui/hls/demux/DemuxHelper.as
|
src/org/mangui/hls/demux/DemuxHelper.as
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls.demux {
import flash.utils.ByteArray;
import org.mangui.hls.model.Level;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
public class DemuxHelper {
public static function probe(data : ByteArray, level : Level, audioselect : Function, progress : Function, complete : Function, videometadata : Function, id3tagfound : Function, audioOnly : Boolean) : Demuxer {
data.position = 0;
CONFIG::LOGGING {
Log.debug("probe fragment type");
}
var aac_match : Boolean = AACDemuxer.probe(data);
var mp3_match : Boolean = MP3Demuxer.probe(data);
var ts_match : Boolean = TSDemuxer.probe(data);
CONFIG::LOGGING {
Log.debug("AAC/MP3/TS match:" + aac_match + "/" + mp3_match + "/" + ts_match);
}
/* prioritize level info :
* if ts_match && codec_avc => TS demuxer
* if aac_match && codec_aac => AAC demuxer
* if mp3_match && codec_mp3 => MP3 demuxer
* if no codec info in Manifest, use fallback order : AAC/MP3/TS
*/
if (ts_match && level && level.codec_h264) {
CONFIG::LOGGING {
Log.debug("TS match + H264 signaled in Manifest, use TS demuxer");
}
return new TSDemuxer(audioselect, progress, complete, videometadata, audioOnly);
} else if (aac_match && level && level.codec_aac) {
CONFIG::LOGGING {
Log.debug("AAC match + AAC signaled in Manifest, use AAC demuxer");
}
return new AACDemuxer(audioselect, progress, complete, id3tagfound);
} else if (mp3_match && level && level.codec_mp3) {
CONFIG::LOGGING {
Log.debug("MP3 match + MP3 signaled in Manifest, use MP3 demuxer");
}
return new MP3Demuxer(audioselect, progress, complete, id3tagfound);
} else if (aac_match) {
return new AACDemuxer(audioselect, progress, complete, id3tagfound);
} else if (mp3_match) {
return new MP3Demuxer(audioselect, progress, complete, id3tagfound);
} else if (ts_match) {
return new TSDemuxer(audioselect, progress, complete, videometadata, audioOnly);
} else {
CONFIG::LOGGING {
Log.debug("probe fails");
}
return null;
}
}
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls.demux {
import flash.utils.ByteArray;
import org.mangui.hls.model.Level;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
public class DemuxHelper {
public static function probe(data : ByteArray, level : Level, audioselect : Function, progress : Function, complete : Function, videometadata : Function, id3tagfound : Function, audioOnly : Boolean) : Demuxer {
data.position = 0;
CONFIG::LOGGING {
Log.debug("probe fragment type");
}
var aac_match : Boolean = AACDemuxer.probe(data);
var mp3_match : Boolean = MP3Demuxer.probe(data);
var ts_match : Boolean = TSDemuxer.probe(data);
CONFIG::LOGGING {
Log.debug("AAC/MP3/TS match:" + aac_match + "/" + mp3_match + "/" + ts_match);
}
/* prioritize level info :
* if ts_match && codec_avc => TS demuxer
* if aac_match && codec_aac => AAC demuxer
* if mp3_match && codec_mp3 => MP3 demuxer
* if no codec info in Manifest, use fallback order : AAC/MP3/TS
*/
if (ts_match && level.codec_h264) {
CONFIG::LOGGING {
Log.debug("TS match + H264 signaled in Manifest, use TS demuxer");
}
return new TSDemuxer(audioselect, progress, complete, videometadata, audioOnly);
} else if (aac_match && level.codec_aac) {
CONFIG::LOGGING {
Log.debug("AAC match + AAC signaled in Manifest, use AAC demuxer");
}
return new AACDemuxer(audioselect, progress, complete, id3tagfound);
} else if (mp3_match && level.codec_mp3) {
CONFIG::LOGGING {
Log.debug("MP3 match + MP3 signaled in Manifest, use MP3 demuxer");
}
return new MP3Demuxer(audioselect, progress, complete, id3tagfound);
} else if (aac_match) {
return new AACDemuxer(audioselect, progress, complete, id3tagfound);
} else if (mp3_match) {
return new MP3Demuxer(audioselect, progress, complete, id3tagfound);
} else if (ts_match) {
return new TSDemuxer(audioselect, progress, complete, videometadata, audioOnly);
} else {
CONFIG::LOGGING {
Log.debug("probe fails");
}
return null;
}
}
}
}
|
Revert "[Mangui.DemuxHelper] Make probe Level parameter optional"
|
Revert "[Mangui.DemuxHelper] Make probe Level parameter optional"
This reverts commit 3b6ac534dc61f2d9e09b0ed3e15141b1bb25a64b.
|
ActionScript
|
mpl-2.0
|
codex-corp/flashls,codex-corp/flashls
|
9edd0cb4b7c34899a47143f6e9de7592b9fc1258
|
src/org/mangui/HLS/muxing/ID3.as
|
src/org/mangui/HLS/muxing/ID3.as
|
package org.mangui.HLS.muxing {
import flash.utils.ByteArray;
import org.mangui.HLS.utils.Log;
public class ID3
{
public var len:Number;
public var hasTimestamp:Boolean = false;
public var timestamp:Number;
/* create ID3 object by parsing ByteArray, looking for ID3 tag length, and timestamp */
public function ID3(data:ByteArray) {
var tagSize:uint = 0;
try {
var pos:Number = data.position;
do {
if(data.readUTFBytes(3) == 'ID3') {
// skip 24 bits
data.position += 3;
// retrieve tag length
var byte1:uint = data.readUnsignedByte() & 0x7f;
var byte2:uint = data.readUnsignedByte() & 0x7f;
var byte3:uint = data.readUnsignedByte() & 0x7f;
var byte4:uint = data.readUnsignedByte() & 0x7f;
tagSize = (byte1 << 21) + (byte2 << 14) + (byte3 << 7) + byte4;
var end_pos:Number = data.position + tagSize;
// read tag
_parseFrame(data);
data.position = end_pos;
} else {
data.position-=3;
//Log.txt("ID3 len:"+ (data.position-pos));
len = data.position-pos;
return;
}
} while (true);
} catch(e:Error)
{
}
len = 0;
return;
};
/* Each Elementary Audio Stream segment MUST signal the timestamp of
its first sample with an ID3 PRIV tag [ID3] at the beginning of
the segment. The ID3 PRIV owner identifier MUST be
"com.apple.streaming.transportStreamTimestamp". The ID3 payload
MUST be a 33-bit MPEG-2 Program Elementary Stream timestamp
expressed as a big-endian eight-octet number, with the upper 31
bits set to zero.
*/
private function _parseFrame(data:ByteArray):void {
if (data.readUTFBytes(4) == "PRIV") {
var frame_len:uint = data.readUnsignedInt();
// smelling good ! 53 is the size of tag we are looking for
if(frame_len == 53) {
// skip flags (2 bytes)
data.position+=2;
// owner should be "com.apple.streaming.transportStreamTimestamp"
if(data.readUTFBytes(44) == 'com.apple.streaming.transportStreamTimestamp') {
// smelling even better ! we found the right descriptor
// skip null character (string end) + 3 first bytes
data.position+=4;
// timestamp is 33 bit expressed as a big-endian eight-octet number, with the upper 31 bits set to zero.
var pts_33_bit:Number = data.readUnsignedByte() & 0x1;
hasTimestamp = true;
timestamp = (data.readUnsignedInt()/90) << pts_33_bit;
//Log.txt("timestamp found:"+timestamp);
}
}
}
}
}
}
|
package org.mangui.HLS.muxing {
import flash.utils.ByteArray;
//import org.mangui.HLS.utils.Log;
public class ID3
{
public var len:Number;
public var hasTimestamp:Boolean = false;
public var timestamp:Number;
/* create ID3 object by parsing ByteArray, looking for ID3 tag length, and timestamp */
public function ID3(data:ByteArray) {
var tagSize:uint = 0;
try {
var pos:Number = data.position;
do {
if(data.readUTFBytes(3) == 'ID3') {
// skip 24 bits
data.position += 3;
// retrieve tag length
var byte1:uint = data.readUnsignedByte() & 0x7f;
var byte2:uint = data.readUnsignedByte() & 0x7f;
var byte3:uint = data.readUnsignedByte() & 0x7f;
var byte4:uint = data.readUnsignedByte() & 0x7f;
tagSize = (byte1 << 21) + (byte2 << 14) + (byte3 << 7) + byte4;
var end_pos:Number = data.position + tagSize;
// read tag
_parseFrame(data);
data.position = end_pos;
} else {
data.position-=3;
//Log.txt("ID3 len:"+ (data.position-pos));
len = data.position-pos;
return;
}
} while (true);
} catch(e:Error)
{
}
len = 0;
return;
};
/* Each Elementary Audio Stream segment MUST signal the timestamp of
its first sample with an ID3 PRIV tag [ID3] at the beginning of
the segment. The ID3 PRIV owner identifier MUST be
"com.apple.streaming.transportStreamTimestamp". The ID3 payload
MUST be a 33-bit MPEG-2 Program Elementary Stream timestamp
expressed as a big-endian eight-octet number, with the upper 31
bits set to zero.
*/
private function _parseFrame(data:ByteArray):void {
if (data.readUTFBytes(4) == "PRIV") {
var frame_len:uint = data.readUnsignedInt();
// smelling good ! 53 is the size of tag we are looking for
if(frame_len == 53) {
// skip flags (2 bytes)
data.position+=2;
// owner should be "com.apple.streaming.transportStreamTimestamp"
if(data.readUTFBytes(44) == 'com.apple.streaming.transportStreamTimestamp') {
// smelling even better ! we found the right descriptor
// skip null character (string end) + 3 first bytes
data.position+=4;
// timestamp is 33 bit expressed as a big-endian eight-octet number, with the upper 31 bits set to zero.
var pts_33_bit:Number = data.readUnsignedByte() & 0x1;
hasTimestamp = true;
timestamp = (data.readUnsignedInt()/90) << pts_33_bit;
//Log.txt("timestamp found:"+timestamp);
}
}
}
}
}
}
|
remove unused import
|
remove unused import
|
ActionScript
|
mpl-2.0
|
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
|
473dde47921b76bda1d75e65b2f859c5ff12e07b
|
src/avm2/builtin/actionscript.lang.as
|
src/avm2/builtin/actionscript.lang.as
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is [Open Source Virtual Machine.].
*
* The Initial Developer of the Original Code is
* Adobe System Incorporated.
* Portions created by the Initial Developer are Copyright (C) 2004-2006
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adobe AS3 Team
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package
{
public namespace AS3 = "http://adobe.com/AS3/2006/builtin";
// Query whether a particular bugfix is in effect for this object.
// information. Note that we use VM_INTERNAL to hide it from non-builtin code.
public function bugzilla(n:int):Boolean {
return false;
}
/**
* @name Toplevel Function Properties
* Function properties of the global object (ECMA 15.1.2)
*/
// {DontEnum} length=1
[native("decodeURI")]
public native function decodeURI(uri:String="undefined"):String;
// {DontEnum} length=1
[native("decodeURIComponent")]
public native function decodeURIComponent(uri:String="undefined"):String;
// {DontEnum} length=1
[native("encodeURI")]
public native function encodeURI(uri:String="undefined"):String;
// {DontEnum} length=1
[native("encodeURIComponent")]
public native function encodeURIComponent(uri:String="undefined"):String;
// {DontEnum} length=1
[native("isNaN")]
public native function isNaN(n:Number = void 0):Boolean;
// {DontEnum} length=1
[native("isFinite")]
public native function isFinite(n:Number = void 0):Boolean;
// {DontEnum} length=1
[native("parseInt")]
public native function parseInt(s:String = "NaN", radix:int=0):Number;
// {DontEnum} length=1
[native("parseFloat")]
public native function parseFloat(str:String = "NaN"):Number;
/**
* @name ECMA-262 Appendix B.2 extensions
* Extensions to ECMAScript, in ECMA-262 Appendix B.2
*/
// {DontEnum} length=1
[native("escape")]
public native function escape(s:String="undefined"):String;
// {DontEnum} length=1
[native("unescape")]
public native function unescape(s:String="undefined"):String;
// {DontEnum} length=1
[native("isXMLName")]
public native function isXMLName(str=void 0):Boolean; // moved here from XML.as
// value properties of global object (ECMA 15.1.1)
// in E262, these are var {DontEnum,DontDelete} but not ReadOnly
// but in E327, these are {ReadOnly, DontEnum, DontDelete}
// we choose to make them const ala E327
// The initial value of NaN is NaN (section 8.5).
// E262 { DontEnum, DontDelete}
// E327 { DontEnum, DontDelete, ReadOnly}
public const NaN:Number = NaN;
// The initial value of Infinity is +8 (section 8.5).
// E262 { DontEnum, DontDelete}
// E327 { DontEnum, DontDelete, ReadOnly}
public const Infinity:Number = 1/0;
// The initial value of undefined is undefined (section 8.1).
// E262 { DontEnum, DontDelete}
// E327 { DontEnum, DontDelete, ReadOnly}
public const undefined = void 0;
}
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is [Open Source Virtual Machine.].
*
* The Initial Developer of the Original Code is
* Adobe System Incorporated.
* Portions created by the Initial Developer are Copyright (C) 2004-2006
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adobe AS3 Team
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package
{
public namespace AS3 = "http://adobe.com/AS3/2006/builtin";
// Query whether a particular bugfix is in effect for this object.
// information. Note that we use VM_INTERNAL to hide it from non-builtin code.
public function bugzilla(n:int):Boolean {
return false;
}
/**
* @name Toplevel Function Properties
* Function properties of the global object (ECMA 15.1.2)
*/
// {DontEnum} length=1
[native("decodeURI")]
public native function decodeURI(uri:String="undefined"):String;
// {DontEnum} length=1
[native("decodeURIComponent")]
public native function decodeURIComponent(uri:String="undefined"):String;
// {DontEnum} length=1
[native("encodeURI")]
public native function encodeURI(uri:String="undefined"):String;
// {DontEnum} length=1
[native("encodeURIComponent")]
public native function encodeURIComponent(uri:String="undefined"):String;
// {DontEnum} length=1
[native("isNaN")]
public native function isNaN(n:Number = void 0):Boolean;
// {DontEnum} length=1
[native("isFinite")]
public native function isFinite(n:Number = void 0):Boolean;
// {DontEnum} length=1
[native("parseInt")]
public native function parseInt(s:String = "NaN", radix:int=0):Number;
// {DontEnum} length=1
[native("parseFloat")]
public native function parseFloat(str:String = "NaN"):Number;
/**
* @name ECMA-262 Appendix B.2 extensions
* Extensions to ECMAScript, in ECMA-262 Appendix B.2
*/
// {DontEnum} length=1
[native("escape")]
public native function escape(s:String="undefined"):String;
// {DontEnum} length=1
[native("unescape")]
public native function unescape(s:String="undefined"):String;
// {DontEnum} length=1
[native("isXMLName")]
public native function isXMLName(str=void 0):Boolean; // moved here from XML.as
// value properties of global object (ECMA 15.1.1)
// in E262, these are var {DontEnum,DontDelete} but not ReadOnly
// but in E327, these are {ReadOnly, DontEnum, DontDelete}
// we choose to make them const ala E327
// The initial value of NaN is NaN (section 8.5).
// E262 { DontEnum, DontDelete}
// E327 { DontEnum, DontDelete, ReadOnly}
public const NaN:Number = 0/0;
// The initial value of Infinity is +8 (section 8.5).
// E262 { DontEnum, DontDelete}
// E327 { DontEnum, DontDelete, ReadOnly}
public const Infinity:Number = 1/0;
// The initial value of undefined is undefined (section 8.1).
// E262 { DontEnum, DontDelete}
// E327 { DontEnum, DontDelete, ReadOnly}
public const undefined = void 0;
}
|
Fix top-level NaN constant.
|
Fix top-level NaN constant.
|
ActionScript
|
apache-2.0
|
mbebenita/shumway,tschneidereit/shumway,yurydelendik/shumway,mbebenita/shumway,mbebenita/shumway,mozilla/shumway,mozilla/shumway,mozilla/shumway,tschneidereit/shumway,tschneidereit/shumway,mbebenita/shumway,yurydelendik/shumway,yurydelendik/shumway,tschneidereit/shumway,yurydelendik/shumway,yurydelendik/shumway,mbebenita/shumway,mozilla/shumway,yurydelendik/shumway,tschneidereit/shumway,tschneidereit/shumway,tschneidereit/shumway,mbebenita/shumway,tschneidereit/shumway,mozilla/shumway,mozilla/shumway,mozilla/shumway,mozilla/shumway,mbebenita/shumway,mbebenita/shumway,yurydelendik/shumway,yurydelendik/shumway
|
32da3ad433edf282e8b4b3d2bd28fab0e5a658ee
|
src/aerys/minko/render/shader/part/projection/BlinnNewellProjectionShaderPart.as
|
src/aerys/minko/render/shader/part/projection/BlinnNewellProjectionShaderPart.as
|
package aerys.minko.render.shader.part.projection
{
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.render.shader.part.ShaderPart;
import aerys.minko.render.shader.part.coordinates.SphericalCoordinatesShaderPart;
import flash.geom.Rectangle;
/**
* Blinn-Newell projection and deprojection.
* It simply maps spherical coordinates to the plane (theta is x, phi is y).
*
* @author Romain Gilliotte
*/
public class BlinnNewellProjectionShaderPart extends ShaderPart implements IProjectionShaderPart
{
private static const SPHERICAL_COORDINATES_RECTANGLE : Rectangle = new Rectangle(0, 0, 2 * Math.PI, Math.PI);
private var _sphericalPart : SphericalCoordinatesShaderPart;
public function BlinnNewellProjectionShaderPart(main : Shader)
{
super(main);
_sphericalPart = new SphericalCoordinatesShaderPart(main);
}
/**
* Project a vector into a plane with Blinn-Newell projection
*
* @param vector The vector to be projected
* @param target The rectangle to project into. Can be new Rectangle(0, 0, 1, 1) for UV projection, or new Rectangle(-1, -1, 2, 2) for clipspace projection.
* @return The projected vector (is a 3d vector, with depth).
*/
public function projectVector(vector : SFloat,
target : Rectangle,
zNear : Number = 0,
zFar : Number = 1000) : SFloat
{
var sphericalCoordinates : SFloat = _sphericalPart.fromOrtho(vector);
var projectedVector : SFloat = sphericalCoordinates.zy;
return transform2DCoordinates(projectedVector, SPHERICAL_COORDINATES_RECTANGLE, target);
}
/**
* Unproject a vector from a plane with Blinn-Newell projection
*
* @param projectedVector The vector to be unprojected
* @param source The rectangle to unproject from. Should be new Rectangle(0, 0, 1, 1) most of the time (if used to read from a texture).
* @return The unprojected vector (which is normalized).
*/
public function unprojectVector(projectedVector : SFloat,
source : Rectangle) : SFloat
{
var coordinates : SFloat = transform2DCoordinates(projectedVector, source, SPHERICAL_COORDINATES_RECTANGLE);
var unprojectedVector : SFloat = _sphericalPart.toOrtho(float3(1, coordinates.yx));
return unprojectedVector;
}
}
}
|
package aerys.minko.render.shader.part.projection
{
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.render.shader.part.ShaderPart;
import aerys.minko.render.shader.part.coordinates.SphericalCoordinatesShaderPart;
import flash.geom.Rectangle;
/**
* Blinn-Newell projection and deprojection.
* It simply maps spherical coordinates to the plane (theta is x, phi is y).
*
* @author Romain Gilliotte
*/
public class BlinnNewellProjectionShaderPart extends ShaderPart implements IProjectionShaderPart
{
private static const SPHERICAL_COORDINATES_RECTANGLE : Rectangle = new Rectangle(0, 0, 2 * Math.PI, Math.PI);
private var _sphericalPart : SphericalCoordinatesShaderPart;
public function BlinnNewellProjectionShaderPart(main : Shader)
{
super(main);
_sphericalPart = new SphericalCoordinatesShaderPart(main);
}
/**
* Project a vector into a plane with Blinn-Newell projection
*
* @param vector The vector to be projected
* @param target The rectangle to project into. Can be new Rectangle(0, 0, 1, 1) for UV projection, or new Rectangle(-1, -1, 2, 2) for clipspace projection.
* @return The projected vector (is a 3d vector, with depth).
*/
public function projectVector(vector : SFloat,
target : Rectangle,
zNear : Number = 0.,
zFar : Number = 1000.) : SFloat
{
var sphericalCoordinates : SFloat = _sphericalPart.fromOrtho(vector);
var projectedVector : SFloat = sphericalCoordinates.zy;
return transform2DCoordinates(projectedVector, SPHERICAL_COORDINATES_RECTANGLE, target);
}
/**
* Unproject a vector from a plane with Blinn-Newell projection
*
* @param projectedVector The vector to be unprojected
* @param source The rectangle to unproject from. Should be new Rectangle(0, 0, 1, 1) most of the time (if used to read from a texture).
* @return The unprojected vector (which is normalized).
*/
public function unprojectVector(projectedVector : SFloat,
source : Rectangle) : SFloat
{
var coordinates : SFloat = transform2DCoordinates(projectedVector, source, SPHERICAL_COORDINATES_RECTANGLE);
return _sphericalPart.toOrtho(float3(1, coordinates.yx));
}
}
}
|
fix minor coding style issues
|
fix minor coding style issues
|
ActionScript
|
mit
|
aerys/minko-as3
|
510247e755aa4d15eeda594250ea6f46e87d0fb6
|
lib/streamio/Stat.as
|
lib/streamio/Stat.as
|
package streamio
{
import flash.events.*
import flash.net.*
import goplayer.StreamioAPI
public class Stat
{
public static var trackerId:String = "global"
public static function view(movieId:String)
{
update(movieId, "views")
}
public static function play(movieId:String)
{
update(movieId, "plays")
}
public static function heatmap(movieId:String, time:Number)
{
update(movieId, "heat", time)
}
private static function update(movieId:String, event:String, time = null)
{
var params:URLVariables = new URLVariables()
params.movie_id = movieId
params.event = event
params.tracker_id = trackerId
if(time) params.time = time
var request:URLRequest = new URLRequest("http://"+StreamioAPI.host+"/stats")
request.method = URLRequestMethod.POST
request.data = params
var loader:URLLoader = new URLLoader()
loader.load(request)
}
}
}
|
// XXX: Make this file conform to Goplayer code style.
package streamio
{
import flash.events.*
import flash.net.*
import goplayer.StreamioAPI
public class Stat
{
public static var trackerId:String = "global"
public static function view(movieId:String) : void
{
update(movieId, "views")
}
public static function play(movieId:String) : void
{
update(movieId, "plays")
}
public static function heatmap(movieId:String, time:Number) : void
{
update(movieId, "heat", time)
}
private static function update(movieId:String, event:String, time:Number = NaN) : void
{
var params:URLVariables = new URLVariables()
params.movie_id = movieId
params.event = event
params.tracker_id = trackerId
if(!isNaN(time)) params.time = time
var request:URLRequest = new URLRequest("http://"+StreamioAPI.host+"/stats")
request.method = URLRequestMethod.POST
request.data = params
var loader:URLLoader = new URLLoader()
loader.load(request)
}
}
}
|
Fix problems and warnings in Stat.as.
|
Fix problems and warnings in Stat.as.
|
ActionScript
|
mit
|
dbrock/goplayer,dbrock/goplayer
|
3fa6608cecd6cf82cbbc1adb4419790507cf5821
|
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.get = Native.wrap_get;
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);
Frame.prototype.addProperty ("this", Native.frame_this_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);
Breakpoint.prototype.toString = function () {
return "user-defined breakpoint";
};
/*** information about the player ***/
Player = {};
Player.addProperty ("filename", Native.player_filename_get, Native.player_filename_set);
Player.addProperty ("frame", Native.player_frame_get, null);
Player.addProperty ("global", Native.player_global_get, null);
Player.addProperty ("sound", Native.player_sound_get, Native.player_sound_set);
Player.addProperty ("variables", Native.player_variables_get, Native.player_variables_set);
/*** commands available for debugging ***/
Commands = new Object ();
Commands.print = Native.print;
Commands.error = Native.error;
Commands.r = Native.run;
Commands.run = Native.run;
Commands.halt = Native.stop;
Commands.stop = Native.stop;
Commands.s = Native.step;
Commands.step = Native.step;
Commands.reset = Native.reset;
Commands.restart = function () {
Commands.reset ();
Commands.run ();
};
Commands.quit = Native.quit;
/* can't use "break" as a function name, it's a keyword in JS */
Commands.add = function (name) {
if (name == undefined) {
Commands.error ("add command requires a function name");
return undefined;
}
var ret = new Breakpoint ();
ret.onEnterFrame = function (frame) {
if (frame.name != name)
return false;
Commands.print ("Breakpoint: function " + name + " called");
Commands.print (" " + frame);
return true;
};
ret.toString = function () {
return "function call " + name;
};
return ret;
};
Commands.list = function () {
var a = Breakpoint.list;
var i;
for (i = 0; i < a.length; i++) {
Commands.print (i + ": " + a[i]);
}
};
Commands.del = function (id) {
var a = Breakpoint.list;
if (id == undefined) {
while (a[0])
Commands.del (0);
}
var b = a[id];
a.splice (id, 1);
b.active = false;
};
Commands.delete = Commands.del;
Commands.where = function () {
var frame = Player.frame;
if (frame == undefined) {
Commands.print ("---");
return;
}
var i = 0;
while (frame) {
Commands.print (i++ + ": " + frame);
frame = frame.next;
}
};
Commands.backtrace = Commands.where;
Commands.bt = Commands.where;
Commands.watch = function () {
var object;
var name;
if (arguments.length == 1) {
name = arguments[0];
} else if (arguments.length == 2) {
object = arguments[0];
name = arguments[1];
} else {
Commands.error ("usage: watch [object] name");
return;
}
var ret = new Breakpoint ();
ret.onSetVariable = function (o, variable, value) {
if (object && o != object)
return false;
if (variable != name)
return;
if (object) {
Commands.print ("Breakpoint: variable " + name + " on " + object);
} else {
Commands.print ("Breakpoint: variable " + name);
}
Commands.print (" " + Player.frame);
return true;
};
ret.toString = function () {
var s = "watch " + name;
if (object)
s += " on " + object;
return s;
};
return ret;
};
|
/* 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.get = Native.wrap_get;
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);
Frame.prototype.addProperty ("this", Native.frame_this_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);
Breakpoint.prototype.toString = function () {
return "user-defined breakpoint";
};
/*** information about the player ***/
Player = {};
Player.addProperty ("filename", Native.player_filename_get, Native.player_filename_set);
Player.addProperty ("frame", Native.player_frame_get, null);
Player.addProperty ("global", Native.player_global_get, null);
Player.addProperty ("sound", Native.player_sound_get, Native.player_sound_set);
Player.addProperty ("variables", Native.player_variables_get, Native.player_variables_set);
/*** commands available for debugging ***/
Commands = new Object ();
Commands.print = Native.print;
Commands.error = Native.error;
Commands.r = Native.run;
Commands.run = Native.run;
Commands.halt = Native.stop;
Commands.stop = Native.stop;
Commands.s = Native.step;
Commands.step = Native.step;
Commands.reset = Native.reset;
Commands.restart = function () {
Commands.reset ();
Commands.run ();
};
Commands.quit = Native.quit;
/* can't use "break" as a function name, it's a keyword in JS */
Commands.add = function (name) {
if (name == undefined) {
Commands.error ("add command requires a function name");
return undefined;
}
var ret = new Breakpoint ();
ret.onEnterFrame = function (frame) {
if (frame.name != name)
return false;
Commands.print ("Breakpoint: function " + name + " called");
Commands.print (" " + frame);
return true;
};
ret.toString = function () {
return "function call " + name;
};
return ret;
};
Commands.list = function () {
var a = Breakpoint.list;
var i;
for (i = 0; i < a.length; i++) {
Commands.print (i + ": " + a[i]);
}
};
Commands.del = function (id) {
var a = Breakpoint.list;
if (id == undefined) {
while (a[0])
Commands.del (0);
}
var b = a[id];
a.splice (id, 1);
b.active = false;
};
Commands.delete = Commands.del;
Commands.where = function () {
var frame = Player.frame;
if (frame == undefined) {
Commands.print ("---");
return;
}
var i = 0;
while (frame) {
Commands.print (i++ + ": " + frame);
frame = frame.next;
}
};
Commands.backtrace = Commands.where;
Commands.bt = Commands.where;
Commands.watch = function () {
var object;
var name;
if (arguments.length == 1) {
name = arguments[0];
} else if (arguments.length == 2) {
object = arguments[0];
name = arguments[1];
} else {
Commands.error ("usage: watch [object] name");
return;
}
var ret = new Breakpoint ();
ret.onSetVariable = function (o, variable, value) {
if (object && o != object)
return false;
if (variable != name)
return;
if (object) {
Commands.print ("Breakpoint: variable " + name + " on " + object + " set to: " + value);
} else {
Commands.print ("Breakpoint: variable " + name + " set to: " + value);
}
Commands.print (" " + Player.frame);
return true;
};
ret.toString = function () {
var s = "watch " + name;
if (object)
s += " on " + object;
return s;
};
return ret;
};
|
print the value the variable will be set to
|
print the value the variable will be set to
|
ActionScript
|
lgpl-2.1
|
mltframework/swfdec,freedesktop-unofficial-mirror/swfdec__swfdec,mltframework/swfdec,freedesktop-unofficial-mirror/swfdec__swfdec,freedesktop-unofficial-mirror/swfdec__swfdec
|
dabfe03e024e9f940391f2b5c8c5ed1df1bb6251
|
RTMFPSocket.as
|
RTMFPSocket.as
|
/*
The RTMFPSocket class provides a socket-like interface around RTMFP
NetConnection and NetStream. Each RTMFPSocket contains one NetConnection and two
NetStreams, one for reading and one for writing.
To create a listening socket:
var rs:RTMFPSocket = new RTMFPSocket(url, key);
rs.addEventListener(Event.COMPLETE, function (e:Event):void {
// rs.id is set and can be sent out of band to the client.
});
rs.addEventListener(RTMFPSocket.ACCEPT_EVENT, function (e:Event):void {
// rs.peer_id is the ID of the connected client.
});
rs.listen();
To connect to a listening socket:
// Receive peer_id out of band.
var rs:RTMFPSocket = new RTMFPSocket(url, key);
rs.addEventListener(Event.CONNECT, function (e:Event):void {
// rs.id and rs.peer_id are now set.
});
*/
package
{
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.NetStatusEvent;
import flash.events.ProgressEvent;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.utils.ByteArray;
public class RTMFPSocket extends EventDispatcher
{
public static const ACCEPT_EVENT:String = "accept";
public var connected:Boolean;
private var nc:NetConnection;
private var incoming:NetStream;
private var outgoing:NetStream;
/* Cache to hold the peer ID between when connect is called and the
NetConnection exists. */
private var connect_peer_id:String;
private var buffer:ByteArray;
private var cirrus_url:String;
private var cirrus_key:String;
public function RTMFPSocket(cirrus_url:String, cirrus_key:String = "")
{
connected = false;
buffer = new ByteArray();
this.cirrus_url = cirrus_url;
this.cirrus_key = cirrus_key;
nc = new NetConnection();
}
public function get id():String
{
return nc.nearID;
}
public function get peer_id():String
{
return incoming.farID;
}
/* NetStatusEvents that aren't handled more specifically in
listen_netstatus_event or connect_netstatus_event. */
private function generic_netstatus_event(e:NetStatusEvent):void
{
switch (e.info.code) {
case "NetConnection.Connect.Closed":
dispatchEvent(new Event(Event.CLOSE));
break;
case "NetStream.Connect.Closed":
connected = false;
close();
break;
default:
var event:IOErrorEvent = new IOErrorEvent(IOErrorEvent.IO_ERROR);
event.text = e.info.code;
dispatchEvent(event);
break;
}
}
private function listen_netstatus_event(e:NetStatusEvent):void
{
switch (e.info.code) {
case "NetConnection.Connect.Success":
outgoing = new NetStream(nc, NetStream.DIRECT_CONNECTIONS);
outgoing.client = {
onPeerConnect: listen_onpeerconnect
};
outgoing.publish("server");
/* listen is complete, ready to accept. */
dispatchEvent(new Event(Event.COMPLETE));
break;
case "NetStream.Connect.Success":
break;
default:
return generic_netstatus_event(e);
break;
}
}
private function listen_onpeerconnect(peer:NetStream):Boolean {
incoming = new NetStream(nc, peer.farID);
incoming.client = {
r: receive_data
};
incoming.play("client");
connected = true;
dispatchEvent(new Event(ACCEPT_EVENT));
return true;
}
private function connect_netstatus_event(e:NetStatusEvent):void
{
switch (e.info.code) {
case "NetConnection.Connect.Success":
outgoing = new NetStream(nc, NetStream.DIRECT_CONNECTIONS);
outgoing.publish("client");
incoming = new NetStream(nc, connect_peer_id);
incoming.client = {
r: receive_data
};
incoming.play("server");
break;
case "NetStream.Connect.Success":
connected = true;
dispatchEvent(new Event(Event.CONNECT));
break;
default:
return generic_netstatus_event(e);
break;
}
}
/* Function called back when the other side does a send. */
private function receive_data(bytes:ByteArray):void {
var event:ProgressEvent;
event = new ProgressEvent(ProgressEvent.SOCKET_DATA);
event.bytesLoaded = bytes.bytesAvailable;
bytes.readBytes(buffer, buffer.length, bytes.bytesAvailable);
dispatchEvent(event);
}
public function listen():void
{
nc.addEventListener(NetStatusEvent.NET_STATUS, listen_netstatus_event);
nc.connect(cirrus_url, cirrus_key);
}
public function connect(peer_id:String):void
{
/* Store for later reading by connect_netstatus_event. */
this.connect_peer_id = peer_id;
nc.addEventListener(NetStatusEvent.NET_STATUS, connect_netstatus_event);
nc.connect(cirrus_url, cirrus_key);
}
public function close():void
{
if (outgoing)
outgoing.close();
if (incoming)
incoming.close();
if (nc)
nc.close();
}
public function readBytes(output:ByteArray, offset:uint = 0, length:uint = 0):void
{
buffer.readBytes(output, offset, length);
if (buffer.bytesAvailable == 0) {
/* Reclaim memory space. */
buffer.position = 0;
buffer.length = 0;
}
}
public function writeBytes(input:ByteArray, offset:uint = 0, length:uint = 0):void
{
var sendbuf:ByteArray;
/* Read into a new buffer, in case offset and length do not
completely span input. */
sendbuf = new ByteArray();
sendbuf.writeBytes(input, offset, length);
/* Use a short method name because it's sent over the wire. */
outgoing.send("r", sendbuf);
}
public function flush():void
{
/* Ignored. */
}
}
}
|
/*
The RTMFPSocket class provides a socket-like interface around RTMFP
NetConnection and NetStream. Each RTMFPSocket contains one NetConnection and two
NetStreams, one for reading and one for writing.
To create a listening socket:
var rs:RTMFPSocket = new RTMFPSocket(url, key);
rs.addEventListener(Event.COMPLETE, function (e:Event):void {
// rs.id is set and can be sent out of band to the client.
});
rs.addEventListener(RTMFPSocket.ACCEPT_EVENT, function (e:Event):void {
// rs.peer_id is the ID of the connected client.
});
rs.listen();
To connect to a listening socket:
// Receive peer_id out of band.
var rs:RTMFPSocket = new RTMFPSocket(url, key);
rs.addEventListener(Event.CONNECT, function (e:Event):void {
// rs.id and rs.peer_id are now set.
});
*/
package
{
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.NetStatusEvent;
import flash.events.ProgressEvent;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.utils.ByteArray;
public class RTMFPSocket extends EventDispatcher
{
public static const ACCEPT_EVENT:String = "accept";
public var connected:Boolean;
private var nc:NetConnection;
private var incoming:NetStream;
private var outgoing:NetStream;
/* Cache to hold the peer ID between when connect is called and the
NetConnection exists. */
private var connect_peer_id:String;
private var buffer:ByteArray;
private var cirrus_url:String;
private var cirrus_key:String;
public function RTMFPSocket(cirrus_url:String, cirrus_key:String = "")
{
connected = false;
buffer = new ByteArray();
this.cirrus_url = cirrus_url;
this.cirrus_key = cirrus_key;
nc = new NetConnection();
}
public function get id():String
{
return nc.nearID;
}
public function get peer_id():String
{
return incoming.farID;
}
/* NetStatusEvents that aren't handled more specifically in
listen_netstatus_event or connect_netstatus_event. */
private function generic_netstatus_event(e:NetStatusEvent):void
{
switch (e.info.code) {
case "NetConnection.Connect.Closed":
connected = false;
dispatchEvent(new Event(Event.CLOSE));
break;
case "NetStream.Connect.Closed":
connected = false;
close();
break;
default:
var event:IOErrorEvent = new IOErrorEvent(IOErrorEvent.IO_ERROR);
event.text = e.info.code;
dispatchEvent(event);
break;
}
}
private function listen_netstatus_event(e:NetStatusEvent):void
{
switch (e.info.code) {
case "NetConnection.Connect.Success":
outgoing = new NetStream(nc, NetStream.DIRECT_CONNECTIONS);
outgoing.client = {
onPeerConnect: listen_onpeerconnect
};
outgoing.publish("server");
/* listen is complete, ready to accept. */
dispatchEvent(new Event(Event.COMPLETE));
break;
case "NetStream.Connect.Success":
break;
default:
return generic_netstatus_event(e);
break;
}
}
private function listen_onpeerconnect(peer:NetStream):Boolean {
incoming = new NetStream(nc, peer.farID);
incoming.client = {
r: receive_data
};
incoming.play("client");
connected = true;
dispatchEvent(new Event(ACCEPT_EVENT));
return true;
}
private function connect_netstatus_event(e:NetStatusEvent):void
{
switch (e.info.code) {
case "NetConnection.Connect.Success":
outgoing = new NetStream(nc, NetStream.DIRECT_CONNECTIONS);
outgoing.publish("client");
incoming = new NetStream(nc, connect_peer_id);
incoming.client = {
r: receive_data
};
incoming.play("server");
break;
case "NetStream.Connect.Success":
connected = true;
dispatchEvent(new Event(Event.CONNECT));
break;
default:
return generic_netstatus_event(e);
break;
}
}
/* Function called back when the other side does a send. */
private function receive_data(bytes:ByteArray):void {
var event:ProgressEvent;
event = new ProgressEvent(ProgressEvent.SOCKET_DATA);
event.bytesLoaded = bytes.bytesAvailable;
bytes.readBytes(buffer, buffer.length, bytes.bytesAvailable);
dispatchEvent(event);
}
public function listen():void
{
nc.addEventListener(NetStatusEvent.NET_STATUS, listen_netstatus_event);
nc.connect(cirrus_url, cirrus_key);
}
public function connect(peer_id:String):void
{
/* Store for later reading by connect_netstatus_event. */
this.connect_peer_id = peer_id;
nc.addEventListener(NetStatusEvent.NET_STATUS, connect_netstatus_event);
nc.connect(cirrus_url, cirrus_key);
}
public function close():void
{
if (outgoing)
outgoing.close();
if (incoming)
incoming.close();
if (nc)
nc.close();
}
public function readBytes(output:ByteArray, offset:uint = 0, length:uint = 0):void
{
buffer.readBytes(output, offset, length);
if (buffer.bytesAvailable == 0) {
/* Reclaim memory space. */
buffer.position = 0;
buffer.length = 0;
}
}
public function writeBytes(input:ByteArray, offset:uint = 0, length:uint = 0):void
{
var sendbuf:ByteArray;
/* Read into a new buffer, in case offset and length do not
completely span input. */
sendbuf = new ByteArray();
sendbuf.writeBytes(input, offset, length);
/* Use a short method name because it's sent over the wire. */
outgoing.send("r", sendbuf);
}
public function flush():void
{
/* Ignored. */
}
}
}
|
Reset the "connected" property on NetConnection.Connect.Closed.
|
Reset the "connected" property on NetConnection.Connect.Closed.
|
ActionScript
|
mit
|
infinity0/flashproxy,infinity0/flashproxy,infinity0/flashproxy,arlolra/flashproxy,arlolra/flashproxy,arlolra/flashproxy,arlolra/flashproxy,arlolra/flashproxy,glamrock/flashproxy,infinity0/flashproxy,glamrock/flashproxy,glamrock/flashproxy,glamrock/flashproxy,glamrock/flashproxy,infinity0/flashproxy,arlolra/flashproxy,arlolra/flashproxy,glamrock/flashproxy,infinity0/flashproxy
|
8d68d025912b7563318979b2464f9c7f8ea85fd6
|
src/aerys/minko/scene/controller/AbstractController.as
|
src/aerys/minko/scene/controller/AbstractController.as
|
package aerys.minko.scene.controller
{
import aerys.minko.ns.minko_scene;
import aerys.minko.render.Viewport;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.Signal;
import flash.display.BitmapData;
import flash.utils.getQualifiedClassName;
/**
* Controllers work on scene nodes to modify and update them. They offer the best
* way to add any kind of behavior on one or multiple scene nodes. They can be used
* to create animations, add physics, artificial intelligence...
*
* @author Jean-Marc Le Roux
*
*/
public class AbstractController
{
private var _targetType : Class = null;
private var _targets : Vector.<ISceneNode> = new <ISceneNode>[];
private var _ticked : Signal = new Signal('AbstractController.ticked');
private var _targetAdded : Signal = new Signal('AbstractController.targetAdded');
private var _targetRemoved : Signal = new Signal('AbstractController.targetRemoved');
/**
* The number of scene nodes targeted by this very controller.
* @return
*
*/
public function get numTargets() : uint
{
return _targets.length;
}
/**
* The signal executed when a target is added to the controller.
* @return
*
*/
public function get targetAdded() : Signal
{
return _targetAdded;
}
/**
* The signal executed when a target is removed from the controller.
* @return
*
*/
public function get targetRemoved() : Signal
{
return _targetRemoved;
}
public function AbstractController(targetType : Class = null)
{
_targetType = targetType || ISceneNode;
}
/**
* Add a target to the controller.
* @param target
*
*/
minko_scene function addTarget(target : ISceneNode) : void
{
if (_targetType && !(target is _targetType))
{
throw new Error(
"Controller '" + getQualifiedClassName(this)
+ " cannot target objects from class '"
+ getQualifiedClassName(target) + "'."
);
}
_targets.push(target);
_targetAdded.execute(this, target);
}
/**
* Remove a target from the controller.
* @param target
*
*/
minko_scene function removeTarget(target : ISceneNode) : void
{
var index : int = _targets.indexOf(target);
var numTargets : int = _targets.length - 1;
if (index < 0)
throw new Error();
_targets[index] = _targets[numTargets];
_targets.length = numTargets;
_targetRemoved.execute(this, target);
}
/**
* Get the target at the specified index.
* @param index
* @return
*
*/
public function getTarget(index : uint) : ISceneNode
{
return _targets[index];
}
public function clone() : AbstractController
{
throw new Error("The method AbstractController.clone() must be overriden.");
}
}
}
|
package aerys.minko.scene.controller
{
import aerys.minko.ns.minko_scene;
import aerys.minko.render.Viewport;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.Signal;
import flash.display.BitmapData;
import flash.utils.getQualifiedClassName;
/**
* Controllers work on scene nodes to modify and update them. They offer the best
* way to add any kind of behavior on one or multiple scene nodes. They can be used
* to create animations, add physics, artificial intelligence...
*
* @author Jean-Marc Le Roux
*
*/
public class AbstractController
{
private var _targetType : Class = null;
private var _targets : Vector.<ISceneNode> = new <ISceneNode>[];
private var _targetAdded : Signal = new Signal('AbstractController.targetAdded');
private var _targetRemoved : Signal = new Signal('AbstractController.targetRemoved');
/**
* The number of scene nodes targeted by this very controller.
* @return
*
*/
public function get numTargets() : uint
{
return _targets.length;
}
/**
* The signal executed when a target is added to the controller.
* @return
*
*/
public function get targetAdded() : Signal
{
return _targetAdded;
}
/**
* The signal executed when a target is removed from the controller.
* @return
*
*/
public function get targetRemoved() : Signal
{
return _targetRemoved;
}
public function AbstractController(targetType : Class = null)
{
_targetType = targetType || ISceneNode;
}
/**
* Add a target to the controller.
* @param target
*
*/
minko_scene function addTarget(target : ISceneNode) : void
{
if (_targetType && !(target is _targetType))
{
throw new Error(
"Controller '" + getQualifiedClassName(this)
+ " cannot target objects from class '"
+ getQualifiedClassName(target) + "'."
);
}
_targets.push(target);
_targetAdded.execute(this, target);
}
/**
* Remove a target from the controller.
* @param target
*
*/
minko_scene function removeTarget(target : ISceneNode) : void
{
var index : int = _targets.indexOf(target);
var numTargets : int = _targets.length - 1;
if (index < 0)
throw new Error();
_targets[index] = _targets[numTargets];
_targets.length = numTargets;
_targetRemoved.execute(this, target);
}
/**
* Get the target at the specified index.
* @param index
* @return
*
*/
public function getTarget(index : uint) : ISceneNode
{
return _targets[index];
}
public function clone() : AbstractController
{
throw new Error("The method AbstractController.clone() must be overriden.");
}
}
}
|
remove deprecated AbstractController._ticked : Signal
|
remove deprecated AbstractController._ticked : Signal
|
ActionScript
|
mit
|
aerys/minko-as3
|
ab59c19e1b31a281e652d2d80490be4b52c9d18d
|
src/com/google/analytics/utils/Environment.as
|
src/com/google/analytics/utils/Environment.as
|
/*
* Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributor(s):
* Zwetan Kjukov <[email protected]>.
* Marc Alcaraz <[email protected]>.
*/
package com.google.analytics.utils
{
import core.strings.userAgent;
import com.google.analytics.core.ga_internal;
import com.google.analytics.debug.DebugConfiguration;
import com.google.analytics.external.HTMLDOM;
import flash.system.Capabilities;
import flash.system.Security;
import flash.system.System;
/**
* Environment provides informations for the local environment.
*/
public class Environment
{
private var _debug:DebugConfiguration;
private var _dom:HTMLDOM;
private var _protocol:Protocols;
private var _appName:String;
private var _appVersion:Version;
private var _userAgent:String;
private var _url:String;
/**
* Creates a new Environment instance.
* @param url The URL of the SWF.
* @param app The application name
* @param version The application version
* @param dom the HTMLDOM reference.
*/
public function Environment( url:String = "", app:String = "", version:String = "",
debug:DebugConfiguration = null, dom:HTMLDOM = null )
{
var v:Version;
if( app == "" )
{
if( isAIR() )
{
app = "AIR";
}
else
{
app = "Flash";
}
}
if( version == "" )
{
v = flashVersion;
}
else
{
v = Version.fromString( version );
}
_url = url;
_appName = app;
_appVersion = v;
_debug = debug;
_dom = dom;
}
/**
* @private
*/
private function _findProtocol():void
{
var p:Protocols = Protocols.none;
if(_url != "")
{
// file://
// http://
// https://
var URL:String = _url.toLowerCase();
var test:String = URL.substr(0,5);
switch( test )
{
case "file:":
{
p = Protocols.file;
break;
}
case "http:":
{
p = Protocols.HTTP;
break;
}
case "https":
{
if(URL.charAt(5) == ":")
{
p = Protocols.HTTPS;
}
break;
}
default:
{
_protocol = Protocols.none;
}
}
}
/*TODO:
if _url is not found (if someone forgot to add the tracker to the display list)
we could use the alternative to get the dom.location and find the protocol from that string
off course only if we have access to ExternalInterface
*/
var _proto:String = _dom.protocol;
var proto:String = (p.toString()+":").toLowerCase();
if( _proto && _proto != proto && _debug )
{
_debug.warning( "Protocol mismatch: SWF="+proto+", DOM="+_proto );
}
_protocol = p;
}
/**
* Indicates the name of the application.
*/
public function get appName():String
{
return _appName;
}
/**
* @private
*/
public function set appName( value:String ):void
{
_appName = value;
_defineUserAgent();
}
/**
* Indicates the version of the application.
*/
public function get appVersion():Version
{
return _appVersion;
}
/**
* @private
*/
public function set appVersion( value:Version ):void
{
_appVersion = value;
_defineUserAgent();
}
/**
* Sets the stage reference value of the application.
*/
ga_internal function set url( value:String ):void
{
_url = value;
}
/**
* Indicates the location of swf.
*/
public function get locationSWFPath():String
{
return _url;
}
/**
* Indicates the referrer value.
*/
public function get referrer():String
{
var _referrer:String = _dom.referrer;
if( _referrer )
{
return _referrer;
}
if( protocol == Protocols.file )
{
return "localhost";
}
return "";
}
/**
* Indicates the title of the document.
*/
public function get documentTitle():String
{
var _title:String = _dom.title;
if( _title )
{
return _title;
}
return "";
}
/**
* Indicates the local domain name value.
*/
public function get domainName():String
{
if( protocol == Protocols.HTTP ||
protocol == Protocols.HTTPS )
{
var URL:String = _url.toLowerCase();
var str:String;
var end:int;
if( protocol == Protocols.HTTP )
{
str = URL.split( "http://" ).join( "" );
}
else if( protocol == Protocols.HTTPS )
{
str = URL.split( "https://" ).join( "" );
}
end = str.indexOf( "/" );
if( end > -1 )
{
str = str.substring(0,end);
}
return str;
}
if( protocol == Protocols.file )
{
return "localhost";
}
return "";
}
/**
* Indicates if the application is running in AIR.
*/
public function isAIR():Boolean
{
//return (playerType == "Desktop") && (Security.sandboxType.toString() == "application");
return Security.sandboxType == "application";
}
/**
* Indicates if the SWF is embeded in an HTML page.
* @return <code class="prettyprint">true</code> if the SWF is embeded in an HTML page.
*/
public function isInHTML():Boolean
{
return Capabilities.playerType == "PlugIn" ;
}
/**
* Indicates the locationPath value.
*/
public function get locationPath():String
{
var _pathname:String = _dom.pathname;
if( _pathname )
{
return _pathname;
}
return "";
}
/**
* Indicates the locationSearch value.
*/
public function get locationSearch():String
{
var _search:String = _dom.search;
if( _search )
{
return _search;
}
return "";
}
/**
* Returns the flash version object representation of the application.
* <p>This object contains the attributes major, minor, build and revision :</p>
* <p><b>Example :</b></b>
* <pre class="prettyprint">
* import com.google.analytics.utils.Environment ;
*
* var info:Environment = new Environment( "http://www.domain.com" ) ;
* var version:Object = info.flashVersion ;
*
* trace( version.major ) ; // 9
* trace( version.minor ) ; // 0
* trace( version.build ) ; // 124
* trace( version.revision ) ; // 0
* </pre>
* @return the flash version object representation of the application.
*/
public function get flashVersion():Version
{
var v:Version = Version.fromString( Capabilities.version.split( " " )[1], "," ) ;
return v ;
}
/**
* Returns the language string as a lowercase two-letter language code from ISO 639-1.
* @see Capabilities.language
*/
public function get language():String
{
var _lang:String = _dom.language;
var lang:String = Capabilities.language;
if( _lang )
{
if( (_lang.length > lang.length) &&
(_lang.substr(0,lang.length) == lang) )
{
lang = _lang;
}
}
return lang;
}
/**
* Returns the internal character set used by the flash player
* <p>Logic : by default flash player use unicode internally so we return UTF-8.</p>
* <p>If the player use the system code page then we try to return the char set of the browser.</p>
* @return the internal character set used by the flash player
*/
public function get languageEncoding():String
{
if( System.useCodePage )
{
var _charset:String = _dom.characterSet;
if( _charset )
{
return _charset;
}
return "-"; //not found
}
//default
return "UTF-8" ;
}
/**
* Returns the operating system string.
* <p><b>Note:</b> The flash documentation indicate those strings</p>
* <li>"Windows XP"</li>
* <li>"Windows 2000"</li>
* <li>"Windows NT"</li>
* <li>"Windows 98/ME"</li>
* <li>"Windows 95"</li>
* <li>"Windows CE" (available only in Flash Player SDK, not in the desktop version)</li>
* <li>"Linux"</li>
* <li>"MacOS"</li>
* <p>Other strings we can obtain ( not documented : "Mac OS 10.5.4" , "Windows Vista")</p>
* @return the operating system string.
* @see Capabilities.os
*/
public function get operatingSystem():String
{
return Capabilities.os ;
}
/**
* Returns the player type.
* <p><b>Note :</b> The flash documentation indicate those strings.</p>
* <li><b>"ActiveX"</b> : for the Flash Player ActiveX control used by Microsoft Internet Explorer.</li>
* <li><b>"Desktop"</b> : for the Adobe AIR runtime (except for SWF content loaded by an HTML page, which has Capabilities.playerType set to "PlugIn").</li>
* <li><b>"External"</b> : for the external Flash Player "PlugIn" for the Flash Player browser plug-in (and for SWF content loaded by an HTML page in an AIR application).</li>
* <li><b>"StandAlone"</b> : for the stand-alone Flash Player.</li>
* @return the player type.
* @see Capabilities.playerType
*/
public function get playerType():String
{
return Capabilities.playerType;
}
/**
* Returns the platform, can be "Windows", "Macintosh" or "Linux"
* @see Capabilities.manufacturer
*/
public function get platform():String
{
var p:String = Capabilities.manufacturer;
return p.split( "Adobe " )[1];
}
/**
* Indicates the Protocols object of this local info.
*/
public function get protocol():Protocols
{
if(!_protocol)
{
_findProtocol();
}
return _protocol;
}
/**
* Indicates the height of the screen.
* @see Capabilities.screenResolutionY
*/
public function get screenHeight():Number
{
return Capabilities.screenResolutionY;
}
/**
* Indicates the width of the screen.
* @see Capabilities.screenResolutionX
*/
public function get screenWidth():Number
{
return Capabilities.screenResolutionX;
}
/**
* In AIR we can use flash.display.Screen to directly get the colorDepth property
* in flash player we can only access screenColor in flash.system.Capabilities.
* <p>Some ref : <a href="http://en.wikipedia.org/wiki/Color_depth">http://en.wikipedia.org/wiki/Color_depth</a></p>
* <li>"color" -> 16-bit or 24-bit or 32-bit</li>
* <li>"gray" -> 2-bit</li>
* <li>"bw" -> 1-bit</li>
*/
public function get screenColorDepth():String
{
var color:String;
switch( Capabilities.screenColor )
{
case "bw":
{
color = "1";
break;
}
case "gray":
{
color = "2";
break;
}
/* note:
as we have no way to know if
we are in 16-bit, 24-bit or 32-bit
we gives 24-bit by default
*/
case "color" :
default :
{
color = "24" ;
}
}
var _colorDepth:String = _dom.colorDepth;
if( _colorDepth )
{
color = _colorDepth;
}
return color;
}
private function _defineUserAgent():void
{
_userAgent = core.strings.userAgent( appName + "/" + appVersion.toString(4) );
}
/**
* Defines a custom user agent.
* <p>For case where the user would want to define its own application name and version
* it is possible to change appName and appVersion which are in sync with
* applicationProduct and applicationVersion properties.</p>
*/
public function get userAgent():String
{
if( !_userAgent )
{
_defineUserAgent();
}
return _userAgent;
}
/**
* @private
*/
public function set userAgent( custom:String ):void
{
_userAgent = custom;
}
}
}
|
/*
* Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributor(s):
* Zwetan Kjukov <[email protected]>.
* Marc Alcaraz <[email protected]>.
*/
package com.google.analytics.utils
{
import core.strings.userAgent;
import com.google.analytics.core.ga_internal;
import com.google.analytics.debug.DebugConfiguration;
import com.google.analytics.external.HTMLDOM;
import flash.system.Capabilities;
import flash.system.Security;
import flash.system.System;
/**
* Environment provides informations for the local environment.
*/
public class Environment
{
private var _debug:DebugConfiguration;
private var _dom:HTMLDOM;
private var _protocol:Protocols;
private var _appName:String;
private var _appVersion:Version;
private var _userAgent:String;
private var _url:String;
/**
* Creates a new Environment instance.
* @param url The URL of the SWF.
* @param app The application name
* @param version The application version
* @param dom the HTMLDOM reference.
*/
public function Environment( url:String = "", app:String = "", version:String = "",
debug:DebugConfiguration = null, dom:HTMLDOM = null )
{
var v:Version;
if( app == "" )
{
if( isAIR() )
{
app = "AIR";
}
else
{
app = "Flash";
}
}
if( version == "" )
{
v = flashVersion;
}
else
{
v = Version.fromString( version );
}
_url = url;
_appName = app;
_appVersion = v;
_debug = debug;
_dom = dom;
}
/**
* @private
*/
private function _findProtocol():void
{
var p:Protocols = Protocols.none;
if(_url != "")
{
// file://
// http://
// https://
var URL:String = _url.toLowerCase();
var test:String = URL.substr(0,5);
switch( test )
{
case "file:":
{
p = Protocols.file;
break;
}
case "http:":
{
p = Protocols.HTTP;
break;
}
case "https":
{
if(URL.charAt(5) == ":")
{
p = Protocols.HTTPS;
}
break;
}
default:
{
_protocol = Protocols.none;
}
}
}
/*TODO:
if _url is not found (if someone forgot to add the tracker to the display list)
we could use the alternative to get the dom.location and find the protocol from that string
off course only if we have access to ExternalInterface
*/
var _proto:String = _dom.protocol;
var proto:String = (p.toString()+":").toLowerCase();
if( _proto && _proto != proto && _debug )
{
_debug.warning( "Protocol mismatch: SWF="+proto+", DOM="+_proto );
}
_protocol = p;
}
/**
* Indicates the name of the application.
*/
public function get appName():String
{
return _appName;
}
/**
* @private
*/
public function set appName( value:String ):void
{
_appName = value;
_defineUserAgent();
}
/**
* Indicates the version of the application.
*/
public function get appVersion():Version
{
return _appVersion;
}
/**
* @private
*/
public function set appVersion( value:Version ):void
{
_appVersion = value;
_defineUserAgent();
}
/**
* Sets the stage reference value of the application.
*/
ga_internal function set url( value:String ):void
{
_url = value;
}
/**
* Indicates the location of swf.
*/
public function get locationSWFPath():String
{
return _url;
}
/**
* Indicates the referrer value.
*/
public function get referrer():String
{
var _referrer:String = _dom.referrer;
if( _referrer )
{
return _referrer;
}
if( protocol == Protocols.file )
{
return "localhost";
}
return "";
}
/**
* Indicates the title of the document.
*/
public function get documentTitle():String
{
var _title:String = _dom.title;
if( _title )
{
return _title;
}
return "";
}
/**
* Indicates the local domain name value.
*/
public function get domainName():String
{
if( protocol == Protocols.HTTP ||
protocol == Protocols.HTTPS )
{
var URL:String = _url.toLowerCase();
var str:String;
var end:int;
if( protocol == Protocols.HTTP )
{
str = URL.split( "http://" ).join( "" );
}
else if( protocol == Protocols.HTTPS )
{
str = URL.split( "https://" ).join( "" );
}
end = str.indexOf( "/" );
if( end > -1 )
{
str = str.substring(0,end);
}
return str;
}
if( protocol == Protocols.file )
{
return "localhost";
}
return "";
}
/**
* Indicates if the application is running in AIR.
*/
public function isAIR():Boolean
{
//return (playerType == "Desktop") && (Security.sandboxType.toString() == "application");
return Security.sandboxType == "application";
}
/**
* Indicates if the SWF is embeded in an HTML page.
* @return <code class="prettyprint">true</code> if the SWF is embeded in an HTML page.
*/
public function isInHTML():Boolean
{
return Capabilities.playerType == "PlugIn" ;
}
/**
* Indicates the locationPath value.
*/
public function get locationPath():String
{
var _pathname:String = _dom.pathname;
if( _pathname )
{
return _pathname;
}
return "";
}
/**
* Indicates the locationSearch value.
*/
public function get locationSearch():String
{
var _search:String = _dom.search;
if( _search )
{
return _search;
}
return "";
}
/**
* Returns the flash version object representation of the application.
* <p>This object contains the attributes major, minor, build and revision :</p>
* <p><b>Example :</b></p>
* <pre class="prettyprint">
* import com.google.analytics.utils.Environment ;
*
* var info:Environment = new Environment( "http://www.domain.com" ) ;
* var version:Object = info.flashVersion ;
*
* trace( version.major ) ; // 9
* trace( version.minor ) ; // 0
* trace( version.build ) ; // 124
* trace( version.revision ) ; // 0
* </pre>
* @return the flash version object representation of the application.
*/
public function get flashVersion():Version
{
var v:Version = Version.fromString( Capabilities.version.split( " " )[1], "," ) ;
return v ;
}
/**
* Returns the language string as a lowercase two-letter language code from ISO 639-1.
* @see Capabilities.language
*/
public function get language():String
{
var _lang:String = _dom.language;
var lang:String = Capabilities.language;
if( _lang )
{
if( (_lang.length > lang.length) &&
(_lang.substr(0,lang.length) == lang) )
{
lang = _lang;
}
}
return lang;
}
/**
* Returns the internal character set used by the flash player
* <p>Logic : by default flash player use unicode internally so we return UTF-8.</p>
* <p>If the player use the system code page then we try to return the char set of the browser.</p>
* @return the internal character set used by the flash player
*/
public function get languageEncoding():String
{
if( System.useCodePage )
{
var _charset:String = _dom.characterSet;
if( _charset )
{
return _charset;
}
return "-"; //not found
}
//default
return "UTF-8" ;
}
/**
* Returns the operating system string.
* <p><b>Note:</b> The flash documentation indicate those strings</p>
* <li>"Windows XP"</li>
* <li>"Windows 2000"</li>
* <li>"Windows NT"</li>
* <li>"Windows 98/ME"</li>
* <li>"Windows 95"</li>
* <li>"Windows CE" (available only in Flash Player SDK, not in the desktop version)</li>
* <li>"Linux"</li>
* <li>"MacOS"</li>
* <p>Other strings we can obtain ( not documented : "Mac OS 10.5.4" , "Windows Vista")</p>
* @return the operating system string.
* @see Capabilities.os
*/
public function get operatingSystem():String
{
return Capabilities.os ;
}
/**
* Returns the player type.
* <p><b>Note :</b> The flash documentation indicate those strings.</p>
* <li><b>"ActiveX"</b> : for the Flash Player ActiveX control used by Microsoft Internet Explorer.</li>
* <li><b>"Desktop"</b> : for the Adobe AIR runtime (except for SWF content loaded by an HTML page, which has Capabilities.playerType set to "PlugIn").</li>
* <li><b>"External"</b> : for the external Flash Player "PlugIn" for the Flash Player browser plug-in (and for SWF content loaded by an HTML page in an AIR application).</li>
* <li><b>"StandAlone"</b> : for the stand-alone Flash Player.</li>
* @return the player type.
* @see Capabilities.playerType
*/
public function get playerType():String
{
return Capabilities.playerType;
}
/**
* Returns the platform, can be "Windows", "Macintosh" or "Linux"
* @see Capabilities.manufacturer
*/
public function get platform():String
{
var p:String = Capabilities.manufacturer;
return p.split( "Adobe " )[1];
}
/**
* Indicates the Protocols object of this local info.
*/
public function get protocol():Protocols
{
if(!_protocol)
{
_findProtocol();
}
return _protocol;
}
/**
* Indicates the height of the screen.
* @see Capabilities.screenResolutionY
*/
public function get screenHeight():Number
{
return Capabilities.screenResolutionY;
}
/**
* Indicates the width of the screen.
* @see Capabilities.screenResolutionX
*/
public function get screenWidth():Number
{
return Capabilities.screenResolutionX;
}
/**
* In AIR we can use flash.display.Screen to directly get the colorDepth property
* in flash player we can only access screenColor in flash.system.Capabilities.
* <p>Some ref : <a href="http://en.wikipedia.org/wiki/Color_depth">http://en.wikipedia.org/wiki/Color_depth</a></p>
* <li>"color" -> 16-bit or 24-bit or 32-bit</li>
* <li>"gray" -> 2-bit</li>
* <li>"bw" -> 1-bit</li>
*/
public function get screenColorDepth():String
{
var color:String;
switch( Capabilities.screenColor )
{
case "bw":
{
color = "1";
break;
}
case "gray":
{
color = "2";
break;
}
/* note:
as we have no way to know if
we are in 16-bit, 24-bit or 32-bit
we gives 24-bit by default
*/
case "color" :
default :
{
color = "24" ;
}
}
var _colorDepth:String = _dom.colorDepth;
if( _colorDepth )
{
color = _colorDepth;
}
return color;
}
private function _defineUserAgent():void
{
_userAgent = core.strings.userAgent( appName + "/" + appVersion.toString(4) );
}
/**
* Defines a custom user agent.
* <p>For case where the user would want to define its own application name and version
* it is possible to change appName and appVersion which are in sync with
* applicationProduct and applicationVersion properties.</p>
*/
public function get userAgent():String
{
if( !_userAgent )
{
_defineUserAgent();
}
return _userAgent;
}
/**
* @private
*/
public function set userAgent( custom:String ):void
{
_userAgent = custom;
}
}
}
|
fix comment for asdoc
|
fix comment for asdoc
|
ActionScript
|
apache-2.0
|
jeremy-wischusen/gaforflash,jisobkim/gaforflash,mrthuanvn/gaforflash,DimaBaliakin/gaforflash,dli-iclinic/gaforflash,mrthuanvn/gaforflash,Vigmar/gaforflash,Vigmar/gaforflash,DimaBaliakin/gaforflash,dli-iclinic/gaforflash,soumavachakraborty/gaforflash,jeremy-wischusen/gaforflash,Miyaru/gaforflash,soumavachakraborty/gaforflash,Miyaru/gaforflash,jisobkim/gaforflash,drflash/gaforflash,drflash/gaforflash
|
51e191e5e42b3f7d45b42a2040c9828a95b8cd4b
|
SoundMain.as
|
SoundMain.as
|
package {
import flash.display.Sprite;
import flash.events.Event;
import flash.events.SampleDataEvent;
import flash.external.ExternalInterface;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import flash.utils.Endian;
import flash.utils.getQualifiedClassName;
import flash.system.Security;
/**
* Audio main.
*/
public class SoundMain extends Sprite {
private var ns:String;
private var debug:Boolean;
private var sounds:Array;
/**
* Constructor
*/
public function SoundMain() {
if (!ExternalInterface.available) {
throw new Error("ExternalInterface not available");
}
ns = loaderInfo.parameters["namespace"] || getQualifiedClassName(this);
debug = false;
Security.allowDomain("*");
sounds = [];
/**
* Javascript can call these
*/
ExternalInterface.addCallback("__create", create);
ExternalInterface.addCallback("__load", load);
ExternalInterface.addCallback("__play", play);
ExternalInterface.addCallback("__setDebug", setDebug);
ExternalInterface.addCallback("__stop", stop);
ExternalInterface.addCallback("__destroy", destroy);
invoke("__onFlashInitialized");
}
private function setDebug(val:Boolean):void {
invoke("__onLog", "setDebug");
ExternalInterface.marshallExceptions = val;
debug = val;
}
/**
* Creates a new Audio
*/
private function create(id:int):void {
sounds[id] = {
instance: new Sound(),
channel: null
};
}
/**
* Loads audio from URL
*/
private function load(id:int, uri:String):void {
if (uri.substr(0, 4) == "data") {
invoke("__onLog", "Data URI not supported");
return;
}
sounds[id].instance.load(new URLRequest(uri));
}
/**
* Plays audio
*/
private function play(id:int, startTime:Number = 0, loops:int = 1):void {
if (sounds[id].channel) {
invoke("__onLog", "Already playing this sound");
return;
}
var channel:SoundChannel = sounds[id].instance.play(startTime, loops);
channel.addEventListener(Event.SOUND_COMPLETE, function(_:Event):void {
if (id in sounds) sounds[id].channel = null;
});
sounds[id].channel = channel;
}
/**
* Stops playing audio
*/
private function stop(id:int):void {
sounds[id].channel.stop();
}
/**
* Cleans up resources
*/
private function destroy(id:int):void {
sounds[id].instance = null;
if (sounds[id].channel) {
sounds[id].channel.stop();
}
delete sounds[id];
}
/**
* Conveniently invoke a function in Javascript.
*
* @param method String The method to call.
*/
private function invoke(method:String, ...params):void {
params = params || [];
ExternalInterface.call.apply(ExternalInterface,
[ns + "." + method].concat(params));
}
}
}
|
package {
import flash.display.Sprite;
import flash.events.Event;
import flash.events.SampleDataEvent;
import flash.external.ExternalInterface;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import flash.utils.Endian;
import flash.utils.getQualifiedClassName;
import flash.system.Security;
/**
* Audio main.
*/
public class SoundMain extends Sprite {
private var ns:String;
private var debug:Boolean;
private var sounds:Array;
/**
* Constructor
*/
public function SoundMain() {
if (!ExternalInterface.available) {
throw new Error("ExternalInterface not available");
}
ns = loaderInfo.parameters["namespace"] || getQualifiedClassName(this);
debug = false;
Security.allowDomain("*");
sounds = [];
/**
* Javascript can call these
*/
ExternalInterface.addCallback("__create", create);
ExternalInterface.addCallback("__load", load);
ExternalInterface.addCallback("__play", play);
ExternalInterface.addCallback("__setDebug", setDebug);
ExternalInterface.addCallback("__stop", stop);
ExternalInterface.addCallback("__destroy", destroy);
invoke("__onFlashInitialized");
}
private function setDebug(val:Boolean):void {
invoke("__onLog", "setDebug");
ExternalInterface.marshallExceptions = val;
debug = val;
}
/**
* Creates a new Audio
*/
private function create(id:int):void {
sounds[id] = {
instance: new Sound(),
channel: null
};
}
/**
* Loads audio from URL
*/
private function load(id:int, uri:String):void {
if (uri.substr(0, 4) == "data") {
invoke("__onLog", "Data URI not supported");
return;
}
sounds[id].instance.load(new URLRequest(uri));
}
/**
* Plays audio
*/
private function play(id:int, startTime:Number = 0, loops:int = 1):void {
if (sounds[id].channel) {
invoke("__onLog", "Already playing this sound");
return;
}
var channel:SoundChannel = sounds[id].instance.play(startTime, loops);
channel.addEventListener(Event.SOUND_COMPLETE, function(_:Event):void {
if (id in sounds) sounds[id].channel = null;
});
sounds[id].channel = channel;
}
/**
* Stops playing audio
*/
private function stop(id:int):void {
sounds[id].channel.stop();
sounds[id].channel = null;
}
/**
* Cleans up resources
*/
private function destroy(id:int):void {
sounds[id].instance = null;
if (sounds[id].channel) {
sounds[id].channel.stop();
}
delete sounds[id];
}
/**
* Conveniently invoke a function in Javascript.
*
* @param method String The method to call.
*/
private function invoke(method:String, ...params):void {
params = params || [];
ExternalInterface.call.apply(ExternalInterface,
[ns + "." + method].concat(params));
}
}
}
|
Set channel to null when sound stops playing
|
Set channel to null when sound stops playing
|
ActionScript
|
bsd-3-clause
|
luciferous/Sound
|
598979fa0848921961ef97f001b5021863f78806
|
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.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 com.adobe.crypto.MD5;
import deng.fzip.FZip;
import deng.fzip.FZipFile;
import flump.bytesToXML;
import flump.display.Movie;
import flump.executor.Executor;
import flump.executor.Future;
import flump.export.Ternary;
import flump.xfl.ParseError;
import flump.xfl.XflLibrary;
import flump.xfl.XflMovie;
import mx.collections.ArrayCollection;
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;
protected static const IMPORT_ROOT :String = "IMPORT_ROOT";
protected static const AUTHORED_RESOLUTION :String = "AUTHORED_RESOLUTION";
public function Exporter (win :ExporterWindow) {
_win = win;
_errors = _win.errors;
_libraries = _win.libraries;
_authoredResolution = _win.authoredResolutionPopup;
_authoredResolution.dataProvider = new ArrayCollection(DeviceType.values().map(
function (type :DeviceType, ..._) :Object {
return new DeviceSelection(type);
}));
var initialSelection :DeviceType = null;
if (_settings.data.hasOwnProperty(AUTHORED_RESOLUTION)) {
try {
initialSelection = DeviceType.valueOf(_settings.data[AUTHORED_RESOLUTION]);
} catch (e :Error) {}
}
if (initialSelection == null) {
initialSelection = DeviceType.IPHONE_RETINA;
}
_authoredResolution.selectedIndex = DeviceType.values().indexOf(initialSelection);
_authoredResolution.addEventListener(Event.CHANGE, function (..._) :void {
var selectedType :DeviceType = DeviceSelection(_authoredResolution.selectedItem).type;
_settings.data[AUTHORED_RESOLUTION] = selectedType.name();
});
function updateExportEnabled (..._) :void {
_win.export.enabled = _exportChooser.dir != null && _libraries.selectionLength > 0 &&
_libraries.selectedItems.some(function (status :DocStatus, ..._) :Boolean {
return status.isValid;
});
}
_libraries.addEventListener(GridSelectionEvent.SELECTION_CHANGE, function (..._) :void {
log.info("Changed", "selected", _libraries.selectedIndices);
updateExportEnabled();
_win.preview.enabled = _libraries.selectedItem.isValid;
});
_win.reload.addEventListener(MouseEvent.CLICK, function (..._) :void {
setImport(_importChooser.dir);
});
_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(_settings, "IMPORT_ROOT", _win.importRoot, _win.browseImport);
_importChooser.changed.add(setImport);
setImport(_importChooser.dir);
_exportChooser =
new DirChooser(_settings, "EXPORT_ROOT", _win.exportRoot, _win.browseExport);
_exportChooser.changed.add(updateExportEnabled);
function updatePublisher (..._) :void {
if (_exportChooser.dir == null) _publisher = null;
else {
_publisher =
new Publisher(_exportChooser.dir, new XMLFormat(), new JSONFormat(), new StarlingFormat());
}
};
_exportChooser.changed.add(updatePublisher);
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(2);
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, _previewControls);
}
_previewWindow.open();
_previewControls.open();
preventWindowClose(_previewWindow.nativeWindow);
preventWindowClose(_previewControls.nativeWindow);
} else {
_previewController.lib = lib;
_previewWindow.nativeWindow.visible = true;
_previewControls.nativeWindow.visible = true;
}
}
// 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.parent);
}
return;
}
}
for each (file in files) {
if (file.isDirectory) findFlashDocuments(file, exec);
else if (Files.hasExtension(file, "fla")) addFlashDocument(file);
}
});
}
protected function addFlashDocument (file :File) :void {
const status :DocStatus = new DocStatus(file, _rootLen, Ternary.UNKNOWN, Ternary.UNKNOWN, null);
_libraries.dataProvider.addItem(status);
loadFlashDocument(status);
}
protected function exportFlashDocument (status :DocStatus) :void {
var stage :Stage = NA.activeWindow.stage;
var prevQuality :String = stage.quality;
stage.quality = StageQuality.BEST;
_publisher.publish(status.lib, DeviceSelection(_authoredResolution.selectedItem).type);
stage.quality = prevQuality;
status.updateModified(Ternary.FALSE);
}
protected function loadFlashDocument (status :DocStatus) :void {
if (Files.hasExtension(status.file, "xfl")) status.file = status.file.parent;
if (status.file.isDirectory) {
const name :String = status.file.nativePath
.substring(_rootLen).replace(File.separator, "/");
const load :Future = new XflLoader().load(name, status.file);
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 (e :Error) :void {
trace("Failed to load " + status.file.nativePath + ":" + e);
status.updateValid(Ternary.FALSE);
throw e;
});
} else loadFla(status.file);
}
protected function loadFla (file :File) :void {
log.info("fla support not implemented", "path", file.nativePath);
return;
Files.load(file).succeeded.add(function (file :File) :void {
const zip :FZip = new FZip();
zip.loadBytes(file.data);
const files :Array = [];
for (var ii :int = 0; ii < zip.getFileCount(); ii++) files.push(zip.getFileAt(ii));
const xmls :Array = F.filter(files, function (fz :FZipFile) :Boolean {
return StringUtil.endsWith(fz.filename, ".xml");
});
const movies :Array = F.filter(xmls, function (fz :FZipFile) :Boolean {
return StringUtil.startsWith(fz.filename, "LIBRARY/Animations/");
});
const textures :Array = F.filter(xmls, function (fz :FZipFile) :Boolean {
return StringUtil.startsWith(fz.filename, "LIBRARY/Textures/");
});
function toFn (fz :FZipFile) :String { return fz.filename };
log.info("Loaded", "bytes", file.data.length, "movies", F.map(movies, toFn),
"textures", F.map(textures, toFn));
for each (var fz :FZipFile in movies) {
XflMovie.parse(null, bytesToXML(fz.content), MD5.hashBytes(fz.content));
}
NA.exit(0);
});
}
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 const _settings :SharedObject = SharedObject.getLocal("flump/Exporter");
private static const log :Log = Log.getLog(Exporter);
}
}
import flump.export.DeviceType;
class DeviceSelection {
public var type :DeviceType;
public function DeviceSelection (type :DeviceType) {
this.type = type;
}
public function toString () :String {
return type.displayName + " (" + type.resWidth + "x" + type.resHeight + ")";
}
}
import flash.events.EventDispatcher;
import flash.filesystem.File;
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 file :File;
public var lib :XflLibrary;
public function DocStatus (file :File, rootLen :int, modified :Ternary, valid :Ternary, lib :XflLibrary) {
this.file = file;
this.lib = lib;
path = file.nativePath.substring(rootLen);
_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.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 com.adobe.crypto.MD5;
import deng.fzip.FZip;
import deng.fzip.FZipFile;
import flump.bytesToXML;
import flump.display.Movie;
import flump.executor.Executor;
import flump.executor.Future;
import flump.export.Ternary;
import flump.xfl.ParseError;
import flump.xfl.XflLibrary;
import flump.xfl.XflMovie;
import mx.collections.ArrayCollection;
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;
protected static const IMPORT_ROOT :String = "IMPORT_ROOT";
protected static const AUTHORED_RESOLUTION :String = "AUTHORED_RESOLUTION";
public function Exporter (win :ExporterWindow) {
Log.setLevel("", Log.INFO);
_win = win;
_errors = _win.errors;
_libraries = _win.libraries;
_authoredResolution = _win.authoredResolutionPopup;
_authoredResolution.dataProvider = new ArrayCollection(DeviceType.values().map(
function (type :DeviceType, ..._) :Object {
return new DeviceSelection(type);
}));
var initialSelection :DeviceType = null;
if (_settings.data.hasOwnProperty(AUTHORED_RESOLUTION)) {
try {
initialSelection = DeviceType.valueOf(_settings.data[AUTHORED_RESOLUTION]);
} catch (e :Error) {}
}
if (initialSelection == null) {
initialSelection = DeviceType.IPHONE_RETINA;
}
_authoredResolution.selectedIndex = DeviceType.values().indexOf(initialSelection);
_authoredResolution.addEventListener(Event.CHANGE, function (..._) :void {
var selectedType :DeviceType = DeviceSelection(_authoredResolution.selectedItem).type;
_settings.data[AUTHORED_RESOLUTION] = selectedType.name();
});
function updateExportEnabled (..._) :void {
_win.export.enabled = _exportChooser.dir != null && _libraries.selectionLength > 0 &&
_libraries.selectedItems.some(function (status :DocStatus, ..._) :Boolean {
return status.isValid;
});
}
_libraries.addEventListener(GridSelectionEvent.SELECTION_CHANGE, function (..._) :void {
log.info("Changed", "selected", _libraries.selectedIndices);
updateExportEnabled();
_win.preview.enabled = _libraries.selectedItem.isValid;
});
_win.reload.addEventListener(MouseEvent.CLICK, function (..._) :void {
setImport(_importChooser.dir);
});
_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(_settings, "IMPORT_ROOT", _win.importRoot, _win.browseImport);
_importChooser.changed.add(setImport);
setImport(_importChooser.dir);
_exportChooser =
new DirChooser(_settings, "EXPORT_ROOT", _win.exportRoot, _win.browseExport);
_exportChooser.changed.add(updateExportEnabled);
function updatePublisher (..._) :void {
if (_exportChooser.dir == null) _publisher = null;
else {
_publisher =
new Publisher(_exportChooser.dir, new XMLFormat(), new JSONFormat(), new StarlingFormat());
}
};
_exportChooser.changed.add(updatePublisher);
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(2);
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, _previewControls);
}
_previewWindow.open();
_previewControls.open();
preventWindowClose(_previewWindow.nativeWindow);
preventWindowClose(_previewControls.nativeWindow);
} else {
_previewController.lib = lib;
_previewWindow.nativeWindow.visible = true;
_previewControls.nativeWindow.visible = true;
}
}
// 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.parent);
}
return;
}
}
for each (file in files) {
if (file.isDirectory) findFlashDocuments(file, exec);
else if (Files.hasExtension(file, "fla")) addFlashDocument(file);
}
});
}
protected function addFlashDocument (file :File) :void {
const status :DocStatus = new DocStatus(file, _rootLen, Ternary.UNKNOWN, Ternary.UNKNOWN, null);
_libraries.dataProvider.addItem(status);
loadFlashDocument(status);
}
protected function exportFlashDocument (status :DocStatus) :void {
var stage :Stage = NA.activeWindow.stage;
var prevQuality :String = stage.quality;
stage.quality = StageQuality.BEST;
_publisher.publish(status.lib, DeviceSelection(_authoredResolution.selectedItem).type);
stage.quality = prevQuality;
status.updateModified(Ternary.FALSE);
}
protected function loadFlashDocument (status :DocStatus) :void {
if (Files.hasExtension(status.file, "xfl")) status.file = status.file.parent;
if (status.file.isDirectory) {
const name :String = status.file.nativePath
.substring(_rootLen).replace(File.separator, "/");
const load :Future = new XflLoader().load(name, status.file);
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 (e :Error) :void {
trace("Failed to load " + status.file.nativePath + ":" + e);
status.updateValid(Ternary.FALSE);
throw e;
});
} else loadFla(status.file);
}
protected function loadFla (file :File) :void {
log.info("fla support not implemented", "path", file.nativePath);
return;
Files.load(file).succeeded.add(function (file :File) :void {
const zip :FZip = new FZip();
zip.loadBytes(file.data);
const files :Array = [];
for (var ii :int = 0; ii < zip.getFileCount(); ii++) files.push(zip.getFileAt(ii));
const xmls :Array = F.filter(files, function (fz :FZipFile) :Boolean {
return StringUtil.endsWith(fz.filename, ".xml");
});
const movies :Array = F.filter(xmls, function (fz :FZipFile) :Boolean {
return StringUtil.startsWith(fz.filename, "LIBRARY/Animations/");
});
const textures :Array = F.filter(xmls, function (fz :FZipFile) :Boolean {
return StringUtil.startsWith(fz.filename, "LIBRARY/Textures/");
});
function toFn (fz :FZipFile) :String { return fz.filename };
log.info("Loaded", "bytes", file.data.length, "movies", F.map(movies, toFn),
"textures", F.map(textures, toFn));
for each (var fz :FZipFile in movies) {
XflMovie.parse(null, bytesToXML(fz.content), MD5.hashBytes(fz.content));
}
NA.exit(0);
});
}
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 const _settings :SharedObject = SharedObject.getLocal("flump/Exporter");
private static const log :Log = Log.getLog(Exporter);
}
}
import flump.export.DeviceType;
class DeviceSelection {
public var type :DeviceType;
public function DeviceSelection (type :DeviceType) {
this.type = type;
}
public function toString () :String {
return type.displayName + " (" + type.resWidth + "x" + type.resHeight + ")";
}
}
import flash.events.EventDispatcher;
import flash.filesystem.File;
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 file :File;
public var lib :XflLibrary;
public function DocStatus (file :File, rootLen :int, modified :Ternary, valid :Ternary, lib :XflLibrary) {
this.file = file;
this.lib = lib;
path = file.nativePath.substring(rootLen);
_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 = "✓";
}
|
Cut logging back to INFO by default
|
Cut logging back to INFO by default
|
ActionScript
|
mit
|
funkypandagame/flump,mathieuanthoine/flump,funkypandagame/flump,mathieuanthoine/flump,mathieuanthoine/flump,tconkling/flump,tconkling/flump
|
1f690495728e604df4b3c2ada00018578ef284aa
|
src/aerys/minko/scene/controller/TransformController.as
|
src/aerys/minko/scene/controller/TransformController.as
|
package aerys.minko.scene.controller
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.Viewport;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.math.Matrix4x4;
import flash.display.BitmapData;
import flash.utils.Dictionary;
use namespace minko_math;
/**
* The TransformController handles the batched update of all the local to world matrices
* of a sub-scene. As such, it will only be active on the root node of a sub-scene and will
* automatically disable itself on other nodes.
*
* @author Jean-Marc Le Roux
*
*/
public final class TransformController extends AbstractController
{
private var _target : ISceneNode;
private var _invalidList : Boolean;
private var _nodeToId : Dictionary;
private var _idToNode : Vector.<ISceneNode>
private var _transforms : Vector.<Matrix4x4>;
private var _localToWorldTransformsInitialized : Vector.<Boolean>;
private var _localToWorldTransforms : Vector.<Matrix4x4>;
private var _worldToLocalTransforms : Vector.<Matrix4x4>;
private var _numChildren : Vector.<uint>;
private var _firstChildId : Vector.<uint>;
private var _parentId : Vector.<int>;
public function TransformController()
{
super();
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function renderingBeginHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : Number) : void
{
if (_invalidList)
updateTransformsList();
if (_transforms.length)
updateLocalToWorld();
}
private function updateLocalToWorld(nodeId : uint = 0) : void
{
var numNodes : uint = _transforms.length;
var childrenOffset : uint = 1;
var rootLocalToWorld : Matrix4x4 = _localToWorldTransforms[nodeId];
var rootTransform : Matrix4x4 = _transforms[nodeId];
var root : ISceneNode = _idToNode[childId];
if (rootTransform._hasChanged || !_localToWorldTransformsInitialized[nodeId])
{
rootLocalToWorld.copyFrom(rootTransform);
if (nodeId != 0)
rootLocalToWorld.append(_localToWorldTransforms[_parentId[nodeId]]);
rootTransform._hasChanged = false;
_localToWorldTransformsInitialized[nodeId] = true;
root.localToWorldTransformChanged.execute(root, rootLocalToWorld);
}
for (; nodeId < numNodes; ++nodeId)
{
var localToWorld : Matrix4x4 = _localToWorldTransforms[nodeId];
var numChildren : uint = _numChildren[nodeId];
var firstChildId : uint = _firstChildId[nodeId];
var lastChildId : uint = firstChildId + numChildren;
var isDirty : Boolean = localToWorld._hasChanged ||
!_localToWorldTransformsInitialized[nodeId];
localToWorld._hasChanged = false;
_localToWorldTransformsInitialized[nodeId] = true;
for (var childId : uint = firstChildId; childId < lastChildId; ++childId)
{
var childTransform : Matrix4x4 = _transforms[childId];
var childLocalToWorld : Matrix4x4 = _localToWorldTransforms[childId];
var childIsDirty : Boolean = isDirty || childTransform._hasChanged
|| !_localToWorldTransformsInitialized[childId];
if (childIsDirty || _localToWorldTransformsInitialized[childId])
{
var child : ISceneNode = _idToNode[childId];
childLocalToWorld
.copyFrom(childTransform)
.append(localToWorld);
childTransform._hasChanged = false;
_localToWorldTransformsInitialized[childId] = true;
child.localToWorldTransformChanged.execute(child, childLocalToWorld);
}
}
}
}
private function getDirtyRoot(nodeId : int) : int
{
var dirtyRoot : int = -1;
while (nodeId >= 0)
{
if ((_transforms[nodeId] as Matrix4x4)._hasChanged ||
!_localToWorldTransformsInitialized[nodeId])
dirtyRoot = nodeId;
nodeId = _parentId[nodeId];
}
return dirtyRoot;
}
private function targetAddedHandler(ctrl : TransformController,
target : ISceneNode) : void
{
if (_target)
throw new Error('The TransformController cannot have more than one target.');
_target = target;
_invalidList = true;
if (target is Scene)
{
(target as Scene).renderingBegin.add(renderingBeginHandler);
return;
}
if (target is Group)
{
var targetGroup : Group = target as Group;
targetGroup.descendantAdded.add(descendantAddedHandler);
targetGroup.descendantRemoved.add(descendantRemovedHandler);
}
target.added.add(addedHandler);
}
private function targetRemovedHandler(ctrl : TransformController,
target : ISceneNode) : void
{
target.added.remove(addedHandler);
if (target is Group)
{
var targetGroup : Group = target as Group;
targetGroup.descendantAdded.remove(descendantAddedHandler);
targetGroup.descendantRemoved.remove(descendantRemovedHandler);
}
_invalidList = false;
_target = null;
_nodeToId = null;
_transforms = null;
_localToWorldTransformsInitialized = null;
_localToWorldTransforms = null;
_worldToLocalTransforms = null;
_numChildren = null;
_idToNode = null;
_parentId = null;
}
private function addedHandler(target : ISceneNode, ancestor : Group) : void
{
// the controller will remove itself from the node when it's not its own root anymore
// but it will watch for the 'removed' signal to add itself back if the node becomes
// its own root again
_target.removed.add(removedHandler);
_target.removeController(this);
}
private function removedHandler(target : ISceneNode, ancestor : Group) : void
{
if (target.root == target)
{
target.removed.remove(removedHandler);
target.addController(this);
}
}
private function descendantAddedHandler(root : Group,
descendant : ISceneNode) : void
{
_invalidList = true;
}
private function descendantRemovedHandler(root : Group,
descendant : ISceneNode) : void
{
_invalidList = true;
}
private function updateTransformsList() : void
{
var root : ISceneNode = _target.root;
var nodes : Vector.<ISceneNode> = new <ISceneNode>[root];
var nodeId : uint = 0;
_nodeToId = new Dictionary(true);
_transforms = new <Matrix4x4>[];
_localToWorldTransformsInitialized = new <Boolean>[];
_localToWorldTransforms = new <Matrix4x4>[];
_worldToLocalTransforms = new <Matrix4x4>[];
_numChildren = new <uint>[];
_firstChildId = new <uint>[];
_idToNode = new <ISceneNode>[];
_parentId = new <int>[-1];
while (nodes.length)
{
var node : ISceneNode = nodes.shift();
var group : Group = node as Group;
_nodeToId[node] = nodeId;
_idToNode[nodeId] = node;
_transforms[nodeId] = node.transform;
_localToWorldTransforms[nodeId] = new Matrix4x4().lock();
_localToWorldTransformsInitialized[nodeId] = false;
if (group)
{
var numChildren : uint = group.numChildren;
var firstChildId : uint = nodeId + nodes.length + 1;
_numChildren[nodeId] = numChildren;
_firstChildId[nodeId] = firstChildId;
for (var childId : uint = 0; childId < numChildren; ++childId)
{
_parentId[uint(firstChildId + childId)] = nodeId;
nodes.push(group.getChildAt(childId));
}
}
else
{
_numChildren[nodeId] = 0;
_firstChildId[nodeId] = 0;
}
++nodeId;
}
_worldToLocalTransforms.length = _localToWorldTransforms.length;
_invalidList = false;
}
public function getLocalToWorldTransform(node : ISceneNode,
forceUpdate : Boolean = false) : Matrix4x4
{
if (_invalidList || _nodeToId[node] == undefined)
updateTransformsList();
var nodeId : uint = _nodeToId[node];
if (forceUpdate)
{
var dirtyRoot : int = getDirtyRoot(nodeId);
if (dirtyRoot >= 0)
updateLocalToWorld(dirtyRoot);
}
return _localToWorldTransforms[nodeId];
}
public function getWorldToLocalTransform(node : ISceneNode,
forceUpdate : Boolean = false) : Matrix4x4
{
if (_invalidList || _nodeToId[node] == undefined)
updateTransformsList();
var nodeId : uint = _nodeToId[node];
var worldToLocalTransform : Matrix4x4 = _worldToLocalTransforms[nodeId];
if (!worldToLocalTransform)
{
_worldToLocalTransforms[nodeId] = worldToLocalTransform = new Matrix4x4();
if (!forceUpdate)
worldToLocalTransform.copyFrom(_localToWorldTransforms[nodeId]).invert();
}
if (forceUpdate)
{
var dirtyRoot : int = getDirtyRoot(nodeId);
if (dirtyRoot >= 0)
{
updateLocalToWorld(dirtyRoot);
worldToLocalTransform
.copyFrom(_localToWorldTransforms[nodeId])
.invert();
}
}
return worldToLocalTransform;
}
}
}
|
package aerys.minko.scene.controller
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.Viewport;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.math.Matrix4x4;
import flash.display.BitmapData;
import flash.utils.Dictionary;
use namespace minko_math;
/**
* The TransformController handles the batched update of all the local to world matrices
* of a sub-scene. As such, it will only be active on the root node of a sub-scene and will
* automatically disable itself on other nodes.
*
* @author Jean-Marc Le Roux
*
*/
public final class TransformController extends AbstractController
{
private var _target : ISceneNode;
private var _invalidList : Boolean;
private var _nodeToId : Dictionary;
private var _idToNode : Vector.<ISceneNode>
private var _transforms : Vector.<Matrix4x4>;
private var _localToWorldTransformsInitialized : Vector.<Boolean>;
private var _localToWorldTransforms : Vector.<Matrix4x4>;
private var _worldToLocalTransforms : Vector.<Matrix4x4>;
private var _numChildren : Vector.<uint>;
private var _firstChildId : Vector.<uint>;
private var _parentId : Vector.<int>;
public function TransformController()
{
super();
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function renderingBeginHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : Number) : void
{
if (_invalidList)
updateTransformsList();
if (_transforms.length)
updateLocalToWorld();
}
private function updateLocalToWorld(nodeId : uint = 0) : void
{
var numNodes : uint = _transforms.length;
var childrenOffset : uint = 1;
var rootLocalToWorld : Matrix4x4 = _localToWorldTransforms[nodeId];
var rootTransform : Matrix4x4 = _transforms[nodeId];
var root : ISceneNode = _idToNode[childId];
if (rootTransform._hasChanged || !_localToWorldTransformsInitialized[nodeId])
{
rootLocalToWorld.copyFrom(rootTransform);
if (nodeId != 0)
rootLocalToWorld.append(_localToWorldTransforms[_parentId[nodeId]]);
rootTransform._hasChanged = false;
_localToWorldTransformsInitialized[nodeId] = true;
root.localToWorldTransformChanged.execute(root, rootLocalToWorld);
}
for (; nodeId < numNodes; ++nodeId)
{
var localToWorld : Matrix4x4 = _localToWorldTransforms[nodeId];
var numChildren : uint = _numChildren[nodeId];
var firstChildId : uint = _firstChildId[nodeId];
var lastChildId : uint = firstChildId + numChildren;
var isDirty : Boolean = localToWorld._hasChanged;
localToWorld._hasChanged = false;
for (var childId : uint = firstChildId; childId < lastChildId; ++childId)
{
var childTransform : Matrix4x4 = _transforms[childId];
var childLocalToWorld : Matrix4x4 = _localToWorldTransforms[childId];
var childIsDirty : Boolean = isDirty || childTransform._hasChanged
|| !_localToWorldTransformsInitialized[childId];
if (childIsDirty)
{
var child : ISceneNode = _idToNode[childId];
childLocalToWorld
.copyFrom(childTransform)
.append(localToWorld);
childTransform._hasChanged = false;
_localToWorldTransformsInitialized[childId] = true;
child.localToWorldTransformChanged.execute(child, childLocalToWorld);
}
}
}
}
private function getDirtyRoot(nodeId : int) : int
{
var dirtyRoot : int = -1;
while (nodeId >= 0)
{
if ((_transforms[nodeId] as Matrix4x4)._hasChanged ||
!_localToWorldTransformsInitialized[nodeId])
dirtyRoot = nodeId;
nodeId = _parentId[nodeId];
}
return dirtyRoot;
}
private function targetAddedHandler(ctrl : TransformController,
target : ISceneNode) : void
{
if (_target)
throw new Error('The TransformController cannot have more than one target.');
_target = target;
_invalidList = true;
if (target is Scene)
{
(target as Scene).renderingBegin.add(renderingBeginHandler);
return;
}
if (target is Group)
{
var targetGroup : Group = target as Group;
targetGroup.descendantAdded.add(descendantAddedHandler);
targetGroup.descendantRemoved.add(descendantRemovedHandler);
}
target.added.add(addedHandler);
}
private function targetRemovedHandler(ctrl : TransformController,
target : ISceneNode) : void
{
target.added.remove(addedHandler);
if (target is Group)
{
var targetGroup : Group = target as Group;
targetGroup.descendantAdded.remove(descendantAddedHandler);
targetGroup.descendantRemoved.remove(descendantRemovedHandler);
}
_invalidList = false;
_target = null;
_nodeToId = null;
_transforms = null;
_localToWorldTransformsInitialized = null;
_localToWorldTransforms = null;
_worldToLocalTransforms = null;
_numChildren = null;
_idToNode = null;
_parentId = null;
}
private function addedHandler(target : ISceneNode, ancestor : Group) : void
{
// the controller will remove itself from the node when it's not its own root anymore
// but it will watch for the 'removed' signal to add itself back if the node becomes
// its own root again
_target.removed.add(removedHandler);
_target.removeController(this);
}
private function removedHandler(target : ISceneNode, ancestor : Group) : void
{
if (target.root == target)
{
target.removed.remove(removedHandler);
target.addController(this);
}
}
private function descendantAddedHandler(root : Group,
descendant : ISceneNode) : void
{
_invalidList = true;
}
private function descendantRemovedHandler(root : Group,
descendant : ISceneNode) : void
{
_invalidList = true;
}
private function updateTransformsList() : void
{
var root : ISceneNode = _target.root;
var nodes : Vector.<ISceneNode> = new <ISceneNode>[root];
var nodeId : uint = 0;
_nodeToId = new Dictionary(true);
_transforms = new <Matrix4x4>[];
_localToWorldTransformsInitialized = new <Boolean>[];
_localToWorldTransforms = new <Matrix4x4>[];
_worldToLocalTransforms = new <Matrix4x4>[];
_numChildren = new <uint>[];
_firstChildId = new <uint>[];
_idToNode = new <ISceneNode>[];
_parentId = new <int>[-1];
while (nodes.length)
{
var node : ISceneNode = nodes.shift();
var group : Group = node as Group;
_nodeToId[node] = nodeId;
_idToNode[nodeId] = node;
_transforms[nodeId] = node.transform;
_localToWorldTransforms[nodeId] = new Matrix4x4().lock();
_localToWorldTransformsInitialized[nodeId] = false;
if (group)
{
var numChildren : uint = group.numChildren;
var firstChildId : uint = nodeId + nodes.length + 1;
_numChildren[nodeId] = numChildren;
_firstChildId[nodeId] = firstChildId;
for (var childId : uint = 0; childId < numChildren; ++childId)
{
_parentId[uint(firstChildId + childId)] = nodeId;
nodes.push(group.getChildAt(childId));
}
}
else
{
_numChildren[nodeId] = 0;
_firstChildId[nodeId] = 0;
}
++nodeId;
}
_worldToLocalTransforms.length = _localToWorldTransforms.length;
_invalidList = false;
}
public function getLocalToWorldTransform(node : ISceneNode,
forceUpdate : Boolean = false) : Matrix4x4
{
if (_invalidList || _nodeToId[node] == undefined)
updateTransformsList();
var nodeId : uint = _nodeToId[node];
if (forceUpdate)
{
var dirtyRoot : int = getDirtyRoot(nodeId);
if (dirtyRoot >= 0)
updateLocalToWorld(dirtyRoot);
}
return _localToWorldTransforms[nodeId];
}
public function getWorldToLocalTransform(node : ISceneNode,
forceUpdate : Boolean = false) : Matrix4x4
{
if (_invalidList || _nodeToId[node] == undefined)
updateTransformsList();
var nodeId : uint = _nodeToId[node];
var worldToLocalTransform : Matrix4x4 = _worldToLocalTransforms[nodeId];
if (!worldToLocalTransform)
{
_worldToLocalTransforms[nodeId] = worldToLocalTransform = new Matrix4x4();
if (!forceUpdate)
worldToLocalTransform.copyFrom(_localToWorldTransforms[nodeId]).invert();
}
if (forceUpdate)
{
var dirtyRoot : int = getDirtyRoot(nodeId);
if (dirtyRoot >= 0)
{
updateLocalToWorld(dirtyRoot);
worldToLocalTransform
.copyFrom(_localToWorldTransforms[nodeId])
.invert();
}
}
return worldToLocalTransform;
}
}
}
|
fix TransformController.updateLocalToWorld() to use !_localToWorldTransformsInitialized[childId] instead of _localToWorldTransformsInitialized[childId] to check if the child is dirty
|
fix TransformController.updateLocalToWorld() to use !_localToWorldTransformsInitialized[childId] instead of _localToWorldTransformsInitialized[childId] to check if the child is dirty
|
ActionScript
|
mit
|
aerys/minko-as3
|
dca4680d87577951eb0e72ca4215330a4dd7df42
|
frameworks/projects/framework/src/mx/utils/AndroidPlatformVersionOverride.as
|
frameworks/projects/framework/src/mx/utils/AndroidPlatformVersionOverride.as
|
package mx.utils
{
import flash.display.DisplayObject;
import flash.system.Capabilities;
import mx.core.mx_internal;
[Mixin]
public class AndroidPlatformVersionOverride
{
public static function init(root:DisplayObject):void
{
var c:Class = Capabilities;
//Set this override value on if we are
// a. on the AIR Simulator
// b. simulating Android
if(c.version.indexOf("AND") > -1 && c.manufacturer != "Android Linux")
{
Platform.mx_internal::androidVersionOverride = "4.1.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 mx.utils
{
import flash.display.DisplayObject;
import flash.system.Capabilities;
import mx.core.mx_internal;
[Mixin]
public class AndroidPlatformVersionOverride
{
public static function init(root:DisplayObject):void
{
var c:Class = Capabilities;
//Set this override value on if we are
// a. on the AIR Simulator
// b. simulating Android
if(c.version.indexOf("AND") > -1 && c.manufacturer != "Android Linux")
{
Platform.mx_internal::androidVersionOverride = "4.1.2";
}
}
}
}
|
Add Apache license header
|
Add Apache license header
|
ActionScript
|
apache-2.0
|
apache/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk
|
a0a19059f3cea08899eb57b25542231085d8c14b
|
src/aerys/minko/type/loader/SceneLoader.as
|
src/aerys/minko/type/loader/SceneLoader.as
|
package aerys.minko.type.loader
{
import aerys.minko.render.resource.texture.TextureResource;
import aerys.minko.scene.node.AbstractSceneNode;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.type.Signal;
import aerys.minko.type.loader.parser.IParser;
import aerys.minko.type.loader.parser.ParserOptions;
import flash.events.Event;
import flash.events.ProgressEvent;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import flash.utils.getQualifiedClassName;
public class SceneLoader implements ILoader
{
private static const REGISTERED_PARSERS : Vector.<Class> = new <Class>[];
private static const STATE_IDLE : uint = 0;
private static const STATE_LOADING : uint = 1;
private static const STATE_PARSING : uint = 2;
private static const STATE_COMPLETE : uint = 3;
private var _currentState : int;
private var _progress : Signal;
private var _complete : Signal;
private var _error : Signal;
private var _data : ISceneNode;
private var _parser : IParser;
private var _numDependencies : uint;
private var _dependencies : Vector.<ILoader>;
private var _parserOptions : ParserOptions;
private var _currentProgress : Number;
private var _currentProgressChanged : Boolean;
private var _isComplete : Boolean;
public function get error() : Signal
{
return _error;
}
public function get progress() : Signal
{
return _progress;
}
public function get complete() : Signal
{
return _complete;
}
public function get isComplete() : Boolean
{
return _isComplete;
}
public function get data() : ISceneNode
{
return _data;
}
public static function registerParser(parserClass : Class) : void
{
if (REGISTERED_PARSERS.indexOf(parserClass) != -1)
return;
if (!(new parserClass(new ParserOptions()) is IParser))
throw new Error('Parsers must implement the IParser interface.');
REGISTERED_PARSERS.push(parserClass);
}
public function SceneLoader(parserOptions : ParserOptions = null)
{
_currentState = STATE_IDLE;
_progress = new Signal('SceneLoader.progress');
_complete = new Signal('SceneLoader.complete');
_data = null;
_isComplete = false;
_parserOptions = parserOptions || new ParserOptions();
}
public function load(urlRequest : URLRequest) : void
{
if (_currentState != STATE_IDLE)
throw new Error('This controller is already loading an asset.');
_currentState = STATE_LOADING;
var urlLoader : URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
urlLoader.addEventListener(ProgressEvent.PROGRESS, loadProgressHandler);
urlLoader.addEventListener(Event.COMPLETE, loadCompleteHandler);
urlLoader.load(urlRequest);
}
private function loadProgressHandler(e : ProgressEvent) : void
{
_progress.execute(this, 0.5 * e.bytesLoaded / e.bytesTotal);
}
private function loadCompleteHandler(e : Event) : void
{
_currentState = STATE_IDLE;
loadBytes(URLLoader(e.currentTarget).data);
}
public function loadClass(classObject : Class) : void
{
loadBytes(new classObject());
}
public function loadBytes(byteArray : ByteArray) : void
{
var startPosition : uint = byteArray.position;
if (_currentState != STATE_IDLE)
throw new Error('This loader is already loading an asset.');
_currentState = STATE_PARSING;
_progress.execute(this, 0.5);
if (_parserOptions != null && _parserOptions.parser != null)
{
_parser = new (_parserOptions.parser)(_parserOptions);
if (!_parser.isParsable(byteArray))
throw new Error('Invalid datatype for this parser.');
}
else
{
// search a parser by testing registered parsers.
var numRegisteredParser : uint = REGISTERED_PARSERS.length;
for (var parserId : uint = 0; parserId < numRegisteredParser; ++parserId)
{
_parser = new REGISTERED_PARSERS[parserId](_parserOptions);
byteArray.position = startPosition;
if (_parser.isParsable(byteArray))
break;
}
if (parserId == numRegisteredParser)
throw new Error('No parser could be found for this datatype.');
}
byteArray.position = startPosition;
_dependencies = _parser.getDependencies(byteArray);
_numDependencies = 0;
if (_dependencies != null)
for each (var dependency : ILoader in _dependencies)
if (!dependency.isComplete)
{
dependency.error.add(decrementDependencyCounter);
dependency.complete.add(decrementDependencyCounter);
_numDependencies++;
}
if (_numDependencies == 0)
parse();
}
private function decrementDependencyCounter(...args) : void
{
--_numDependencies;
if (_numDependencies == 0)
parse();
}
private function parse() : void
{
_parser.error.add(onParseError);
_parser.progress.add(onParseProgress);
_parser.complete.add(onParseComplete);
_parser.parse();
}
private function onParseError(parser : IParser) : void
{
_isComplete = true;
}
private function onParseProgress(parser : IParser, progress : Number) : void
{
_progress.execute(this, 0.5 * (1 + progress));
}
private function onParseComplete(parser : IParser, loadedData : ISceneNode) : void
{
_isComplete = true;
_data = loadedData;
_complete.execute(this, loadedData);
}
}
}
|
package aerys.minko.type.loader
{
import aerys.minko.render.resource.texture.TextureResource;
import aerys.minko.scene.node.AbstractSceneNode;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.type.Signal;
import aerys.minko.type.loader.parser.IParser;
import aerys.minko.type.loader.parser.ParserOptions;
import flash.events.Event;
import flash.events.ProgressEvent;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import flash.utils.getQualifiedClassName;
import flash.utils.setTimeout;
public class SceneLoader implements ILoader
{
private static const REGISTERED_PARSERS : Vector.<Class> = new <Class>[];
private static const STATE_IDLE : uint = 0;
private static const STATE_LOADING : uint = 1;
private static const STATE_PARSING : uint = 2;
private static const STATE_COMPLETE : uint = 3;
private var _currentState : int;
private var _progress : Signal;
private var _complete : Signal;
private var _error : Signal;
private var _data : ISceneNode;
private var _parser : IParser;
private var _numDependencies : uint;
private var _dependencies : Vector.<ILoader>;
private var _parserOptions : ParserOptions;
private var _currentProgress : Number;
private var _currentProgressChanged : Boolean;
private var _isComplete : Boolean;
public function get error() : Signal
{
return _error;
}
public function get progress() : Signal
{
return _progress;
}
public function get complete() : Signal
{
return _complete;
}
public function get isComplete() : Boolean
{
return _isComplete;
}
public function get data() : ISceneNode
{
return _data;
}
public static function registerParser(parserClass : Class) : void
{
if (REGISTERED_PARSERS.indexOf(parserClass) != -1)
return;
if (!(new parserClass(new ParserOptions()) is IParser))
throw new Error('Parsers must implement the IParser interface.');
REGISTERED_PARSERS.push(parserClass);
}
public function SceneLoader(parserOptions : ParserOptions = null)
{
_currentState = STATE_IDLE;
_progress = new Signal('SceneLoader.progress');
_complete = new Signal('SceneLoader.complete');
_data = null;
_isComplete = false;
_parserOptions = parserOptions || new ParserOptions();
}
public function load(urlRequest : URLRequest) : void
{
if (_currentState != STATE_IDLE)
throw new Error('This controller is already loading an asset.');
_currentState = STATE_LOADING;
var urlLoader : URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
urlLoader.addEventListener(ProgressEvent.PROGRESS, loadProgressHandler);
urlLoader.addEventListener(Event.COMPLETE, loadCompleteHandler);
urlLoader.load(urlRequest);
}
private function loadProgressHandler(e : ProgressEvent) : void
{
_progress.execute(this, 0.5 * e.bytesLoaded / e.bytesTotal);
}
private function loadCompleteHandler(e : Event) : void
{
_currentState = STATE_IDLE;
loadBytes(URLLoader(e.currentTarget).data);
}
public function loadClass(classObject : Class) : void
{
loadBytes(new classObject());
}
public function loadBytes(byteArray : ByteArray) : void
{
var startPosition : uint = byteArray.position;
if (_currentState != STATE_IDLE)
throw new Error('This loader is already loading an asset.');
_currentState = STATE_PARSING;
_progress.execute(this, 0.5);
if (_parserOptions != null && _parserOptions.parser != null)
{
_parser = new (_parserOptions.parser)(_parserOptions);
if (!_parser.isParsable(byteArray))
throw new Error('Invalid datatype for this parser.');
}
else
{
// search a parser by testing registered parsers.
var numRegisteredParser : uint = REGISTERED_PARSERS.length;
for (var parserId : uint = 0; parserId < numRegisteredParser; ++parserId)
{
_parser = new REGISTERED_PARSERS[parserId](_parserOptions);
byteArray.position = startPosition;
if (_parser.isParsable(byteArray))
break;
}
if (parserId == numRegisteredParser)
throw new Error('No parser could be found for this datatype.');
}
byteArray.position = startPosition;
_dependencies = _parser.getDependencies(byteArray);
_numDependencies = 0;
if (_dependencies != null)
for each (var dependency : ILoader in _dependencies)
if (!dependency.isComplete)
{
dependency.error.add(decrementDependencyCounter);
dependency.complete.add(decrementDependencyCounter);
_numDependencies++;
}
if (_numDependencies == 0)
parse();
}
private function decrementDependencyCounter(...args) : void
{
--_numDependencies;
if (_numDependencies == 0)
parse();
}
private function parse() : void
{
_parser.error.add(parseErrorHandler);
_parser.progress.add(parseProgressHandler);
_parser.complete.add(parseCompleteHandler);
_parser.parse();
}
private function parseErrorHandler(parser : IParser) : void
{
_isComplete = true;
}
private function parseProgressHandler(parser : IParser, progress : Number) : void
{
_progress.execute(this, 0.5 * (1 + progress));
}
private function parseCompleteHandler(parser : IParser, loadedData : ISceneNode) : void
{
_isComplete = true;
_data = loadedData;
// call later to make sure the loading is always seen as asynchronous
setTimeout(callLaterComplete, 0, loadedData);
}
private function callLaterComplete(loadedData : ISceneNode) : void
{
_complete.execute(this, loadedData);
}
}
}
|
update SceneLoader.parseCompleteHandler() to use setTimeout() and enforce asynchronous-like signals even when loading/parsing is synchronous for the sake of consistency
|
update SceneLoader.parseCompleteHandler() to use setTimeout() and enforce asynchronous-like signals even when loading/parsing is synchronous for the sake of consistency
|
ActionScript
|
mit
|
aerys/minko-as3
|
b07522d56449eaa54de1ec2064f3843458d4c1db
|
com/segonquart/Entrar.as
|
com/segonquart/Entrar.as
|
import mx.events.EventDispatcher;
import mx.utils.Delegate;
import mx.transitions.easing.*;
import flash.filters.GlowFilter;
import com.mosesSupposes.fuse.*;
class com.segonquart.Entrar extends MovieClip
{
public var click_mc:MovieClip;
public var entrar_mc:MovieClip;
public var down:MovieClip;
public var ok_mc:MovieClip;
public var v1, v2, v3, b1, b2:MovieClip;
public var m01:MovieClip;
public var m02:MovieClip;
public var botiga_mc:MovieClip;
public var marcMenu_mc:MovieClip;
public var addEventListener:Function;
public var removeEventListener:Function;
public function Entrar ()
{
mx.events.EventDispatcher.initialize (this);
}
private function initAppFrame1 ()
{
var m= enter_mc;
this.m = m;
m.timeToEnter();
this.onRollOver = this.eOver;
this.onRollOut = this.eOut;
this.onPress = this.ePress;
}
private function eOver (m:MovieClip)
{
click_mc.tintTo ("#4A8618", 100, "easeOutSine");
m.scaleTo (110, 2, 'easeOutBounce');
m.DropShadow_distanceTo (3, .9, "easeOutBounce");
addEventListener (this, "onPress");
}
private function eOut (m:MovieClip)
{
click_mc.tintTo ("#FF0000", 100, "easeOutElastic");
m.scaleTo (100, 1, 'easeInBack');
m.DropShadow_distanceTo (0, 2, "easeOutBounce");
}
private function ePress (m:MovieClip)
{
m.Blur_blur = 0;
m.Blur_blurXTo ('100', .25, 'easeOutSine', {cycles:1});
m.alphaTo (0, 0.3, 'easeInOutQuint', .5);
down.tintTo ("#DCEECA", 100, "easeOutSine", .3);
v2.tintTo ("#95C60D", 100, "easeOutSine");
marcMenu_mc.fadeIn ();
titol_mcM.fadeOut () + 10000;
}
function timeToEnter (m:MovieClip)
{
var entrar:Number = getTimer () + 1500;
m.onRelease = function ()
{
if (getTimer () > entrar)
{
nextFrame ();
}
else
{
delete this.onEnterFrame;
}
};
}
}
|
import mx.events.EventDispatcher;
import mx.utils.Delegate;
import mx.transitions.easing.*;
import flash.filters.GlowFilter;
import com.mosesSupposes.fuse.*;
class com.segonquart.Entrar extends MovieClip
{
public var click_mc:MovieClip;
public var entrar_mc:MovieClip;
public var down:MovieClip;
public var ok_mc:MovieClip;
public var v1, v2, v3, b1, b2:MovieClip;
public var m01:MovieClip;
public var m02:MovieClip;
public var botiga_mc:MovieClip;
public var marcMenu_mc:MovieClip;
public var addEventListener:Function;
public var removeEventListener:Function;
public function Entrar ()
{
mx.events.EventDispatcher.initialize (this);
}
private function initAppFrame1 ()
{
var m= enter_mc;
this.m = m;
m.timeToEnter();
this.onRollOver = this.eOver;
this.onRollOut = this.eOut;
this.onPress = this.ePress;
}
private function eOver (m:MovieClip)
{
click_mc.tintTo ("#4A8618", 100, "easeOutSine");
m.scaleTo (110, 2, 'easeOutBounce');
m.DropShadow_distanceTo (3, .9, "easeOutBounce");
addEventListener (this, "onPress");
}
private function eOut (m:MovieClip)
{
click_mc.tintTo ("#FF0000", 100, "easeOutElastic");
m.scaleTo (100, 1, 'easeInBack');
m.DropShadow_distanceTo (0, 2, "easeOutBounce");
}
private function ePress (m:MovieClip)
{
m.Blur_blur = 0;
m.Blur_blurXTo ('100', .25, 'easeOutSine', {cycles:1});
m.alphaTo (0, 0.3, 'easeInOutQuint', .5);
down.tintTo ("#DCEECA", 100, "easeOutSine", .3);
v2.tintTo ("#95C60D", 100, "easeOutSine");
marcMenu_mc.fadeIn ();
titol_mcM.fadeOut () + 10000;
removeEventListener (this, "onPress");
}
private function timeToEnter (m:MovieClip)
{
var entrar:Number = getTimer () + 1500;
m.onRelease = function ()
{
if (getTimer () > entrar)
{
nextFrame ();
}
else
{
this.onEnterFrame = null;
}
};
}
}
|
refactor v2
|
refactor v2
|
ActionScript
|
bsd-3-clause
|
delfiramirez/web-talking-wear,delfiramirez/web-talking-wear,delfiramirez/web-talking-wear
|
a340a01ce0faa0603b6d40be6aad30beaeb6aefc
|
web/src/com/esri/ags/samples/GPXFeed.as
|
web/src/com/esri/ags/samples/GPXFeed.as
|
// Used by TemporalRenderer_FeatureCollection.mxml
package com.esri.ags.samples
{
import com.esri.ags.Graphic;
import com.esri.ags.Map;
import com.esri.ags.TimeExtent;
import com.esri.ags.components.TimeSlider;
import com.esri.ags.events.ExtentEvent;
import com.esri.ags.geometry.MapPoint;
import com.esri.ags.layers.FeatureLayer;
import com.esri.ags.utils.GraphicUtil;
import com.esri.ags.utils.WebMercatorUtil;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
public class GPXFeed
{
// constants
private static const GPX_NS:Namespace = new Namespace("http://www.topografix.com/GPX/1/1");
// constructor
public function GPXFeed()
{
_loader = new URLLoader();
_loader.addEventListener(Event.COMPLETE, loader_completeHandler);
_loader.addEventListener(IOErrorEvent.IO_ERROR, loader_ioErrorHandler);
_loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, loader_securityErrorHandler);
}
// variables
private var _loader:URLLoader;
// properties
public var featureLayer:FeatureLayer;
public var map:Map;
public var timeSlider:TimeSlider; // optional
public var url:String;
// methods
public function fetch():void
{
var request:URLRequest = new URLRequest();
request.url = url;
_loader.load(request);
}
private function parseDate(value:String):Date
{
// assume value is in the form 2009-07-15T14:13:35.000Z
value = value.replace("T", " ");
value = value.replace(/-/g, "/");
value = value.replace(".000Z", " UTC");
// value should now be in the form 2009/07/15 14:13:35 UTC
return new Date(value);
}
// event handlers
private function loader_completeHandler(event:Event):void
{
//trace(event);
var gpxXML:XML = new XML(_loader.data);
default xml namespace = GPX_NS;
var trkpts:XMLList = gpxXML..trkpt;
var timeExtent:TimeExtent = new TimeExtent();
var features:Array = [];
for each (var trkpt:XML in trkpts)
{
//trace(trkpt.@lon, trkpt.@lat, parseDate(trkpt.time).toUTCString());
var point:MapPoint = new MapPoint(trkpt.@lon, trkpt.@lat);
point = WebMercatorUtil.geographicToWebMercator(point) as MapPoint;
var time:Date = parseDate(trkpt.time);
var feature:Graphic = new Graphic(point, null, { "time": time });
features.push(feature);
// find startTime and endTime
if (!timeExtent.startTime || timeExtent.startTime.time > time.time)
{
timeExtent.startTime = time;
}
if (!timeExtent.endTime || timeExtent.endTime.time < time.time)
{
timeExtent.endTime = time;
}
}
if (features.length > 0)
{
featureLayer.applyEdits(features, null, null);
map.addEventListener(ExtentEvent.EXTENT_CHANGE, map_extentChangeHandler);
map.extent = GraphicUtil.getGraphicsExtent(features);
function map_extentChangeHandler(event:ExtentEvent):void
{
map.removeEventListener(ExtentEvent.EXTENT_CHANGE, map_extentChangeHandler);
if (timeExtent.startTime !== timeExtent.endTime)
{
if (timeSlider)
{
timeSlider.createTimeStopsByCount(timeExtent, 15);
}
else
{
map.timeExtent = timeExtent;
}
}
}
}
}
private function loader_ioErrorHandler(event:IOErrorEvent):void
{
trace(event);
}
private function loader_securityErrorHandler(event:SecurityErrorEvent):void
{
trace(event);
}
}
}
|
// Used by TemporalRenderer_FeatureCollection.mxml
package com.esri.ags.samples
{
import com.esri.ags.Graphic;
import com.esri.ags.Map;
import com.esri.ags.TimeExtent;
import com.esri.ags.components.TimeSlider;
import com.esri.ags.events.ExtentEvent;
import com.esri.ags.geometry.MapPoint;
import com.esri.ags.layers.FeatureLayer;
import com.esri.ags.utils.GraphicUtil;
import com.esri.ags.utils.WebMercatorUtil;
import flash.events.Event;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import mx.controls.Alert;
public class GPXFeed
{
// constants
private static const GPX_NS:Namespace = new Namespace("http://www.topografix.com/GPX/1/1");
// constructor
public function GPXFeed()
{
_loader = new URLLoader();
_loader.addEventListener(Event.COMPLETE, loader_completeHandler);
_loader.addEventListener(IOErrorEvent.IO_ERROR, loader_ioErrorHandler);
_loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, loader_securityErrorHandler);
_loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, loader_httpStatusHandler);
}
// variables
private var _loader:URLLoader;
// properties
public var featureLayer:FeatureLayer;
public var map:Map;
public var timeSlider:TimeSlider; // optional
public var url:String;
// methods
public function fetch():void
{
var request:URLRequest = new URLRequest();
request.url = url;
_loader.load(request);
}
private function parseDate(value:String):Date
{
// assume value is in the form 2009-07-15T14:13:35.000Z
value = value.replace("T", " ");
value = value.replace(/-/g, "/");
value = value.replace(".000Z", " UTC");
// value should now be in the form 2009/07/15 14:13:35 UTC
return new Date(value);
}
// event handlers
private function loader_completeHandler(event:Event):void
{
//trace(event);
var gpxXML:XML = new XML(_loader.data);
default xml namespace = GPX_NS;
var trkpts:XMLList = gpxXML..trkpt;
var timeExtent:TimeExtent = new TimeExtent();
var features:Array = [];
for each (var trkpt:XML in trkpts)
{
//trace(trkpt.@lon, trkpt.@lat, parseDate(trkpt.time).toUTCString());
var point:MapPoint = new MapPoint(trkpt.@lon, trkpt.@lat);
point = WebMercatorUtil.geographicToWebMercator(point) as MapPoint;
var time:Date = parseDate(trkpt.time);
var feature:Graphic = new Graphic(point, null, { "time": time });
features.push(feature);
// find startTime and endTime
if (!timeExtent.startTime || timeExtent.startTime.time > time.time)
{
timeExtent.startTime = time;
}
if (!timeExtent.endTime || timeExtent.endTime.time < time.time)
{
timeExtent.endTime = time;
}
}
if (features.length > 0)
{
featureLayer.applyEdits(features, null, null);
map.addEventListener(ExtentEvent.EXTENT_CHANGE, map_extentChangeHandler);
map.extent = GraphicUtil.getGraphicsExtent(features);
function map_extentChangeHandler(event:ExtentEvent):void
{
map.removeEventListener(ExtentEvent.EXTENT_CHANGE, map_extentChangeHandler);
if (timeExtent.startTime !== timeExtent.endTime)
{
if (timeSlider)
{
timeSlider.createTimeStopsByCount(timeExtent, 15);
}
else
{
map.timeExtent = timeExtent;
}
}
}
}
}
private function loader_ioErrorHandler(event:IOErrorEvent):void
{
Alert.show(event.text, "Application IOError");
}
private function loader_securityErrorHandler(event:SecurityErrorEvent):void
{
Alert.show(event.text, "Application Security Error");
}
protected function loader_httpStatusHandler(event:HTTPStatusEvent):void
{
if (event.status == 404)
{
Alert.show("Unable to load the following resource \n" + url, "http error");
}
}
}
}
|
Add alert messages when errors occur loading the file resource.
|
Add alert messages when errors occur loading the file resource.
|
ActionScript
|
apache-2.0
|
Esri/arcgis-samples-flex
|
dce6caf2eed64e4785d5f6a4d878bdb83d553327
|
src/utils/TextureUtil.as
|
src/utils/TextureUtil.as
|
package 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):Rectangle
{
for each(var rect:Rectangle in rectMap)
{
break;
}
if(!rect)
{
return null;
}
var dimensions:uint = 0;
var rectList:Vector.<Rectangle> = new Vector.<Rectangle>;
for each(rect in rectMap)
{
dimensions += rect.width * rect.height;
rectList.push(rect);
}
//sort texture by size
rectList.sort(sortRectList);
if(widthDefault == 0)
{
//calculate width for Auto size
widthDefault = Math.sqrt(dimensions);
}
widthDefault = getNearest2N(Math.max(int(rectList[0].width) + padding, 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 = getNearest2N(heightMax - getLowestArea(remainAreaList).height);
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 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):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 = getNearest2N(Math.max(maxWidth + padding, 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 = getNearest2N(heightMax - getLowestArea(remainAreaList).height);
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 get TextureAtlas width bug
|
fix get TextureAtlas width bug
|
ActionScript
|
mit
|
DragonBones/DesignPanel
|
882a810f9204e38d035988a8506280c899b8c079
|
sdk-remote/src/tests/liburbi-check.as
|
sdk-remote/src/tests/liburbi-check.as
|
m4_pattern_allow([^URBI_SERVER$]) -*- shell-script -*-
AS_INIT()dnl
URBI_PREPARE()
set -e
case $VERBOSE in
x) set -x;;
esac
# Avoid zombies and preserve debugging information.
cleanup ()
{
exit_status=$?
# In case we were caught by set -e, kill the children.
children_kill
children_harvest
children_report
children_sta=$(children_status remote)
# Don't clean before calling children_status...
test x$VERBOSE != x || children_clean
case $exit_status:$children_sta in
0:0) ;;
0:*) # Maybe a children exited for SKIP etc.
exit $children_sta;;
*:*) # If liburbi-check failed, there is a big problem.
error SOFTWARE "liburbi-check itself failed with $exit_status";;
esac
# rst_expect sets exit=false if it saw a failure.
$exit
}
for signal in 1 2 13 15; do
trap 'error $((128 + $signal)) \
"received signal $signal ($(kill -l $signal))"' $signal
done
trap cleanup 0
# Overriden to include the test name.
stderr ()
{
echo >&2 "$(basename $0): $me: $@"
echo >&2
}
# Sleep some time, but taking into account the fact that
# instrumentation slows down a lot.
my_sleep ()
{
if $INSTRUMENT; then
sleep $(($1 * 5))
else
sleep $1
fi
}
## -------------- ##
## Main program. ##
## -------------- ##
exec 3>&2
: ${abs_builddir='@abs_builddir@'}
check_dir abs_builddir liburbi-check
: ${abs_top_builddir='@abs_top_builddir@'}
check_dir abs_top_builddir config.status
# Make it absolute.
chk=$(absolute "$1")
if test ! -f "$chk.cc"; then
fatal "no such file: $chk.cc"
fi
period=32
# ./../../../tests/2.x/andexp-pipeexp.chk -> 2.x
medir=$(basename $(dirname "$chk"))
# ./../../../tests/2.x/andexp-pipeexp.chk -> 2.x/andexp-pipeexp
me=$medir/$(basename "$chk" ".cc")
# ./../../../tests/2.x/andexp-pipeexp.chk -> andexp-pipeexp
meraw=$(basename $me) # MERAW!
srcdir=$(absolute $srcdir)
export srcdir
# Move to a private dir.
rm -rf $me.dir
mkdir -p $me.dir
cd $me.dir
# Help debugging
set | rst_pre "$me variables"
# $URBI_SERVER.
#
# If this SDK-Remote is part of the Kernel package, then we should not
# use an installed urbi-console, but rather the one which is part of
# this package.
if test -x ${abs_top_builddir}/../src/urbi-console; then
URBI_SERVER=${abs_top_builddir}/../src/urbi-console
else
# Leaves trailing files, so run it in subdir.
find_urbi_server
fi
# compute expected output
sed -n -e 's@//= @@p' $chk.cc >output.exp
touch error.exp
echo 0 >status.exp
#start it
valgrind=$(instrument "server.val")
cmd="$valgrind $URBI_SERVER --port 0 -w server.port --period $period"
echo "$cmd" >server.cmd
$cmd >server.out 2>server.err &
children_register server
my_sleep 2
#start the test
valgrind=$(instrument "remote.val")
cmd="$valgrind ../../tests localhost $(cat server.port) $meraw"
echo "$cmd" >remote.cmd
$cmd >remote.out.raw 2>remote.err &
children_register remote
# Let some time to run the tests.
children_wait 10
# Ignore the "client errors".
sed -e '/^E client error/d' remote.out.raw >remote.out.eff
# Compare expected output with actual output.
rst_expect output remote.out
rst_pre "Error output" remote.err
# Display Valgrind report.
rst_pre "Valgrind" remote.val
# Exit with success: liburbi-check made its job. But now clean (on
# trap 0) will check $exit to see if there is a failure in the tests
# and adjust the exit status accordingly.
exit 0
|
m4_pattern_allow([^URBI_(PATH|SERVER)$]) -*- shell-script -*-
AS_INIT()dnl
URBI_PREPARE()
set -e
case $VERBOSE in
x) set -x;;
esac
# Avoid zombies and preserve debugging information.
cleanup ()
{
exit_status=$?
# In case we were caught by set -e, kill the children.
children_kill
children_harvest
children_report
children_sta=$(children_status remote)
# Don't clean before calling children_status...
test x$VERBOSE != x || children_clean
case $exit_status:$children_sta in
0:0) ;;
0:*) # Maybe a children exited for SKIP etc.
exit $children_sta;;
*:*) # If liburbi-check failed, there is a big problem.
error SOFTWARE "liburbi-check itself failed with $exit_status";;
esac
# rst_expect sets exit=false if it saw a failure.
$exit
}
for signal in 1 2 13 15; do
trap 'error $((128 + $signal)) \
"received signal $signal ($(kill -l $signal))"' $signal
done
trap cleanup 0
# Overriden to include the test name.
stderr ()
{
echo >&2 "$(basename $0): $me: $@"
echo >&2
}
# Sleep some time, but taking into account the fact that
# instrumentation slows down a lot.
my_sleep ()
{
if $INSTRUMENT; then
sleep $(($1 * 5))
else
sleep $1
fi
}
## -------------- ##
## Main program. ##
## -------------- ##
exec 3>&2
: ${abs_builddir='@abs_builddir@'}
check_dir abs_builddir liburbi-check
: ${abs_top_builddir='@abs_top_builddir@'}
check_dir abs_top_builddir config.status
: ${abs_top_srcdir='@abs_top_srcdir@'}
check_dir abs_top_srcdir configure.ac
# Make it absolute.
chk=$(absolute "$1")
if test ! -f "$chk.cc"; then
fatal "no such file: $chk.cc"
fi
period=32
# ./../../../tests/2.x/andexp-pipeexp.chk -> 2.x
medir=$(basename $(dirname "$chk"))
# ./../../../tests/2.x/andexp-pipeexp.chk -> 2.x/andexp-pipeexp
me=$medir/$(basename "$chk" ".cc")
# ./../../../tests/2.x/andexp-pipeexp.chk -> andexp-pipeexp
meraw=$(basename $me) # MERAW!
srcdir=$(absolute $srcdir)
export srcdir
# Move to a private dir.
rm -rf $me.dir
mkdir -p $me.dir
cd $me.dir
# Help debugging
set | rst_pre "$me variables"
# $URBI_SERVER.
#
# If this SDK-Remote is part of the Kernel package, then we should not
# use an installed urbi-console, but rather the one which is part of
# this package.
if test -x $abs_top_builddir/../src/urbi-console; then
URBI_SERVER=$abs_top_builddir/../src/urbi-console
export URBI_PATH=$abs_top_srcdir/../share
else
# Leaves trailing files, so run it in subdir.
find_urbi_server
fi
# compute expected output
sed -n -e 's@//= @@p' $chk.cc >output.exp
touch error.exp
echo 0 >status.exp
#start it
valgrind=$(instrument "server.val")
cmd="$valgrind $URBI_SERVER --port 0 -w server.port --period $period"
echo "$cmd" >server.cmd
$cmd >server.out 2>server.err &
children_register server
my_sleep 2
#start the test
valgrind=$(instrument "remote.val")
cmd="$valgrind ../../tests localhost $(cat server.port) $meraw"
echo "$cmd" >remote.cmd
$cmd >remote.out.raw 2>remote.err &
children_register remote
# Let some time to run the tests.
children_wait 10
# Ignore the "client errors".
sed -e '/^E client error/d' remote.out.raw >remote.out.eff
# Compare expected output with actual output.
rst_expect output remote.out
rst_pre "Error output" remote.err
# Display Valgrind report.
rst_pre "Valgrind" remote.val
# Exit with success: liburbi-check made its job. But now clean (on
# trap 0) will check $exit to see if there is a failure in the tests
# and adjust the exit status accordingly.
exit 0
|
Fix make check to use the shipped kernel.
|
Fix make check to use the shipped kernel.
* src/tests/liburbi-check.as: If we are part of a shipped
Kernel, set the appropriate URBI_PATH.
|
ActionScript
|
bsd-3-clause
|
urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi
|
57811f80190f5f421b5c93c45186a40752f559a1
|
exporter/src/main/as/flump/export/PreviewController.as
|
exporter/src/main/as/flump/export/PreviewController.as
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.export {
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Rectangle;
import flash.text.TextField;
import flump.Util;
import flump.display.Movie;
import flump.mold.MovieMold;
import flump.xfl.XflLibrary;
import flump.xfl.XflTexture;
import mx.core.UIComponent;
import spark.components.Group;
import spark.events.GridSelectionEvent;
import spark.formatters.NumberFormatter;
import starling.core.Starling;
import starling.display.DisplayObject;
import starling.display.Sprite;
import com.threerings.util.F;
import com.threerings.util.MathUtil;
import com.threerings.text.TextFieldUtil;
public class PreviewController
{
public function show (project :ProjectConf, lib :XflLibrary) :void {
_lib = lib;
_project = project;
if (_controlsWindow == null || _controlsWindow.closed) {
createControlsWindow();
} else {
_controlsWindow.activate();
}
if (_animPreviewWindow == null || _animPreviewWindow.closed) {
createAnimWindow();
} else {
_animPreviewWindow.activate();
showInternal();
}
}
protected function createAnimWindow () :void {
_animPreviewWindow = new AnimPreviewWindow();
_animPreviewWindow.started = function (container :starling.display.Sprite) :void {
_container = container;
_originIcon = Util.createOriginIcon();
Starling.current.stage.addEventListener(Event.RESIZE, onAnimPreviewResize);
showInternal();
};
_animPreviewWindow.open();
}
protected function createControlsWindow () :void {
_controlsWindow = new PreviewControlsWindow();
_controlsWindow.open();
_controlsWindow.movies.addEventListener(GridSelectionEvent.SELECTION_CHANGE,
function (..._) :void {
_controlsWindow.textures.selectedIndex = -1;
displayLibraryItem(_controlsWindow.movies.selectedItem.movie);
});
_controlsWindow.textures.addEventListener(GridSelectionEvent.SELECTION_CHANGE,
function (..._) :void {
_controlsWindow.movies.selectedIndex = -1;
displayLibraryItem(_controlsWindow.textures.selectedItem.texture);
});
_controlsWindow.showAtlas.addEventListener(MouseEvent.CLICK, function (..._) :void {
if (_atlasPreviewWindow == null || _atlasPreviewWindow.closed) {
createAtlasWindow();
} else {
_atlasPreviewWindow.activate();
}
});
}
protected function createAtlasWindow () :void {
_atlasPreviewWindow = new AtlasPreviewWindow();
_atlasPreviewWindow.open();
// default our atlas scale to our export scale
var scale :Number = 1;
if (_project.exports.length > 0) {
const exportConf :ExportConf = _project.exports[0];
scale = exportConf.scale;
}
_atlasPreviewWindow.scale.text = "" + scale;
_atlasPreviewWindow.setScale.addEventListener(MouseEvent.CLICK, F.callback(updateAtlas));
updateAtlas();
}
protected function updateAtlas () :void {
// create our atlases
const scale :Number = MathUtil.clamp(Number(_atlasPreviewWindow.scale.text), 0.001, 1);
const atlases :Vector.<Atlas> = TexturePacker.withLib(_lib).baseScale(scale).createAtlases();
const sprite :flash.display.Sprite = new flash.display.Sprite();
for (var ii :int = 0; ii < atlases.length; ++ii) {
var atlas :Atlas = atlases[ii];
var atlasSprite :flash.display.Sprite = AtlasUtil.toSprite(atlas);
var w :int = atlasSprite.width;
var h :int = atlasSprite.height;
// atlas info
var tf :TextField = TextFieldUtil.newBuilder()
.text("Atlas " + ii + ": " + int(w) + "x" + int(h))
.color(0x0)
.autoSizeCenter()
.build();
tf.x = 2;
tf.y = sprite.height;
sprite.addChild(tf);
// border
atlasSprite.graphics.lineStyle(1, 0x0000ff);
atlasSprite.graphics.drawRect(0, 0, w, h);
atlasSprite.y = sprite.height;
sprite.addChild(atlasSprite);
}
const uic :UIComponent = new UIComponent();
uic.addChild(sprite);
const group :Group = _atlasPreviewWindow.bitmapLayoutGroup;
group.removeAllElements();
group.addElement(uic);
// Agh. I cannot figure out how to get the group to properly resize itself when
// new elements are added.
group.width = sprite.width;
group.height = sprite.height;
//_atlasPreviewWindow.maxWidth = width;
//_atlasPreviewWindow.maxHeight = height;
}
protected function showInternal () :void {
_creator = new DisplayCreator(_lib);
const intFormatter :NumberFormatter = new NumberFormatter();
const formatMemory :Function = function (item :Object, ..._) :String {
return intFormatter.format(item.memory/1024) + "k";
};
intFormatter.fractionalDigits = 0;
// Use a labelFunction so column sorting works as expected
_controlsWindow.movieMemory.labelFunction = formatMemory;
_controlsWindow.textureMemory.labelFunction = formatMemory;
// All explicitly exported movies
const previewMovies :Vector.<MovieMold> =
_lib.movies.filter(function (movie :MovieMold, ..._) :Boolean {
return _lib.isExported(movie);
});
_controlsWindow.movies.dataProvider.removeAll();
for each (var movie :MovieMold in previewMovies) {
_controlsWindow.movies.dataProvider.addItem({
movie: movie.id,
memory: _creator.getMemoryUsage(movie.id),
drawn: _creator.getMaxDrawn(movie.id)
});
}
var totalUsage :int = 0;
_controlsWindow.textures.dataProvider.removeAll();
for each (var tex :XflTexture in _lib.textures) {
var itemUsage :int = _creator.getMemoryUsage(tex.symbol);
totalUsage += itemUsage;
_controlsWindow.textures.dataProvider.addItem({texture: tex.symbol, memory: itemUsage});
}
_controlsWindow.totalValue.text = formatMemory({memory: totalUsage});
var atlasSize :Number = 0;
var atlasUsed :Number = 0;
for each (var atlas :Atlas in TexturePacker.withLib(_lib).createAtlases()) {
atlasSize += atlas.area;
atlasUsed += atlas.used;
}
const percentFormatter :NumberFormatter = new NumberFormatter();
percentFormatter.fractionalDigits = 2;
_controlsWindow.atlasWasteValue.text = percentFormatter.format((1.0 - (atlasUsed/atlasSize)) * 100) + "%";
if (previewMovies.length > 0) {
// Play the first movie
_controlsWindow.movies.selectedIndex = 0;
// Grumble, wish setting the index above would fire the listener
displayLibraryItem(previewMovies[0].id);
}
Starling.current.stage.color = _lib.backgroundColor;
if (_atlasPreviewWindow != null && !_atlasPreviewWindow.closed) {
updateAtlas();
}
}
protected function displayLibraryItem (name :String) :void {
while (_container.numChildren > 0) _container.removeChildAt(0);
_previewSprite = _creator.createDisplayObject(name);
_container.addChild(_previewSprite);
_container.addChild(_originIcon);
if (_previewSprite is Movie) {
Starling.juggler.add(Movie(_previewSprite));
}
onAnimPreviewResize();
}
protected function onAnimPreviewResize (..._) :void {
var bounds :Rectangle = _previewSprite.bounds;
_previewSprite.x = _originIcon.x = ((_animPreviewWindow.width - bounds.width) * 0.5) - bounds.left;
_previewSprite.y = _originIcon.y = ((_animPreviewWindow.height - bounds.height) * 0.5) - bounds.top;
}
protected var _previewSprite :starling.display.DisplayObject;
protected var _container :starling.display.Sprite;
protected var _originIcon :starling.display.Sprite;
protected var _controlsWindow :PreviewControlsWindow;
protected var _animPreviewWindow :AnimPreviewWindow;
protected var _atlasPreviewWindow :AtlasPreviewWindow;
protected var _creator :DisplayCreator;
protected var _lib :XflLibrary;
protected var _project :ProjectConf;
}
}
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.export {
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Rectangle;
import flash.text.TextField;
import flump.Util;
import flump.display.Movie;
import flump.mold.MovieMold;
import flump.xfl.XflLibrary;
import flump.xfl.XflTexture;
import mx.core.UIComponent;
import spark.components.Group;
import spark.events.GridSelectionEvent;
import spark.formatters.NumberFormatter;
import starling.core.Starling;
import starling.display.DisplayObject;
import starling.display.Sprite;
import com.threerings.util.F;
import com.threerings.util.MathUtil;
import com.threerings.text.TextFieldUtil;
public class PreviewController
{
public function show (project :ProjectConf, lib :XflLibrary) :void {
_lib = lib;
_project = project;
if (_controlsWindow == null || _controlsWindow.closed) {
createControlsWindow();
} else {
_controlsWindow.activate();
}
if (_animPreviewWindow == null || _animPreviewWindow.closed) {
createAnimWindow();
} else {
_animPreviewWindow.activate();
showInternal();
}
}
protected function createAnimWindow () :void {
_animPreviewWindow = new AnimPreviewWindow();
_animPreviewWindow.started = function (container :starling.display.Sprite) :void {
_container = container;
_originIcon = Util.createOriginIcon();
Starling.current.stage.addEventListener(Event.RESIZE, onAnimPreviewResize);
showInternal();
};
_animPreviewWindow.open();
}
protected function createControlsWindow () :void {
_controlsWindow = new PreviewControlsWindow();
_controlsWindow.open();
_controlsWindow.movies.addEventListener(GridSelectionEvent.SELECTION_CHANGE,
function (..._) :void {
_controlsWindow.textures.selectedIndex = -1;
displayLibraryItem(_controlsWindow.movies.selectedItem.movie);
});
_controlsWindow.textures.addEventListener(GridSelectionEvent.SELECTION_CHANGE,
function (..._) :void {
_controlsWindow.movies.selectedIndex = -1;
displayLibraryItem(_controlsWindow.textures.selectedItem.texture);
});
_controlsWindow.showAtlas.addEventListener(MouseEvent.CLICK, function (..._) :void {
if (_atlasPreviewWindow == null || _atlasPreviewWindow.closed) {
createAtlasWindow();
} else {
_atlasPreviewWindow.activate();
}
});
}
protected function createAtlasWindow () :void {
_atlasPreviewWindow = new AtlasPreviewWindow();
_atlasPreviewWindow.open();
// default our atlas scale to our export scale
var scale :Number = 1;
if (_project.exports.length > 0) {
const exportConf :ExportConf = _project.exports[0];
scale = exportConf.scale;
}
_atlasPreviewWindow.scale.text = "" + scale;
_atlasPreviewWindow.setScale.addEventListener(MouseEvent.CLICK, F.callback(updateAtlas));
updateAtlas();
}
protected function updateAtlas () :void {
// create our atlases
const scale :Number = MathUtil.clamp(Number(_atlasPreviewWindow.scale.text), 0.001, 1);
const atlases :Vector.<Atlas> = TexturePacker.withLib(_lib).baseScale(scale).createAtlases();
const sprite :flash.display.Sprite = new flash.display.Sprite();
for (var ii :int = 0; ii < atlases.length; ++ii) {
var atlas :Atlas = atlases[ii];
var atlasSprite :flash.display.Sprite = AtlasUtil.toSprite(atlas);
var w :int = atlasSprite.width;
var h :int = atlasSprite.height;
// atlas info
var tf :TextField = TextFieldUtil.newBuilder()
.text("Atlas " + ii + ": " + int(w) + "x" + int(h))
.color(0x0)
.autoSizeCenter()
.build();
tf.x = 2;
tf.y = sprite.height;
sprite.addChild(tf);
// border
atlasSprite.graphics.lineStyle(1, 0x0000ff);
atlasSprite.graphics.drawRect(0, 0, w, h);
atlasSprite.y = sprite.height;
sprite.addChild(atlasSprite);
}
const uic :UIComponent = new UIComponent();
uic.addChild(sprite);
const group :Group = _atlasPreviewWindow.bitmapLayoutGroup;
group.removeAllElements();
group.addElement(uic);
// Agh. I cannot figure out how to get the group to properly resize itself when
// new elements are added.
group.width = sprite.width;
group.height = sprite.height;
//_atlasPreviewWindow.maxWidth = width;
//_atlasPreviewWindow.maxHeight = height;
}
protected function showInternal () :void {
_creator = new DisplayCreator(_lib);
const intFormatter :NumberFormatter = new NumberFormatter();
const formatMemory :Function = function (item :Object, ..._) :String {
return intFormatter.format(item.memory/1024) + "k";
};
intFormatter.fractionalDigits = 0;
// Use a labelFunction so column sorting works as expected
_controlsWindow.movieMemory.labelFunction = formatMemory;
_controlsWindow.textureMemory.labelFunction = formatMemory;
// All explicitly exported movies
const previewMovies :Vector.<MovieMold> =
_lib.movies.filter(function (movie :MovieMold, ..._) :Boolean {
return _lib.isExported(movie);
});
_controlsWindow.movies.dataProvider.removeAll();
for each (var movie :MovieMold in previewMovies) {
_controlsWindow.movies.dataProvider.addItem({
movie: movie.id,
memory: _creator.getMemoryUsage(movie.id),
drawn: _creator.getMaxDrawn(movie.id)
});
}
var totalUsage :int = 0;
_controlsWindow.textures.dataProvider.removeAll();
for each (var tex :XflTexture in _lib.textures) {
var itemUsage :int = _creator.getMemoryUsage(tex.symbol);
totalUsage += itemUsage;
_controlsWindow.textures.dataProvider.addItem({texture: tex.symbol, memory: itemUsage});
}
_controlsWindow.totalValue.text = formatMemory({memory: totalUsage});
var atlasSize :Number = 0;
var atlasUsed :Number = 0;
for each (var atlas :Atlas in TexturePacker.withLib(_lib).createAtlases()) {
atlasSize += atlas.area;
atlasUsed += atlas.used;
}
const percentFormatter :NumberFormatter = new NumberFormatter();
percentFormatter.fractionalDigits = 2;
_controlsWindow.atlasWasteValue.text = percentFormatter.format((1.0 - (atlasUsed/atlasSize)) * 100) + "%";
if (previewMovies.length > 0) {
// Play the first movie
_controlsWindow.movies.selectedIndex = 0;
// Grumble, wish setting the index above would fire the listener
displayLibraryItem(previewMovies[0].id);
}
Starling.current.stage.color = _lib.backgroundColor;
if (_atlasPreviewWindow != null && !_atlasPreviewWindow.closed) {
updateAtlas();
}
}
protected function displayLibraryItem (name :String) :void {
while (_container.numChildren > 0) _container.removeChildAt(0);
_previewSprite = _creator.createDisplayObject(name);
_previewBounds = _previewSprite.bounds;
_container.addChild(_previewSprite);
_container.addChild(_originIcon);
if (_previewSprite is Movie) {
Starling.juggler.add(Movie(_previewSprite));
}
onAnimPreviewResize();
}
protected function onAnimPreviewResize (..._) :void {
_previewSprite.x = _originIcon.x =
((_animPreviewWindow.width - _previewBounds.width) * 0.5) - _previewBounds.left;
_previewSprite.y = _originIcon.y =
((_animPreviewWindow.height - _previewBounds.height) * 0.5) - _previewBounds.top;
}
protected var _previewSprite :starling.display.DisplayObject;
protected var _previewBounds :Rectangle;
protected var _container :starling.display.Sprite;
protected var _originIcon :starling.display.Sprite;
protected var _controlsWindow :PreviewControlsWindow;
protected var _animPreviewWindow :AnimPreviewWindow;
protected var _atlasPreviewWindow :AtlasPreviewWindow;
protected var _creator :DisplayCreator;
protected var _lib :XflLibrary;
protected var _project :ProjectConf;
}
}
|
Fix animation re-centering on window resize
|
Fix animation re-centering on window resize
|
ActionScript
|
mit
|
tconkling/flump,funkypandagame/flump,funkypandagame/flump,mathieuanthoine/flump,mathieuanthoine/flump,mathieuanthoine/flump,tconkling/flump
|
a6ecf3e95647ba5b88ae1b7a0cc203de634e9fde
|
HLSPlugin/src/com/kaltura/hls/SubtitleTrait.as
|
HLSPlugin/src/com/kaltura/hls/SubtitleTrait.as
|
package com.kaltura.hls
{
import com.kaltura.hls.manifest.HLSManifestPlaylist;
import com.kaltura.hls.manifest.HLSManifestParser;
import com.kaltura.hls.subtitles.SubTitleParser;
import com.kaltura.hls.subtitles.TextTrackCue;
import com.kaltura.hls.HLSDVRTimeTrait;
import org.osmf.traits.MediaTraitBase;
import org.osmf.traits.MediaTraitType;
import org.osmf.traits.TimeTrait;
import org.osmf.traits.SeekTrait;
import org.osmf.media.MediaElement;
import flash.events.*;
import flash.utils.*;
public class SubtitleTrait extends MediaTraitBase
{
public static const TYPE:String = "subtitle";
private var _playLists:Vector.<HLSManifestPlaylist> = new <HLSManifestPlaylist>[];
private var _languages:Vector.<String> = new <String>[];
private var _language:String = "";
public var owningMediaElement:MediaElement;
private var _lastCue:TextTrackCue;
private var _lastInjectedSubtitleTime:Number = -1;
private static var activeTrait:SubtitleTrait = null;
private static var activeReload:HLSManifestParser;
private static var reloadLanguage:String = null;
private static var _reloadTimer:Timer;
private static var _subtitleTimer:Timer;
public function SubtitleTrait()
{
super(TYPE);
activeTrait = this;
if(!_reloadTimer)
{
trace("SubTitleTrait - starting reload timer");
_reloadTimer = new Timer(1000);
_reloadTimer.addEventListener(TimerEvent.TIMER, onReloadTimer);
_reloadTimer.start();
}
if(!_subtitleTimer)
{
trace("SubTitleTrait - starting subtitle timer");
_subtitleTimer = new Timer(50);
_subtitleTimer.addEventListener(TimerEvent.TIMER, onSubtitleTimer);
_subtitleTimer.start();
}
}
/**
* Fired frequently to emit any new subtitle events based on playhead position.
*/
private static function onSubtitleTimer(e:Event):void
{
// If no trait/no titles, ignore it.
if(activeTrait == null || activeTrait.activeSubtitles == null)
return;
// Otherwise, attempt to get the time trait and determine our current playtime.
if(!activeTrait.owningMediaElement)
return;
var tt:TimeTrait = activeTrait.owningMediaElement.getTrait(MediaTraitType.TIME) as TimeTrait;
if(!tt)
return;
// Great, time is knowable - so what is it?
var curTime:Number = tt.currentTime;
if(tt is HLSDVRTimeTrait)
curTime = (tt as HLSDVRTimeTrait).absoluteTime;
// This is quite verbose but useful for debugging.
// trace("onSubtitleTimer - Current time is: " + curTime);
// Now, fire off any subtitles that are new.
activeTrait.emitSubtitles(activeTrait._lastInjectedSubtitleTime, curTime);
}
/**
* Actually fire subtitle events for any subtitles in the specified period.
*/
private function emitSubtitles( startTime:Number, endTime:Number ):void
{
var subtitles:Vector.<SubTitleParser> = activeSubtitles;
var subtitleCount:int = subtitles.length;
for ( var i:int = 0; i < subtitleCount; i++ )
{
var subtitle:SubTitleParser = subtitles[ i ];
if ( subtitle.startTime > endTime ) continue;
if ( subtitle.endTime < startTime ) continue;
var cues:Vector.<TextTrackCue> = subtitle.textTrackCues;
var cueCount:int = cues.length;
var potentials:Vector.<TextTrackCue> = new Vector.<TextTrackCue>();
for ( var j:int = 0; j < cueCount; j++ )
{
var cue:TextTrackCue = cues[ j ];
if ( cue.startTime > endTime ) break;
else if ( cue.startTime >= startTime )
{
potentials.push(cue);
}
}
if(potentials.length > 0)
{
// TODO: Add support for trackid
cue = potentials[potentials.length - 1];
if(cue != _lastCue)
{
dispatchEvent(new SubtitleEvent(cue.startTime, cue.text, language));
_lastInjectedSubtitleTime = cue.startTime;
_lastCue = cue;
}
}
}
}
/**
* Fired intermittently to check for new subtitle segments to download.
*/
private static function onReloadTimer(e:Event):void
{
// Check for any subtitles that have not been requested yet.
if(activeTrait == null || activeTrait.activeManifest == null)
{
trace("SubTitleTrait - skipping reload, inactive")
return;
}
// If reloading but not parsed yet.
if(activeReload && activeReload.timestamp == -1)
{
trace("SubTitleTrait - skipping reload, pending download");
return;
}
// Or it's a VOD or was recently reloaded.
var man:HLSManifestParser = activeTrait.activeManifest;
if(man &&
(man.streamEnds
|| (getTimer() - man.lastReloadRequestTime) < man.targetDuration * 1000 * 0.75))
{
trace("SubTitleTrait - skipping reload, waiting until targetDuration has expired.");
return;
}
if(man)
{
trace("Saw manifest with age " + (getTimer() - man.lastReloadRequestTime) + " and targetDuration " + man.targetDuration * 1000 );
}
trace("SubTitleTrait - initiating reload of " + man.fullUrl);
var manifest:HLSManifestParser = new HLSManifestParser();
manifest.addEventListener(Event.COMPLETE, onManifestReloaded);
manifest.addEventListener(IOErrorEvent.IO_ERROR, onManifestReloadFail);
manifest.type = HLSManifestParser.SUBTITLES;
manifest.reload(man);
activeReload = manifest;
reloadLanguage = activeTrait.language;
}
private static function onManifestReloaded(e:Event):void
{
if(e.target != activeReload || reloadLanguage != activeTrait.language)
{
trace("Got subtitle manifest reload for non-active manifest, ignoring...");
return;
}
// Instate the manifest.
trace("Subtitle manifest downloaded, instating " + reloadLanguage);
activeTrait.instateNewManifest(reloadLanguage, e.target as HLSManifestParser);
activeReload = null;
reloadLanguage = null;
}
private static function onManifestReloadFail(e:Event):void
{
if(e.target != activeReload || reloadLanguage != activeTrait.language)
{
trace("Got subtitle manifest reload for non-active manifest, ignoring...");
return;
}
trace("Subtitle manifest failed, clearing reload attempt.");
activeReload = null;
reloadLanguage = null;
}
protected function instateNewManifest(lang:String, man:HLSManifestParser):void
{
if(language != lang)
return;
if ( _language == "" ) return;
for ( var i:int = 0; i < _playLists.length; i++ )
{
// If the playlist has a language associated with it, use that language
var pLanguage:String;
if (_playLists[ i ].language && _playLists[ i ].language != "")
pLanguage = _playLists[ i ].language;
else
pLanguage = _playLists[ i ].name;
if (pLanguage == _language )
{
_playLists[ i ].manifest = man;
}
}
}
public function set playLists( value:Vector.<HLSManifestPlaylist> ):void
{
_playLists.length = 0;
_languages.length = 0;
if ( !value ) return;
for ( var i:int = 0; i < value.length; i++ )
{
_playLists.push( value[ i ] );
if (value[ i ].language && value[ i ].language != "")
_languages.push( value[ i ].language );
else
_languages.push( value[ i ].name );
}
}
public function set language( value:String ):void
{
// Trigger a seek to flush buffer and get proper language.
if(_language != value)
{
_language = value;
trace("Triggering flush for proper subtitle language.");
if(owningMediaElement)
{
var st:SeekTrait = owningMediaElement.getTrait(MediaTraitType.SEEK) as SeekTrait;
var tt:TimeTrait = owningMediaElement.getTrait(MediaTraitType.TIME) as TimeTrait;
if(st == null)
{
trace(" o No seek trait, skipping...");
}
if(tt == null)
{
trace(" o No time trait, skipping...");
}
if(st != null && tt != null)
{
trace(" o Initiating seek to " + tt.currentTime);
//st.seek(tt.currentTime);
}
}
else
{
trace(" o No media element, skipping...");
}
}
}
public function get language():String
{
return _language;
}
public function get languages():Vector.<String>
{
return _languages;
}
public function get activeManifest():HLSManifestParser
{
if ( _language == "" ) return null;
for ( var i:int = 0; i < _playLists.length; i++ )
{
// If the playlist has a language associated with it, use that language
var pLanguage:String;
if (_playLists[ i ].language && _playLists[ i ].language != "")
pLanguage = _playLists[ i ].language;
else
pLanguage = _playLists[ i ].name;
if (pLanguage == _language ) return _playLists[ i ].manifest;
}
return null;
}
public function get activeSubtitles():Vector.<SubTitleParser>
{
var man:HLSManifestParser = activeManifest;
if(man)
return man.subtitles;
return null;
}
}
}
|
package com.kaltura.hls
{
import com.kaltura.hls.manifest.HLSManifestPlaylist;
import com.kaltura.hls.manifest.HLSManifestParser;
import com.kaltura.hls.subtitles.SubTitleParser;
import com.kaltura.hls.subtitles.TextTrackCue;
import com.kaltura.hls.HLSDVRTimeTrait;
import org.osmf.traits.MediaTraitBase;
import org.osmf.traits.MediaTraitType;
import org.osmf.traits.TimeTrait;
import org.osmf.traits.SeekTrait;
import org.osmf.media.MediaElement;
import flash.events.*;
import flash.utils.*;
public class SubtitleTrait extends MediaTraitBase
{
public static const TYPE:String = "subtitle";
private var _playLists:Vector.<HLSManifestPlaylist> = new <HLSManifestPlaylist>[];
private var _languages:Vector.<String> = new <String>[];
private var _language:String = "";
public var owningMediaElement:MediaElement;
private var _lastCue:TextTrackCue;
private var _lastInjectedSubtitleTime:Number = -1;
private static var activeTrait:SubtitleTrait = null;
private static var activeReload:HLSManifestParser;
private static var reloadLanguage:String = null;
private static var _reloadTimer:Timer;
private static var _subtitleTimer:Timer;
public function SubtitleTrait()
{
super(TYPE);
activeTrait = this;
if(!_reloadTimer)
{
trace("SubTitleTrait - starting reload timer");
_reloadTimer = new Timer(1000);
_reloadTimer.addEventListener(TimerEvent.TIMER, onReloadTimer);
_reloadTimer.start();
}
if(!_subtitleTimer)
{
trace("SubTitleTrait - starting subtitle timer");
_subtitleTimer = new Timer(50);
_subtitleTimer.addEventListener(TimerEvent.TIMER, onSubtitleTimer);
_subtitleTimer.start();
}
}
/**
* Fired frequently to emit any new subtitle events based on playhead position.
*/
private static function onSubtitleTimer(e:Event):void
{
// If no trait/no titles, ignore it.
if(activeTrait == null || activeTrait.activeSubtitles == null)
return;
// Otherwise, attempt to get the time trait and determine our current playtime.
if(!activeTrait.owningMediaElement)
return;
var tt:TimeTrait = activeTrait.owningMediaElement.getTrait(MediaTraitType.TIME) as TimeTrait;
if(!tt)
return;
// Great, time is knowable - so what is it?
var curTime:Number = tt.currentTime;
if(tt is HLSDVRTimeTrait)
curTime = (tt as HLSDVRTimeTrait).absoluteTime;
// This is quite verbose but useful for debugging.
// trace("onSubtitleTimer - Current time is: " + curTime);
// Now, fire off any subtitles that are new.
activeTrait.emitSubtitles(activeTrait._lastInjectedSubtitleTime, curTime);
}
/**
* Actually fire subtitle events for any subtitles in the specified period.
*/
private function emitSubtitles( startTime:Number, endTime:Number ):void
{
var subtitles:Vector.<SubTitleParser> = activeSubtitles;
var subtitleCount:int = subtitles.length;
var potentials:Vector.<TextTrackCue> = new Vector.<TextTrackCue>();
for ( var i:int = 0; i < subtitleCount; i++ )
{
var subtitle:SubTitleParser = subtitles[ i ];
if ( subtitle.startTime > endTime ) continue;
if ( subtitle.endTime < startTime ) continue;
var cues:Vector.<TextTrackCue> = subtitle.textTrackCues;
var cueCount:int = cues.length;
for ( var j:int = 0; j < cueCount; j++ )
{
var cue:TextTrackCue = cues[ j ];
if ( cue.startTime > endTime ) break;
else if ( cue.startTime >= startTime )
{
potentials.push(cue);
}
}
}
if(potentials.length > 0)
{
// TODO: Add support for trackid
cue = potentials[potentials.length - 1];
if(cue != _lastCue)
{
dispatchEvent(new SubtitleEvent(cue.startTime, cue.text, language));
_lastInjectedSubtitleTime = cue.startTime;
_lastCue = cue;
}
}
// Force last time so we eventually show proper subtitles.
_lastInjectedSubtitleTime = endTime;
}
/**
* Fired intermittently to check for new subtitle segments to download.
*/
private static function onReloadTimer(e:Event):void
{
// Check for any subtitles that have not been requested yet.
if(activeTrait == null || activeTrait.activeManifest == null)
{
trace("SubTitleTrait - skipping reload, inactive")
return;
}
// If reloading but not parsed yet.
if(activeReload && activeReload.timestamp == -1)
{
trace("SubTitleTrait - skipping reload, pending download");
return;
}
// Or it's a VOD or was recently reloaded.
var man:HLSManifestParser = activeTrait.activeManifest;
if(man &&
(man.streamEnds
|| (getTimer() - man.lastReloadRequestTime) < man.targetDuration * 1000 * 0.75))
{
trace("SubTitleTrait - skipping reload, waiting until targetDuration has expired.");
return;
}
if(man)
{
trace("Saw manifest with age " + (getTimer() - man.lastReloadRequestTime) + " and targetDuration " + man.targetDuration * 1000 );
}
trace("SubTitleTrait - initiating reload of " + man.fullUrl);
var manifest:HLSManifestParser = new HLSManifestParser();
manifest.addEventListener(Event.COMPLETE, onManifestReloaded);
manifest.addEventListener(IOErrorEvent.IO_ERROR, onManifestReloadFail);
manifest.type = HLSManifestParser.SUBTITLES;
manifest.reload(man);
activeReload = manifest;
reloadLanguage = activeTrait.language;
}
private static function onManifestReloaded(e:Event):void
{
if(e.target != activeReload || reloadLanguage != activeTrait.language)
{
trace("Got subtitle manifest reload for non-active manifest, ignoring...");
return;
}
// Instate the manifest.
trace("Subtitle manifest downloaded, instating " + reloadLanguage);
activeTrait.instateNewManifest(reloadLanguage, e.target as HLSManifestParser);
activeReload = null;
reloadLanguage = null;
}
private static function onManifestReloadFail(e:Event):void
{
if(e.target != activeReload || reloadLanguage != activeTrait.language)
{
trace("Got subtitle manifest reload for non-active manifest, ignoring...");
return;
}
trace("Subtitle manifest failed, clearing reload attempt.");
activeReload = null;
reloadLanguage = null;
}
protected function instateNewManifest(lang:String, man:HLSManifestParser):void
{
if(language != lang)
return;
if ( _language == "" ) return;
for ( var i:int = 0; i < _playLists.length; i++ )
{
// If the playlist has a language associated with it, use that language
var pLanguage:String;
if (_playLists[ i ].language && _playLists[ i ].language != "")
pLanguage = _playLists[ i ].language;
else
pLanguage = _playLists[ i ].name;
if (pLanguage == _language )
{
_playLists[ i ].manifest = man;
}
}
}
public function set playLists( value:Vector.<HLSManifestPlaylist> ):void
{
_playLists.length = 0;
_languages.length = 0;
if ( !value ) return;
for ( var i:int = 0; i < value.length; i++ )
{
_playLists.push( value[ i ] );
if (value[ i ].language && value[ i ].language != "")
_languages.push( value[ i ].language );
else
_languages.push( value[ i ].name );
}
}
public function set language( value:String ):void
{
// No special logic required, we will sort it out elsewhere.
_language = value;
}
public function get language():String
{
return _language;
}
public function get languages():Vector.<String>
{
return _languages;
}
public function get activeManifest():HLSManifestParser
{
if ( _language == "" ) return null;
for ( var i:int = 0; i < _playLists.length; i++ )
{
// If the playlist has a language associated with it, use that language
var pLanguage:String;
if (_playLists[ i ].language && _playLists[ i ].language != "")
pLanguage = _playLists[ i ].language;
else
pLanguage = _playLists[ i ].name;
if (pLanguage == _language ) return _playLists[ i ].manifest;
}
return null;
}
public function get activeSubtitles():Vector.<SubTitleParser>
{
var man:HLSManifestParser = activeManifest;
if(man)
return man.subtitles;
return null;
}
}
}
|
Address seeking issues.
|
Address seeking issues.
|
ActionScript
|
agpl-3.0
|
kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF
|
28e08a415830f26d342df6d83b716176b987f3d7
|
src/flails/resource/RailsResource.as
|
src/flails/resource/RailsResource.as
|
/**
* Copyright (c) 2009 Lance Carlson
* See LICENSE for full license information.
*/
package flails.resource {
import flash.events.EventDispatcher;
import flails.clients.HTTPClientBase;
import flails.clients.RailsClient;
import flails.clients.ResourceClient;
import flails.request.HTTPFilter;
import flails.request.JSONFilter;
import flails.request.RequestConfig;
import flails.request.Result;
import mx.utils.ObjectUtil;
public class RailsResource implements IResource {
public var requestConfig:RequestConfig;
private var filter:HTTPFilter;
private var config:Object;
public function RailsResource(config:Object) {
this.config = config;
filter = new JSONFilter();
}
public function index(data:Object = null):Result {
return new RailsClient(collection('index'), HTTPClientBase.METHOD_GET, filter).send(requestData(data));
}
public function show(id:Object = null, data:Object = null):Result {
return new RailsClient(member('show', id), HTTPClientBase.METHOD_GET, filter).send(requestData(data));
}
public function create(data:Object = null):Result {
return new RailsClient(collection('create'), HTTPClientBase.METHOD_POST, filter).send(requestData(data));
}
public function update(id:Object = null, data:Object = null):Result {
return new RailsClient(member('update', id), HTTPClientBase.METHOD_PUT, filter).send(requestData(data));
}
public function destroy(id:Object, data:Object = null):Result {
return new RailsClient(member('destroy', id), HTTPClientBase.METHOD_DELETE, filter).send(requestData(data));
}
private function collection(method:String):String {
return config.baseURL +
"/" + config.name +
(method == "index" || method == "create" ? "" : "/" + method) +
(filter.extension != null ? "" : "." + filter.extension);
}
private function member(method:String, id:Object):String {
return config.baseURL +
"/" + config.name +
(id != null ? "/" + id : "") +
(method == "show" || method == "update" || method == "destroy" ? "" : "/" + method) +
(filter.extension != null ? "" : "." + filter.extension);
}
private function requestData(data:Object):Object {
var out:Object = new Object();
if (requestConfig) {
for each (var o:Object in requestConfig.extraParams) {
out[o.name] = o.value;
}
}
for (var k:Object in data) {
out[k] = data[k];
}
return out;
}
}
}
|
/**
* Copyright (c) 2009 Lance Carlson
* See LICENSE for full license information.
*/
package flails.resource {
import flash.events.EventDispatcher;
import flails.clients.HTTPClientBase;
import flails.clients.RailsClient;
import flails.clients.ResourceClient;
import flails.request.HTTPFilter;
import flails.request.JSONFilter;
import flails.request.RequestConfig;
import flails.request.Result;
import mx.utils.ObjectUtil;
public class RailsResource implements IResource {
private var filter:HTTPFilter;
private var config:Object;
public function RailsResource(config:Object) {
this.config = config;
filter = new JSONFilter();
}
public function index(data:Object = null):Result {
return new RailsClient(collection('index'), HTTPClientBase.METHOD_GET, filter).send(requestData(data));
}
public function show(id:Object = null, data:Object = null):Result {
return new RailsClient(member('show', id), HTTPClientBase.METHOD_GET, filter).send(requestData(data));
}
public function create(data:Object = null):Result {
return new RailsClient(collection('create'), HTTPClientBase.METHOD_POST, filter).send(requestData(data));
}
public function update(id:Object = null, data:Object = null):Result {
return new RailsClient(member('update', id), HTTPClientBase.METHOD_PUT, filter).send(requestData(data));
}
public function destroy(id:Object, data:Object = null):Result {
return new RailsClient(member('destroy', id), HTTPClientBase.METHOD_DELETE, filter).send(requestData(data));
}
private function collection(method:String):String {
return config.baseURL +
"/" + config.name +
(method == "index" || method == "create" ? "" : "/" + method) +
(filter.extension != null ? "" : "." + filter.extension);
}
private function member(method:String, id:Object):String {
return config.baseURL +
"/" + config.name +
(id != null ? "/" + id : "") +
(method == "show" || method == "update" || method == "destroy" ? "" : "/" + method) +
(filter.extension != null ? "" : "." + filter.extension);
}
private function requestData(data:Object):Object {
var out:Object = new Object();
if (config.requestConfig) {
for each (var o:Object in config.requestConfig.extraParams) {
out[o.name] = o.value;
}
}
for (var k:Object in data) {
out[k] = data[k];
}
return out;
}
}
}
|
Handle RequestConfig.
|
Handle RequestConfig.
|
ActionScript
|
mit
|
lancecarlson/flails,lancecarlson/flails
|
bfaf1d6852d35a648b7316e8764c475a79c7bb07
|
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.*;
import flash.external.ExternalInterface;
import org.hola.ZExternalInterface;
import flash.net.URLRequest;
import flash.net.URLStream;
import flash.net.URLRequestHeader;
import flash.net.URLRequestMethod;
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.hola.HSettings;
public dynamic class JSURLStream extends URLStream {
private static var js_api_inited : Boolean = false;
private static var req_count : Number = 0;
private static var reqs : Object = {};
private var _connected : Boolean;
private var _resource : ByteArray = new ByteArray();
private var _curr_data : Object;
private var _hola_managed : Boolean = false;
private var _req_id : String;
private var _self_load : Boolean = false;
private var _events : Object;
private var _size : Number;
public function JSURLStream(){
_hola_managed = HSettings.enabled && ZExternalInterface.avail();
addEventListener(Event.OPEN, onopen);
super();
if (!_hola_managed || js_api_inited)
return;
// Connect calls to JS.
ZErr.log('JSURLStream init api');
ExternalInterface.marshallExceptions = true;
ExternalInterface.addCallback('hola_onFragmentData',
hola_onFragmentData);
js_api_inited = true;
}
protected function _trigger(cb : String, data : Object) : void {
if (!_hola_managed && !_self_load)
{
// 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 (!_hola_managed)
return super.connected;
return _connected;
}
override public function get bytesAvailable() : uint {
if (!_hola_managed)
return super.bytesAvailable;
return _resource.bytesAvailable;
}
override public function readByte() : int {
if (!_hola_managed)
return super.readByte();
return _resource.readByte();
}
override public function readUnsignedShort() : uint {
if (!_hola_managed)
return super.readUnsignedShort();
return _resource.readUnsignedShort();
}
override public function readBytes(bytes : ByteArray,
offset : uint = 0, length : uint = 0) : void
{
if (!_hola_managed)
return super.readBytes(bytes, offset, length);
_resource.readBytes(bytes, offset, length);
}
override public function close() : void {
if (_hola_managed || _self_load)
{
if (reqs[_req_id])
{
delete 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 {
if (_hola_managed || _self_load)
{
if (reqs[_req_id])
{
delete reqs[_req_id];
_trigger('abortFragment', {req_id: _req_id});
}
WorkerUtils.removeEventListener(HEvent.WORKER_MESSAGE, onmsg);
}
_hola_managed = HSettings.enabled && ZExternalInterface.avail();
req_count++;
_req_id = 'req'+req_count;
if (!_hola_managed)
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(e : Event) : void { _connected = true; }
private function onerror(e : ErrorEvent) : void {
_delete();
if (!_events.error)
return;
_trigger('onRequestEvent', {req_id: _req_id, event: 'error',
error: e.text, text: e.toString()});
}
private function onprogress(e : ProgressEvent) : void {
_size = e.bytesTotal;
if (!_events.progress)
return;
_trigger('onRequestEvent', {req_id: _req_id, event: 'progress',
loaded: e.bytesLoaded, total: e.bytesTotal,
text: e.toString()});
}
private function onstatus(e : HTTPStatusEvent) : void {
if (!_events.status)
return;
// XXX bahaa: get redirected/responseURL/responseHeaders
_trigger('onRequestEvent', {req_id: _req_id, event: 'status',
status: e.status, text: e.toString()});
}
private function oncomplete(e : Event) : void {
_delete();
if (!_events.complete)
return;
_trigger('onRequestEvent', {req_id: _req_id, event: 'complete',
size: _size, text: e.toString()});
}
private function decode(str : String) : void {
if (!str)
return on_decoded_data(null);
if (!HSettings.use_worker)
return on_decoded_data(Base64.decode_str(str));
var data : ByteArray = 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;
on_decoded_data(WorkerUtils.recv());
}
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 self_load(o : Object) : void {
_self_load = true;
_hola_managed = false;
_events = o.events||{};
addEventListener(IOErrorEvent.IO_ERROR, onerror);
addEventListener(SecurityErrorEvent.SECURITY_ERROR, onerror);
addEventListener(ProgressEvent.PROGRESS, onprogress);
addEventListener(HTTPStatusEvent.HTTP_STATUS, onstatus);
addEventListener(Event.COMPLETE, oncomplete);
var req : URLRequest = new URLRequest(o.url);
req.method = o.method=="POST" ? URLRequestMethod.POST :
URLRequestMethod.GET;
// this doesn't seem to work. simply ignored
var headers : Object = o.headers||{};
for (var k : String in headers)
req.requestHeaders.push(new URLRequestHeader(k, headers[k]));
super.load(req);
}
private function on_fragment_data(o : Object) : void {
_curr_data = o;
if (o.self_load)
return self_load(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;
}
}
private function _delete() : void {
delete reqs[_req_id];
}
protected function resourceLoadingError() : void {
_delete();
dispatchEvent(new IOErrorEvent(IOErrorEvent.IO_ERROR));
}
protected function resourceLoadingSuccess() : void {
_delete();
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.*;
import flash.external.ExternalInterface;
import org.hola.ZExternalInterface;
import flash.net.URLRequest;
import flash.net.URLStream;
import flash.net.URLRequestHeader;
import flash.net.URLRequestMethod;
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.hola.HSettings;
public dynamic class JSURLStream extends URLStream {
private static var js_api_inited : Boolean = false;
private static var req_count : Number = 0;
private static var reqs : Object = {};
private var _connected : Boolean;
private var _resource : ByteArray = new ByteArray();
private var _curr_data : Object;
private var _hola_managed : Boolean = false;
private var _req_id : String;
private var _self_load : Boolean = false;
private var _events : Object;
private var _size : Number;
public function JSURLStream(){
_hola_managed = HSettings.enabled && ZExternalInterface.avail();
addEventListener(Event.OPEN, onopen);
super();
if (!ZExternalInterface.avail() || js_api_inited)
return;
// Connect calls to JS.
ZErr.log('JSURLStream init api');
ExternalInterface.marshallExceptions = true;
ExternalInterface.addCallback('hola_onFragmentData',
hola_onFragmentData);
js_api_inited = true;
}
protected function _trigger(cb : String, data : Object) : void {
if (!_hola_managed && !_self_load)
{
// 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 (!_hola_managed)
return super.connected;
return _connected;
}
override public function get bytesAvailable() : uint {
if (!_hola_managed)
return super.bytesAvailable;
return _resource.bytesAvailable;
}
override public function readByte() : int {
if (!_hola_managed)
return super.readByte();
return _resource.readByte();
}
override public function readUnsignedShort() : uint {
if (!_hola_managed)
return super.readUnsignedShort();
return _resource.readUnsignedShort();
}
override public function readBytes(bytes : ByteArray,
offset : uint = 0, length : uint = 0) : void
{
if (!_hola_managed)
return super.readBytes(bytes, offset, length);
_resource.readBytes(bytes, offset, length);
}
override public function close() : void {
if (_hola_managed || _self_load)
{
if (reqs[_req_id])
{
delete 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 {
if (_hola_managed || _self_load)
{
if (reqs[_req_id])
{
delete reqs[_req_id];
_trigger('abortFragment', {req_id: _req_id});
}
WorkerUtils.removeEventListener(HEvent.WORKER_MESSAGE, onmsg);
}
_hola_managed = HSettings.enabled && ZExternalInterface.avail();
req_count++;
_req_id = 'req'+req_count;
if (!_hola_managed)
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(e : Event) : void { _connected = true; }
private function onerror(e : ErrorEvent) : void {
_delete();
if (!_events.error)
return;
_trigger('onRequestEvent', {req_id: _req_id, event: 'error',
error: e.text, text: e.toString()});
}
private function onprogress(e : ProgressEvent) : void {
_size = e.bytesTotal;
if (!_events.progress)
return;
_trigger('onRequestEvent', {req_id: _req_id, event: 'progress',
loaded: e.bytesLoaded, total: e.bytesTotal,
text: e.toString()});
}
private function onstatus(e : HTTPStatusEvent) : void {
if (!_events.status)
return;
// XXX bahaa: get redirected/responseURL/responseHeaders
_trigger('onRequestEvent', {req_id: _req_id, event: 'status',
status: e.status, text: e.toString()});
}
private function oncomplete(e : Event) : void {
_delete();
if (!_events.complete)
return;
_trigger('onRequestEvent', {req_id: _req_id, event: 'complete',
size: _size, text: e.toString()});
}
private function decode(str : String) : void {
if (!str)
return on_decoded_data(null);
if (!HSettings.use_worker)
return on_decoded_data(Base64.decode_str(str));
var data : ByteArray = 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;
on_decoded_data(WorkerUtils.recv());
}
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 self_load(o : Object) : void {
_self_load = true;
_hola_managed = false;
_events = o.events||{};
addEventListener(IOErrorEvent.IO_ERROR, onerror);
addEventListener(SecurityErrorEvent.SECURITY_ERROR, onerror);
addEventListener(ProgressEvent.PROGRESS, onprogress);
addEventListener(HTTPStatusEvent.HTTP_STATUS, onstatus);
addEventListener(Event.COMPLETE, oncomplete);
var req : URLRequest = new URLRequest(o.url);
req.method = o.method=="POST" ? URLRequestMethod.POST :
URLRequestMethod.GET;
// this doesn't seem to work. simply ignored
var headers : Object = o.headers||{};
for (var k : String in headers)
req.requestHeaders.push(new URLRequestHeader(k, headers[k]));
super.load(req);
}
private function on_fragment_data(o : Object) : void {
_curr_data = o;
if (o.self_load)
return self_load(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]))
{
ZErr.log('req_id not found '+o.req_id);
return;
}
stream.on_fragment_data(o);
} catch(err : Error){
ZErr.log('Error in hola_onFragmentData', ''+err,
''+err.getStackTrace());
if (stream)
stream.resourceLoadingError();
throw err;
}
}
private function _delete() : void {
delete reqs[_req_id];
}
protected function resourceLoadingError() : void {
_delete();
dispatchEvent(new IOErrorEvent(IOErrorEvent.IO_ERROR));
}
protected function resourceLoadingSuccess() : void {
_delete();
dispatchEvent(new Event(Event.COMPLETE));
}
}
}
|
fix bug set managed mode after init + don't throw on req_id not found
|
fix bug set managed mode after init + don't throw on req_id not found
|
ActionScript
|
mpl-2.0
|
hola/flashls,hola/flashls
|
30e5a25202f9c5191e366c8fb9f87cee1acd0255
|
src/aerys/minko/render/geometry/primitive/ConeGeometry.as
|
src/aerys/minko/render/geometry/primitive/ConeGeometry.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.StreamUsage;
import aerys.minko.render.geometry.stream.VertexStream;
import aerys.minko.render.geometry.stream.format.VertexFormat;
public class ConeGeometry extends Geometry
{
public function ConeGeometry(numSegments : uint = 10,
vertexStreamUsage : uint = StreamUsage.STATIC,
indexStreamUsage : uint = StreamUsage.STATIC)
{
super(
getVertexStreams(numSegments, vertexStreamUsage),
getIndexStream(numSegments, indexStreamUsage)
);
}
private function getVertexStreams(numSegments : uint,
vertexStreamUsage : uint) : Vector.<IVertexStream>
{
var xyz : Vector.<Number> = new <Number>[0., .5, 0.];
for (var segmentId : uint = 0; segmentId < numSegments; ++segmentId)
{
var angle : Number = (Math.PI * 2.) * (segmentId / numSegments);
xyz.push(
Math.cos(angle),
-.5,
Math.sin(angle)
);
}
xyz.push(0., -.5, 0.);
return new <IVertexStream>[new VertexStream(vertexStreamUsage, VertexFormat.XYZ, xyz)];
}
private function getIndexStream(numSegments : uint,
indexStreamUsage : uint) : IndexStream
{
var indices : Vector.<uint> = new <uint>[];
for (var segmentId : uint = 0; segmentId < numSegments - 1; ++segmentId)
{
indices.push(
0, segmentId + 1, segmentId + 2,
numSegments + 1, segmentId + 2, segmentId + 1
);
}
// close the shape
indices.push(
0, segmentId + 1, 1,
numSegments + 1, 1, segmentId + 1
);
return new IndexStream(indexStreamUsage, 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.StreamUsage;
import aerys.minko.render.geometry.stream.VertexStream;
import aerys.minko.render.geometry.stream.format.VertexFormat;
public class ConeGeometry extends Geometry
{
public function ConeGeometry(numSegments : uint = 10,
vertexStreamUsage : uint = StreamUsage.STATIC,
indexStreamUsage : uint = StreamUsage.STATIC)
{
super(
getVertexStreams(numSegments, vertexStreamUsage),
getIndexStream(numSegments, indexStreamUsage)
);
}
private function getVertexStreams(numSegments : uint,
vertexStreamUsage : uint) : Vector.<IVertexStream>
{
var xyz : Vector.<Number> = new <Number>[0., .5, 0.];
for (var segmentId : uint = 0; segmentId < numSegments; ++segmentId)
{
var angle : Number = (Math.PI * 2.) * (segmentId / numSegments);
xyz.push(Math.cos(angle) * .5, -.5, Math.sin(angle) * .5);
}
xyz.push(0., -.5, 0.);
return new <IVertexStream>[new VertexStream(vertexStreamUsage, VertexFormat.XYZ, xyz)];
}
private function getIndexStream(numSegments : uint,
indexStreamUsage : uint) : IndexStream
{
var indices : Vector.<uint> = new <uint>[];
for (var segmentId : uint = 0; segmentId < numSegments - 1; ++segmentId)
{
indices.push(
0, segmentId + 1, segmentId + 2,
numSegments + 1, segmentId + 2, segmentId + 1
);
}
// close the shape
indices.push(
0, segmentId + 1, 1,
numSegments + 1, 1, segmentId + 1
);
return new IndexStream(indexStreamUsage, indices);
}
}
}
|
update ConeGeometry to create a cone with a radius = 0.5 instead of radius = 1
|
update ConeGeometry to create a cone with a radius = 0.5 instead of radius = 1
|
ActionScript
|
mit
|
aerys/minko-as3
|
63d7fc417c7fe7f6b681b1e8edfe8257ab2b29d8
|
test/org/igniterealtime/xiff/util/DateTimeParserTest.as
|
test/org/igniterealtime/xiff/util/DateTimeParserTest.as
|
/*
* Copyright (C) 2003-2011 Igniterealtime Community Contributors
*
* Daniel Henninger
* Derrick Grigg <[email protected]>
* Juga Paazmaya <[email protected]>
* Nick Velloff <[email protected]>
* Sean Treadway <[email protected]>
* Sean Voisen <[email protected]>
* Mark Walters <[email protected]>
* Michael McCarthy <[email protected]>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.igniterealtime.xiff.util
{
import org.flexunit.asserts.assertEquals;
public class DateTimeParserTest
{
[Test]
public function testDate2String():void
{
var date:Date = new Date( 2000, 10, 30, 0, 0 );
var dateAsString:String = DateTimeParser.date2string( date );
assertEquals( "2000-12-30", dateAsString );
}
}
}
|
/*
* Copyright (C) 2003-2011 Igniterealtime Community Contributors
*
* Daniel Henninger
* Derrick Grigg <[email protected]>
* Juga Paazmaya <[email protected]>
* Nick Velloff <[email protected]>
* Sean Treadway <[email protected]>
* Sean Voisen <[email protected]>
* Mark Walters <[email protected]>
* Michael McCarthy <[email protected]>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.igniterealtime.xiff.util
{
import org.flexunit.asserts.assertEquals;
public class DateTimeParserTest
{
[Test]
public function testDate2String():void
{
var date:Date = new Date( 2000, 10, 30, 0, 0 );
var dateAsString:String = DateTimeParser.date2string( date );
assertEquals( "2000-11-30", dateAsString );
}
}
}
|
Revert of commit test.
|
Revert of commit test.
|
ActionScript
|
apache-2.0
|
igniterealtime/XIFF
|
82ef6d541e91c88c29707f17e1dbfb87e4f12d50
|
frameworks/as/projects/FlexJSUI/src/FlexJSUIClasses.as
|
frameworks/as/projects/FlexJSUI/src/FlexJSUIClasses.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
{
/**
* @private
* This class is used to link additional classes into rpc.swc
* beyond those that are found by dependecy analysis starting
* from the classes specified in manifest.xml.
*/
internal class FlexJSUIClasses
{
import org.apache.cordova.camera.Camera; Camera;
import org.apache.cordova.Application; Application;
import org.apache.cordova.Weinre; Weinre;
import org.apache.flex.charts.core.CartesianChart; CartesianChart;
import org.apache.flex.charts.core.ChartBase; ChartBase;
import org.apache.flex.charts.core.IAxisBead; IAxisBead;
import org.apache.flex.charts.core.IAxisGroup; IAxisGroup;
import org.apache.flex.charts.core.IChart; IChart;
import org.apache.flex.charts.core.ICartesianChartLayout; ICartesianChartLayout;
import org.apache.flex.charts.core.IChartDataGroup; IChartDataGroup;
import org.apache.flex.charts.core.IChartSeries; IChartSeries;
import org.apache.flex.charts.core.IHorizontalAxisBead; IHorizontalAxisBead;
import org.apache.flex.charts.core.IVerticalAxisBead; IVerticalAxisBead;
import org.apache.flex.charts.core.IChartItemRenderer; IChartItemRenderer;
import org.apache.flex.charts.core.IConnectedItemRenderer; IConnectedItemRenderer;
import org.apache.flex.charts.core.PolarChart; PolarChart;
import org.apache.flex.charts.supportClasses.ChartAxisGroup; ChartAxisGroup;
import org.apache.flex.charts.supportClasses.ChartDataGroup; ChartDataGroup;
import org.apache.flex.maps.google.Map; Map;
import org.apache.flex.html.ToolTip; ToolTip;
import org.apache.flex.html.accessories.NumericOnlyTextInputBead; NumericOnlyTextInputBead;
import org.apache.flex.html.accessories.PasswordInputBead; PasswordInputBead;
import org.apache.flex.html.accessories.TextPromptBead; TextPromptBead;
import org.apache.flex.html.beads.AlertView; AlertView;
import org.apache.flex.html.beads.ButtonBarView; ButtonBarView;
import org.apache.flex.html.beads.CheckBoxView; CheckBoxView;
import org.apache.flex.html.beads.ComboBoxView; ComboBoxView;
import org.apache.flex.html.beads.ContainerView; ContainerView;
import org.apache.flex.html.beads.ControlBarMeasurementBead; ControlBarMeasurementBead;
import org.apache.flex.html.beads.CSSButtonView; CSSButtonView;
import org.apache.flex.html.beads.CSSTextButtonView; CSSTextButtonView;
import org.apache.flex.html.beads.CSSTextToggleButtonView; CSSTextToggleButtonView;
import org.apache.flex.html.beads.DropDownListView; DropDownListView;
import org.apache.flex.html.beads.CloseButtonView; CloseButtonView;
import org.apache.flex.html.beads.ImageButtonView; ImageButtonView;
import org.apache.flex.html.beads.ImageAndTextButtonView; ImageAndTextButtonView;
import org.apache.flex.html.beads.ImageView; ImageView;
import org.apache.flex.html.beads.ListView; ListView;
import org.apache.flex.html.beads.NumericStepperView; NumericStepperView;
import org.apache.flex.html.beads.PanelView; PanelView;
import org.apache.flex.html.beads.PanelWithControlBarView; PanelWithControlBarView;
import org.apache.flex.html.beads.RadioButtonView; RadioButtonView;
import org.apache.flex.html.beads.ScrollBarView; ScrollBarView;
import org.apache.flex.html.beads.SimpleAlertView; SimpleAlertView;
import org.apache.flex.html.beads.SingleLineBorderBead; SingleLineBorderBead;
import org.apache.flex.html.beads.SliderView; SliderView;
import org.apache.flex.html.beads.SliderThumbView; SliderThumbView;
import org.apache.flex.html.beads.SliderTrackView; SliderTrackView;
import org.apache.flex.html.beads.SolidBackgroundBead; SolidBackgroundBead;
import org.apache.flex.html.beads.SpinnerView; SpinnerView;
import org.apache.flex.html.beads.TextButtonMeasurementBead; TextButtonMeasurementBead;
import org.apache.flex.html.beads.TextFieldLabelMeasurementBead; TextFieldLabelMeasurementBead;
import org.apache.flex.html.beads.TextAreaView; TextAreaView;
import org.apache.flex.html.beads.TextButtonView; TextButtonView;
import org.apache.flex.html.beads.TextFieldView; TextFieldView;
import org.apache.flex.html.beads.TextInputView; TextInputView;
import org.apache.flex.html.beads.TextInputWithBorderView; TextInputWithBorderView;
import org.apache.flex.html.beads.models.AlertModel; AlertModel;
import org.apache.flex.html.beads.models.ArraySelectionModel; ArraySelectionModel;
import org.apache.flex.html.beads.models.ComboBoxModel; ComboBoxModel;
import org.apache.flex.html.beads.models.ImageModel; ImageModel;
import org.apache.flex.html.beads.models.ImageAndTextModel; ImageAndTextModel;
import org.apache.flex.html.beads.models.PanelModel; PanelModel;
import org.apache.flex.html.beads.models.SingleLineBorderModel; SingleLineBorderModel;
import org.apache.flex.html.beads.models.TextModel; TextModel;
import org.apache.flex.html.beads.models.TitleBarModel; TitleBarModel;
import org.apache.flex.html.beads.models.ToggleButtonModel; ToggleButtonModel;
import org.apache.flex.html.beads.models.ValueToggleButtonModel; ValueToggleButtonModel;
import org.apache.flex.html.beads.controllers.AlertController; AlertController;
import org.apache.flex.html.beads.controllers.ComboBoxController; ComboBoxController;
import org.apache.flex.html.beads.controllers.DropDownListController; DropDownListController;
import org.apache.flex.html.beads.controllers.EditableTextKeyboardController; EditableTextKeyboardController;
import org.apache.flex.html.beads.controllers.ItemRendererMouseController; ItemRendererMouseController;
import org.apache.flex.html.beads.controllers.ListSingleSelectionMouseController; ListSingleSelectionMouseController;
import org.apache.flex.html.beads.controllers.SliderMouseController; SliderMouseController;
import org.apache.flex.html.beads.controllers.SpinnerMouseController; SpinnerMouseController;
import org.apache.flex.html.beads.controllers.VScrollBarMouseController; VScrollBarMouseController;
import org.apache.flex.html.beads.layouts.ButtonBarLayout; ButtonBarLayout;
import org.apache.flex.html.beads.layouts.NonVirtualVerticalScrollingLayout; NonVirtualVerticalScrollingLayout;
import org.apache.flex.html.beads.layouts.NonVirtualHorizontalScrollingLayout; NonVirtualHorizontalScrollingLayout;
import org.apache.flex.html.beads.layouts.NonVirtualBasicLayout; NonVirtualBasicLayout;
import org.apache.flex.html.beads.layouts.VScrollBarLayout; VScrollBarLayout;
import org.apache.flex.html.beads.layouts.TileLayout; TileLayout;
import org.apache.flex.html.beads.TextItemRendererFactoryForArrayData; TextItemRendererFactoryForArrayData;
import org.apache.flex.html.beads.DataItemRendererFactoryForArrayData; DataItemRendererFactoryForArrayData;
import org.apache.flex.html.supportClasses.NonVirtualDataGroup; NonVirtualDataGroup;
import org.apache.flex.core.ItemRendererClassFactory; ItemRendererClassFactory;
import org.apache.flex.core.FilledRectangle; FilledRectangle;
import org.apache.flex.core.FormatBase; FormatBase;
import org.apache.flex.events.CustomEvent; CustomEvent;
import org.apache.flex.events.Event; Event;
import org.apache.flex.events.MouseEvent; MouseEvent;
import org.apache.flex.events.ValueEvent; ValueEvent;
import org.apache.flex.utils.EffectTimer; EffectTimer;
import org.apache.flex.utils.Timer; Timer;
import org.apache.flex.utils.UIUtils; UIUtils;
import org.apache.flex.core.ISelectableItemRenderer; ISelectableItemRenderer;
import org.apache.flex.core.SimpleStatesImpl; SimpleStatesImpl;
import org.apache.flex.core.graphics.GraphicShape; GraphicShape;
import org.apache.flex.core.graphics.Rect; Rect;
import org.apache.flex.core.graphics.Ellipse; Ellipse;
import org.apache.flex.core.graphics.Circle; Circle;
import org.apache.flex.core.graphics.Path; Path;
import org.apache.flex.core.graphics.SolidColor; SolidColor;
import org.apache.flex.core.graphics.SolidColorStroke; SolidColorStroke;
import org.apache.flex.core.graphics.Text; Text;
import org.apache.flex.core.graphics.GraphicsContainer; GraphicsContainer;
import org.apache.flex.core.graphics.LinearGradient; LinearGradient;
import org.apache.flex.core.DataBindingBase; DataBindingBase;
import org.apache.flex.effects.PlatformWiper; PlatformWiper;
import org.apache.flex.events.DragEvent; DragEvent;
import org.apache.flex.events.utils.MouseUtils; MouseUtils;
import org.apache.flex.geom.Rectangle; Rectangle;
import mx.core.ClassFactory; ClassFactory;
import mx.states.AddItems; AddItems;
import mx.states.SetEventHandler; SetEventHandler;
import mx.states.SetProperty; SetProperty;
import mx.states.State; State;
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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
{
/**
* @private
* This class is used to link additional classes into rpc.swc
* beyond those that are found by dependecy analysis starting
* from the classes specified in manifest.xml.
*/
internal class FlexJSUIClasses
{
import org.apache.cordova.camera.Camera; Camera;
import org.apache.cordova.Application; Application;
import org.apache.cordova.Weinre; Weinre;
import org.apache.flex.charts.core.CartesianChart; CartesianChart;
import org.apache.flex.charts.core.ChartBase; ChartBase;
import org.apache.flex.charts.core.IAxisBead; IAxisBead;
import org.apache.flex.charts.core.IAxisGroup; IAxisGroup;
import org.apache.flex.charts.core.IChart; IChart;
import org.apache.flex.charts.core.ICartesianChartLayout; ICartesianChartLayout;
import org.apache.flex.charts.core.IChartDataGroup; IChartDataGroup;
import org.apache.flex.charts.core.IChartSeries; IChartSeries;
import org.apache.flex.charts.core.IHorizontalAxisBead; IHorizontalAxisBead;
import org.apache.flex.charts.core.IVerticalAxisBead; IVerticalAxisBead;
import org.apache.flex.charts.core.IChartItemRenderer; IChartItemRenderer;
import org.apache.flex.charts.core.IConnectedItemRenderer; IConnectedItemRenderer;
import org.apache.flex.charts.core.PolarChart; PolarChart;
import org.apache.flex.charts.supportClasses.ChartAxisGroup; ChartAxisGroup;
import org.apache.flex.charts.supportClasses.ChartDataGroup; ChartDataGroup;
import org.apache.flex.maps.google.Map; Map;
import org.apache.flex.html.ToolTip; ToolTip;
import org.apache.flex.html.accessories.NumericOnlyTextInputBead; NumericOnlyTextInputBead;
import org.apache.flex.html.accessories.PasswordInputBead; PasswordInputBead;
import org.apache.flex.html.accessories.TextPromptBead; TextPromptBead;
import org.apache.flex.html.beads.AlertView; AlertView;
import org.apache.flex.html.beads.ButtonBarView; ButtonBarView;
import org.apache.flex.html.beads.CheckBoxView; CheckBoxView;
import org.apache.flex.html.beads.ComboBoxView; ComboBoxView;
import org.apache.flex.html.beads.ContainerView; ContainerView;
import org.apache.flex.html.beads.ControlBarMeasurementBead; ControlBarMeasurementBead;
import org.apache.flex.html.beads.CSSButtonView; CSSButtonView;
import org.apache.flex.html.beads.CSSTextButtonView; CSSTextButtonView;
import org.apache.flex.html.beads.CSSTextToggleButtonView; CSSTextToggleButtonView;
import org.apache.flex.html.beads.DropDownListView; DropDownListView;
import org.apache.flex.html.beads.CloseButtonView; CloseButtonView;
import org.apache.flex.html.beads.ImageButtonView; ImageButtonView;
import org.apache.flex.html.beads.ImageAndTextButtonView; ImageAndTextButtonView;
import org.apache.flex.html.beads.ImageView; ImageView;
import org.apache.flex.html.beads.ListView; ListView;
import org.apache.flex.html.beads.NumericStepperView; NumericStepperView;
import org.apache.flex.html.beads.PanelView; PanelView;
import org.apache.flex.html.beads.PanelWithControlBarView; PanelWithControlBarView;
import org.apache.flex.html.beads.RadioButtonView; RadioButtonView;
import org.apache.flex.html.beads.ScrollBarView; ScrollBarView;
import org.apache.flex.html.beads.SimpleAlertView; SimpleAlertView;
import org.apache.flex.html.beads.SingleLineBorderBead; SingleLineBorderBead;
import org.apache.flex.html.beads.SliderView; SliderView;
import org.apache.flex.html.beads.SliderThumbView; SliderThumbView;
import org.apache.flex.html.beads.SliderTrackView; SliderTrackView;
import org.apache.flex.html.beads.SolidBackgroundBead; SolidBackgroundBead;
import org.apache.flex.html.beads.SpinnerView; SpinnerView;
import org.apache.flex.html.beads.TextButtonMeasurementBead; TextButtonMeasurementBead;
import org.apache.flex.html.beads.TextFieldLabelMeasurementBead; TextFieldLabelMeasurementBead;
import org.apache.flex.html.beads.TextAreaView; TextAreaView;
import org.apache.flex.html.beads.TextButtonView; TextButtonView;
import org.apache.flex.html.beads.TextFieldView; TextFieldView;
import org.apache.flex.html.beads.TextInputView; TextInputView;
import org.apache.flex.html.beads.TextInputWithBorderView; TextInputWithBorderView;
import org.apache.flex.html.beads.models.AlertModel; AlertModel;
import org.apache.flex.html.beads.models.ArraySelectionModel; ArraySelectionModel;
import org.apache.flex.html.beads.models.ComboBoxModel; ComboBoxModel;
import org.apache.flex.html.beads.models.ImageModel; ImageModel;
import org.apache.flex.html.beads.models.ImageAndTextModel; ImageAndTextModel;
import org.apache.flex.html.beads.models.PanelModel; PanelModel;
import org.apache.flex.html.beads.models.SingleLineBorderModel; SingleLineBorderModel;
import org.apache.flex.html.beads.models.TextModel; TextModel;
import org.apache.flex.html.beads.models.TitleBarModel; TitleBarModel;
import org.apache.flex.html.beads.models.ToggleButtonModel; ToggleButtonModel;
import org.apache.flex.html.beads.models.ValueToggleButtonModel; ValueToggleButtonModel;
import org.apache.flex.html.beads.controllers.AlertController; AlertController;
import org.apache.flex.html.beads.controllers.ComboBoxController; ComboBoxController;
import org.apache.flex.html.beads.controllers.DropDownListController; DropDownListController;
import org.apache.flex.html.beads.controllers.EditableTextKeyboardController; EditableTextKeyboardController;
import org.apache.flex.html.beads.controllers.ItemRendererMouseController; ItemRendererMouseController;
import org.apache.flex.html.beads.controllers.ListSingleSelectionMouseController; ListSingleSelectionMouseController;
import org.apache.flex.html.beads.controllers.SliderMouseController; SliderMouseController;
import org.apache.flex.html.beads.controllers.SpinnerMouseController; SpinnerMouseController;
import org.apache.flex.html.beads.controllers.VScrollBarMouseController; VScrollBarMouseController;
import org.apache.flex.html.beads.layouts.ButtonBarLayout; ButtonBarLayout;
import org.apache.flex.html.beads.layouts.NonVirtualVerticalScrollingLayout; NonVirtualVerticalScrollingLayout;
import org.apache.flex.html.beads.layouts.NonVirtualHorizontalScrollingLayout; NonVirtualHorizontalScrollingLayout;
import org.apache.flex.html.beads.layouts.NonVirtualBasicLayout; NonVirtualBasicLayout;
import org.apache.flex.html.beads.layouts.VScrollBarLayout; VScrollBarLayout;
import org.apache.flex.html.beads.layouts.TileLayout; TileLayout;
import org.apache.flex.html.beads.TextItemRendererFactoryForArrayData; TextItemRendererFactoryForArrayData;
import org.apache.flex.html.beads.DataItemRendererFactoryForArrayData; DataItemRendererFactoryForArrayData;
import org.apache.flex.html.supportClasses.NonVirtualDataGroup; NonVirtualDataGroup;
import org.apache.flex.core.ItemRendererClassFactory; ItemRendererClassFactory;
import org.apache.flex.core.FilledRectangle; FilledRectangle;
import org.apache.flex.core.FormatBase; FormatBase;
import org.apache.flex.events.CustomEvent; CustomEvent;
import org.apache.flex.events.Event; Event;
import org.apache.flex.events.MouseEvent; MouseEvent;
import org.apache.flex.events.ValueEvent; ValueEvent;
import org.apache.flex.utils.EffectTimer; EffectTimer;
import org.apache.flex.utils.Timer; Timer;
import org.apache.flex.utils.UIUtils; UIUtils;
import org.apache.flex.core.ISelectableItemRenderer; ISelectableItemRenderer;
import org.apache.flex.core.SimpleStatesImpl; SimpleStatesImpl;
import org.apache.flex.core.graphics.GraphicShape; GraphicShape;
import org.apache.flex.core.graphics.Rect; Rect;
import org.apache.flex.core.graphics.Ellipse; Ellipse;
import org.apache.flex.core.graphics.Circle; Circle;
import org.apache.flex.core.graphics.Path; Path;
import org.apache.flex.core.graphics.SolidColor; SolidColor;
import org.apache.flex.core.graphics.SolidColorStroke; SolidColorStroke;
import org.apache.flex.core.graphics.Text; Text;
import org.apache.flex.core.graphics.GraphicsContainer; GraphicsContainer;
import org.apache.flex.core.graphics.LinearGradient; LinearGradient;
import org.apache.flex.core.DataBindingBase; DataBindingBase;
import org.apache.flex.binding.ChainBinding; ChainBinding;
import org.apache.flex.effects.PlatformWiper; PlatformWiper;
import org.apache.flex.events.DragEvent; DragEvent;
import org.apache.flex.events.utils.MouseUtils; MouseUtils;
import org.apache.flex.geom.Rectangle; Rectangle;
import mx.core.ClassFactory; ClassFactory;
import mx.states.AddItems; AddItems;
import mx.states.SetEventHandler; SetEventHandler;
import mx.states.SetProperty; SetProperty;
import mx.states.State; State;
}
}
|
add chainbinding
|
add chainbinding
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
cbc1d47ff92096b05b11d483423fda567dee6c28
|
flexEditor/src/org/arisgames/editor/util/AppConstants.as
|
flexEditor/src/org/arisgames/editor/util/AppConstants.as
|
package org.arisgames.editor.util
{
public class AppConstants
{
//Server URL
//public static const APPLICATION_ENVIRONMENT_ROOT_URL:String = "http://arisgames.org/stagingserver1"; //For other URL's to append to- Staging
public static const APPLICATION_ENVIRONMENT_ROOT_URL:String = "http://atsosxdev.doit.wisc.edu/aris/server"; //For other URL's to append to- Dev
public static const APPLICATION_ENVIRONMENT_SERVICES_URL:String = APPLICATION_ENVIRONMENT_ROOT_URL+"/services/aris/"; //staging
public static const APPLICATION_ENVIRONMENT_UPLOAD_SERVER_URL:String = APPLICATION_ENVIRONMENT_ROOT_URL+"/services/aris/uploadhandler.php"; //davembp
public static const APPLICATION_ENVIRONMENT_GATEWAY_URL:String = APPLICATION_ENVIRONMENT_ROOT_URL+"/gateway.php"; //services-config.xml
//Google API
//public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAA-Z69V9McvCh02XYNV5UHBBRloMOfjiI7F4SM41AgXh_4cb6l9xTHRyPNO3mgDcJkTIE742EL8ZoQ_Q"; //staging
//public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAArdp0t4v0pcA_JogLZhjrjBTf4EykMftsP7dwAfDsLsFl_zB7rBTq5-3Hy0k3tU1tgyomozB1YmIfNg"; //davembp
public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAA-Z69V9McvCh02XYNV5UHBBQsvlSBtAWfm4N2P3iTGfWOp-UrmRRTU3pFPQwMJB92SZ3plLjvRpMIIw"; //dev
// Dynamic Events
public static const APPLICATIONDYNAMICEVENT_CURRENTSTATECHANGED:String = "ApplicationDynamicEventCurrentStateChanged";
public static const APPLICATIONDYNAMICEVENT_REDRAWOBJECTPALETTE:String = "ApplicationDynamicEventRedrawObjectPalette";
public static const APPLICATIONDYNAMICEVENT_GAMEPLACEMARKSLOADED:String = "ApplicationDynamicEventGamePlacemarksLoaded";
public static const DYNAMICEVENT_GEOSEARCH:String = "DynamicEventGeoSearch";
public static const DYNAMICEVENT_PLACEMARKSELECTED:String = "DynamicEventPlaceMarkSelected";
public static const DYNAMICEVENT_PLACEMARKREQUESTSDELETION:String = "DynamicEventPlaceMarkRequestsDeletion";
public static const DYNAMICEVENT_EDITOBJECTPALETTEITEM:String = "EditObjectPaletteItem";
public static const DYNAMICEVENT_HIGHLIGHTOBJECTPALETTEITEM:String = "HighlightObjectPaletteItem";
public static const DYNAMICEVENT_CLOSEOBJECTPALETTEITEMEDITOR:String = "CloseObjectPaletteItemEditor";
public static const DYNAMICEVENT_CLOSEMEDIAPICKER:String = "CloseMediaPicker";
public static const DYNAMICEVENT_CLOSEMEDIAUPLOADER:String = "CloseMediaUploader";
public static const DYNAMICEVENT_CLOSEREQUIREMENTSEDITOR:String = "CloseRequirementsEditor";
public static const DYNAMICEVENT_REFRESHDATAINREQUIREMENTSEDITOR:String = "RefreshDataInRequirementsEditor";
public static const DYNAMICEVENT_OPENREQUIREMENTSEDITORMAP:String = "OpenRequirementsEditorMap";
public static const DYNAMICEVENT_CLOSEREQUIREMENTSEDITORMAP:String = "CloseRequirementsEditorMap";
public static const DYNAMICEVENT_SAVEREQUIREMENTDUETOMAPDATACHANGE:String = "SaveRequirementDueToMapDataChange";
public static const DYNAMICEVENT_OPENQUESTSMAP:String = "OpenQuestsMap";
public static const DYNAMICEVENT_CLOSEQUESTSMAP:String = "CloseQuestsMap";
public static const DYNAMICEVENT_REFRESHDATAINQUESTSEDITOR:String = "RefreshDataInQuestsEditor";
public static const DYNAMICEVENT_OPENQUESTSEDITOR:String = "OpenQuestsEditor";
public static const DYNAMICEVENT_CLOSEQUESTSEDITOR:String = "CloseQuestsEditor";
public static const DYNAMICEVENT_REFRESHDATAINPLAYERSTATECHANGESEDITOR:String = "DYNAMICEVENT_REFRESHDATAINPLAYERSTATECHANGESEDITOR";
public static const DYNAMICEVENT_CLOSEPLAYERSTATECHANGEEDITOR:String = "DYNAMICEVENT_CLOSEPLAYERSTATECHANGEEDITOR";
public static const DYNAMICEVENT_REFRESHDATAINCONVERSATIONS:String = "DYNAMICEVENT_DYNAMICEVENT_REFRESHDATAINCONVERSATIONS";
// Placemark Content
public static const CONTENTTYPE_PAGE:String = "Plaque";
public static const CONTENTTYPE_CHARACTER:String = "Character";
public static const CONTENTTYPE_ITEM:String = "Item";
public static const CONTENTTYPE_QRCODEGROUP:String = "QR Code Group";
public static const CONTENTTYPE_PAGE_VAL:Number = 0;
public static const CONTENTTYPE_CHARACTER_VAL:Number = 1;
public static const CONTENTTYPE_ITEM_VAL:Number = 2;
public static const CONTENTTYPE_QRCODEGROUP_VAL:Number = 3;
public static const CONTENTTYPE_PAGE_DATABASE:String = "Node";
public static const CONTENTTYPE_CHARACTER_DATABASE:String = "Npc";
public static const CONTENTTYPE_ITEM_DATABASE:String = "Item";
public static const PLACEMARK_DEFAULT_ERROR_RANGE:Number = 30;
// Label Constants
public static const BUTTON_LOGIN:String = "Login!";
public static const BUTTON_REGISTER:String = "Register!";
public static const RADIO_FORGOTPASSWORD:String = "Forgot Password";
public static const RADIO_FORGOTUSERNAME:String = "Forgot Username";
// Max allowed upload size for media.........MB....KB....Bytes
public static const MAX_UPLOAD_SIZE:Number = 10 * 1024 * 1024 //In bytes
// Media Types
public static const MEDIATYPE:String = "Media Types";
public static const MEDIATYPE_IMAGE:String = "Image";
public static const MEDIATYPE_AUDIO:String = "Audio";
public static const MEDIATYPE_VIDEO:String = "Video";
public static const MEDIATYPE_ICON:String = "Icon";
public static const MEDIATYPE_SEPARATOR:String = " ";
public static const MEDIATYPE_UPLOADNEW:String = " ";
// Media-tree-icon Types
public static const MEDIATREEICON_SEPARATOR:String = "separatorIcon";
public static const MEDIATREEICON_UPLOAD:String = "uploadIcon";
//Player State Changes
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_ITEM:String = "VIEW_ITEM";
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_NODE:String = "VIEW_NODE";
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_NPC:String = "VIEW_NPC";
public static const PLAYERSTATECHANGE_ACTION_GIVEITEM:String = "GIVE_ITEM";
public static const PLAYERSTATECHANGE_ACTION_GIVEITEM_HUMAN:String = "Give Item";
public static const PLAYERSTATECHANGE_ACTION_TAKEITEM:String = "TAKE_ITEM";
public static const PLAYERSTATECHANGE_ACTION_TAKEITEM_HUMAN:String = "Take Item";
// Requirement Types
public static const REQUIREMENTTYPE_LOCATION:String = "Location";
public static const REQUIREMENTTYPE_QUESTDISPLAY:String = "QuestDisplay";
public static const REQUIREMENTTYPE_QUESTCOMPLETE:String = "QuestComplete";
public static const REQUIREMENTTYPE_NODE:String = "Node";
// Requirement Options
public static const REQUIREMENT_PLAYER_HAS_ITEM_DATABASE:String = "PLAYER_HAS_ITEM";
public static const REQUIREMENT_PLAYER_HAS_ITEM_HUMAN:String = "Player Has At Least Qty of an Item";
public static const REQUIREMENT_PLAYER_DOES_NOT_HAVE_ITEM_DATABASE:String = "PLAYER_DOES_NOT_HAVE_ITEM";
public static const REQUIREMENT_PLAYER_DOES_NOT_HAVE_ITEM_HUMAN:String = "Player Has Less Than Qty of an Item";
public static const REQUIREMENT_PLAYER_VIEWED_ITEM_DATABASE:String = "PLAYER_VIEWED_ITEM";
public static const REQUIREMENT_PLAYER_VIEWED_ITEM_HUMAN:String = "Player Viewed Item";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_ITEM_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_ITEM";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_ITEM_HUMAN:String = "Player Never Viewed Item";
public static const REQUIREMENT_PLAYER_VIEWED_NODE_DATABASE:String = "PLAYER_VIEWED_NODE";
public static const REQUIREMENT_PLAYER_VIEWED_NODE_HUMAN:String = "Player Viewed Plaque/Script";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NODE_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_NODE";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NODE_HUMAN:String = "Player Never Viewed Plaque/Script";
public static const REQUIREMENT_PLAYER_VIEWED_NPC_DATABASE:String = "PLAYER_VIEWED_NPC";
public static const REQUIREMENT_PLAYER_VIEWED_NPC_HUMAN:String = "Player Greeted By Character";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NPC_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_NPC";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NPC_HUMAN:String = "Player Never Greeted By Character";
public static const REQUIREMENT_PLAYER_HAS_UPLOADED_MEDIA_ITEM_DATABASE:String = "PLAYER_HAS_UPLOADED_MEDIA_ITEM";
public static const REQUIREMENT_PLAYER_HAS_UPLOADED_MEDIA_ITEM_HUMAN:String = "Player Has Uploaded Media Item";
public static const REQUIREMENT_PLAYER_HAS_COMPLETED_QUEST_DATABASE:String = "PLAYER_HAS_COMPLETED_QUEST";
public static const REQUIREMENT_PLAYER_HAS_COMPLETED_QUEST_HUMAN:String = "Player Has Completed Quest";
public static const REQUIREMENT_BOOLEAN_AND_DATABASE:String = "AND";
public static const REQUIREMENT_BOOLEAN_AND_HUMAN:String = "All";
public static const REQUIREMENT_BOOLEAN_OR_DATABASE:String = "OR";
public static const REQUIREMENT_BOOLEAN_OR_HUMAN:String = "Only this one";
// Defaults
public static const DEFAULT_ICON_MEDIA_ID_NPC:Number = 1;
public static const DEFAULT_ICON_MEDIA_ID_ITEM:Number = 2;
public static const DEFAULT_ICON_MEDIA_ID_PLAQUE:Number = 3;
// Palette Tree Stuff
public static const PALETTE_TREE_SELF_FOLDER_ID:Number = 0;
public static const PLAYER_GENERATED_MEDIA_FOLDER_ID:Number = 99;
public static const PLAYER_GENERATED_MEDIA_FOLDER_NAME:String = "Player Created Items";
/**
* Constructor
*/
public function AppConstants()
{
super();
}
}
}
|
package org.arisgames.editor.util
{
public class AppConstants
{
//Server URL
//public static const APPLICATION_ENVIRONMENT_ROOT_URL:String = "http://arisgames.org/stagingserver1"; //For other URL's to append to- Staging
public static const APPLICATION_ENVIRONMENT_ROOT_URL:String = "http://atsosxdev.doit.wisc.edu/aris/server"; //For other URL's to append to- Dev
public static const APPLICATION_ENVIRONMENT_SERVICES_URL:String = APPLICATION_ENVIRONMENT_ROOT_URL+"/services/aris/"; //staging
public static const APPLICATION_ENVIRONMENT_UPLOAD_SERVER_URL:String = APPLICATION_ENVIRONMENT_ROOT_URL+"/services/aris/uploadhandler.php"; //davembp
public static const APPLICATION_ENVIRONMENT_GATEWAY_URL:String = APPLICATION_ENVIRONMENT_ROOT_URL+"/gateway.php"; //services-config.xml
//Google API
//public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAA-Z69V9McvCh02XYNV5UHBBRloMOfjiI7F4SM41AgXh_4cb6l9xTHRyPNO3mgDcJkTIE742EL8ZoQ_Q"; //staging
//public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAArdp0t4v0pcA_JogLZhjrjBTf4EykMftsP7dwAfDsLsFl_zB7rBTq5-3Hy0k3tU1tgyomozB1YmIfNg"; //davembp
public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAA-Z69V9McvCh02XYNV5UHBBQsvlSBtAWfm4N2P3iTGfWOp-UrmRRTU3pFPQwMJB92SZ3plLjvRpMIIw"; //dev
// Dynamic Events
public static const APPLICATIONDYNAMICEVENT_CURRENTSTATECHANGED:String = "ApplicationDynamicEventCurrentStateChanged";
public static const APPLICATIONDYNAMICEVENT_REDRAWOBJECTPALETTE:String = "ApplicationDynamicEventRedrawObjectPalette";
public static const APPLICATIONDYNAMICEVENT_GAMEPLACEMARKSLOADED:String = "ApplicationDynamicEventGamePlacemarksLoaded";
public static const DYNAMICEVENT_GEOSEARCH:String = "DynamicEventGeoSearch";
public static const DYNAMICEVENT_PLACEMARKSELECTED:String = "DynamicEventPlaceMarkSelected";
public static const DYNAMICEVENT_PLACEMARKREQUESTSDELETION:String = "DynamicEventPlaceMarkRequestsDeletion";
public static const DYNAMICEVENT_EDITOBJECTPALETTEITEM:String = "EditObjectPaletteItem";
public static const DYNAMICEVENT_HIGHLIGHTOBJECTPALETTEITEM:String = "HighlightObjectPaletteItem";
public static const DYNAMICEVENT_CLOSEOBJECTPALETTEITEMEDITOR:String = "CloseObjectPaletteItemEditor";
public static const DYNAMICEVENT_CLOSEMEDIAPICKER:String = "CloseMediaPicker";
public static const DYNAMICEVENT_CLOSEMEDIAUPLOADER:String = "CloseMediaUploader";
public static const DYNAMICEVENT_CLOSEREQUIREMENTSEDITOR:String = "CloseRequirementsEditor";
public static const DYNAMICEVENT_REFRESHDATAINREQUIREMENTSEDITOR:String = "RefreshDataInRequirementsEditor";
public static const DYNAMICEVENT_OPENREQUIREMENTSEDITORMAP:String = "OpenRequirementsEditorMap";
public static const DYNAMICEVENT_CLOSEREQUIREMENTSEDITORMAP:String = "CloseRequirementsEditorMap";
public static const DYNAMICEVENT_SAVEREQUIREMENTDUETOMAPDATACHANGE:String = "SaveRequirementDueToMapDataChange";
public static const DYNAMICEVENT_OPENQUESTSMAP:String = "OpenQuestsMap";
public static const DYNAMICEVENT_CLOSEQUESTSMAP:String = "CloseQuestsMap";
public static const DYNAMICEVENT_REFRESHDATAINQUESTSEDITOR:String = "RefreshDataInQuestsEditor";
public static const DYNAMICEVENT_OPENQUESTSEDITOR:String = "OpenQuestsEditor";
public static const DYNAMICEVENT_CLOSEQUESTSEDITOR:String = "CloseQuestsEditor";
public static const DYNAMICEVENT_REFRESHDATAINPLAYERSTATECHANGESEDITOR:String = "DYNAMICEVENT_REFRESHDATAINPLAYERSTATECHANGESEDITOR";
public static const DYNAMICEVENT_CLOSEPLAYERSTATECHANGEEDITOR:String = "DYNAMICEVENT_CLOSEPLAYERSTATECHANGEEDITOR";
public static const DYNAMICEVENT_REFRESHDATAINCONVERSATIONS:String = "DYNAMICEVENT_DYNAMICEVENT_REFRESHDATAINCONVERSATIONS";
// Placemark Content
public static const CONTENTTYPE_PAGE:String = "Plaque";
public static const CONTENTTYPE_CHARACTER:String = "Character";
public static const CONTENTTYPE_ITEM:String = "Item";
public static const CONTENTTYPE_QRCODEGROUP:String = "QR Code Group";
public static const CONTENTTYPE_PAGE_VAL:Number = 0;
public static const CONTENTTYPE_CHARACTER_VAL:Number = 1;
public static const CONTENTTYPE_ITEM_VAL:Number = 2;
public static const CONTENTTYPE_QRCODEGROUP_VAL:Number = 3;
public static const CONTENTTYPE_PAGE_DATABASE:String = "Node";
public static const CONTENTTYPE_CHARACTER_DATABASE:String = "Npc";
public static const CONTENTTYPE_ITEM_DATABASE:String = "Item";
public static const PLACEMARK_DEFAULT_ERROR_RANGE:Number = 30;
// Label Constants
public static const BUTTON_LOGIN:String = "Login!";
public static const BUTTON_REGISTER:String = "Register!";
public static const RADIO_FORGOTPASSWORD:String = "Forgot Password";
public static const RADIO_FORGOTUSERNAME:String = "Forgot Username";
// Max allowed upload size for media.........MB....KB....Bytes
public static const MAX_UPLOAD_SIZE:Number = 10 * 1024 * 1024 //In bytes
// Media Types
public static const MEDIATYPE:String = "Media Types";
public static const MEDIATYPE_IMAGE:String = "Image";
public static const MEDIATYPE_AUDIO:String = "Audio";
public static const MEDIATYPE_VIDEO:String = "Video";
public static const MEDIATYPE_ICON:String = "Icon";
public static const MEDIATYPE_SEPARATOR:String = " ";
public static const MEDIATYPE_UPLOADNEW:String = " ";
// Media-tree-icon Types
public static const MEDIATREEICON_SEPARATOR:String = "separatorIcon";
public static const MEDIATREEICON_UPLOAD:String = "uploadIcon";
//Player State Changes
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_ITEM:String = "VIEW_ITEM";
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_NODE:String = "VIEW_NODE";
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_NPC:String = "VIEW_NPC";
public static const PLAYERSTATECHANGE_ACTION_GIVEITEM:String = "GIVE_ITEM";
public static const PLAYERSTATECHANGE_ACTION_GIVEITEM_HUMAN:String = "Give Item";
public static const PLAYERSTATECHANGE_ACTION_TAKEITEM:String = "TAKE_ITEM";
public static const PLAYERSTATECHANGE_ACTION_TAKEITEM_HUMAN:String = "Take Item";
// Requirement Types
public static const REQUIREMENTTYPE_LOCATION:String = "Location";
public static const REQUIREMENTTYPE_QUESTDISPLAY:String = "QuestDisplay";
public static const REQUIREMENTTYPE_QUESTCOMPLETE:String = "QuestComplete";
public static const REQUIREMENTTYPE_NODE:String = "Node";
// Requirement Options
public static const REQUIREMENT_PLAYER_HAS_ITEM_DATABASE:String = "PLAYER_HAS_ITEM";
public static const REQUIREMENT_PLAYER_HAS_ITEM_HUMAN:String = "Player Has At Least Qty of an Item";
public static const REQUIREMENT_PLAYER_DOES_NOT_HAVE_ITEM_DATABASE:String = "PLAYER_DOES_NOT_HAVE_ITEM";
public static const REQUIREMENT_PLAYER_DOES_NOT_HAVE_ITEM_HUMAN:String = "Player Has Less Than Qty of an Item";
public static const REQUIREMENT_PLAYER_VIEWED_ITEM_DATABASE:String = "PLAYER_VIEWED_ITEM";
public static const REQUIREMENT_PLAYER_VIEWED_ITEM_HUMAN:String = "Player Viewed Item";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_ITEM_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_ITEM";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_ITEM_HUMAN:String = "Player Never Viewed Item";
public static const REQUIREMENT_PLAYER_VIEWED_NODE_DATABASE:String = "PLAYER_VIEWED_NODE";
public static const REQUIREMENT_PLAYER_VIEWED_NODE_HUMAN:String = "Player Viewed Plaque/Script";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NODE_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_NODE";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NODE_HUMAN:String = "Player Never Viewed Plaque/Script";
public static const REQUIREMENT_PLAYER_VIEWED_NPC_DATABASE:String = "PLAYER_VIEWED_NPC";
public static const REQUIREMENT_PLAYER_VIEWED_NPC_HUMAN:String = "Player Greeted By Character";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NPC_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_NPC";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NPC_HUMAN:String = "Player Never Greeted By Character";
public static const REQUIREMENT_PLAYER_HAS_UPLOADED_MEDIA_ITEM_DATABASE:String = "PLAYER_HAS_UPLOADED_MEDIA_ITEM";
public static const REQUIREMENT_PLAYER_HAS_UPLOADED_MEDIA_ITEM_HUMAN:String = "Player Has Uploaded Media Item";
public static const REQUIREMENT_PLAYER_HAS_COMPLETED_QUEST_DATABASE:String = "PLAYER_HAS_COMPLETED_QUEST";
public static const REQUIREMENT_PLAYER_HAS_COMPLETED_QUEST_HUMAN:String = "Player Has Completed Quest";
public static const REQUIREMENT_BOOLEAN_AND_DATABASE:String = "AND";
public static const REQUIREMENT_BOOLEAN_AND_HUMAN:String = "All";
public static const REQUIREMENT_BOOLEAN_OR_DATABASE:String = "OR";
public static const REQUIREMENT_BOOLEAN_OR_HUMAN:String = "Only this one";
// Defaults
public static const DEFAULT_ICON_MEDIA_ID_NPC:Number = 1;
public static const DEFAULT_ICON_MEDIA_ID_ITEM:Number = 2;
public static const DEFAULT_ICON_MEDIA_ID_PLAQUE:Number = 3;
// Palette Tree Stuff
public static const PALETTE_TREE_SELF_FOLDER_ID:Number = 0;
public static const PLAYER_GENERATED_MEDIA_FOLDER_ID:Number = -1;
public static const PLAYER_GENERATED_MEDIA_FOLDER_NAME:String = "Player Created Items";
/**
* Constructor
*/
public function AppConstants()
{
super();
}
}
}
|
Set constant of Folder ID to -1
|
Set constant of Folder ID to -1
|
ActionScript
|
mit
|
inesaloulou21/arisgames,augustozuniga/arisgames,inesaloulou21/arisgames,augustozuniga/arisgames,inesaloulou21/arisgames,inesaloulou21/arisgames,augustozuniga/arisgames,inesaloulou21/arisgames,augustozuniga/arisgames,inesaloulou21/arisgames,inesaloulou21/arisgames,augustozuniga/arisgames,augustozuniga/arisgames,augustozuniga/arisgames,augustozuniga/arisgames,augustozuniga/arisgames,inesaloulou21/arisgames,inesaloulou21/arisgames
|
609ad432ceefd49a856618e2cb4a1d93517c205b
|
WEB-INF/lps/lfc/kernel/swf9/LzFontManager.as
|
WEB-INF/lps/lfc/kernel/swf9/LzFontManager.as
|
/**
* LzFontManager.as
*
* @copyright Copyright 2001-2009 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic Kernel
* @subtopic swf9
*/
/** Manages the font dictionary.
*
* @devnote In addition to any fields documented in the section below, these fields
* are also available:
*
* dictionary <attribute>fonts</attribute>: A hash holding named font objects.
* Each font object contains slots for the styles that are available
* (plain, bold, italic, and/or bolditalic).
*/
public class LzFontManager {
#passthrough (toplevel:true) {
import flash.text.Font;
}#
static var fonts :Object = {};
/** @devnote currently doesn't support sending variables...
*/
/**
* Creates an <class>LzFont</class> with the given parameters and adds it to
* the <attribute>fonts</attribute> list.
*
* @param fontname: The name of the font. This is the string that will be used
* when requesting a font via <method>getFont</method>
* @param Object n: The plain style of the font.
* @param Object b: The bold style of the font.
* @param Object i: The italic style of the font.
* @param Object bi: The bold italic style of the font.
* @access private
*/
public static function addFont (fontname:String, n:Object, b:Object, i:Object, bi:Object) :void {
var ff:Object = new Object;
ff.name = fontname;
if ( n ){
new LzFont( ff, n, "plain");
}
if ( b ) {
new LzFont( ff, b, "bold");
}
if ( i ){
new LzFont( ff, i, "italic" );
}
if ( bi ){
new LzFont( ff, bi, "bolditalic");
}
LzFontManager.fonts[ fontname ] = ff;
}
/**
* Get the named <class>LzFont</class> of the given style.
* @param String fontname: The name of the font.
* @param String style: The style of the font. One of <constant>plain</constant>, <constant>bold</constant>, <constant>italic</constant>
* or <constant>bolditalic</constant>. If style is <constant>null</constant>, <constant>plain</constant> is assumed.
* @return any: An <class>LzFont</class> object, or undefined if not found
*
*/
public static function getFont (fontname:String, style:String) :LzFont {
if ( style == null ) { style = "plain" }
var fns:Array = fontname.split(',');
if (fns.length > 0) {
for (var i:int = 0; i < fns.length; i++) {
fontname = fns[i];
var tfn:LzFont = LzFontManager.fonts[ fontname ];
if (tfn) {
return tfn[ style ];
}
}
return null;
} else {
var tfn:LzFont = LzFontManager.fonts[ fontname ];
if (tfn) {
return tfn[ style ];
} else {
return null;
}
}
}
/**
* Apply/add the requested style to the given <class>LzFont</class> and
* return the new <class>LzFont</class>.
*
* @param f: An <class>LzFont</class>.
* @param s: the style string (One of "plain", "bold", "italic", or "bolditalic").
* @return LzFont: The new <class>LzFont</class>.
* @access private
*/
public static function addStyle (f:LzFont, s:String) :LzFont {
//not pretty -- especially if the complexity of styles grows -- but works
//for now
if ( f.style == "bolditalic") {
return f;
} else if ( s == "bold" ){
if ( f.style == "italic" ){
return f.fontobject.bolditalic;
} else {
return f.fontobject.bold;
}
} else if ( s == "italic" ) {
if ( f.style == "bold" ){
return f.fontobject.bolditalic;
} else {
return f.fontobject.italic;
}
} else if ( s == "bolditalic" ){
return f.fontobject.bolditalic;
}
// no change
return f;
}
// Map {font-name -> true} of client font names. convertFontList
// initializes this.
static var __clientFontNames :Object;
// A map from CSS generic font family names such as 'sans-serif' to
// Flash names such as '_sans'.
static var __fontFamilyMap :Object = {'monospace': '_typewriter', 'serif': '_serif', 'sans-serif': '_sans'};
// A hashset of device font family names.
static var __genericClientFontFamilyNames :Object = {'_typewriter': true, '_serif': true, '_sans': true};
static public var __fontnameCacheMap :Object = {};
static var __debugWarnedFonts :Object = {};
/**
* Convert an LZX font name to one that the Flash runtime can render.
* This involves removing whitespace, and changing CSS generic font family
* names such as 'sans-serif' to Flash names such as '_sans'.
*/
public static function __convertFontName (name:String) :String {
// FIXME [2004-11-29 ows]: trim other types of whitespace too
while (name.charAt(0) == ' ') name = name.slice(1);
while (name.charAt(name.length - 1) == ' ') name = name.slice(0, name.length-1);
var map:Object = LzFontManager.__fontFamilyMap;
// Warn about uses of Flash-specific names. These won't work on
// other runtimes.
if ($debug) {
for (var i:String in map)
if (name == map[i] && !LzFontManager.__debugWarnedFonts[name]) {
LzFontManager.__debugWarnedFonts[name] = true;
Debug.warn("Undefined font %w. Use %w instead", name, i);
}
}
if (typeof map[name] == 'string') name = map[name];
return name;
}
/**
* Return the first name that can be rendered, or the first name if
* none of the names can be rendered. str is a comma-separated list
* of font names.
*/
public static function __findMatchingFont (str:String) :String {
if (LzFontManager.__clientFontNames == null) {
LzFontManager.__clientFontNames = {};
var fonts:Array = Font.enumerateFonts(true);
for (var i:int = 0; i < fonts.length; ++i) {
LzFontManager.__clientFontNames[fonts[i].fontName] = true;
}
}
var name:String = null;
if (str.indexOf(',') >= 0) {
var names:Array = str.split(',');
for (var i:int = 0; i < names.length; i++) {
name = names[i] = LzFontManager.__convertFontName(names[i]);
if (LzFontManager.__clientFontNames[name] || LzFontManager.__genericClientFontFamilyNames[name]) {
return name;
}
}
} else {
name = LzFontManager.__convertFontName(str);
}
if ($debug) {
if (!LzFontManager.__fontExists(name)) {
Debug.warn("Undefined font %w", name);
}
}
return name;
}
/**
* @access private
*/
public static function __fontExists (str:String) :Boolean {
return (LzFontManager.fonts[ str ] != null ||
LzFontManager.__clientFontNames[str] != null ||
LzFontManager.__genericClientFontFamilyNames[str] != null ||
LzFontManager.__fontFamilyMap[str] != null);
}
}
|
/**
* LzFontManager.as
*
* @copyright Copyright 2001-2009 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic Kernel
* @subtopic swf9
*/
/** Manages the font dictionary.
*
* @devnote In addition to any fields documented in the section below, these fields
* are also available:
*
* dictionary <attribute>fonts</attribute>: A hash holding named font objects.
* Each font object contains slots for the styles that are available
* (plain, bold, italic, and/or bolditalic).
*/
public class LzFontManager {
#passthrough (toplevel:true) {
import flash.text.Font;
}#
static var fonts :Object = {};
/** @devnote currently doesn't support sending variables...
*/
/**
* Creates an <class>LzFont</class> with the given parameters and adds it to
* the <attribute>fonts</attribute> list.
*
* @param fontname: The name of the font. This is the string that will be used
* when requesting a font via <method>getFont</method>
* @param Object n: The plain style of the font.
* @param Object b: The bold style of the font.
* @param Object i: The italic style of the font.
* @param Object bi: The bold italic style of the font.
* @access private
*/
public static function addFont (fontname:String, n:Object, b:Object, i:Object, bi:Object) :void {
var ff:Object = new Object;
ff.name = fontname;
if ( n ){
new LzFont( ff, n, "plain");
}
if ( b ) {
new LzFont( ff, b, "bold");
}
if ( i ){
new LzFont( ff, i, "italic" );
}
if ( bi ){
new LzFont( ff, bi, "bolditalic");
}
LzFontManager.fonts[ fontname ] = ff;
}
/**
* Get the named <class>LzFont</class> of the given style.
* @param String fontname: The name of the font.
* @param String style: The style of the font. One of <constant>plain</constant>, <constant>bold</constant>, <constant>italic</constant>
* or <constant>bolditalic</constant>. If style is <constant>null</constant>, <constant>plain</constant> is assumed.
* @return any: An <class>LzFont</class> object, or undefined if not found
*
*/
public static function getFont (fontname:String, style:String) :LzFont {
if ( style == null ) { style = "plain" }
var fns:Array = fontname.split(',');
if (fns.length > 0) {
for (var i:int = 0; i < fns.length; i++) {
fontname = fns[i];
var tfn:Object = LzFontManager.fonts[ fontname ];
if (tfn) {
return tfn[ style ];
}
}
return null;
} else {
var tfn:Object = LzFontManager.fonts[ fontname ];
if (tfn) {
return tfn[ style ];
} else {
return null;
}
}
}
/**
* Apply/add the requested style to the given <class>LzFont</class> and
* return the new <class>LzFont</class>.
*
* @param f: An <class>LzFont</class>.
* @param s: the style string (One of "plain", "bold", "italic", or "bolditalic").
* @return LzFont: The new <class>LzFont</class>.
* @access private
*/
public static function addStyle (f:LzFont, s:String) :LzFont {
//not pretty -- especially if the complexity of styles grows -- but works
//for now
if ( f.style == "bolditalic") {
return f;
} else if ( s == "bold" ){
if ( f.style == "italic" ){
return f.fontobject.bolditalic;
} else {
return f.fontobject.bold;
}
} else if ( s == "italic" ) {
if ( f.style == "bold" ){
return f.fontobject.bolditalic;
} else {
return f.fontobject.italic;
}
} else if ( s == "bolditalic" ){
return f.fontobject.bolditalic;
}
// no change
return f;
}
// Map {font-name -> true} of client font names. convertFontList
// initializes this.
static var __clientFontNames :Object;
// A map from CSS generic font family names such as 'sans-serif' to
// Flash names such as '_sans'.
static var __fontFamilyMap :Object = {'monospace': '_typewriter', 'serif': '_serif', 'sans-serif': '_sans'};
// A hashset of device font family names.
static var __genericClientFontFamilyNames :Object = {'_typewriter': true, '_serif': true, '_sans': true};
static public var __fontnameCacheMap :Object = {};
static var __debugWarnedFonts :Object = {};
/**
* Convert an LZX font name to one that the Flash runtime can render.
* This involves removing whitespace, and changing CSS generic font family
* names such as 'sans-serif' to Flash names such as '_sans'.
*/
public static function __convertFontName (name:String) :String {
// FIXME [2004-11-29 ows]: trim other types of whitespace too
while (name.charAt(0) == ' ') name = name.slice(1);
while (name.charAt(name.length - 1) == ' ') name = name.slice(0, name.length-1);
var map:Object = LzFontManager.__fontFamilyMap;
// Warn about uses of Flash-specific names. These won't work on
// other runtimes.
if ($debug) {
for (var i:String in map)
if (name == map[i] && !LzFontManager.__debugWarnedFonts[name]) {
LzFontManager.__debugWarnedFonts[name] = true;
Debug.warn("Undefined font %w. Use %w instead", name, i);
}
}
if (typeof map[name] == 'string') name = map[name];
return name;
}
/**
* Return the first name that can be rendered, or the first name if
* none of the names can be rendered. str is a comma-separated list
* of font names.
*/
public static function __findMatchingFont (str:String) :String {
if (LzFontManager.__clientFontNames == null) {
LzFontManager.__clientFontNames = {};
var fonts:Array = Font.enumerateFonts(true);
for (var i:int = 0; i < fonts.length; ++i) {
LzFontManager.__clientFontNames[fonts[i].fontName] = true;
}
}
var name:String = null;
if (str.indexOf(',') >= 0) {
var names:Array = str.split(',');
for (var i:int = 0; i < names.length; i++) {
name = names[i] = LzFontManager.__convertFontName(names[i]);
if (LzFontManager.__clientFontNames[name] || LzFontManager.__genericClientFontFamilyNames[name]) {
return name;
}
}
} else {
name = LzFontManager.__convertFontName(str);
}
if ($debug) {
if (!LzFontManager.__fontExists(name)) {
Debug.warn("Undefined font %w", name);
}
}
return name;
}
/**
* @access private
*/
public static function __fontExists (str:String) :Boolean {
return (LzFontManager.fonts[ str ] != null ||
LzFontManager.__clientFontNames[str] != null ||
LzFontManager.__genericClientFontFamilyNames[str] != null ||
LzFontManager.__fontFamilyMap[str] != null);
}
}
|
Change 20090401-hqm-L by [email protected] on 2009-04-01 19:01:21 EDT in /Users/hqm/openlaszlo/trunk/WEB-INF/lps/lfc for http://svn.openlaszlo.org/openlaszlo/trunk/WEB-INF/lps/lfc
|
Change 20090401-hqm-L by [email protected] on 2009-04-01 19:01:21 EDT
in /Users/hqm/openlaszlo/trunk/WEB-INF/lps/lfc
for http://svn.openlaszlo.org/openlaszlo/trunk/WEB-INF/lps/lfc
Summary: fix swf9 embedded font declarations
New Features:
Bugs Fixed: LPP-8011
Technical Reviewer: ptw
QA Reviewer: (pending)
Doc Reviewer: (pending)
Documentation:
Release Notes:
Details:
+ change type of var in lookup from LzFont to Object
Tests:
embedded font example runs without error
<canvas>
<font src="uni-5-plain-expanded-s.ttf" name="myfont"/>
<text font="myfont">myfont is oh-so good!</text>
</canvas>
git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@13581 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
|
ActionScript
|
epl-1.0
|
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
|
8cddf9ef1baace35e1ede47f109ab94b737cd3e4
|
src/as/com/threerings/flash/DisplayUtil.as
|
src/as/com/threerings/flash/DisplayUtil.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 {
import com.threerings.util.ArrayUtil;
import com.threerings.util.ClassUtil;
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.geom.Point;
import flash.geom.Rectangle;
public class DisplayUtil
{
/**
* Adds newChild to container, directly below another child of the container.
*/
public static function addChildBelow (container :DisplayObjectContainer,
newChild :DisplayObject,
below :DisplayObject) :void
{
var ii :int = (below.parent == container ? container.getChildIndex(below) : 0);
container.addChildAt(newChild, ii);
}
/**
* Adds newChild to container, directly above another child of the container.
*/
public static function addChildAbove (container :DisplayObjectContainer,
newChild :DisplayObject,
above :DisplayObject) :void
{
var ii :int = (above.parent == container ? container.getChildIndex(above) + 1 : 0);
container.addChildAt(newChild, ii);
}
/**
* Sets the top-left pixel of a DisplayObject to the given location, relative to another
* DisplayObject's coordinate space.
*/
public static function positionBoundsRelative (disp :DisplayObject, relativeTo :DisplayObject,
x :Number, y :Number) :void
{
var bounds :Rectangle = disp.getBounds(relativeTo);
disp.x = x - bounds.left;
disp.y = y - bounds.top;
}
/**
* Sets the top-left pixel of a DisplayObject to the given location, taking the
* object's bounds into account.
*/
public static function positionBounds (disp :DisplayObject, x :Number, y :Number) :void
{
positionBoundsRelative(disp, disp, x, y);
}
/**
* Sorts a container's children, using ArrayUtil.stableSort.
*
* comp is a function that takes two DisplayObjects, and returns int -1 if the first
* object should appear before the second in the container, 1 if it should appear after,
* and 0 if the order does not matter. If omitted, Comparators.COMPARABLE
* will be used- all the children should implement Comparable.
*/
public static function sortDisplayChildren (
container :DisplayObjectContainer, comp :Function = null) :void
{
var numChildren :int = container.numChildren;
// put all children in an array
var children :Array = new Array(numChildren);
var ii :int;
for (ii = 0; ii < numChildren; ii++) {
children[ii] = container.getChildAt(ii);
}
// stable sort the array
ArrayUtil.stableSort(children, comp);
// set their new indexes
for (ii = 0; ii < numChildren; ii++) {
container.setChildIndex(DisplayObject(children[ii]), ii);
}
}
/**
* Call the specified function for the display object and all descendants.
*
* This is nearly exactly like mx.utils.DisplayUtil.walkDisplayObjects,
* except this method copes with security errors when examining a child.
*/
public static function applyToHierarchy (
disp :DisplayObject, callbackFunction :Function) :void
{
callbackFunction(disp);
if (disp is DisplayObjectContainer) {
var container :DisplayObjectContainer = disp as DisplayObjectContainer;
var nn :int = container.numChildren;
for (var ii :int = 0; ii < nn; ii++) {
try {
disp = container.getChildAt(ii);
} catch (err :SecurityError) {
continue;
}
// and then we apply outside of the try/catch block so that
// we don't hide errors thrown by the callbackFunction.
applyToHierarchy(disp, callbackFunction);
}
}
}
/**
* Center the specified rectangle within the specified bounds. If the bounds are too
* small then the rectangle will be pinned to the upper-left.
*/
public static function centerRectInRect (rect :Rectangle, bounds :Rectangle) :Point
{
return new Point(
bounds.x + Math.max(0, (bounds.width - rect.width) / 2),
bounds.y + Math.max(0, (bounds.height - rect.height) / 2));
}
/**
* Returns the most reasonable position for the specified rectangle to
* be placed at so as to maximize its containment by the specified
* bounding rectangle while still placing it as near its original
* coordinates as possible.
*
* @param rect the rectangle to be positioned.
* @param bounds the containing rectangle.
*/
public static function fitRectInRect (rect :Rectangle, bounds :Rectangle) :Point
{
// Guarantee that the right and bottom edges will be contained
// and do our best for the top and left edges.
return new Point(
Math.min(bounds.right - rect.width, Math.max(rect.x, bounds.x)),
Math.min(bounds.bottom - rect.height, Math.max(rect.y, bounds.y)));
}
/**
* Position the specified rectangle within the bounds, avoiding
* any of the Rectangles in the avoid array, which may be destructively
* modified.
*
* @return true if the rectangle was successfully placed, given the
* constraints, or false if the positioning failed (the rectangle will
* be left at its original location.
*/
public static function positionRect (
r :Rectangle, bounds :Rectangle, avoid :Array) :Boolean
{
var origPos :Point = r.topLeft;
var pointSorter :Function = createPointSorter(origPos);
var possibles :Array = new Array();
// start things off with the passed-in point (adjusted to
// be inside the bounds, if needed)
possibles.push(fitRectInRect(r, bounds));
// keep track of area that doesn't generate new possibles
var dead :Array = new Array();
// Note: labeled breaks and continues are supposed to be legal,
// but they throw wacky runtime exceptions for me. So instead
// I'm throwing a boolean and using that to continue the while
/* CHECKPOSSIBLES: */ while (possibles.length > 0) {
try {
var p :Point = (possibles.shift() as Point);
r.x = p.x;
r.y = p.y;
// make sure the rectangle is in the view
if (!bounds.containsRect(r)) {
continue;
}
// and not over a dead area
for each (var deadRect :Rectangle in dead) {
if (deadRect.intersects(r)) {
//continue CHECKPOSSIBLES;
throw true; // continue outer loop
}
}
// see if it hits any rects we're trying to avoid
for (var ii :int = 0; ii < avoid.length; ii++) {
var avoidRect :Rectangle = (avoid[ii] as Rectangle);
if (avoidRect.intersects(r)) {
// remove it from the avoid list
avoid.splice(ii, 1);
// but add it to the dead list
dead.push(avoidRect);
// add 4 new possible points, each pushed in
// one direction
possibles.push(
new Point(avoidRect.x - r.width, r.y),
new Point(r.x, avoidRect.y - r.height),
new Point(avoidRect.x + avoidRect.width, r.y),
new Point(r.x, avoidRect.y + avoidRect.height));
// re-sort the list
possibles.sort(pointSorter);
//continue CHECKPOSSIBLES;
throw true; // continue outer loop
}
}
// hey! if we got here, then it worked!
return true;
} catch (continueWhile :Boolean) {
// simply catch the boolean and use it to continue inner loops
}
}
// we never found a match, move the rectangle back
r.x = origPos.x;
r.y = origPos.y;
return false;
}
/**
* Create a sort Function that can be used to compare Points in an
* Array according to their distance from the specified Point.
*
* Note: The function will always sort according to distance from the
* passed-in point, even if that point's coordinates change after
* the function is created.
*/
public static function createPointSorter (origin :Point) :Function
{
return function (p1 :Point, p2 :Point) :Number {
var dist1 :Number = Point.distance(origin, p1);
var dist2 :Number = Point.distance(origin, p2);
return (dist1 > dist2) ? 1 : ((dist1 < dist2) ? -1 : 0); // signum
};
}
/**
* Find a component with the specified name in the specified display hierarchy.
* Whether finding deeply or shallowly, if two components have the target name and are
* at the same depth, the first one found will be returned.
*
* Note: This method will not find rawChildren of flex componenets.
*/
public static function findInHierarchy (
top :DisplayObject, name :String, findShallow :Boolean = true,
maxDepth :int = int.MAX_VALUE) :DisplayObject
{
var result :Array = findInHierarchy0(top, name, findShallow, maxDepth);
return (result != null) ? DisplayObject(result[0]) : null;
}
/**
* Dump the display hierarchy to a String, each component on a newline, children indented
* two spaces:
* "instance0" flash.display.Sprite
* "instance1" flash.display.Sprite
* "entry_box" flash.text.TextField
*
* Note: This method will not dump rawChildren of flex componenets.
*/
public static function dumpHierarchy (top :DisplayObject) :String
{
return dumpHierarchy0(top);
}
/**
* Internal worker method for findInHierarchy.
*/
private static function findInHierarchy0 (
obj :DisplayObject, name :String, shallow :Boolean, maxDepth :int, curDepth :int = 0) :Array
{
if (obj == null) {
return null;
}
var bestResult :Array;
if (obj.name == name) {
if (shallow) {
return [ obj, curDepth ];
} else {
bestResult = [ obj, curDepth ];
}
} else {
bestResult = null;
}
if (curDepth < maxDepth && (obj is DisplayObjectContainer)) {
var cont :DisplayObjectContainer = obj as DisplayObjectContainer;
var nextDepth :int = curDepth + 1;
for (var ii :int = 0; ii < cont.numChildren; ii++) {
try {
var result :Array = findInHierarchy0(
cont.getChildAt(ii), name, shallow, maxDepth, nextDepth);
if (result != null) {
if (shallow) {
// we update maxDepth for every hit, so result is always
// shallower than any current bestResult
bestResult = result;
maxDepth = int(result[1]) - 1;
if (maxDepth == curDepth) {
break; // stop looking
}
} else {
// only replace if it's deeper
if (bestResult == null || int(result[1]) > int(bestResult[1])) {
bestResult = result;
}
}
}
} catch (err :SecurityError) {
// skip this child
}
}
}
return bestResult;
}
/**
* Internal worker method for dumpHierarchy.
*/
private static function dumpHierarchy0 (
obj :DisplayObject, spaces :String = "", inStr :String = "") :String
{
if (obj != null) {
if (inStr != "") {
inStr += "\n";
}
inStr += spaces + "\"" + obj.name + "\" " + ClassUtil.getClassName(obj);
if (obj is DisplayObjectContainer) {
spaces += " ";
var container :DisplayObjectContainer = obj as DisplayObjectContainer;
for (var ii :int = 0; ii < container.numChildren; ii++) {
try {
var child :DisplayObject = container.getChildAt(ii);
inStr = dumpHierarchy0(container.getChildAt(ii), spaces, inStr);
} catch (err :SecurityError) {
inStr += "\n" + spaces + "SECURITY-BLOCKED";
}
}
}
}
return inStr;
}
}
}
|
//
// $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 {
import com.threerings.util.ArrayUtil;
import com.threerings.util.ClassUtil;
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.geom.Point;
import flash.geom.Rectangle;
public class DisplayUtil
{
/**
* Adds newChild to container, directly below another child of the container.
*/
public static function addChildBelow (container :DisplayObjectContainer,
newChild :DisplayObject,
below :DisplayObject) :void
{
container.addChildAt(newChild, container.getChildIndex(below));
}
/**
* Adds newChild to container, directly above another child of the container.
*/
public static function addChildAbove (container :DisplayObjectContainer,
newChild :DisplayObject,
above :DisplayObject) :void
{
container.addChildAt(newChild, container.getChildIndex(above) + 1);
}
/**
* Sets the top-left pixel of a DisplayObject to the given location, relative to another
* DisplayObject's coordinate space.
*/
public static function positionBoundsRelative (disp :DisplayObject, relativeTo :DisplayObject,
x :Number, y :Number) :void
{
var bounds :Rectangle = disp.getBounds(relativeTo);
disp.x = x - bounds.left;
disp.y = y - bounds.top;
}
/**
* Sets the top-left pixel of a DisplayObject to the given location, taking the
* object's bounds into account.
*/
public static function positionBounds (disp :DisplayObject, x :Number, y :Number) :void
{
positionBoundsRelative(disp, disp, x, y);
}
/**
* Sorts a container's children, using ArrayUtil.stableSort.
*
* comp is a function that takes two DisplayObjects, and returns int -1 if the first
* object should appear before the second in the container, 1 if it should appear after,
* and 0 if the order does not matter. If omitted, Comparators.COMPARABLE
* will be used- all the children should implement Comparable.
*/
public static function sortDisplayChildren (
container :DisplayObjectContainer, comp :Function = null) :void
{
var numChildren :int = container.numChildren;
// put all children in an array
var children :Array = new Array(numChildren);
var ii :int;
for (ii = 0; ii < numChildren; ii++) {
children[ii] = container.getChildAt(ii);
}
// stable sort the array
ArrayUtil.stableSort(children, comp);
// set their new indexes
for (ii = 0; ii < numChildren; ii++) {
container.setChildIndex(DisplayObject(children[ii]), ii);
}
}
/**
* Call the specified function for the display object and all descendants.
*
* This is nearly exactly like mx.utils.DisplayUtil.walkDisplayObjects,
* except this method copes with security errors when examining a child.
*/
public static function applyToHierarchy (
disp :DisplayObject, callbackFunction :Function) :void
{
callbackFunction(disp);
if (disp is DisplayObjectContainer) {
var container :DisplayObjectContainer = disp as DisplayObjectContainer;
var nn :int = container.numChildren;
for (var ii :int = 0; ii < nn; ii++) {
try {
disp = container.getChildAt(ii);
} catch (err :SecurityError) {
continue;
}
// and then we apply outside of the try/catch block so that
// we don't hide errors thrown by the callbackFunction.
applyToHierarchy(disp, callbackFunction);
}
}
}
/**
* Center the specified rectangle within the specified bounds. If the bounds are too
* small then the rectangle will be pinned to the upper-left.
*/
public static function centerRectInRect (rect :Rectangle, bounds :Rectangle) :Point
{
return new Point(
bounds.x + Math.max(0, (bounds.width - rect.width) / 2),
bounds.y + Math.max(0, (bounds.height - rect.height) / 2));
}
/**
* Returns the most reasonable position for the specified rectangle to
* be placed at so as to maximize its containment by the specified
* bounding rectangle while still placing it as near its original
* coordinates as possible.
*
* @param rect the rectangle to be positioned.
* @param bounds the containing rectangle.
*/
public static function fitRectInRect (rect :Rectangle, bounds :Rectangle) :Point
{
// Guarantee that the right and bottom edges will be contained
// and do our best for the top and left edges.
return new Point(
Math.min(bounds.right - rect.width, Math.max(rect.x, bounds.x)),
Math.min(bounds.bottom - rect.height, Math.max(rect.y, bounds.y)));
}
/**
* Position the specified rectangle within the bounds, avoiding
* any of the Rectangles in the avoid array, which may be destructively
* modified.
*
* @return true if the rectangle was successfully placed, given the
* constraints, or false if the positioning failed (the rectangle will
* be left at its original location.
*/
public static function positionRect (
r :Rectangle, bounds :Rectangle, avoid :Array) :Boolean
{
var origPos :Point = r.topLeft;
var pointSorter :Function = createPointSorter(origPos);
var possibles :Array = new Array();
// start things off with the passed-in point (adjusted to
// be inside the bounds, if needed)
possibles.push(fitRectInRect(r, bounds));
// keep track of area that doesn't generate new possibles
var dead :Array = new Array();
// Note: labeled breaks and continues are supposed to be legal,
// but they throw wacky runtime exceptions for me. So instead
// I'm throwing a boolean and using that to continue the while
/* CHECKPOSSIBLES: */ while (possibles.length > 0) {
try {
var p :Point = (possibles.shift() as Point);
r.x = p.x;
r.y = p.y;
// make sure the rectangle is in the view
if (!bounds.containsRect(r)) {
continue;
}
// and not over a dead area
for each (var deadRect :Rectangle in dead) {
if (deadRect.intersects(r)) {
//continue CHECKPOSSIBLES;
throw true; // continue outer loop
}
}
// see if it hits any rects we're trying to avoid
for (var ii :int = 0; ii < avoid.length; ii++) {
var avoidRect :Rectangle = (avoid[ii] as Rectangle);
if (avoidRect.intersects(r)) {
// remove it from the avoid list
avoid.splice(ii, 1);
// but add it to the dead list
dead.push(avoidRect);
// add 4 new possible points, each pushed in
// one direction
possibles.push(
new Point(avoidRect.x - r.width, r.y),
new Point(r.x, avoidRect.y - r.height),
new Point(avoidRect.x + avoidRect.width, r.y),
new Point(r.x, avoidRect.y + avoidRect.height));
// re-sort the list
possibles.sort(pointSorter);
//continue CHECKPOSSIBLES;
throw true; // continue outer loop
}
}
// hey! if we got here, then it worked!
return true;
} catch (continueWhile :Boolean) {
// simply catch the boolean and use it to continue inner loops
}
}
// we never found a match, move the rectangle back
r.x = origPos.x;
r.y = origPos.y;
return false;
}
/**
* Create a sort Function that can be used to compare Points in an
* Array according to their distance from the specified Point.
*
* Note: The function will always sort according to distance from the
* passed-in point, even if that point's coordinates change after
* the function is created.
*/
public static function createPointSorter (origin :Point) :Function
{
return function (p1 :Point, p2 :Point) :Number {
var dist1 :Number = Point.distance(origin, p1);
var dist2 :Number = Point.distance(origin, p2);
return (dist1 > dist2) ? 1 : ((dist1 < dist2) ? -1 : 0); // signum
};
}
/**
* Find a component with the specified name in the specified display hierarchy.
* Whether finding deeply or shallowly, if two components have the target name and are
* at the same depth, the first one found will be returned.
*
* Note: This method will not find rawChildren of flex componenets.
*/
public static function findInHierarchy (
top :DisplayObject, name :String, findShallow :Boolean = true,
maxDepth :int = int.MAX_VALUE) :DisplayObject
{
var result :Array = findInHierarchy0(top, name, findShallow, maxDepth);
return (result != null) ? DisplayObject(result[0]) : null;
}
/**
* Dump the display hierarchy to a String, each component on a newline, children indented
* two spaces:
* "instance0" flash.display.Sprite
* "instance1" flash.display.Sprite
* "entry_box" flash.text.TextField
*
* Note: This method will not dump rawChildren of flex componenets.
*/
public static function dumpHierarchy (top :DisplayObject) :String
{
return dumpHierarchy0(top);
}
/**
* Internal worker method for findInHierarchy.
*/
private static function findInHierarchy0 (
obj :DisplayObject, name :String, shallow :Boolean, maxDepth :int, curDepth :int = 0) :Array
{
if (obj == null) {
return null;
}
var bestResult :Array;
if (obj.name == name) {
if (shallow) {
return [ obj, curDepth ];
} else {
bestResult = [ obj, curDepth ];
}
} else {
bestResult = null;
}
if (curDepth < maxDepth && (obj is DisplayObjectContainer)) {
var cont :DisplayObjectContainer = obj as DisplayObjectContainer;
var nextDepth :int = curDepth + 1;
for (var ii :int = 0; ii < cont.numChildren; ii++) {
try {
var result :Array = findInHierarchy0(
cont.getChildAt(ii), name, shallow, maxDepth, nextDepth);
if (result != null) {
if (shallow) {
// we update maxDepth for every hit, so result is always
// shallower than any current bestResult
bestResult = result;
maxDepth = int(result[1]) - 1;
if (maxDepth == curDepth) {
break; // stop looking
}
} else {
// only replace if it's deeper
if (bestResult == null || int(result[1]) > int(bestResult[1])) {
bestResult = result;
}
}
}
} catch (err :SecurityError) {
// skip this child
}
}
}
return bestResult;
}
/**
* Internal worker method for dumpHierarchy.
*/
private static function dumpHierarchy0 (
obj :DisplayObject, spaces :String = "", inStr :String = "") :String
{
if (obj != null) {
if (inStr != "") {
inStr += "\n";
}
inStr += spaces + "\"" + obj.name + "\" " + ClassUtil.getClassName(obj);
if (obj is DisplayObjectContainer) {
spaces += " ";
var container :DisplayObjectContainer = obj as DisplayObjectContainer;
for (var ii :int = 0; ii < container.numChildren; ii++) {
try {
var child :DisplayObject = container.getChildAt(ii);
inStr = dumpHierarchy0(container.getChildAt(ii), spaces, inStr);
} catch (err :SecurityError) {
inStr += "\n" + spaces + "SECURITY-BLOCKED";
}
}
}
}
return inStr;
}
}
}
|
Allow Flash to throw an exception if the input is invalid
|
Allow Flash to throw an exception if the input is invalid
git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@766 ed5b42cb-e716-0410-a449-f6a68f950b19
|
ActionScript
|
lgpl-2.1
|
threerings/nenya,threerings/nenya
|
32c4eeeb44055c8139df7060112123a3c919d52f
|
src/org/mangui/hls/HLSSettings.as
|
src/org/mangui/hls/HLSSettings.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 org.mangui.hls.constant.HLSSeekMode;
import org.mangui.hls.constant.HLSMaxLevelCappingMode;
public final class HLSSettings extends Object {
/**
* capLevelToStage
*
* Limit levels usable in auto-quality by the stage dimensions (width and height).
* true - level width and height (defined in m3u8 playlist) will be compared with the player width and height (stage.stageWidth and stage.stageHeight).
* Max level will be set depending on the maxLevelCappingMode option.
* false - levels will not be limited. All available levels could be used in auto-quality mode taking only bandwidth into consideration.
*
* Note: this setting is ignored in manual mode so all the levels could be selected manually.
*
* Default is false
*/
public static var capLevelToStage : Boolean = false;
/**
* maxLevelCappingMode
*
* Defines the max level capping mode to the one available in HLSMaxLevelCappingMode
* HLSMaxLevelCappingMode.DOWNSCALE - max capped level should be the one with the dimensions equal or greater than the stage dimensions (so the video will be downscaled)
* HLSMaxLevelCappingMode.UPSCALE - max capped level should be the one with the dimensions equal or lower than the stage dimensions (so the video will be upscaled)
*
* Default is HLSMaxLevelCappingMode.DOWNSCALE
*/
public static var maxLevelCappingMode : String = HLSMaxLevelCappingMode.DOWNSCALE;
// // // // // // /////////////////////////////////
//
// org.mangui.hls.stream.HLSNetStream
//
// // // // // // /////////////////////////////////
/**
* minBufferLength
*
* Defines minimum buffer length in seconds before playback can start, after seeking or buffer stalling.
*
* Default is -1 = auto
*/
public static var minBufferLength : Number = -1;
/**
* maxBufferLength
*
* Defines maximum buffer length in seconds.
* (0 means infinite buffering)
*
* Default is 120
*/
public static var maxBufferLength : Number = 120;
/**
* maxBackBufferLength
*
* Defines maximum back buffer length in seconds.
* (0 means infinite back buffering)
*
* Default is 30
*/
public static var maxBackBufferLength : Number = 30;
/**
* lowBufferLength
*
* Defines low buffer length in seconds.
* When crossing down this threshold, HLS will switch to buffering state.
*
* Default is 3
*/
public static var lowBufferLength : Number = 3;
/**
* fpsDroppedMonitoringPeriod
*
* dropped FPS Monitor Period in ms
* period at which nb dropped FPS will be checked
* Default is 5000 ms
*/
public static var fpsDroppedMonitoringPeriod : int = 5000;
/**
* fpsDroppedMonitoringThreshold
*
* dropped FPS Threshold
* every fpsDroppedMonitoringPeriod, dropped FPS will be compared to displayed FPS.
* if during that period, ratio of (dropped FPS/displayed FPS) is greater or equal
* than fpsDroppedMonitoringThreshold, HLSEvent.FPS_DROP event will be fired
* Default is 0.2 (20%)
*/
public static var fpsDroppedMonitoringThreshold : Number = 0.2;
/**
* capLevelonFPSDrop
*
* Limit levels usable in auto-quality when FPS drop is detected
* i.e. if frame drop is detected on level 5, auto level will be capped to level 4 a
* true - enabled
* false - disabled
*
* Note: this setting is ignored in manual mode so all the levels could be selected manually.
*
* Default is true
*/
public static var capLevelonFPSDrop : Boolean = true;
/**
* smoothAutoSwitchonFPSDrop
*
* force a smooth level switch Limit when FPS drop is detected in auto-quality
* i.e. if frame drop is detected on level 5, it will trigger an auto quality level switch
* to level 4 for next fragment
* true - enabled
* false - disabled
*
* Note: this setting is active only if capLevelonFPSDrop==true
*
* Default is true
*/
public static var smoothAutoSwitchonFPSDrop : Boolean = true;
/**
* seekMode
*
* Defines seek mode to one form available in HLSSeekMode class:
* HLSSeekMode.ACCURATE_SEEK - accurate seeking to exact requested position
* HLSSeekMode.KEYFRAME_SEEK - key-frame based seeking (seek to nearest key frame before requested seek position)
*
* Default is HLSSeekMode.KEYFRAME_SEEK
*/
public static var seekMode : String = HLSSeekMode.KEYFRAME_SEEK;
/**
* keyLoadMaxRetry
*
* Max nb of retries for Key Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*
* Default is 3
*/
public static var keyLoadMaxRetry : int = 3;
/**
* keyLoadMaxRetryTimeout
*
* Maximum key retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on key request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until keyLoadMaxRetryTimeout is reached.
*
* Default is 64000.
*/
public static var keyLoadMaxRetryTimeout : Number = 64000;
/**
* fragmentLoadMaxRetry
*
* Max number of retries for Fragment Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*
* Default is 3
*/
public static var fragmentLoadMaxRetry : int = 3;
/**
* fragmentLoadMaxRetryTimeout
*
* Maximum Fragment retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on fragment request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until fragmentLoadMaxRetryTimeout is reached.
*
* Default is 4000
*/
public static var fragmentLoadMaxRetryTimeout : Number = 4000
/**
* fragmentLoadSkipAfterMaxRetry
*
* control behaviour in case fragment load still fails after max retry timeout
* if set to true, fragment will be skipped and next one will be loaded.
* If set to false, an I/O Error will be raised.
*
* Default is true.
*/
public static var fragmentLoadSkipAfterMaxRetry : Boolean = true;
/**
* flushLiveURLCache
*
* If set to true, live playlist will be flushed from URL cache before reloading
* (this is to workaround some cache issues with some combination of Flash Player / IE version)
*
* Default is false
*/
public static var flushLiveURLCache : Boolean = false;
/**
* manifestLoadMaxRetry
*
* max nb of retries for Manifest Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*/
public static var manifestLoadMaxRetry : int = 3;
/**
* manifestLoadMaxRetryTimeout
*
* Maximum Manifest retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on fragment request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until manifestLoadMaxRetryTimeout is reached.
*
* Default is 64000
*/
public static var manifestLoadMaxRetryTimeout : Number = 64000;
/**
* startFromBitrate
*
* If greater than 0, specifies the preferred bitrate.
* If -1, and startFromLevel is not specified, automatic start level selection will be used.
* This parameter, if set, will take priority over startFromLevel.
*
* Default is -1
*/
public static var startFromBitrate : Number = -1;
/**
* startFromLevel
*
* start level :
* from 0 to 1 : indicates the "normalized" preferred level. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first.
* -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment)
* -2 : playback will start from the first level appearing in Manifest (not sorted by bitrate)
*
* Default is -1
*/
public static var startFromLevel : Number = -1;
/**
* seekFromLevel
*
* Seek level:
* from 0 to 1: indicates the "normalized" preferred bitrate. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first.
* -1 : automatic start level selection, keep previous level matching previous download bandwidth
*
* Default is -1
*/
public static var seekFromLevel : Number = -1;
/**
* useHardwareVideoDecoder
*
* Use hardware video decoder:
* it will set NetStream.useHardwareDecoder
* refer to http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetStream.html#useHardwareDecoder
*
* Default is true
*/
public static var useHardwareVideoDecoder : Boolean = true;
/**
* logInfo
*
* Defines whether INFO level log messages will will appear in the console
*
* Default is true
*/
public static var logInfo : Boolean = true;
/**
* logDebug
*
* Defines whether DEBUG level log messages will will appear in the console
*
* Default is false
*/
public static var logDebug : Boolean = false;
/**
* logDebug2
*
* Defines whether DEBUG2 level log messages will will appear in the console
*
* Default is false
*/
public static var logDebug2 : Boolean = false;
/**
* logWarn
*
* Defines whether WARN level log messages will will appear in the console
*
* Default is true
*/
public static var logWarn : Boolean = true;
/**
* logError
*
* Defines whether ERROR level log messages will will appear in the console
*
* Default is true
*/
public static var logError : Boolean = true;
}
}
|
/* 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 org.mangui.hls.constant.HLSSeekMode;
import org.mangui.hls.constant.HLSMaxLevelCappingMode;
public final class HLSSettings extends Object {
/**
* capLevelToStage
*
* Limit levels usable in auto-quality by the stage dimensions (width and height).
* true - level width and height (defined in m3u8 playlist) will be compared with the player width and height (stage.stageWidth and stage.stageHeight).
* Max level will be set depending on the maxLevelCappingMode option.
* false - levels will not be limited. All available levels could be used in auto-quality mode taking only bandwidth into consideration.
*
* Note: this setting is ignored in manual mode so all the levels could be selected manually.
*
* Default is false
*/
public static var capLevelToStage : Boolean = false;
/**
* maxLevelCappingMode
*
* Defines the max level capping mode to the one available in HLSMaxLevelCappingMode
* HLSMaxLevelCappingMode.DOWNSCALE - max capped level should be the one with the dimensions equal or greater than the stage dimensions (so the video will be downscaled)
* HLSMaxLevelCappingMode.UPSCALE - max capped level should be the one with the dimensions equal or lower than the stage dimensions (so the video will be upscaled)
*
* Default is HLSMaxLevelCappingMode.DOWNSCALE
*/
public static var maxLevelCappingMode : String = HLSMaxLevelCappingMode.DOWNSCALE;
// // // // // // /////////////////////////////////
//
// org.mangui.hls.stream.HLSNetStream
//
// // // // // // /////////////////////////////////
/**
* minBufferLength
*
* Defines minimum buffer length in seconds before playback can start, after seeking or buffer stalling.
*
* Default is -1 = auto
*/
public static var minBufferLength : Number = -1;
/**
* maxBufferLength
*
* Defines maximum buffer length in seconds.
* (0 means infinite buffering)
*
* Default is 120
*/
public static var maxBufferLength : Number = 120;
/**
* maxBackBufferLength
*
* Defines maximum back buffer length in seconds.
* (0 means infinite back buffering)
*
* Default is 30
*/
public static var maxBackBufferLength : Number = 30;
/**
* lowBufferLength
*
* Defines low buffer length in seconds.
* When crossing down this threshold, HLS will switch to buffering state.
*
* Default is 3
*/
public static var lowBufferLength : Number = 3;
/**
* fpsDroppedMonitoringPeriod
*
* dropped FPS Monitor Period in ms
* period at which nb dropped FPS will be checked
* Default is 5000 ms
*/
public static var fpsDroppedMonitoringPeriod : int = 5000;
/**
* fpsDroppedMonitoringThreshold
*
* dropped FPS Threshold
* every fpsDroppedMonitoringPeriod, dropped FPS will be compared to displayed FPS.
* if during that period, ratio of (dropped FPS/displayed FPS) is greater or equal
* than fpsDroppedMonitoringThreshold, HLSEvent.FPS_DROP event will be fired
* Default is 0.2 (20%)
*/
public static var fpsDroppedMonitoringThreshold : Number = 0.2;
/**
* capLevelonFPSDrop
*
* Limit levels usable in auto-quality when FPS drop is detected
* i.e. if frame drop is detected on level 5, auto level will be capped to level 4 a
* true - enabled
* false - disabled
*
* Note: this setting is ignored in manual mode so all the levels could be selected manually.
*
* Default is true
*/
public static var capLevelonFPSDrop : Boolean = true;
/**
* smoothAutoSwitchonFPSDrop
*
* force a smooth level switch Limit when FPS drop is detected in auto-quality
* i.e. if frame drop is detected on level 5, it will trigger an auto quality level switch
* to level 4 for next fragment
* true - enabled
* false - disabled
*
* Note: this setting is active only if capLevelonFPSDrop==true
*
* Default is true
*/
public static var smoothAutoSwitchonFPSDrop : Boolean = true;
/**
* seekMode
*
* Defines seek mode to one form available in HLSSeekMode class:
* HLSSeekMode.ACCURATE_SEEK - accurate seeking to exact requested position
* HLSSeekMode.KEYFRAME_SEEK - key-frame based seeking (seek to nearest key frame before requested seek position)
*
* Default is HLSSeekMode.KEYFRAME_SEEK
*/
public static var seekMode : String = HLSSeekMode.KEYFRAME_SEEK;
/**
* keyLoadMaxRetry
*
* Max nb of retries for Key Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*
* Default is 3
*/
public static var keyLoadMaxRetry : int = 3;
/**
* keyLoadMaxRetryTimeout
*
* Maximum key retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on key request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until keyLoadMaxRetryTimeout is reached.
*
* Default is 64000.
*/
public static var keyLoadMaxRetryTimeout : Number = 64000;
/**
* fragmentLoadMaxRetry
*
* Max number of retries for Fragment Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*
* Default is 3
*/
public static var fragmentLoadMaxRetry : int = 3;
/**
* fragmentLoadMaxRetryTimeout
*
* Maximum Fragment retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on fragment request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until fragmentLoadMaxRetryTimeout is reached.
*
* Default is 4000
*/
public static var fragmentLoadMaxRetryTimeout : Number = 4000
/**
* fragmentLoadSkipAfterMaxRetry
*
* control behaviour in case fragment load still fails after max retry timeout
* if set to true, fragment will be skipped and next one will be loaded.
* If set to false, an I/O Error will be raised.
*
* Default is true.
*/
public static var fragmentLoadSkipAfterMaxRetry : Boolean = true;
/**
* flushLiveURLCache
*
* If set to true, live playlist will be flushed from URL cache before reloading
* (this is to workaround some cache issues with some combination of Flash Player / IE version)
*
* Default is false
*/
public static var flushLiveURLCache : Boolean = false;
/**
* manifestLoadMaxRetry
*
* max nb of retries for Manifest Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*/
public static var manifestLoadMaxRetry : int = 3;
/**
* manifestLoadMaxRetryTimeout
*
* Maximum Manifest retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on fragment request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until manifestLoadMaxRetryTimeout is reached.
*
* Default is 64000
*/
public static var manifestLoadMaxRetryTimeout : Number = 64000;
/**
* startFromBitrate
*
* If greater than 0, specifies the preferred bitrate.
* If -1, and startFromLevel is not specified, automatic start level selection will be used.
* This parameter, if set, will take priority over startFromLevel.
*
* Default is -1
*/
public static var startFromBitrate : Number = -1;
/**
* startFromLevel
*
* start level :
* from 0 to 1 : indicates the "normalized" preferred level. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first.
* -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment)
* -2 : playback will start from the first level appearing in Manifest (not sorted by bitrate)
*
* Default is -1
*/
public static var startFromLevel : Number = -1;
/**
* seekFromLevel
*
* Seek level:
* from 0 to 1: indicates the "normalized" preferred bitrate. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first.
* -1 : automatic start level selection, keep previous level matching previous download bandwidth
*
* Default is -1
*/
public static var seekFromLevel : Number = -1;
/**
* useHardwareVideoDecoder
*
* Use hardware video decoder:
* it will set NetStream.useHardwareDecoder
* refer to http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetStream.html#useHardwareDecoder
*
* Default is true
*/
public static var useHardwareVideoDecoder : Boolean = true;
/**
* logInfo
*
* Defines whether INFO level log messages will will appear in the console
*
* Default is true
*/
public static var logInfo : Boolean = true;
/**
* logDebug
*
* Defines whether DEBUG level log messages will will appear in the console
*
* Default is false
*/
public static var logDebug : Boolean = false;
/**
* logDebug2
*
* Defines whether DEBUG2 level log messages will will appear in the console
*
* Default is false
*/
public static var logDebug2 : Boolean = false;
/**
* logWarn
*
* Defines whether WARN level log messages will will appear in the console
*
* Default is true
*/
public static var logWarn : Boolean = true;
/**
* logError
*
* Defines whether ERROR level log messages will will appear in the console
*
* Default is true
*/
public static var logError : Boolean = true;
/**
* recoverFromNonIDRStartFragment
*
* Load same sequence Fragment from previous Level and splice with
* current Fragment when that Fragment does not start with necessary
* AVC header.
*
* Default is true
*/
public static var recoverFromNonIDRStartFragment : Boolean = true;
}
}
|
Add HLSSettings.recoverFromNonIDRStartFragment
|
[HLSSettings] Add HLSSettings.recoverFromNonIDRStartFragment
|
ActionScript
|
mpl-2.0
|
codex-corp/flashls,codex-corp/flashls
|
e81537762a0a42a161685b7846c5b04b4389e282
|
src/battlecode/client/viewer/render/DrawHUDResearch.as
|
src/battlecode/client/viewer/render/DrawHUDResearch.as
|
package battlecode.client.viewer.render {
import battlecode.common.ResearchType;
import flash.utils.getTimer;
import mx.containers.Canvas;
import mx.controls.Image;
public class DrawHUDResearch extends Canvas {
private var image:Image;
private var type:String;
private var progress:Number;
public function DrawHUDResearch(type:String) {
width = 50;
height = 50;
horizontalScrollPolicy = "off";
verticalScrollPolicy = "off";
image = new Image();
image.source = ResearchType.getImageAsset(type);
image.width = 50;
image.height = 50;
image.x = 0;
image.y = 0;
progress = 0;
this.type = type;
addChild(image);
}
public function resize(size:Number):void {
width = Math.max(size, 50);
image.x = size - 50;
}
public function setProgress(val:Number):void {
progress = val;
draw();
}
public function getProgress():Number {
return progress;
}
public function draw():void {
if (progress == 0) {
visible = false;
return;
}
visible = true;
this.graphics.clear();
var color:uint = progress < 1.0 ? 0x00FFFF : 0x00FF00;
if (progress < 1.0 && progress > 0.5
&& type == ResearchType.NUKE && Math.floor(getTimer() / 400) % 2 == 0) {
color = 0xFFFF66;
}
// draw progress bar
var progressBarWidth:Number = width - image.width;
this.graphics.lineStyle();
this.graphics.beginFill(color, 0.8);
this.graphics.drawRect(0, (height / 2) - 2.5, progress * progressBarWidth, 5);
this.graphics.endFill();
this.graphics.beginFill(0x000000, 0.8);
this.graphics.drawRect(progress * progressBarWidth, (height / 2) - 2.5, (1 - progress) * progressBarWidth, 5);
this.graphics.endFill();
}
}
}
|
package battlecode.client.viewer.render {
import battlecode.common.ResearchType;
import flash.utils.getTimer;
import mx.containers.Canvas;
import mx.controls.Image;
public class DrawHUDResearch extends Canvas {
private var image:Image;
private var type:String;
private var progress:Number;
public function DrawHUDResearch(type:String) {
width = 50;
height = 50;
horizontalScrollPolicy = "off";
verticalScrollPolicy = "off";
toolTip = type;
image = new Image();
image.source = ResearchType.getImageAsset(type);
image.width = 50;
image.height = 50;
image.x = 0;
image.y = 0;
progress = 0;
this.type = type;
addChild(image);
}
public function resize(size:Number):void {
width = Math.max(size, 50);
image.x = size - 50;
}
public function setProgress(val:Number):void {
progress = val;
draw();
}
public function getProgress():Number {
return progress;
}
public function draw():void {
if (progress == 0) {
visible = false;
return;
}
visible = true;
this.graphics.clear();
var color:uint = progress < 1.0 ? 0x00FFFF : 0x00FF00;
if (progress < 1.0 && progress > 0.5
&& type == ResearchType.NUKE && Math.floor(getTimer() / 400) % 2 == 0) {
color = 0xFFFF66;
}
// draw progress bar
var progressBarWidth:Number = width - image.width;
this.graphics.lineStyle();
this.graphics.beginFill(color, 0.8);
this.graphics.drawRect(0, (height / 2) - 2.5, progress * progressBarWidth, 5);
this.graphics.endFill();
this.graphics.beginFill(0x000000, 0.8);
this.graphics.drawRect(progress * progressBarWidth, (height / 2) - 2.5, (1 - progress) * progressBarWidth, 5);
this.graphics.endFill();
}
}
}
|
add tooltips for research progress indicators
|
add tooltips for research progress indicators
|
ActionScript
|
mit
|
trun/battlecode-webclient
|
6a7dee98e7eac1448d84836b18f7c594c9c74b02
|
plugins/akamaiMediaAnalyticsPlugin/src/com/kaltura/kdpfl/plugin/akamaiMediaAnalyticsMediator.as
|
plugins/akamaiMediaAnalyticsPlugin/src/com/kaltura/kdpfl/plugin/akamaiMediaAnalyticsMediator.as
|
package com.kaltura.kdpfl.plugin
{
import com.akamai.playeranalytics.AnalyticsPluginLoader;
import com.kaltura.kdpfl.model.ConfigProxy;
import com.kaltura.kdpfl.model.MediaProxy;
import com.kaltura.kdpfl.model.type.NotificationType;
import com.kaltura.kdpfl.model.type.StreamerType;
import com.kaltura.types.KalturaMediaType;
import com.kaltura.vo.KalturaBaseEntry;
import com.kaltura.vo.KalturaFlavorAsset;
import com.kaltura.vo.KalturaMediaEntry;
import flash.system.Capabilities;
import org.puremvc.as3.interfaces.INotification;
import org.puremvc.as3.patterns.mediator.Mediator;
public class akamaiMediaAnalyticsMediator extends Mediator
{
public static const NAME:String = "akamaiMediaAnalyticsMediator";
private var _mediaProxy:MediaProxy;
public function akamaiMediaAnalyticsMediator(viewComponent:Object=null)
{
super(NAME, viewComponent);
}
override public function onRegister():void
{
_mediaProxy = facade.retrieveProxy(MediaProxy.NAME) as MediaProxy;
super.onRegister();
}
override public function listNotificationInterests():Array
{
return [NotificationType.MEDIA_READY, NotificationType.MEDIA_ELEMENT_READY, NotificationType.SWITCHING_CHANGE_COMPLETE];
}
override public function handleNotification(notification:INotification):void
{
switch (notification.getName())
{
case NotificationType.MEDIA_READY:
//populate analytics metadata
var configProxy:ConfigProxy = facade.retrieveProxy(ConfigProxy.NAME) as ConfigProxy;
var entry:KalturaBaseEntry = _mediaProxy.vo.entry;
AnalyticsPluginLoader.setData("title", entry.id);
AnalyticsPluginLoader.setData("category", entry.categories);
//since we don't have a partnerID field, we will send it as "subCategory"
AnalyticsPluginLoader.setData("subCategory", configProxy.vo.flashvars.partnerId);
//find content type
if (entry is KalturaMediaEntry)
{
var mediaEntry:KalturaMediaEntry = entry as KalturaMediaEntry;
AnalyticsPluginLoader.setData("contentLength", mediaEntry.duration);
var contentType:String;
switch (mediaEntry.mediaType)
{
case KalturaMediaType.VIDEO:
contentType = "video";
break;
case KalturaMediaType.AUDIO:
contentType = "audio";
break;
case KalturaMediaType.IMAGE:
contentType = "image";
break;
default:
contentType = "live";
}
AnalyticsPluginLoader.setData("contentType", contentType);
}
AnalyticsPluginLoader.setData("device", Capabilities.os );
AnalyticsPluginLoader.setData("playerId", configProxy.vo.flashvars.uiConfId);
break;
case NotificationType.SWITCHING_CHANGE_COMPLETE:
AnalyticsPluginLoader.setData("show", getFlavorIdByIndex(notification.getBody().newIndex));
break;
case NotificationType.MEDIA_ELEMENT_READY:
//find starting flavor ID
var flavorId:String;
if (_mediaProxy.vo.deliveryType == StreamerType.HTTP)
{
flavorId = _mediaProxy.vo.selectedFlavorId;
}
else if (_mediaProxy.vo.deliveryType == StreamerType.RTMP)
{
flavorId = getFlavorIdByIndex(_mediaProxy.startingIndex);
}
//since we don't have "flavor" field, we will send it as "show"
if (flavorId)
AnalyticsPluginLoader.setData("show", flavorId);
break;
}
}
/**
* returns the id of the flavor asset in the given index. null if index is invalid.
* @param index
* @return
*
*/
private function getFlavorIdByIndex(index:int):String
{
var flavorId:String;
if (index >= 0 &&
_mediaProxy.vo.kalturaMediaFlavorArray &&
index < _mediaProxy.vo.kalturaMediaFlavorArray.length) {
flavorId = (_mediaProxy.vo.kalturaMediaFlavorArray[index] as KalturaFlavorAsset).id;
}
return flavorId;
}
}
}
|
package com.kaltura.kdpfl.plugin
{
import com.akamai.playeranalytics.AnalyticsPluginLoader;
import com.kaltura.kdpfl.model.ConfigProxy;
import com.kaltura.kdpfl.model.MediaProxy;
import com.kaltura.kdpfl.model.type.NotificationType;
import com.kaltura.kdpfl.model.type.StreamerType;
import com.kaltura.types.KalturaMediaType;
import com.kaltura.vo.KalturaBaseEntry;
import com.kaltura.vo.KalturaFlavorAsset;
import com.kaltura.vo.KalturaMediaEntry;
import flash.system.Capabilities;
import org.puremvc.as3.interfaces.INotification;
import org.puremvc.as3.patterns.mediator.Mediator;
public class akamaiMediaAnalyticsMediator extends Mediator
{
public static const NAME:String = "akamaiMediaAnalyticsMediator";
private var _mediaProxy:MediaProxy;
public function akamaiMediaAnalyticsMediator(viewComponent:Object=null)
{
super(NAME, viewComponent);
}
override public function onRegister():void
{
_mediaProxy = facade.retrieveProxy(MediaProxy.NAME) as MediaProxy;
super.onRegister();
}
override public function listNotificationInterests():Array
{
return [NotificationType.MEDIA_READY, NotificationType.MEDIA_ELEMENT_READY, NotificationType.SWITCHING_CHANGE_COMPLETE];
}
override public function handleNotification(notification:INotification):void
{
switch (notification.getName())
{
case NotificationType.MEDIA_READY:
//populate analytics metadata
var configProxy:ConfigProxy = facade.retrieveProxy(ConfigProxy.NAME) as ConfigProxy;
var entry:KalturaBaseEntry = _mediaProxy.vo.entry;
AnalyticsPluginLoader.setData("title", entry.name);
AnalyticsPluginLoader.setData("entryId", entry.id);
AnalyticsPluginLoader.setData("category", entry.categories);
AnalyticsPluginLoader.setData("partnerId", configProxy.vo.flashvars.partnerId);
//find content type
if (entry is KalturaMediaEntry)
{
var mediaEntry:KalturaMediaEntry = entry as KalturaMediaEntry;
AnalyticsPluginLoader.setData("contentLength", mediaEntry.duration);
var contentType:String;
switch (mediaEntry.mediaType)
{
case KalturaMediaType.VIDEO:
contentType = "video";
break;
case KalturaMediaType.AUDIO:
contentType = "audio";
break;
case KalturaMediaType.IMAGE:
contentType = "image";
break;
default:
contentType = "live";
}
AnalyticsPluginLoader.setData("contentType", contentType);
}
AnalyticsPluginLoader.setData("device", Capabilities.os );
AnalyticsPluginLoader.setData("playerId", configProxy.vo.flashvars.uiConfId);
break;
case NotificationType.SWITCHING_CHANGE_COMPLETE:
AnalyticsPluginLoader.setData("flavorId", getFlavorIdByIndex(notification.getBody().newIndex));
break;
case NotificationType.MEDIA_ELEMENT_READY:
//find starting flavor ID
var flavorId:String;
if (_mediaProxy.vo.deliveryType == StreamerType.HTTP)
{
flavorId = _mediaProxy.vo.selectedFlavorId;
}
else if (_mediaProxy.vo.deliveryType == StreamerType.RTMP)
{
flavorId = getFlavorIdByIndex(_mediaProxy.startingIndex);
}
if (flavorId)
AnalyticsPluginLoader.setData("flavorId", flavorId);
break;
}
}
/**
* returns the id of the flavor asset in the given index. null if index is invalid.
* @param index
* @return
*
*/
private function getFlavorIdByIndex(index:int):String
{
var flavorId:String;
if (index >= 0 &&
_mediaProxy.vo.kalturaMediaFlavorArray &&
index < _mediaProxy.vo.kalturaMediaFlavorArray.length) {
flavorId = (_mediaProxy.vo.kalturaMediaFlavorArray[index] as KalturaFlavorAsset).id;
}
return flavorId;
}
}
}
|
fix names
|
qnd: fix names
git-svn-id: 3f608e5a9a704dd448217c0a64c508e7f145cfa1@87235 6b8eccd3-e8c5-4e7d-8186-e12b5326b719
|
ActionScript
|
agpl-3.0
|
shvyrev/kdp,shvyrev/kdp,kaltura/kdp,kaltura/kdp,kaltura/kdp,shvyrev/kdp
|
40053fa13ffd1f80d23a0c4a023c9087a88041a6
|
library/src/flexlib/styles/StyleDeclarationHelper.as
|
library/src/flexlib/styles/StyleDeclarationHelper.as
|
package flexlib.styles
{
import flash.utils.getQualifiedClassName;
import mx.core.FlexVersion;
public class StyleDeclarationHelper
{
/**
* Gets the style selector for the specified class.
* @see getStyleSelectorForClassName
*
* @param c The component class to get the style selector for
* @return style selector string for given class
*
*/
public static function getStyleSelectorForClass(c:Class):String
{
return getStyleSelectorForClassName(flash.utils.getQualifiedClassName(c));
}
/**
* Gets the style selector for the specified class name.
*
* Starting in Flex 4, component selectors passed to StyleManager.getStyleDeclaration and StyleManager.setStyleDeclaration
* must be fully qualified class names. In versions of Flex < 4, the class name itself was used.
*
* @see http://flexdevtips.blogspot.com/2009/03/setting-default-styles-for-custom.html
*
* @param fullyQualifiedName The fully qualified name of the class to get the selector for
* @return style selector string
*
*/
public static function getStyleSelectorForClassName(fullyQualifiedName:String):String
{
if (FlexVersion.compatibilityVersion >= FlexVersion.VERSION_4_0)
return fullyQualifiedName.replace("::", ".");
var classNameStart:int = fullyQualifiedName.lastIndexOf(":");
if(classNameStart != -1)
return fullyQualifiedName.substr(classNameStart + 1);
return fullyQualifiedName;
}
}
}
|
package flexlib.styles
{
import flash.utils.getQualifiedClassName;
import mx.core.FlexVersion;
public class StyleDeclarationHelper
{
/**
* Gets the style selector for the specified class.
* @see getStyleSelectorForClassName
*
* @param c The component class to get the style selector for
* @return style selector string for given class
*
*/
public static function getStyleSelectorForClass(c:Class):String
{
return getStyleSelectorForClassName(flash.utils.getQualifiedClassName(c));
}
/**
* Gets the style selector for the specified class name.
*
* Starting in Flex 4, component selectors passed to StyleManager.getStyleDeclaration and StyleManager.setStyleDeclaration
* must be fully qualified class names. In versions of Flex < 4, the class name itself was used.
*
* @see http://flexdevtips.blogspot.com/2009/03/setting-default-styles-for-custom.html
*
* @param fullyQualifiedName The fully qualified name of the class to get the selector for
* @return style selector string
*
*/
public static function getStyleSelectorForClassName(fullyQualifiedName:String):String
{
if (FlexVersion.compatibilityVersion >= FlexVersion.VERSION_4_0)
return fullyQualifiedName.replace("::", ".");
var classNameStart:int = fullyQualifiedName.lastIndexOf(":");
if(classNameStart != -1)
return fullyQualifiedName.substr(classNameStart + 1);
return fullyQualifiedName;
}
}
}
|
Fix asdoc generation broken
|
Fix asdoc generation broken
|
ActionScript
|
mit
|
Acidburn0zzz/flexlib
|
4c0337a4fcdc5da593e5eef7218d0f012bcee8fb
|
src/aerys/minko/render/shader/compiler/graph/ShaderGraph.as
|
src/aerys/minko/render/shader/compiler/graph/ShaderGraph.as
|
package aerys.minko.render.shader.compiler.graph
{
import aerys.minko.Minko;
import aerys.minko.render.geometry.stream.format.VertexComponent;
import aerys.minko.render.resource.Program3DResource;
import aerys.minko.render.resource.texture.ITextureResource;
import aerys.minko.render.shader.Signature;
import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode;
import aerys.minko.render.shader.compiler.graph.visitors.*;
import aerys.minko.render.shader.compiler.register.Components;
import aerys.minko.render.shader.compiler.sequence.AgalInstruction;
import aerys.minko.type.log.DebugLevel;
import flash.utils.ByteArray;
import flash.utils.Endian;
/**
* @private
* @author Romain Gilliotte
*
*/
public class ShaderGraph
{
private static const SPLITTER : SplitterVisitor = new SplitterVisitor();
private static const REMOVE_EXTRACT : RemoveExtractsVisitor = new RemoveExtractsVisitor();
private static const MERGER : MergeVisitor = new MergeVisitor();
private static const OVERWRITER_CLEANER : OverwriterCleanerVisitor = new OverwriterCleanerVisitor();
private static const RESOLVE_CONSTANT : ResolveConstantComputationVisitor = new ResolveConstantComputationVisitor();
private static const CONSTANT_PACKER : ConstantPackerVisitor = new ConstantPackerVisitor();
private static const CONSTANT_GROUPER : ConstantGrouperVisitor = new ConstantGrouperVisitor();
private static const RESOLVE_PARAMETRIZED : ResolveParametrizedComputationVisitor = new ResolveParametrizedComputationVisitor();
private static const REMOVE_USELESS : RemoveUselessComputation = new RemoveUselessComputation();
private static const COPY_INSERTER : CopyInserterVisitor = new CopyInserterVisitor();
private static const ALLOCATOR : AllocationVisitor = new AllocationVisitor();
private static const INTERPOLATE_FINDER : InterpolateFinder = new InterpolateFinder();
private static const WRITE_DOT : WriteDot = new WriteDot();
private static const MATRIX_TRANSFORMATION : MatrixTransformationGrouper = new MatrixTransformationGrouper();
private var _position : AbstractNode;
private var _positionComponents : uint;
private var _interpolates : Vector.<AbstractNode>;
private var _color : AbstractNode;
private var _colorComponents : uint;
private var _kills : Vector.<AbstractNode>;
private var _killComponents : Vector.<uint>;
private var _computableConstants : Object;
private var _isCompiled : Boolean;
private var _vertexSequence : Vector.<AgalInstruction>;
private var _fragmentSequence : Vector.<AgalInstruction>;
private var _bindings : Object;
private var _vertexComponents : Vector.<VertexComponent>;
private var _vertexIndices : Vector.<uint>;
private var _vsConstants : Vector.<Number>;
private var _fsConstants : Vector.<Number>;
private var _textures : Vector.<ITextureResource>;
public function get position() : AbstractNode
{
return _position;
}
public function set position(v : AbstractNode) : void
{
_position = v;
}
public function get interpolates() : Vector.<AbstractNode>
{
return _interpolates;
}
public function get color() : AbstractNode
{
return _color;
}
public function set color(v : AbstractNode) : void
{
_color = v;
}
public function get kills() : Vector.<AbstractNode>
{
return _kills;
}
public function get positionComponents() : uint
{
return _positionComponents;
}
public function set positionComponents(v : uint) : void
{
_positionComponents = v;
}
public function get colorComponents() : uint
{
return _colorComponents;
}
public function set colorComponents(v : uint) : void
{
_colorComponents = v;
}
public function get killComponents() : Vector.<uint>
{
return _killComponents;
}
public function get computableConstants() : Object
{
return _computableConstants;
}
public function ShaderGraph(position : AbstractNode,
color : AbstractNode,
kills : Vector.<AbstractNode>)
{
_isCompiled = false;
_position = position;
_positionComponents = Components.createContinuous(0, 0, 4, position.size);
_interpolates = new Vector.<AbstractNode>();
_color = color;
_colorComponents = Components.createContinuous(0, 0, 4, color.size);
_kills = kills;
_killComponents = new Vector.<uint>();
_computableConstants = new Object();
var numKills : uint = kills.length;
for (var killId : uint = 0; killId < numKills; ++killId)
_killComponents[killId] = Components.createContinuous(0, 0, 1, 1);
}
public function generateProgram(name : String, signature : Signature) : Program3DResource
{
if (!_isCompiled)
compile();
if (Minko.debugLevel & DebugLevel.SHADER_AGAL)
Minko.log(DebugLevel.SHADER_AGAL, generateAGAL(name));
var vsProgram : ByteArray = computeBinaryProgram(_vertexSequence, true);
var fsProgram : ByteArray = computeBinaryProgram(_fragmentSequence, false);
var program : Program3DResource = new Program3DResource(
name,
signature,
vsProgram,
fsProgram,
_vertexComponents,
_vertexIndices,
_vsConstants,
_fsConstants,
_textures,
_bindings
);
return program;
}
public function generateAGAL(name : String) : String
{
var instruction : AgalInstruction;
var shader : String = name + "\n";
if (!_isCompiled)
compile();
shader += "- vertex shader\n";
for each (instruction in _vertexSequence)
shader += instruction.getAgal(true);
shader += "- fragment shader\n";
for each (instruction in _fragmentSequence)
shader += instruction.getAgal(false);
return shader;
}
private function compile() : void
{
// execute consecutive visitors to optimize the shader graph.
// Warning: the order matters, do not swap lines.
MERGER .process(this); // merge duplicate nodes
REMOVE_EXTRACT .process(this); // remove all extract nodes
OVERWRITER_CLEANER .process(this); // remove nested overwriters
RESOLVE_CONSTANT .process(this); // resolve constant computation
CONSTANT_PACKER .process(this); // pack constants [0,0,0,1] => [0,1].xxxy
REMOVE_USELESS .process(this); // remove some useless operations (add 0, mul 0, mul 1...)
// RESOLVE_PARAMETRIZED .process(this); // replace computations that depend on parameters by evalexp parameters
// MATRIX_TRANSFORMATION .process(this); // replace ((vector * matrix1) * matrix2) by vector * (matrix1 * matrix2) to save registers on GPU
COPY_INSERTER .process(this); // ensure there are no operations between constants
SPLITTER .process(this); // clone nodes that are shared between vertex and fragment shader
CONSTANT_GROUPER .process(this); // group constants [0,1] & [0,2] => [0, 1, 2]
if (Minko.debugLevel & DebugLevel.SHADER_DOTTY)
{
WRITE_DOT.process(this);
Minko.log(DebugLevel.SHADER_DOTTY, WRITE_DOT.result);
WRITE_DOT.clear();
}
// generate final program
INTERPOLATE_FINDER .process(this); // find interpolate nodes. We may skip that in the future.
ALLOCATOR .process(this); // allocate memory and generate final code.
// retrieve program
_vertexSequence = ALLOCATOR.vertexSequence;
_fragmentSequence = ALLOCATOR.fragmentSequence;
_bindings = ALLOCATOR.parameterBindings;
_vertexComponents = ALLOCATOR.vertexComponents;
_vertexIndices = ALLOCATOR.vertexIndices;
_vsConstants = ALLOCATOR.vertexConstants;
_fsConstants = ALLOCATOR.fragmentConstants;
_textures = ALLOCATOR.textures;
ALLOCATOR.clear();
_isCompiled = true;
}
private function computeBinaryProgram(sequence : Vector.<AgalInstruction>,
isVertexShader : Boolean) : ByteArray
{
var program : ByteArray = new ByteArray();
program.endian = Endian.LITTLE_ENDIAN;
program.writeByte(0xa0); // tag version
program.writeUnsignedInt(1); // AGAL version, big endian, bit pattern will be 0x01000000
program.writeByte(0xa1); // tag program id
program.writeByte(isVertexShader ? 0 : 1); // vertex or fragment
for each (var instruction : AgalInstruction in sequence)
instruction.getBytecode(program);
return program;
}
}
}
|
package aerys.minko.render.shader.compiler.graph
{
import aerys.minko.Minko;
import aerys.minko.render.geometry.stream.format.VertexComponent;
import aerys.minko.render.resource.Program3DResource;
import aerys.minko.render.resource.texture.ITextureResource;
import aerys.minko.render.shader.Signature;
import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode;
import aerys.minko.render.shader.compiler.graph.visitors.*;
import aerys.minko.render.shader.compiler.register.Components;
import aerys.minko.render.shader.compiler.sequence.AgalInstruction;
import aerys.minko.type.log.DebugLevel;
import flash.utils.ByteArray;
import flash.utils.Endian;
/**
* @private
* @author Romain Gilliotte
*
*/
public class ShaderGraph
{
private static const SPLITTER : SplitterVisitor = new SplitterVisitor();
private static const REMOVE_EXTRACT : RemoveExtractsVisitor = new RemoveExtractsVisitor();
private static const MERGER : MergeVisitor = new MergeVisitor();
private static const OVERWRITER_CLEANER : OverwriterCleanerVisitor = new OverwriterCleanerVisitor();
private static const RESOLVE_CONSTANT : ResolveConstantComputationVisitor = new ResolveConstantComputationVisitor();
private static const CONSTANT_PACKER : ConstantPackerVisitor = new ConstantPackerVisitor();
private static const CONSTANT_GROUPER : ConstantGrouperVisitor = new ConstantGrouperVisitor();
private static const RESOLVE_PARAMETRIZED : ResolveParametrizedComputationVisitor = new ResolveParametrizedComputationVisitor();
private static const REMOVE_USELESS : RemoveUselessComputation = new RemoveUselessComputation();
private static const COPY_INSERTER : CopyInserterVisitor = new CopyInserterVisitor();
private static const ALLOCATOR : AllocationVisitor = new AllocationVisitor();
private static const INTERPOLATE_FINDER : InterpolateFinder = new InterpolateFinder();
private static const WRITE_DOT : WriteDot = new WriteDot();
private static const MATRIX_TRANSFORMATION : MatrixTransformationGrouper = new MatrixTransformationGrouper();
private var _position : AbstractNode;
private var _positionComponents : uint;
private var _interpolates : Vector.<AbstractNode>;
private var _color : AbstractNode;
private var _colorComponents : uint;
private var _kills : Vector.<AbstractNode>;
private var _killComponents : Vector.<uint>;
private var _computableConstants : Object;
private var _isCompiled : Boolean;
private var _vertexSequence : Vector.<AgalInstruction>;
private var _fragmentSequence : Vector.<AgalInstruction>;
private var _bindings : Object;
private var _vertexComponents : Vector.<VertexComponent>;
private var _vertexIndices : Vector.<uint>;
private var _vsConstants : Vector.<Number>;
private var _fsConstants : Vector.<Number>;
private var _textures : Vector.<ITextureResource>;
public function get position() : AbstractNode
{
return _position;
}
public function set position(v : AbstractNode) : void
{
_position = v;
}
public function get interpolates() : Vector.<AbstractNode>
{
return _interpolates;
}
public function get color() : AbstractNode
{
return _color;
}
public function set color(v : AbstractNode) : void
{
_color = v;
}
public function get kills() : Vector.<AbstractNode>
{
return _kills;
}
public function get positionComponents() : uint
{
return _positionComponents;
}
public function set positionComponents(v : uint) : void
{
_positionComponents = v;
}
public function get colorComponents() : uint
{
return _colorComponents;
}
public function set colorComponents(v : uint) : void
{
_colorComponents = v;
}
public function get killComponents() : Vector.<uint>
{
return _killComponents;
}
public function get computableConstants() : Object
{
return _computableConstants;
}
public function ShaderGraph(position : AbstractNode,
color : AbstractNode,
kills : Vector.<AbstractNode>)
{
_isCompiled = false;
_position = position;
_positionComponents = Components.createContinuous(0, 0, 4, position.size);
_interpolates = new Vector.<AbstractNode>();
_color = color;
_colorComponents = Components.createContinuous(0, 0, 4, color.size);
_kills = kills;
_killComponents = new Vector.<uint>();
_computableConstants = new Object();
var numKills : uint = kills.length;
for (var killId : uint = 0; killId < numKills; ++killId)
_killComponents[killId] = Components.createContinuous(0, 0, 1, 1);
}
public function generateProgram(name : String, signature : Signature) : Program3DResource
{
if (!_isCompiled)
compile();
if (Minko.debugLevel & DebugLevel.SHADER_AGAL)
Minko.log(DebugLevel.SHADER_AGAL, generateAGAL(name));
var vsProgram : ByteArray = computeBinaryProgram(_vertexSequence, true);
var fsProgram : ByteArray = computeBinaryProgram(_fragmentSequence, false);
var program : Program3DResource = new Program3DResource(
name,
signature,
vsProgram,
fsProgram,
_vertexComponents,
_vertexIndices,
_vsConstants,
_fsConstants,
_textures,
_bindings
);
return program;
}
public function generateAGAL(name : String) : String
{
var instruction : AgalInstruction;
var shader : String = name + "\n";
if (!_isCompiled)
compile();
shader += "- vertex shader\n";
for each (instruction in _vertexSequence)
shader += instruction.getAgal(true);
shader += "- fragment shader\n";
for each (instruction in _fragmentSequence)
shader += instruction.getAgal(false);
return shader;
}
private function compile() : void
{
// execute consecutive visitors to optimize the shader graph.
// Warning: the order matters, do not swap lines.
MERGER .process(this); // merge duplicate nodes
REMOVE_EXTRACT .process(this); // remove all extract nodes
OVERWRITER_CLEANER .process(this); // remove nested overwriters
RESOLVE_CONSTANT .process(this); // resolve constant computation
CONSTANT_PACKER .process(this); // pack constants [0,0,0,1] => [0,1].xxxy
// REMOVE_USELESS .process(this); // remove some useless operations (add 0, mul 0, mul 1...)
// RESOLVE_PARAMETRIZED .process(this); // replace computations that depend on parameters by evalexp parameters
// MATRIX_TRANSFORMATION .process(this); // replace ((vector * matrix1) * matrix2) by vector * (matrix1 * matrix2) to save registers on GPU
COPY_INSERTER .process(this); // ensure there are no operations between constants
SPLITTER .process(this); // clone nodes that are shared between vertex and fragment shader
CONSTANT_GROUPER .process(this); // group constants [0,1] & [0,2] => [0, 1, 2]
if (Minko.debugLevel & DebugLevel.SHADER_DOTTY)
{
WRITE_DOT.process(this);
Minko.log(DebugLevel.SHADER_DOTTY, WRITE_DOT.result);
WRITE_DOT.clear();
}
// generate final program
INTERPOLATE_FINDER .process(this); // find interpolate nodes. We may skip that in the future.
ALLOCATOR .process(this); // allocate memory and generate final code.
// retrieve program
_vertexSequence = ALLOCATOR.vertexSequence;
_fragmentSequence = ALLOCATOR.fragmentSequence;
_bindings = ALLOCATOR.parameterBindings;
_vertexComponents = ALLOCATOR.vertexComponents;
_vertexIndices = ALLOCATOR.vertexIndices;
_vsConstants = ALLOCATOR.vertexConstants;
_fsConstants = ALLOCATOR.fragmentConstants;
_textures = ALLOCATOR.textures;
ALLOCATOR.clear();
_isCompiled = true;
}
private function computeBinaryProgram(sequence : Vector.<AgalInstruction>,
isVertexShader : Boolean) : ByteArray
{
var program : ByteArray = new ByteArray();
program.endian = Endian.LITTLE_ENDIAN;
program.writeByte(0xa0); // tag version
program.writeUnsignedInt(1); // AGAL version, big endian, bit pattern will be 0x01000000
program.writeByte(0xa1); // tag program id
program.writeByte(isVertexShader ? 0 : 1); // vertex or fragment
for each (var instruction : AgalInstruction in sequence)
instruction.getBytecode(program);
return program;
}
}
}
|
disable RemoveUselessComputation shader graph visitor to fix multiple minor issues
|
disable RemoveUselessComputation shader graph visitor to fix multiple minor issues
|
ActionScript
|
mit
|
aerys/minko-as3
|
419b3eda2264f6c2064bb1fb3c86d3b6aeadcb99
|
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.messaging.messages.HTTPRequestMessage;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
import org.jivesoftware.xiff.auth.Anonymous;
import org.jivesoftware.xiff.auth.External;
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.IncomingDataEvent;
import org.jivesoftware.xiff.events.LoginEvent;
import org.jivesoftware.xiff.util.Callback;
public class XMPPBOSHConnection extends XMPPConnection
{
private static var saslMechanisms:Object = {
"PLAIN":Plain,
"ANONYMOUS":Anonymous,
"EXTERNAL":External
};
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 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 = new Timer(1, 1);
private var pollTimeoutTimer:Timer = new Timer(1, 1);
private var auth:SASLAuth;
private var authHandler:Function;
private var https:Boolean = false;
private var _port:Number = -1;
private var callbacks:Object = {};
public static var logger:Object = null;
private var lastPollTime:Date = null;
public override function connect(streamType:String=null):Boolean
{
if(logger)
logger.log("CONNECT()", "INFO");
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 static function registerSASLMechanism(name:String, authClass:Class):void
{
saslMechanisms[name] = authClass;
}
public static function disableSASLMechanism(name:String):void
{
saslMechanisms[name] = null;
}
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
{
super.disconnect();
pollTimer.stop();
pollTimer = null;
pollTimeoutTimer.stop();
pollTimeoutTimer = null;
}
public function processConnectionResponse(responseBody:XMLNode):void
{
var attributes:Object = responseBody.attributes;
sid = attributes.sid;
boshPollingInterval = attributes.polling * 1000;
wait = attributes.wait;
inactivity = attributes.inactivity * 1000;
if(inactivity - 2000 >= boshPollingInterval || (boshPollingInterval <= 1000 && boshPollingInterval > 0))
{
boshPollingInterval += 1000;
}
inactivity -= 1000;
var serverRequests:int = attributes.requests;
if (serverRequests)
maxConcurrentRequests = Math.min(serverRequests, maxConcurrentRequests);
active = true;
configureConnection(responseBody);
responseTimer.addEventListener(TimerEvent.TIMER_COMPLETE, processResponse);
trace(boshPollingInterval);
pollTimer.delay = boshPollingInterval;
pollTimer.addEventListener(TimerEvent.TIMER_COMPLETE, pollServer);
pollTimer.start();
pollTimeoutTimer.delay = inactivity;
pollTimeoutTimer.addEventListener(TimerEvent.TIMER_COMPLETE, function(evt:TimerEvent):void {
trace("Poll timed out, resuming");
pollServer(evt, true);
});
}
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;
case "failure":
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;
if(logger)
logger.log(rawXML, "INCOMING");
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 have no outstanding requests, then we're free to send a poll at the next opportunity
if(requestCount == 0 && !sendQueuedRequests())
resetPollTimer();
}
private function httpError(req:XMLNode, isPollResponse:Boolean, evt:FaultEvent):void
{
disconnect();
dispatchError("Unknown HTTP Error", evt.fault.rootCause.text, "", -1);
}
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);
if(logger)
logger.log(data, "OUTGOING");
request.send(data);
if(isPoll) {
lastPollTime = new Date();
pollTimeoutTimer.reset();
pollTimeoutTimer.start();
trace("Polling at: " + lastPollTime.getMinutes() + ":" + lastPollTime.getSeconds());
}
pollTimer.stop();
return true;
}
private function resetPollTimer():void
{
if(!pollTimer)
return;
pollTimeoutTimer.stop();
pollTimer.reset();
var timeSinceLastPoll:Number = 0;
if(lastPollTime)
timeSinceLastPoll = new Date().time - lastPollTime.time;
if(timeSinceLastPoll >= boshPollingInterval)
timeSinceLastPoll = 0;
pollTimer.delay = boshPollingInterval - timeSinceLastPoll;
pollTimer.start();
}
private function pollServer(evt:TimerEvent, force:Boolean=false):void
{
if(force)
trace("Forcing poll!");
//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() || requestCount > 0) && !force))
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()
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 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 {
dispatchError("Authentication Error", "", "", 401);
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());
authHandler = handleAuthentication;
sendXML(auth.request);
}
private function configureAuthMechanisms(mechanisms:XMLNode):SASLAuth
{
var authMechanism:SASLAuth;
var authClass:Class;
for each(var mechanism:XMLNode in mechanisms.childNodes)
{
authClass = saslMechanisms[mechanism.firstChild.nodeValue];
if(authClass)
break;
}
if (!authClass) {
dispatchError("SASL missing", "The server is not configured to support any available SASL mechanisms", "SASL", -1);
return null;
}
return new authClass(this);
}
public function handleBindResponse(packet:IQ):void
{
var bind:BindExtension = packet.getExtension("bind") as BindExtension;
var jid:UnescapedJID = bind.jid.unescaped;
myResource = jid.resource;
myUsername = jid.node;
domain = jid.domain;
establishSession();
}
private function bindConnection():void
{
var bindIQ:IQ = new IQ(null, "set");
var bindExt:BindExtension = new BindExtension();
if(resource)
bindExt.resource = resource;
bindIQ.addExtension(bindExt);
//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.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.Anonymous;
import org.jivesoftware.xiff.auth.External;
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.IncomingDataEvent;
import org.jivesoftware.xiff.events.LoginEvent;
import org.jivesoftware.xiff.util.Callback;
public class XMPPBOSHConnection extends XMPPConnection
{
private static var saslMechanisms:Object = {
"PLAIN":Plain,
"ANONYMOUS":Anonymous,
"EXTERNAL":External
};
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 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 = new Timer(1, 1);
private var pollTimeoutTimer:Timer = new Timer(1, 1);
private var auth:SASLAuth;
private var authHandler:Function;
private var https:Boolean = false;
private var _port:Number = -1;
private var callbacks:Object = {};
public static var logger:Object = null;
private var lastPollTime:Date = null;
public override function connect(streamType:String=null):Boolean
{
if(logger)
logger.log("CONNECT()", "INFO");
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 static function registerSASLMechanism(name:String, authClass:Class):void
{
saslMechanisms[name] = authClass;
}
public static function disableSASLMechanism(name:String):void
{
saslMechanisms[name] = null;
}
public function set secure(flag:Boolean):void
{
https = flag;
}
public function get secure():Boolean
{
return https;
}
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
{
super.disconnect();
pollTimer.stop();
pollTimer = null;
pollTimeoutTimer.stop();
pollTimeoutTimer = null;
}
public function processConnectionResponse(responseBody:XMLNode):void
{
var attributes:Object = responseBody.attributes;
sid = attributes.sid;
boshPollingInterval = attributes.polling * 1000;
wait = attributes.wait;
inactivity = attributes.inactivity * 1000;
if(inactivity - 2000 >= boshPollingInterval || (boshPollingInterval <= 1000 && boshPollingInterval > 0))
{
boshPollingInterval += 1000;
}
inactivity -= 1000;
var serverRequests:int = attributes.requests;
if (serverRequests)
maxConcurrentRequests = Math.min(serverRequests, maxConcurrentRequests);
active = true;
configureConnection(responseBody);
responseTimer.addEventListener(TimerEvent.TIMER_COMPLETE, processResponse);
trace(boshPollingInterval);
pollTimer.delay = boshPollingInterval;
pollTimer.addEventListener(TimerEvent.TIMER_COMPLETE, pollServer);
pollTimer.start();
pollTimeoutTimer.delay = inactivity;
pollTimeoutTimer.addEventListener(TimerEvent.TIMER_COMPLETE, function(evt:TimerEvent):void {
trace("Poll timed out, resuming");
pollServer(evt, true);
});
}
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;
case "failure":
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;
if(logger)
logger.log(rawXML, "INCOMING");
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 have no outstanding requests, then we're free to send a poll at the next opportunity
if(requestCount == 0 && !sendQueuedRequests())
resetPollTimer();
}
private function httpError(req:XMLNode, isPollResponse:Boolean, evt:FaultEvent):void
{
disconnect();
dispatchError("Unknown HTTP Error", evt.fault.rootCause.text, "", -1);
}
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);
if(logger)
logger.log(data, "OUTGOING");
request.send(data);
if(isPoll) {
lastPollTime = new Date();
pollTimeoutTimer.reset();
pollTimeoutTimer.start();
trace("Polling at: " + lastPollTime.getMinutes() + ":" + lastPollTime.getSeconds());
}
pollTimer.stop();
return true;
}
private function resetPollTimer():void
{
if(!pollTimer)
return;
pollTimeoutTimer.stop();
pollTimer.reset();
var timeSinceLastPoll:Number = 0;
if(lastPollTime)
timeSinceLastPoll = new Date().time - lastPollTime.time;
if(timeSinceLastPoll >= boshPollingInterval)
timeSinceLastPoll = 0;
pollTimer.delay = boshPollingInterval - timeSinceLastPoll;
pollTimer.start();
}
private function pollServer(evt:TimerEvent, force:Boolean=false):void
{
if(force)
trace("Forcing poll!");
//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() || requestCount > 0) && !force))
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()
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 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 {
dispatchError("Authentication Error", "", "", 401);
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());
authHandler = handleAuthentication;
sendXML(auth.request);
}
private function configureAuthMechanisms(mechanisms:XMLNode):SASLAuth
{
var authMechanism:SASLAuth;
var authClass:Class;
for each(var mechanism:XMLNode in mechanisms.childNodes)
{
authClass = saslMechanisms[mechanism.firstChild.nodeValue];
if(authClass)
break;
}
if (!authClass) {
dispatchError("SASL missing", "The server is not configured to support any available SASL mechanisms", "SASL", -1);
return null;
}
return new authClass(this);
}
public function handleBindResponse(packet:IQ):void
{
var bind:BindExtension = packet.getExtension("bind") as BindExtension;
var jid:UnescapedJID = bind.jid.unescaped;
myResource = jid.resource;
myUsername = jid.node;
domain = jid.domain;
establishSession();
}
private function bindConnection():void
{
var bindIQ:IQ = new IQ(null, "set");
var bindExt:BindExtension = new BindExtension();
if(resource)
bindExt.resource = resource;
bindIQ.addExtension(bindExt);
//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 {}
}
}
|
Add an accessor for whether or not we are using https. r=Armando
|
Add an accessor for whether or not we are using https. r=Armando
|
ActionScript
|
apache-2.0
|
igniterealtime/XIFF
|
9f6505358e051cf59606b80721a10ac37f4e9b5c
|
actionscript/src/com/freshplanet/ane/AirAACPlayer/AirAACPlayer.as
|
actionscript/src/com/freshplanet/ane/AirAACPlayer/AirAACPlayer.as
|
//////////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2012 Freshplanet (http://freshplanet.com | [email protected])
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//////////////////////////////////////////////////////////////////////////////////////
package com.freshplanet.ane.AirAACPlayer
{
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.StatusEvent;
import flash.external.ExtensionContext;
import flash.system.Capabilities;
public class AirAACPlayer extends EventDispatcher
{
// --------------------------------------------------------------------------------------//
// //
// PUBLIC API //
// //
// --------------------------------------------------------------------------------------//
public static const AAC_PLAYER_PREPARED:String = "AAC_PLAYER_PREPARED";
/** AirAACPlayer is supported on Android devices. */
public static function get isSupported():Boolean
{
var isAndroid:Boolean = (Capabilities.manufacturer.indexOf("Android") != -1)
return isAndroid;
}
public function AirAACPlayer()
{
if (!_instance)
{
_context = ExtensionContext.createExtensionContext(EXTENSION_ID, null);
if (!_context)
{
log("ERROR - Extension context is null. Please check if extension.xml is setup correctly.");
return;
}
_context.addEventListener(StatusEvent.STATUS, onStatus);
_instance = this;
}
else
{
throw Error("This is a singleton, use getInstance(), do not call the constructor directly.");
}
}
public static function getInstance():AirAACPlayer
{
return _instance ? _instance:new AirAACPlayer();
}
public var logEnabled:Boolean = true;
/**
* Load a music stream url
* @param url:String
*/
public function loadUrl(url:String):void
{
_context.call("loadUrl", url);
}
/**
* Start playing the stream.
* If the playback has been paused before, it will continue from this point.
* @param startTime:int the start time in milliseconds
*/
public function play(startTime:int=0):void
{
_context.call("play", startTime);
}
/**
* Pause the playback
*/
public function pause():void
{
_context.call("pause");
}
/**
* Stop the playback
*/
public function stop():void
{
_context.call("stop");
}
/**
* Close the stream and release.
* Note that loadUrl() has to be called again before replaying if close has been called.
*/
public function close():void
{
_context.call("close");
}
/**
* Length in milliseconds
*/
public function get length():int
{
return _context.call("getLength") as int;
}
/**
* Progress in milliseconds
*/
public function get progress():int
{
return _context.call("getProgress") as int;
}
// --------------------------------------------------------------------------------------//
// //
// PRIVATE API //
// //
// --------------------------------------------------------------------------------------//
private static const EXTENSION_ID:String = "com.freshplanet.AirAACPlayer";
private static var _instance:AirAACPlayer;
private var _context:ExtensionContext;
private function onStatus( event:StatusEvent ):void
{
if (event.code == "LOGGING") // Simple log message
{
log(event.level);
}
else if (event.code == AAC_PLAYER_PREPARED)
{
dispatchEvent(new Event(event.code));
}
}
private function log( message:String ):void
{
if (logEnabled) trace("[AirAACPlayer] " + message);
}
}
}
|
//////////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2012 Freshplanet (http://freshplanet.com | [email protected])
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//////////////////////////////////////////////////////////////////////////////////////
package com.freshplanet.ane.AirAACPlayer
{
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.StatusEvent;
import flash.external.ExtensionContext;
import flash.system.Capabilities;
public class AirAACPlayer extends EventDispatcher
{
// --------------------------------------------------------------------------------------//
// //
// PUBLIC API //
// //
// --------------------------------------------------------------------------------------//
public static const AAC_PLAYER_PREPARED:String = "AAC_PLAYER_PREPARED";
/** AirAACPlayer is supported on Android devices. */
public static function get isSupported():Boolean
{
var isAndroid:Boolean = (Capabilities.manufacturer.indexOf("Android") != -1)
return isAndroid;
}
public function AirAACPlayer()
{
_context = ExtensionContext.createExtensionContext(EXTENSION_ID, null);
if (!_context)
{
log("ERROR - Extension context is null. Please check if extension.xml is setup correctly.");
return;
}
_context.addEventListener(StatusEvent.STATUS, onStatus);
}
public var logEnabled:Boolean = true;
/**
* Load a music stream url
* @param url:String
*/
public function loadUrl(url:String):void
{
_context.call("loadUrl", url);
}
/**
* Start playing the stream.
* If the playback has been paused before, it will continue from this point.
* @param startTime:int the start time in milliseconds
*/
public function play(startTime:int=0):void
{
_context.call("play", startTime);
}
/**
* Pause the playback
*/
public function pause():void
{
_context.call("pause");
}
/**
* Stop the playback
*/
public function stop():void
{
_context.call("stop");
}
/**
* Close the stream and release.
* Note that loadUrl() has to be called again before replaying if close has been called.
*/
public function close():void
{
_context.call("close");
}
/**
* Length in milliseconds
*/
public function get length():int
{
return _context.call("getLength") as int;
}
/**
* Progress in milliseconds
*/
public function get progress():int
{
return _context.call("getProgress") as int;
}
// --------------------------------------------------------------------------------------//
// //
// PRIVATE API //
// //
// --------------------------------------------------------------------------------------//
private static const EXTENSION_ID:String = "com.freshplanet.AirAACPlayer";
private static var _instance:AirAACPlayer;
private var _context:ExtensionContext;
private function onStatus( event:StatusEvent ):void
{
if (event.code == "LOGGING") // Simple log message
{
log(event.level);
}
else if (event.code == AAC_PLAYER_PREPARED)
{
dispatchEvent(new Event(event.code));
}
}
private function log( message:String ):void
{
if (logEnabled) trace("[AirAACPlayer] " + message);
}
}
}
|
Convert ACC ane to instantiable from singleton
|
Convert ACC ane to instantiable from singleton
|
ActionScript
|
apache-2.0
|
freshplanet/ANE-AACPlayer,freshplanet/ANE-AACPlayer,freshplanet/ANE-AACPlayer
|
660090bd175a6acc4e2908f17088096a2f575c9f
|
sdk-remote/src/tests/liburbi-check.as
|
sdk-remote/src/tests/liburbi-check.as
|
m4_pattern_allow([^URBI_(PATH|SERVER)$]) -*- shell-script -*-
AS_INIT()dnl
URBI_PREPARE()
set -e
case $VERBOSE in
x) set -x;;
esac
# Avoid zombies and preserve debugging information.
cleanup ()
{
exit_status=$?
# In case we were caught by set -e, kill the children.
children_kill
children_harvest
children_report
children_sta=$(children_status remote)
# Don't clean before calling children_status...
test x$VERBOSE != x || children_clean
case $exit_status:$children_sta in
0:0) ;;
0:*) # Maybe a children exited for SKIP etc.
exit $children_sta;;
*:*) # If liburbi-check failed, there is a big problem.
error SOFTWARE "liburbi-check itself failed with $exit_status";;
esac
# rst_expect sets exit=false if it saw a failure.
$exit
}
for signal in 1 2 13 15; do
trap 'error $((128 + $signal)) \
"received signal $signal ($(kill -l $signal))"' $signal
done
trap cleanup 0
# Overriden to include the test name.
stderr ()
{
echo >&2 "$(basename $0): $me: $@"
echo >&2
}
# Sleep some time, but taking into account the fact that
# instrumentation slows down a lot.
my_sleep ()
{
if $INSTRUMENT; then
sleep $(($1 * 5))
else
sleep $1
fi
}
## -------------- ##
## Main program. ##
## -------------- ##
exec 3>&2
: ${abs_builddir='@abs_builddir@'}
check_dir abs_builddir liburbi-check
: ${abs_top_builddir='@abs_top_builddir@'}
check_dir abs_top_builddir config.status
: ${abs_top_srcdir='@abs_top_srcdir@'}
check_dir abs_top_srcdir configure.ac
# Make it absolute.
chk=$(absolute "$1")
if test ! -f "$chk.cc"; then
fatal "no such file: $chk.cc"
fi
period=32
# ./../../../tests/2.x/andexp-pipeexp.chk -> 2.x
medir=$(basename $(dirname "$chk"))
# ./../../../tests/2.x/andexp-pipeexp.chk -> 2.x/andexp-pipeexp
me=$medir/$(basename "$chk" ".cc")
# ./../../../tests/2.x/andexp-pipeexp.chk -> andexp-pipeexp
meraw=$(basename $me) # MERAW!
srcdir=$(absolute $srcdir)
export srcdir
# Move to a private dir.
rm -rf $me.dir
mkdir -p $me.dir
cd $me.dir
# Help debugging
set | rst_pre "$me variables"
# $URBI_SERVER.
#
# If this SDK-Remote is part of the Kernel package, then we should not
# use an installed urbi-console, but rather the one which is part of
# this package.
if test -x $abs_top_builddir/../src/urbi-console; then
URBI_SERVER=$abs_top_builddir/../src/urbi-console
export URBI_PATH=$abs_top_srcdir/../share
else
# Leaves trailing files, so run it in subdir.
find_urbi_server
fi
# compute expected output
sed -n -e 's@//= @@p' $chk.cc >output.exp
touch error.exp
echo 0 >status.exp
#start it
valgrind=$(instrument "server.val")
cmd="$valgrind $URBI_SERVER --port 0 -w server.port --period $period"
echo "$cmd" >server.cmd
$cmd >server.out 2>server.err &
children_register server
my_sleep 2
#start the test
valgrind=$(instrument "remote.val")
cmd="$valgrind ../../tests localhost $(cat server.port) $meraw"
echo "$cmd" >remote.cmd
$cmd >remote.out.raw 2>remote.err &
children_register remote
# Let some time to run the tests.
children_wait 10
# Ignore the "client errors".
sed -e '/^E client error/d' remote.out.raw >remote.out.eff
# Compare expected output with actual output.
rst_expect output remote.out
rst_pre "Error output" remote.err
# Display Valgrind report.
rst_pre "Valgrind" remote.val
# Exit with success: liburbi-check made its job. But now clean (on
# trap 0) will check $exit to see if there is a failure in the tests
# and adjust the exit status accordingly.
exit 0
|
m4_pattern_allow([^URBI_(PATH|SERVER)$]) -*- shell-script -*-
AS_INIT()dnl
URBI_PREPARE()
set -e
case $VERBOSE in
x) set -x;;
esac
# Avoid zombies and preserve debugging information.
cleanup ()
{
exit_status=$?
# In case we were caught by set -e, kill the children.
children_kill
children_harvest
children_report
children_sta=$(children_status remote)
# Don't clean before calling children_status...
test x$VERBOSE != x || children_clean
case $exit_status:$children_sta in
0:0) ;;
0:*) # Maybe a children exited for SKIP etc.
exit $children_sta;;
*:*) # If liburbi-check failed, there is a big problem.
error SOFTWARE "liburbi-check itself failed with $exit_status";;
esac
# rst_expect sets exit=false if it saw a failure.
$exit
}
for signal in 1 2 13 15; do
trap 'error $((128 + $signal)) \
"received signal $signal ($(kill -l $signal))"' $signal
done
trap cleanup 0
# Overriden to include the test name.
stderr ()
{
echo >&2 "$(basename $0): $me: $@"
echo >&2
}
# Sleep some time, but taking into account the fact that
# instrumentation slows down a lot.
my_sleep ()
{
if $INSTRUMENT; then
sleep $(($1 * 5))
else
sleep $1
fi
}
## -------------- ##
## Main program. ##
## -------------- ##
exec 3>&2
: ${abs_builddir='@abs_builddir@'}
check_dir abs_builddir liburbi-check
: ${abs_top_builddir='@abs_top_builddir@'}
check_dir abs_top_builddir config.status
: ${abs_top_srcdir='@abs_top_srcdir@'}
check_dir abs_top_srcdir configure.ac
# Make it absolute.
chk=$(absolute "$1")
if test ! -f "$chk.cc"; then
fatal "no such file: $chk.cc"
fi
period=32
# ./../../../tests/2.x/andexp-pipeexp.chk -> 2.x
medir=$(basename $(dirname "$chk"))
# ./../../../tests/2.x/andexp-pipeexp.chk -> 2.x/andexp-pipeexp
me=$medir/$(basename "$chk" ".cc")
# ./../../../tests/2.x/andexp-pipeexp.chk -> andexp-pipeexp
meraw=$(basename $me) # MERAW!
srcdir=$(absolute $srcdir)
export srcdir
# Move to a private dir.
rm -rf $me.dir
mkdir -p $me.dir
cd $me.dir
# Help debugging
set | rst_pre "$me variables"
# $URBI_SERVER.
#
# If this SDK-Remote is part of the Kernel package, then we should not
# use an installed urbi-console, but rather the one which is part of
# this package.
if test -d $abs_top_srcdir/../../src/kernel; then
stderr "This SDK-Remote is part of a kernel package."
URBI_SERVER=$abs_top_builddir/../src/urbi-console
export URBI_PATH=$abs_top_srcdir/../share
else
stderr "This SDK-Remote is standalone."
fi
# Leaves trailing files, so run it in subdir.
find_urbi_server
# Compute expected output.
sed -n -e 's@//= @@p' $chk.cc >output.exp
touch error.exp
echo 0 >status.exp
# Start it.
valgrind=$(instrument "server.val")
cmd="$valgrind $URBI_SERVER --port 0 -w server.port --period $period"
echo "$cmd" >server.cmd
$cmd >server.out 2>server.err &
children_register server
my_sleep 2
# Start the test.
valgrind=$(instrument "remote.val")
cmd="$valgrind ../../tests localhost $(cat server.port) $meraw"
echo "$cmd" >remote.cmd
$cmd >remote.out.raw 2>remote.err &
children_register remote
# Let some time to run the tests.
children_wait 10
# Ignore the "client errors".
sed -e '/^E client error/d' remote.out.raw >remote.out.eff
# Compare expected output with actual output.
rst_expect output remote.out
rst_pre "Error output" remote.err
# Display Valgrind report.
rst_pre "Valgrind" remote.val
# Exit with success: liburbi-check made its job. But now clean (on
# trap 0) will check $exit to see if there is a failure in the tests
# and adjust the exit status accordingly.
exit 0
|
Fix embed SDK-Remote test suite.
|
Fix embed SDK-Remote test suite.
* src/tests/liburbi-check.as: Also define URBI_PATH.
Be sure to issue messages when embedded urbi-console is not found.
|
ActionScript
|
bsd-3-clause
|
urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi
|
eaeb4135a26fa38646b49e00bf0bb5be843e049a
|
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.display.Sprite;
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.raw",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();
var inputBytesAvailable:int = audioPcmAsset.bytesAvailable;
assertTrue("embedded bytesAvailable", inputBytesAvailable > 0);
assertNotNull(container.stage);
var rootSprite:Sprite = new Sprite();
container.addChild(rootSprite);
// ffmpeg -loglevel debug -f f32be -acodec pcm_f32be -ar 16000 -ac 1 -channel_layout mono -i audio.raw -b:a 32000 -f mp4 -acodec aac audio.mp4
/*
ffmpeg version 3.0 Copyright (c) 2000-2016 the FFmpeg developers
built with Apple LLVM version 7.0.2 (clang-700.1.81)
configuration: --prefix=/usr/local/Cellar/ffmpeg/3.0 --enable-shared --enable-pthreads --enable-gpl --enable-version3 --enable-hardcoded-tables --enable-avresample --cc=clang --host-cflags= --host-ldflags= --enable-opencl --enable-libx264 --enable-libmp3lame --enable-libxvid --enable-libfontconfig --enable-libfreetype --enable-libtheora --enable-libvorbis --enable-librtmp --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libass --enable-libspeex --enable-libfdk-aac --enable-libopus --enable-libx265 --enable-libdcadec --enable-nonfree --enable-vda
libavutil 55. 17.103 / 55. 17.103
libavcodec 57. 24.102 / 57. 24.102
libavformat 57. 25.100 / 57. 25.100
libavdevice 57. 0.101 / 57. 0.101
libavfilter 6. 31.100 / 6. 31.100
libavresample 3. 0. 0 / 3. 0. 0
libswscale 4. 0.100 / 4. 0.100
libswresample 2. 0.101 / 2. 0.101
libpostproc 54. 0.100 / 54. 0.100
Splitting the commandline.
Reading option '-loglevel' ... matched as option 'loglevel' (set logging level) with argument 'debug'.
Reading option '-f' ... matched as option 'f' (force format) with argument 'f32be'.
Reading option '-acodec' ... matched as option 'acodec' (force audio codec ('copy' to copy stream)) with argument 'pcm_f32be'.
Reading option '-ar' ... matched as option 'ar' (set audio sampling rate (in Hz)) with argument '16000'.
Reading option '-ac' ... matched as option 'ac' (set number of audio channels) with argument '1'.
Reading option '-channel_layout' ... matched as option 'channel_layout' (set channel layout) with argument 'mono'.
Reading option '-i' ... matched as input file with argument 'audio.raw'.
Reading option '-b:a' ... matched as option 'b' (video bitrate (please use -b:v)) with argument '32000'.
Reading option '-f' ... matched as option 'f' (force format) with argument 'mp4'.
Reading option '-acodec' ... matched as option 'acodec' (force audio codec ('copy' to copy stream)) with argument 'aac'.
Reading option 'audio.mp4' ... matched as output file.
Finished splitting the commandline.
Parsing a group of options: global .
Applying option loglevel (set logging level) with argument debug.
Successfully parsed a group of options.
Parsing a group of options: input file audio.raw.
Applying option f (force format) with argument f32be.
Applying option acodec (force audio codec ('copy' to copy stream)) with argument pcm_f32be.
Applying option ar (set audio sampling rate (in Hz)) with argument 16000.
Applying option ac (set number of audio channels) with argument 1.
Applying option channel_layout (set channel layout) with argument mono.
Successfully parsed a group of options.
Opening an input file: audio.raw.
[file @ 0x7f97b9d17360] Setting default whitelist 'file'
[f32be @ 0x7f97ba00fa00] Before avformat_find_stream_info() pos: 0 bytes read:32768 seeks:0
[f32be @ 0x7f97ba00fa00] All info found
[f32be @ 0x7f97ba00fa00] Estimating duration from bitrate, this may be inaccurate
[f32be @ 0x7f97ba00fa00] After avformat_find_stream_info() pos: 204800 bytes read:229376 seeks:0 frames:50
Input #0, f32be, from 'audio.raw':
Duration: 00:00:04.32, bitrate: 512 kb/s
Stream #0:0, 50, 1/16000: Audio: pcm_f32be, 16000 Hz, mono, flt, 512 kb/s
Successfully opened the file.
Parsing a group of options: output file audio.mp4.
Applying option b:a (video bitrate (please use -b:v)) with argument 32000.
Applying option f (force format) with argument mp4.
Applying option acodec (force audio codec ('copy' to copy stream)) with argument aac.
Successfully parsed a group of options.
Opening an output file: audio.mp4.
[file @ 0x7f97b9d17dc0] Setting default whitelist 'file'
Successfully opened the file.
detected 8 logical cores
[graph 0 input from stream 0:0 @ 0x7f97b9d1b640] Setting 'time_base' to value '1/16000'
[graph 0 input from stream 0:0 @ 0x7f97b9d1b640] Setting 'sample_rate' to value '16000'
[graph 0 input from stream 0:0 @ 0x7f97b9d1b640] Setting 'sample_fmt' to value 'flt'
[graph 0 input from stream 0:0 @ 0x7f97b9d1b640] Setting 'channel_layout' to value '0x4'
[graph 0 input from stream 0:0 @ 0x7f97b9d1b640] tb:1/16000 samplefmt:flt samplerate:16000 chlayout:0x4
[audio format for output stream 0:0 @ 0x7f97b9d1bb20] Setting 'sample_fmts' to value 'fltp'
[audio format for output stream 0:0 @ 0x7f97b9d1bb20] Setting 'sample_rates' to value '96000|88200|64000|48000|44100|32000|24000|22050|16000|12000|11025|8000|7350'
[audio format for output stream 0:0 @ 0x7f97b9d1bb20] auto-inserting filter 'auto-inserted resampler 0' between the filter 'Parsed_anull_0' and the filter 'audio format for output stream 0:0'
[AVFilterGraph @ 0x7f97b9d16f40] query_formats: 4 queried, 6 merged, 3 already done, 0 delayed
[auto-inserted resampler 0 @ 0x7f97b9d1c260] [SWR @ 0x7f97ba05fc00] Using fltp internally between filters
[auto-inserted resampler 0 @ 0x7f97b9d1c260] ch:1 chl:mono fmt:flt r:16000Hz -> ch:1 chl:mono fmt:fltp r:16000Hz
Output #0, mp4, to 'audio.mp4':
Metadata:
encoder : Lavf57.25.100
Stream #0:0, 0, 1/16000: Audio: aac (LC) ([64][0][0][0] / 0x0040), 16000 Hz, mono, fltp, 32 kb/s
Metadata:
encoder : Lavc57.24.102 aac
Stream mapping:
Stream #0:0 -> #0:0 (pcm_f32be (native) -> aac (native))
Press [q] to stop, [?] for help
cur_dts is invalid (this is harmless if it occurs once at the start per stream)
Last message repeated 1 times
[output stream 0:0 @ 0x7f97b9d1b960] EOF on sink link output stream 0:0:default.
No more output streams to write to, finishing.
[aac @ 0x7f97ba057000] Trying to remove 512 more samples than there are in the queue
size= 18kB time=00:00:04.35 bitrate= 34.7kbits/s speed=64.1x
video:0kB audio:17kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 5.758254%
Input file #0 (audio.raw):
Input stream #0:0 (audio): 68 packets read (276480 bytes); 68 frames decoded (69120 samples);
Total: 68 packets (276480 bytes) demuxed
Output file #0 (audio.mp4):
Output stream #0:0 (audio): 68 frames encoded (69120 samples); 69 packets muxed (17870 bytes);
Total: 69 packets (17870 bytes) muxed
68 frames successfully decoded, 0 decoding errors
[AVIOContext @ 0x7f97b9d1b260] Statistics: 30 seeks, 92 writeouts
[aac @ 0x7f97ba057000] Qavg: 107.061
[AVIOContext @ 0x7f97b9d17400] Statistics: 276480 bytes read, 0 seeks
*/
// audio.raw = 276480 bytes, audio.mp4 = 18899 bytes
const inputCodec:String = 'pcm_f32be';
const inputSampleRate:int = 16000;
const inputChannels:int = 1;
const outputCodec:String = 'aac';
const outputFormat:String = 'mp4';
const outputSampleRate:int = 16000;
const outputChannels:int = 1;
const outputBitRate:int = 32000;
var encoder:Encoder = new Encoder(rootSprite);
encoder.init(inputCodec, inputSampleRate, inputChannels, outputCodec, outputFormat, outputSampleRate, outputChannels, outputBitRate);
encoder.load(audioPcmAsset);
var output:ByteArray = encoder.flush();
var outputBytesAvailable:int = output.bytesAvailable;
var encoderOutputFormat:String = encoder.getOutputFormat();
var encoderOutputSampleRate:int = encoder.getOutputSampleRate();
var encoderOutputLength:int = encoder.getOutputLength();
var compressionRatio:Number = Math.round(1000 * outputBytesAvailable / inputBytesAvailable) / 10;
trace("+++++++++++++++++++++++++++++++++++++++++++++++++++++++");
trace("inputBytesAvailable = " + inputBytesAvailable);
trace("outputBytesAvailable = " + outputBytesAvailable);
trace("expected output filesize 6.8% of input, actual filesize:" + compressionRatio + "%");
trace("encoder.getOutputFormat() = " + encoderOutputFormat);
trace("encoder.getOutputSampleRate() = " + encoderOutputSampleRate);
trace("encoder.getOutputLength() = " + encoderOutputLength);
trace("+++++++++++++++++++++++++++++++++++++++++++++++++++++++");
sleep(1000);
assertTrue("outputFormat set to " + outputFormat, encoderOutputFormat == outputFormat);
assertTrue("outputSampleRate set to " + outputSampleRate, encoderOutputSampleRate == outputSampleRate);
assertTrue("encoder.getOutputLength() > 0", encoderOutputLength > 0);
assertTrue("outputBytesAvailable > 0", outputBytesAvailable > 0);
assertTrue("outputBytesAvailable = encoder.getOutputLength()", outputBytesAvailable == encoderOutputLength);
assertTrue("outputBytesAvailable * 10 < inputBytesAvailable", outputBytesAvailable * 10 < inputBytesAvailable);
assertTrue("outputBytesAvailable * 20 > inputBytesAvailable", outputBytesAvailable * 20 > inputBytesAvailable);
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;
}
}
}
}
}
|
package {
import com.marstonstudio.crossusermedia.encoder.Encoder;
import flash.display.DisplayObjectContainer;
import flash.display.Sprite;
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;
// ffmpeg -loglevel debug -f f32be -acodec pcm_f32be -ar 16000 -ac 1 -channel_layout mono -i audio.raw -b:a 32000 -f mp4 -acodec aac audio.mp4
// audio.raw = 276480 bytes, audio.mp4 = 18899 bytes
/*
ffmpeg version 3.0 Copyright (c) 2000-2016 the FFmpeg developers
built with Apple LLVM version 7.0.2 (clang-700.1.81)
configuration: --prefix=/usr/local/Cellar/ffmpeg/3.0 --enable-shared --enable-pthreads --enable-gpl --enable-version3 --enable-hardcoded-tables --enable-avresample --cc=clang --host-cflags= --host-ldflags= --enable-opencl --enable-libx264 --enable-libmp3lame --enable-libxvid --enable-libfontconfig --enable-libfreetype --enable-libtheora --enable-libvorbis --enable-librtmp --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libass --enable-libspeex --enable-libfdk-aac --enable-libopus --enable-libx265 --enable-libdcadec --enable-nonfree --enable-vda
libavutil 55. 17.103 / 55. 17.103
libavcodec 57. 24.102 / 57. 24.102
libavformat 57. 25.100 / 57. 25.100
libavdevice 57. 0.101 / 57. 0.101
libavfilter 6. 31.100 / 6. 31.100
libavresample 3. 0. 0 / 3. 0. 0
libswscale 4. 0.100 / 4. 0.100
libswresample 2. 0.101 / 2. 0.101
libpostproc 54. 0.100 / 54. 0.100
Splitting the commandline.
Reading option '-loglevel' ... matched as option 'loglevel' (set logging level) with argument 'debug'.
Reading option '-f' ... matched as option 'f' (force format) with argument 'f32be'.
Reading option '-acodec' ... matched as option 'acodec' (force audio codec ('copy' to copy stream)) with argument 'pcm_f32be'.
Reading option '-ar' ... matched as option 'ar' (set audio sampling rate (in Hz)) with argument '16000'.
Reading option '-ac' ... matched as option 'ac' (set number of audio channels) with argument '1'.
Reading option '-channel_layout' ... matched as option 'channel_layout' (set channel layout) with argument 'mono'.
Reading option '-i' ... matched as input file with argument 'audio.raw'.
Reading option '-b:a' ... matched as option 'b' (video bitrate (please use -b:v)) with argument '32000'.
Reading option '-f' ... matched as option 'f' (force format) with argument 'mp4'.
Reading option '-acodec' ... matched as option 'acodec' (force audio codec ('copy' to copy stream)) with argument 'aac'.
Reading option 'audio.mp4' ... matched as output file.
Finished splitting the commandline.
Parsing a group of options: global .
Applying option loglevel (set logging level) with argument debug.
Successfully parsed a group of options.
Parsing a group of options: input file audio.raw.
Applying option f (force format) with argument f32be.
Applying option acodec (force audio codec ('copy' to copy stream)) with argument pcm_f32be.
Applying option ar (set audio sampling rate (in Hz)) with argument 16000.
Applying option ac (set number of audio channels) with argument 1.
Applying option channel_layout (set channel layout) with argument mono.
Successfully parsed a group of options.
Opening an input file: audio.raw.
[file @ 0x7f97b9d17360] Setting default whitelist 'file'
[f32be @ 0x7f97ba00fa00] Before avformat_find_stream_info() pos: 0 bytes read:32768 seeks:0
[f32be @ 0x7f97ba00fa00] All info found
[f32be @ 0x7f97ba00fa00] Estimating duration from bitrate, this may be inaccurate
[f32be @ 0x7f97ba00fa00] After avformat_find_stream_info() pos: 204800 bytes read:229376 seeks:0 frames:50
Input #0, f32be, from 'audio.raw':
Duration: 00:00:04.32, bitrate: 512 kb/s
Stream #0:0, 50, 1/16000: Audio: pcm_f32be, 16000 Hz, mono, flt, 512 kb/s
Successfully opened the file.
Parsing a group of options: output file audio.mp4.
Applying option b:a (video bitrate (please use -b:v)) with argument 32000.
Applying option f (force format) with argument mp4.
Applying option acodec (force audio codec ('copy' to copy stream)) with argument aac.
Successfully parsed a group of options.
Opening an output file: audio.mp4.
[file @ 0x7f97b9d17dc0] Setting default whitelist 'file'
Successfully opened the file.
detected 8 logical cores
[graph 0 input from stream 0:0 @ 0x7f97b9d1b640] Setting 'time_base' to value '1/16000'
[graph 0 input from stream 0:0 @ 0x7f97b9d1b640] Setting 'sample_rate' to value '16000'
[graph 0 input from stream 0:0 @ 0x7f97b9d1b640] Setting 'sample_fmt' to value 'flt'
[graph 0 input from stream 0:0 @ 0x7f97b9d1b640] Setting 'channel_layout' to value '0x4'
[graph 0 input from stream 0:0 @ 0x7f97b9d1b640] tb:1/16000 samplefmt:flt samplerate:16000 chlayout:0x4
[audio format for output stream 0:0 @ 0x7f97b9d1bb20] Setting 'sample_fmts' to value 'fltp'
[audio format for output stream 0:0 @ 0x7f97b9d1bb20] Setting 'sample_rates' to value '96000|88200|64000|48000|44100|32000|24000|22050|16000|12000|11025|8000|7350'
[audio format for output stream 0:0 @ 0x7f97b9d1bb20] auto-inserting filter 'auto-inserted resampler 0' between the filter 'Parsed_anull_0' and the filter 'audio format for output stream 0:0'
[AVFilterGraph @ 0x7f97b9d16f40] query_formats: 4 queried, 6 merged, 3 already done, 0 delayed
[auto-inserted resampler 0 @ 0x7f97b9d1c260] [SWR @ 0x7f97ba05fc00] Using fltp internally between filters
[auto-inserted resampler 0 @ 0x7f97b9d1c260] ch:1 chl:mono fmt:flt r:16000Hz -> ch:1 chl:mono fmt:fltp r:16000Hz
Output #0, mp4, to 'audio.mp4':
Metadata:
encoder : Lavf57.25.100
Stream #0:0, 0, 1/16000: Audio: aac (LC) ([64][0][0][0] / 0x0040), 16000 Hz, mono, fltp, 32 kb/s
Metadata:
encoder : Lavc57.24.102 aac
Stream mapping:
Stream #0:0 -> #0:0 (pcm_f32be (native) -> aac (native))
Press [q] to stop, [?] for help
cur_dts is invalid (this is harmless if it occurs once at the start per stream)
Last message repeated 1 times
[output stream 0:0 @ 0x7f97b9d1b960] EOF on sink link output stream 0:0:default.
No more output streams to write to, finishing.
[aac @ 0x7f97ba057000] Trying to remove 512 more samples than there are in the queue
size= 18kB time=00:00:04.35 bitrate= 34.7kbits/s speed=64.1x
video:0kB audio:17kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 5.758254%
Input file #0 (audio.raw):
Input stream #0:0 (audio): 68 packets read (276480 bytes); 68 frames decoded (69120 samples);
Total: 68 packets (276480 bytes) demuxed
Output file #0 (audio.mp4):
Output stream #0:0 (audio): 68 frames encoded (69120 samples); 69 packets muxed (17870 bytes);
Total: 69 packets (17870 bytes) muxed
68 frames successfully decoded, 0 decoding errors
[AVIOContext @ 0x7f97b9d1b260] Statistics: 30 seeks, 92 writeouts
[aac @ 0x7f97ba057000] Qavg: 107.061
[AVIOContext @ 0x7f97b9d17400] Statistics: 276480 bytes read, 0 seeks
*/
public class TestApp {
public function TestApp() {}
[Embed(source="../resources/audio.raw",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();
var inputBytesAvailable:int = audioPcmAsset.bytesAvailable;
assertTrue("embedded bytesAvailable", inputBytesAvailable > 0);
assertNotNull(container.stage);
var rootSprite:Sprite = new Sprite();
container.addChild(rootSprite);
const inputCodec:String = 'pcm_f32be';
const inputSampleRate:int = 16000;
const inputChannels:int = 1;
const outputCodec:String = 'aac';
const outputFormat:String = 'mp4';
const outputSampleRate:int = 16000;
const outputChannels:int = 1;
const outputBitRate:int = 32000;
var encoder:Encoder = new Encoder(rootSprite);
encoder.init(inputCodec, inputSampleRate, inputChannels, outputCodec, outputFormat, outputSampleRate, outputChannels, outputBitRate);
encoder.load(audioPcmAsset);
var output:ByteArray = encoder.flush();
var outputBytesAvailable:int = output.bytesAvailable;
var encoderOutputFormat:String = encoder.getOutputFormat();
var encoderOutputSampleRate:int = encoder.getOutputSampleRate();
var encoderOutputLength:int = encoder.getOutputLength();
var compressionRatio:Number = Math.round(1000 * outputBytesAvailable / inputBytesAvailable) / 10;
trace("+++++++++++++++++++++++++++++++++++++++++++++++++++++++");
trace("inputBytesAvailable = " + inputBytesAvailable);
trace("outputBytesAvailable = " + outputBytesAvailable);
trace("expected output filesize 6.8% of input, actual filesize:" + compressionRatio + "%");
trace("encoder.getOutputFormat() = " + encoderOutputFormat);
trace("encoder.getOutputSampleRate() = " + encoderOutputSampleRate);
trace("encoder.getOutputLength() = " + encoderOutputLength);
trace("+++++++++++++++++++++++++++++++++++++++++++++++++++++++");
sleep(1000);
assertTrue("outputFormat set to " + outputFormat, encoderOutputFormat == outputFormat);
assertTrue("outputSampleRate set to " + outputSampleRate, encoderOutputSampleRate == outputSampleRate);
assertTrue("encoder.getOutputLength() > 0", encoderOutputLength > 0);
assertTrue("outputBytesAvailable > 0", outputBytesAvailable > 0);
assertTrue("outputBytesAvailable = encoder.getOutputLength()", outputBytesAvailable == encoderOutputLength);
assertTrue("outputBytesAvailable * 10 < inputBytesAvailable", outputBytesAvailable * 10 < inputBytesAvailable);
assertTrue("outputBytesAvailable * 20 > inputBytesAvailable", outputBytesAvailable * 20 > inputBytesAvailable);
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;
}
}
}
}
}
|
clean up test
|
clean up test
|
ActionScript
|
mit
|
marstonstudio/crossUserMedia,marstonstudio/crossUserMedia,marstonstudio/crossUserMedia,marstonstudio/crossUserMedia,marstonstudio/crossUserMedia
|
2db51fe5a466f50b2bd5caa09987902b8f2f4356
|
Arguments/src/ValueObjects/AGORAParameters.as
|
Arguments/src/ValueObjects/AGORAParameters.as
|
package ValueObjects
{
public class AGORAParameters
{
public static var reference:AGORAParameters;
public var listMapsURL:String;
public var myMapsURL:String;
public var loginURL:String;
public var registrationURL:String;
public var mapRemoveURL:String;
public var insertURL:String;
public var loadMapURL:String;
public var gridWidth:int;
public var version:String;
//prompts
public var MAP_LOADING_FAILED:String;
public var STATEMENT_TOGGLE_FAILED:String;
public var NETWORK_ERROR:String;
public var IF:String = "If";
public var THEN:String = "then";
public var OR:String = "or";
public var AND:String = "and";
//constants
public var MOD_PON:String = "Modus Ponens";
public var MOD_TOL:String = "Modus Tollens";
public var COND_SYLL:String = "Conditional Syllogism";
public var DIS_SYLL:String = "Disjunctive Syllogism";
public var NOT_ALL_SYLL:String = "Not-All Syllogism";
public var CONST_DILEM:String = "Constructive Dilemma";
public var IF_THEN:String = "If-then";
public var IMPLIES:String = "Implies";
public var WHENEVER:String = "Whenever";
public var ONLY_IF:String = "Only if";
public var ONLY_IF_OR:String = "OnlyIfOR";
public var ONLY_IF_AND:String = "OnlyIfAnd";
public var PROVIDED_THAT:String = "Provided that";
public var SUFFICIENT_CONDITION:String = "Sufficient condition";
public var NECESSARY_CONDITION:String = "Necessary Condition";
public const DB_IF_THEN:String = "ifthen";
public const DB_IMPLIES:String = "implies";
public const DB_WHENEVER:String = "whenever";
public const DB_ONLY_IF:String = "onlyif";
public const DB_PROVIDED_THAT:String = "providedthat";
public const DB_SUFFICIENT:String = "sufficient";
public const DB_NECESSARY:String = "necessary";
public const MPIfThen:String = "MPifthen";
public const MPimplies:String = "MPimplies";
public const MPwhenever:String = "MPwhenever";
public const MPonlyif:String = "MPonlyif";
public const MPprovidedthat:String = "MPprovidedthat";
public const MPsufficient:String = "MPsufficient";
public const MPnecessary:String = "MPnecessary";
public const dbMP:String = "MP";
public const MTifthen:String = "MTifthen";
public const MTimplies:String = "MTimplies";
public const MTwhenever:String = "MTwhenever";
public const MTonlyif:String = "MTonlyif";
public const MTonlyiffor:String = "MTonlyiffor";
public const MTprovidedthat:String = "MTprovidedthat";
public const MTsufficient:String = "MTsufficient";
public const MTnecessary:String = "MTnecessary";
public const dbMT:String = "MT";
public const DisjSyl:String = "DisjSyl";
public const dbDisjSyl:String = "DisjSyl";
public const NotAllSyll:String = "NotAllSyl";
public const dbNotAllSyll:String = "NotAllSyl";
public const EQiff:String = "EQiff";
public const EQnecsuf:String = "EQnecsuf";
public const EQ:String = "EQ";
public const CSifthen:String = "CSifthen";
public const CSimplies:String = "CSimplies";
public const dbCS:String = "CS";
public const CDaltclaim:String = "CDaltclaim";
public const CDpropclaim:String = "CDpropclaim";
public const dbCD:String = "CD";
public const Unset:String = "Unset";
public function AGORAParameters()
{
listMapsURL = "http://agora.gatech.edu/dev/list_maps.php";
myMapsURL = "http://agora.gatech.edu/dev/my_maps.php";
loginURL = "http://agora.gatech.edu/dev/login.php";
registrationURL = "http://agora.gatech.edu/dev/register.php";
mapRemoveURL = "http://agora.gatech.edu/dev/remove_map.php";
insertURL = "http://agora.gatech.edu/dev/insert.php";
loadMapURL = "http://agora.gatech.edu/dev/load_map.php";
MAP_LOADING_FAILED = "Error occured when loading map";
STATEMENT_TOGGLE_FAILED = "Error occurred when trying to toggle the type of statement";
NETWORK_ERROR = "Unable to reach server. Please check your Internet connection...";
gridWidth = 25;
version = "11.8.30";
reference = this;
}
public static function getInstance():AGORAParameters{
if(!reference){
reference = new AGORAParameters;
}
return reference;
}
}
}
|
package ValueObjects
{
public class AGORAParameters
{
public static var reference:AGORAParameters;
public var listMapsURL:String;
public var myMapsURL:String;
public var loginURL:String;
public var registrationURL:String;
public var mapRemoveURL:String;
public var insertURL:String;
public var loadMapURL:String;
public var gridWidth:int;
public var version:String;
//prompts
public var MAP_LOADING_FAILED:String;
public var STATEMENT_TOGGLE_FAILED:String;
public var NETWORK_ERROR:String;
public var IF:String = "If";
public var THEN:String = "then";
public var OR:String = "or";
public var AND:String = "and";
//constants
public var MOD_PON:String = "Modus Ponens";
public var MOD_TOL:String = "Modus Tollens";
public var COND_SYLL:String = "Conditional Syllogism";
public var DIS_SYLL:String = "Disjunctive Syllogism";
public var NOT_ALL_SYLL:String = "Not-All Syllogism";
public var CONST_DILEM:String = "Constructive Dilemma";
public var IF_THEN:String = "If-then";
public var IMPLIES:String = "Implies";
public var WHENEVER:String = "Whenever";
public var ONLY_IF:String = "Only if";
public var ONLY_IF_OR:String = "OnlyIfOR";
public var ONLY_IF_AND:String = "OnlyIfAnd";
public var PROVIDED_THAT:String = "Provided that";
public var SUFFICIENT_CONDITION:String = "Sufficient condition";
public var NECESSARY_CONDITION:String = "Necessary Condition";
public const DB_IF_THEN:String = "ifthen";
public const DB_IMPLIES:String = "implies";
public const DB_WHENEVER:String = "whenever";
public const DB_ONLY_IF:String = "onlyif";
public const DB_PROVIDED_THAT:String = "providedthat";
public const DB_SUFFICIENT:String = "sufficient";
public const DB_NECESSARY:String = "necessary";
public const MPIfThen:String = "MPifthen";
public const MPimplies:String = "MPimplies";
public const MPwhenever:String = "MPwhenever";
public const MPonlyif:String = "MPonlyif";
public const MPprovidedthat:String = "MPprovidedthat";
public const MPsufficient:String = "MPsufficient";
public const MPnecessary:String = "MPnecessary";
public const dbMP:String = "MP";
public const MTifthen:String = "MTifthen";
public const MTimplies:String = "MTimplies";
public const MTwhenever:String = "MTwhenever";
public const MTonlyif:String = "MTonlyif";
public const MTonlyiffor:String = "MTonlyiffor";
public const MTprovidedthat:String = "MTprovidedthat";
public const MTsufficient:String = "MTsufficient";
public const MTnecessary:String = "MTnecessary";
public const dbMT:String = "MT";
public const DisjSyl:String = "DisjSyl";
public const dbDisjSyl:String = "DisjSyl";
public const NotAllSyll:String = "NotAllSyl";
public const dbNotAllSyll:String = "NotAllSyl";
public const EQiff:String = "EQiff";
public const EQnecsuf:String = "EQnecsuf";
public const EQ:String = "EQ";
public const CSifthen:String = "CSifthen";
public const CSimplies:String = "CSimplies";
public const dbCS:String = "CS";
public const CDaltclaim:String = "CDaltclaim";
public const CDpropclaim:String = "CDpropclaim";
public const dbCD:String = "CD";
public const Unset:String = "Unset";
public function AGORAParameters()
{
listMapsURL = "http://agora.gatech.edu/dev/list_maps.php";
myMapsURL = "http://agora.gatech.edu/dev/my_maps.php";
loginURL = "http://agora.gatech.edu/dev/login.php";
registrationURL = "http://agora.gatech.edu/dev/register.php";
mapRemoveURL = "http://agora.gatech.edu/dev/remove_map.php";
insertURL = "http://agora.gatech.edu/dev/insert.php";
loadMapURL = "http://agora.gatech.edu/dev/load_map.php";
MAP_LOADING_FAILED = "Error occured when loading map";
STATEMENT_TOGGLE_FAILED = "Error occurred when trying to toggle the type of statement";
NETWORK_ERROR = "Unable to reach server. Please check your Internet connection...";
gridWidth = 25;
version = "11.8.30";
reference = this;
}
public static function getInstance():AGORAParameters{
if(!reference){
reference = new AGORAParameters;
}
return reference;
}
}
}
|
Remove unnecessary duplicate spaces to clean up code
|
Remove unnecessary duplicate spaces to clean up code
|
ActionScript
|
agpl-3.0
|
mbjornas3/AGORA,MichaelHoffmann/AGORA,mbjornas3/AGORA,MichaelHoffmann/AGORA,MichaelHoffmann/AGORA
|
a143acdb7d67cdbca9245d92243e8d7a824a11f4
|
src/com/axis/httpclient/HTTPClient.as
|
src/com/axis/httpclient/HTTPClient.as
|
package com.axis.httpclient {
import com.axis.ClientEvent;
import com.axis.NetStreamClient;
import com.axis.ErrorManager;
import com.axis.IClient;
import com.axis.Logger;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.NetStatusEvent;
import flash.media.Video;
import flash.net.NetConnection;
import flash.net.NetStream;
public class HTTPClient extends NetStreamClient implements IClient {
private var urlParsed:Object;
private var nc:NetConnection;
public function HTTPClient(urlParsed:Object) {
this.urlParsed = urlParsed;
}
public function start(options:Object):Boolean {
Logger.log('HTTPClient: playing:', urlParsed.full);
nc = new NetConnection();
nc.connect(null);
nc.addEventListener(NetStatusEvent.NET_STATUS, onConnectionStatus);
this.ns = new NetStream(nc);
this.setupNetStream();
this.ns.play(urlParsed.full);
return true;
}
public function stop():Boolean {
this.ns.dispose();
this.nc.close();
this.currentState = 'stopped';
return true;
}
public function seek(position:Number):Boolean {
this.ns.seek(position);
return true;
}
public function pause():Boolean {
if (this.currentState !== 'playing') {
ErrorManager.dispatchError(800);
return false;
}
this.ns.pause();
return true;
}
public function resume():Boolean {
if (this.currentState !== 'paused') {
ErrorManager.dispatchError(801);
return false;
}
this.ns.resume();
return true;
}
public function setFrameByFrame(frameByFrame:Boolean):Boolean {
return false;
}
public function playFrames(timestamp:Number):void {}
public function setBuffer(seconds:Number):Boolean {
this.ns.bufferTime = seconds;
this.ns.pause();
this.ns.resume();
return true;
}
private function onConnectionStatus(event:NetStatusEvent):void {
if ('NetConnection.Connect.Closed' === event.info.code) {
this.currentState = 'stopped';
dispatchEvent(new ClientEvent(ClientEvent.STOPPED));
this.ns.dispose();
}
}
}
}
|
package com.axis.httpclient {
import com.axis.ClientEvent;
import com.axis.NetStreamClient;
import com.axis.ErrorManager;
import com.axis.IClient;
import com.axis.Logger;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.NetStatusEvent;
import flash.media.Video;
import flash.net.NetConnection;
import flash.net.NetStream;
public class HTTPClient extends NetStreamClient implements IClient {
private var urlParsed:Object;
private var nc:NetConnection;
public function HTTPClient(urlParsed:Object) {
this.urlParsed = urlParsed;
}
public function start(options:Object):Boolean {
Logger.log('HTTPClient: playing:', urlParsed.full);
nc = new NetConnection();
nc.connect(null);
nc.addEventListener(NetStatusEvent.NET_STATUS, onConnectionStatus);
this.ns = new NetStream(nc);
this.setupNetStream();
this.ns.play(urlParsed.full);
return true;
}
public function stop():Boolean {
this.ns.dispose();
this.nc.close();
this.currentState = 'stopped';
dispatchEvent(new ClientEvent(ClientEvent.STOPPED));
return true;
}
public function seek(position:Number):Boolean {
this.ns.seek(position);
return true;
}
public function pause():Boolean {
if (this.currentState !== 'playing') {
ErrorManager.dispatchError(800);
return false;
}
this.ns.pause();
return true;
}
public function resume():Boolean {
if (this.currentState !== 'paused') {
ErrorManager.dispatchError(801);
return false;
}
this.ns.resume();
return true;
}
public function setFrameByFrame(frameByFrame:Boolean):Boolean {
return false;
}
public function playFrames(timestamp:Number):void {}
public function setBuffer(seconds:Number):Boolean {
this.ns.bufferTime = seconds;
this.ns.pause();
this.ns.resume();
return true;
}
private function onConnectionStatus(event:NetStatusEvent):void {
if ('NetConnection.Connect.Closed' === event.info.code && this.currentState !== 'stopped') {
this.currentState = 'stopped';
dispatchEvent(new ClientEvent(ClientEvent.STOPPED));
this.ns.dispose();
}
}
}
}
|
Fix STOPPED event not triggered in a timely fashion
|
Fix STOPPED event not triggered in a timely fashion
The stopped event from the http client was not triggered immediately on
clean up but after the connection was closed. If a call to streamStatus
would be made between clean up and connection closed event it would
throw an exception.
|
ActionScript
|
bsd-3-clause
|
AxisCommunications/locomote-video-player,gaetancollaud/locomote-video-player
|
8b08cb868a739a59071db619066b479eaad64275
|
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 org.mangui.hls.playlist.DataUri;
import org.mangui.hls.playlist.AltAudioTrack;
import org.mangui.hls.playlist.Manifest;
import org.mangui.hls.constant.HLSPlayStates;
import org.mangui.hls.constant.HLSTypes;
import org.mangui.hls.event.HLSEvent;
import org.mangui.hls.event.HLSError;
import org.mangui.hls.model.Level;
import org.mangui.hls.model.Fragment;
import org.mangui.hls.HLS;
import org.mangui.hls.HLSSettings;
import flash.events.*;
import flash.net.*;
import flash.utils.*;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
/** Loader for hls manifests. **/
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 _reload_playlists_timer : uint;
/** current level **/
private var _current_level : int;
/** reference to manifest being loaded **/
private var _manifest_loading : Manifest;
/** is this loader closed **/
private var _closed : Boolean = false;
/* playlist retry timeout */
private var _retry_timeout : Number;
private var _retry_count : int;
/* alt audio tracks */
private var _alt_audio_tracks : Vector.<AltAudioTrack>;
/** 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>();
_urlloader = new URLLoader();
_urlloader.addEventListener(Event.COMPLETE, _loaderHandler);
_urlloader.addEventListener(IOErrorEvent.IO_ERROR, _errorHandler);
_urlloader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, _errorHandler);
};
public function dispose() : void {
_close();
_urlloader.removeEventListener(Event.COMPLETE, _loaderHandler);
_urlloader.removeEventListener(IOErrorEvent.IO_ERROR, _errorHandler);
_urlloader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, _errorHandler);
_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 || _retry_count < HLSSettings.manifestLoadMaxRetry)) {
CONFIG::LOGGING {
Log.warn("I/O Error while trying to load Playlist, retry in " + _retry_timeout + " ms");
}
_timeoutID = setTimeout(_loadActiveLevelPlaylist, _retry_timeout);
/* exponential increase of retry timeout, capped to manifestLoadMaxRetryTimeout */
_retry_timeout = Math.min(HLSSettings.manifestLoadMaxRetryTimeout, 2 * _retry_timeout);
_retry_count++;
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 _alt_audio_tracks;
}
/** Load the manifest file. **/
public function load(url : String) : void {
_close();
_closed = false;
_url = url;
_levels = new Vector.<Level>();
_canStart = false;
_reload_playlists_timer = getTimer();
_retry_timeout = 1000;
_retry_count = 0;
_alt_audio_tracks = null;
_hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_LOADING, url));
if (DataUri.isDataUri(url)) {
CONFIG::LOGGING {
Log.debug("Identified main manifest <" + url + "> as a data URI.");
}
var data : String = new DataUri(url).extractData();
_parseManifest(data || "");
} else {
_urlloader.load(new URLRequest(url));
}
};
/** Manifest loaded; check and parse it **/
private function _loaderHandler(event : Event) : void {
// successful loading, reset retry counter
_retry_timeout = 1000;
_retry_count = 0;
var loader : URLLoader = URLLoader(event.target);
_parseManifest(String(loader.data));
};
/** parse a playlist **/
private function _parseLevelPlaylist(string : String, url : String, level : int) : 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;
var timeout : Number = Math.max(100, _reload_playlists_timer + 1000 * _levels[level].averageduration - 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));
}
}
_hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_LOADED, level));
_manifest_loading = 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);
_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");
}
_current_level = 0;
_parseLevelPlaylist(string, _url, 0);
} 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(_hls, string, _url);
// retrieve start level from helper function
_current_level = _hls.startlevel;
_hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_PARSED, _levels));
_loadActiveLevelPlaylist();
if (string.indexOf(Manifest.ALTERNATE_AUDIO) > 0) {
CONFIG::LOGGING {
Log.debug("alternate audio level found");
}
// parse alternate audio tracks
_alt_audio_tracks = Manifest.extractAltAudioTracks(string, _url);
CONFIG::LOGGING {
if (_alt_audio_tracks.length > 0) {
Log.debug(_alt_audio_tracks.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;
}
_reload_playlists_timer = getTimer();
// load active M3U8 playlist only
_manifest_loading = new Manifest();
_hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_LOADING, _current_level));
_manifest_loading.loadPlaylist(_levels[_current_level].url, _parseLevelPlaylist, _errorHandler, _current_level, _type, HLSSettings.flushLiveURLCache);
};
/** When level switch occurs, assess the need of (re)loading new level playlist **/
private function _levelSwitchHandler(event : HLSEvent) : void {
if (_current_level != event.level) {
_current_level = event.level;
CONFIG::LOGGING {
Log.debug("switch to level " + _current_level);
}
if (_type == HLSTypes.LIVE || _levels[_current_level].fragments.length == 0) {
_closed = false;
CONFIG::LOGGING {
Log.debug("(re)load Playlist");
}
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 (_manifest_loading) {
_manifest_loading.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 org.mangui.hls.playlist.DataUri;
import org.mangui.hls.playlist.AltAudioTrack;
import org.mangui.hls.playlist.Manifest;
import org.mangui.hls.constant.HLSPlayStates;
import org.mangui.hls.constant.HLSTypes;
import org.mangui.hls.event.HLSEvent;
import org.mangui.hls.event.HLSError;
import org.mangui.hls.model.Level;
import org.mangui.hls.model.Fragment;
import org.mangui.hls.HLS;
import org.mangui.hls.HLSSettings;
import flash.events.*;
import flash.net.*;
import flash.utils.*;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
/** Loader for hls manifests. **/
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 _reload_playlists_timer : uint;
/** current level **/
private var _current_level : int;
/** reference to manifest being loaded **/
private var _manifest_loading : Manifest;
/** is this loader closed **/
private var _closed : Boolean = false;
/* playlist retry timeout */
private var _retry_timeout : Number;
private var _retry_count : int;
/* alt audio tracks */
private var _alt_audio_tracks : Vector.<AltAudioTrack>;
/** 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>();
_urlloader = new URLLoader();
_urlloader.addEventListener(Event.COMPLETE, _loaderHandler);
_urlloader.addEventListener(IOErrorEvent.IO_ERROR, _errorHandler);
_urlloader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, _errorHandler);
};
public function dispose() : void {
_close();
_urlloader.removeEventListener(Event.COMPLETE, _loaderHandler);
_urlloader.removeEventListener(IOErrorEvent.IO_ERROR, _errorHandler);
_urlloader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, _errorHandler);
_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 || _retry_count < HLSSettings.manifestLoadMaxRetry)) {
CONFIG::LOGGING {
Log.warn("I/O Error while trying to load Playlist, retry in " + _retry_timeout + " ms");
}
_timeoutID = setTimeout(_loadActiveLevelPlaylist, _retry_timeout);
/* exponential increase of retry timeout, capped to manifestLoadMaxRetryTimeout */
_retry_timeout = Math.min(HLSSettings.manifestLoadMaxRetryTimeout, 2 * _retry_timeout);
_retry_count++;
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 _alt_audio_tracks;
}
/** Load the manifest file. **/
public function load(url : String) : void {
_close();
_closed = false;
_url = url;
_levels = new Vector.<Level>();
_canStart = false;
_reload_playlists_timer = getTimer();
_retry_timeout = 1000;
_retry_count = 0;
_alt_audio_tracks = null;
_hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_LOADING, url));
if (DataUri.isDataUri(url)) {
CONFIG::LOGGING {
Log.debug("Identified main manifest <" + url + "> as a data URI.");
}
var data : String = new DataUri(url).extractData();
_parseManifest(data || "");
} else {
_urlloader.load(new URLRequest(url));
}
};
/** Manifest loaded; check and parse it **/
private function _loaderHandler(event : Event) : void {
// successful loading, reset retry counter
_retry_timeout = 1000;
_retry_count = 0;
var loader : URLLoader = URLLoader(event.target);
_parseManifest(String(loader.data));
};
/** parse a playlist **/
private function _parseLevelPlaylist(string : String, url : String, level : int) : 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 reload_interval : 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, _reload_playlists_timer + reload_interval - 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));
}
}
_hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_LOADED, level));
_manifest_loading = 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);
_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");
}
_current_level = 0;
_parseLevelPlaylist(string, _url, 0);
} 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(_hls, string, _url);
// retrieve start level from helper function
_current_level = _hls.startlevel;
_hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_PARSED, _levels));
_loadActiveLevelPlaylist();
if (string.indexOf(Manifest.ALTERNATE_AUDIO) > 0) {
CONFIG::LOGGING {
Log.debug("alternate audio level found");
}
// parse alternate audio tracks
_alt_audio_tracks = Manifest.extractAltAudioTracks(string, _url);
CONFIG::LOGGING {
if (_alt_audio_tracks.length > 0) {
Log.debug(_alt_audio_tracks.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;
}
_reload_playlists_timer = getTimer();
// load active M3U8 playlist only
_manifest_loading = new Manifest();
_hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_LOADING, _current_level));
_manifest_loading.loadPlaylist(_levels[_current_level].url, _parseLevelPlaylist, _errorHandler, _current_level, _type, HLSSettings.flushLiveURLCache);
};
/** When level switch occurs, assess the need of (re)loading new level playlist **/
private function _levelSwitchHandler(event : HLSEvent) : void {
if (_current_level != event.level) {
_current_level = event.level;
CONFIG::LOGGING {
Log.debug("switch to level " + _current_level);
}
if (_type == HLSTypes.LIVE || _levels[_current_level].fragments.length == 0) {
_closed = false;
CONFIG::LOGGING {
Log.debug("(re)load Playlist");
}
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 (_manifest_loading) {
_manifest_loading.close();
}
} catch(e : Error) {
}
}
/** When the framework idles out, stop reloading manifest **/
private function _stateHandler(event : HLSEvent) : void {
if (event.state == HLSPlayStates.IDLE) {
_close();
}
};
}
}
|
adjust live playlist reload timer when play position is near the edge of the live playlist related to #198
|
adjust live playlist reload timer when play position is near the edge of the live playlist
related to #198
|
ActionScript
|
mpl-2.0
|
vidible/vdb-flashls,clappr/flashls,thdtjsdn/flashls,Peer5/flashls,aevange/flashls,jlacivita/flashls,codex-corp/flashls,Boxie5/flashls,Boxie5/flashls,aevange/flashls,loungelogic/flashls,NicolasSiver/flashls,suuhas/flashls,fixedmachine/flashls,dighan/flashls,hola/flashls,JulianPena/flashls,Corey600/flashls,tedconf/flashls,mangui/flashls,neilrackett/flashls,aevange/flashls,fixedmachine/flashls,Peer5/flashls,aevange/flashls,JulianPena/flashls,dighan/flashls,suuhas/flashls,suuhas/flashls,hola/flashls,vidible/vdb-flashls,NicolasSiver/flashls,Corey600/flashls,loungelogic/flashls,Peer5/flashls,codex-corp/flashls,Peer5/flashls,thdtjsdn/flashls,suuhas/flashls,tedconf/flashls,mangui/flashls,clappr/flashls,neilrackett/flashls,jlacivita/flashls
|
63d7c9eeaa667e01f5c8eb6d8a7eab95e15e6731
|
lib/src_linux/com/amanitadesign/steam/FRESteamWorks.as
|
lib/src_linux/com/amanitadesign/steam/FRESteamWorks.as
|
/*
* FRESteamWorks.as
* This file is part of FRESteamWorks.
*
* Created by Ventero <http://github.com/Ventero>
* Copyright (c) 2012-2013 Level Up Labs, LLC. All rights reserved.
*/
package com.amanitadesign.steam {
import flash.desktop.NativeProcess;
import flash.desktop.NativeProcessStartupInfo;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.StatusEvent;
import flash.filesystem.File;
import flash.utils.ByteArray;
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
import flash.utils.clearInterval;
import flash.utils.setInterval;
public class FRESteamWorks extends EventDispatcher {
[Event(name="steam_response", type="com.amanitadesign.steam.SteamEvent")]
private static const PATH:String = "NativeApps/Linux/APIWrapper";
private var _file:File;
private var _process:NativeProcess;
private var _tm:int;
private var _init:Boolean = false;
private var _error:Boolean = false;
private var _crashHandlerArgs:Array = null;
public var isReady:Boolean = false;
private static const AIRSteam_Init:int = 0;
private static const AIRSteam_RunCallbacks:int = 1;
private static const AIRSteam_RequestStats:int = 2;
private static const AIRSteam_SetAchievement:int = 3;
private static const AIRSteam_ClearAchievement:int = 4;
private static const AIRSteam_IsAchievement:int = 5;
private static const AIRSteam_GetStatInt:int = 6;
private static const AIRSteam_GetStatFloat:int = 7;
private static const AIRSteam_SetStatInt:int = 8;
private static const AIRSteam_SetStatFloat:int = 9;
private static const AIRSteam_StoreStats:int = 10;
private static const AIRSteam_ResetAllStats:int = 11;
private static const AIRSteam_GetFileCount:int = 12;
private static const AIRSteam_GetFileSize:int = 13;
private static const AIRSteam_FileExists:int = 14;
private static const AIRSteam_FileWrite:int = 15;
private static const AIRSteam_FileRead:int = 16;
private static const AIRSteam_FileDelete:int = 17;
private static const AIRSteam_IsCloudEnabledForApp:int = 18;
private static const AIRSteam_SetCloudEnabledForApp:int = 19;
private static const AIRSteam_GetUserID:int = 20;
private static const AIRSteam_GetPersonaName:int = 21;
private static const AIRSteam_UseCrashHandler:int = 22;
public function FRESteamWorks (target:IEventDispatcher = null) {
_file = File.applicationDirectory.resolvePath(PATH);
_process = new NativeProcess();
_process.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, eventDispatched);
_process.addEventListener(IOErrorEvent.STANDARD_INPUT_IO_ERROR, errorCallback);
super(target);
}
public function dispose():void {
if(_process.running) {
_process.closeInput();
_process.exit();
}
clearInterval(_tm);
isReady = false;
}
private function startProcess():void {
var startupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
startupInfo.executable = _file;
_process.start(startupInfo);
}
public function init():Boolean {
if(!_file.exists) return false;
try {
startProcess();
} catch(e:Error) {
return false;
}
// try to start the process a second time, but this time ignoring any
// potential errors. this seems to give the runtime enough time to check
// for any stderr output of the initial call to startProcess(), so that we
// now can check if it actually started. process.running is unreliable,
// in that it's always set to true, even if the process didn't start at all
// in case it couldn't load one of the libraries it depends on, it prints
// something like "error while loading shared libraries" to stderr,
// which we're trying to detect here
try {
startProcess();
} catch(e:Error) {
// no-op
}
if(!_process.running) return false;
if(_process.standardError.bytesAvailable > 0) return false;
// initialization seems to be successful
_init = true;
// UseCrashHandler has to be called before Steam_Init
// but we still have to make sure the process is actually running
// so FRESteamWorks#useCrashHandler just sets _crashHandlerArgs
// and the actual call is handled here
if(_crashHandlerArgs) {
if(!callWrapper(AIRSteam_UseCrashHandler, _crashHandlerArgs))
return false;
}
if(!callWrapper(AIRSteam_Init)) return false;
isReady = readBoolResponse();
if(isReady) _tm = setInterval(runCallbacks, 100);
return isReady;
}
private function errorCallback(e:IOErrorEvent):void {
_error = true;
// the process doesn't accept our input anymore, so just stop it
clearInterval(_tm);
if(_process.running) {
try {
_process.closeInput();
} catch(e:*) {
// no-op
}
_process.exit();
}
}
private function callWrapper(funcName:int, params:Array = null):Boolean {
_error = false;
if(!_process.running) return false;
var stdin:IDataOutput = _process.standardInput;
stdin.writeUTFBytes(funcName + "\n");
if (params) {
for(var i:int = 0; i < params.length; ++i) {
if(params[i] is ByteArray) {
var length:uint = params[i].length;
// length + 1 for the added newline
stdin.writeUTFBytes(String(length + 1) + "\n");
stdin.writeBytes(params[i]);
stdin.writeUTFBytes("\n");
} else {
stdin.writeUTFBytes(String(params[i]) + "\n");
}
}
}
return !_error;
}
private function waitForData(output:IDataInput):uint {
while(!output.bytesAvailable) {
// wait
if(!_process.running) return 0;
}
return output.bytesAvailable;
}
private function readBoolResponse():Boolean {
if(!_process.running) return false;
var stdout:IDataInput = _process.standardOutput;
var avail:uint = waitForData(stdout);
var response:String = stdout.readUTFBytes(1);
return (response == "t");
}
private function readIntResponse():int {
if(!_process.running) return 0;
var stdout:IDataInput = _process.standardOutput;
var avail:uint = waitForData(stdout);
var response:String = stdout.readUTFBytes(avail);
return parseInt(response, 10);
}
private function readFloatResponse():Number {
if(!_process.running) return 0.0;
var stdout:IDataInput = _process.standardOutput;
var avail:uint = waitForData(stdout);
var response:String = stdout.readUTFBytes(avail)
return parseFloat(response);
}
private function readStringResponse():String {
if(!_process.running) return "";
var stdout:IDataInput = _process.standardOutput;
var avail:uint = waitForData(stdout);
var response:String = stdout.readUTFBytes(avail)
return response;
}
private function eventDispatched(e:ProgressEvent):void {
var stderr:IDataInput = _process.standardError;
var avail:uint = stderr.bytesAvailable;
var data:String = stderr.readUTFBytes(avail);
var pattern:RegExp = /__event__<(\d+),(\d+)>/g;
var result:Object;
while((result = pattern.exec(data))) {
var req_type:int = new int(result[1]);
var response:int = new int(result[2]);
var steamEvent:SteamEvent = new SteamEvent(SteamEvent.STEAM_RESPONSE, req_type, response);
dispatchEvent(steamEvent);
}
}
public function requestStats():Boolean {
if(!callWrapper(AIRSteam_RequestStats)) return false;
return readBoolResponse();
}
public function runCallbacks():Boolean {
if(!callWrapper(AIRSteam_RunCallbacks)) return false;
return true;
}
public function getUserID():String {
if(!callWrapper(AIRSteam_GetUserID)) return "";
return readStringResponse();
}
public function getPersonaName():String {
if(!callWrapper(AIRSteam_GetPersonaName)) return "";
return readStringResponse();
}
public function useCrashHandler(appID:uint, version:String, date:String, time:String):Boolean {
// only allow calls before SteamAPI_Init was called
if(_init) return false;
_crashHandlerArgs = [appID, version, date, time];
return true;
}
public function setAchievement(id:String):Boolean {
if(!callWrapper(AIRSteam_SetAchievement, [id])) return false;
return readBoolResponse();
}
public function clearAchievement(id:String):Boolean {
if(!callWrapper(AIRSteam_ClearAchievement, [id])) return false;
return readBoolResponse();
}
public function isAchievement(id:String):Boolean {
if(!callWrapper(AIRSteam_IsAchievement, [id])) return false;
return readBoolResponse();
}
public function getStatInt(id:String):int {
if(!callWrapper(AIRSteam_GetStatInt, [id])) return 0;
return readIntResponse();
}
public function getStatFloat(id:String):Number {
if(!callWrapper(AIRSteam_GetStatFloat, [id])) return 0.0;
return readFloatResponse();
}
public function setStatInt(id:String, value:int):Boolean {
if(!callWrapper(AIRSteam_SetStatInt, [id, value])) return false;
return readBoolResponse();
}
public function setStatFloat(id:String, value:Number):Boolean {
if(!callWrapper(AIRSteam_SetStatFloat, [id, value])) return false;
return readBoolResponse();
}
public function storeStats():Boolean {
if(!callWrapper(AIRSteam_StoreStats)) return false;
return readBoolResponse();
}
public function resetAllStats(bAchievementsToo:Boolean):Boolean {
if(!callWrapper(AIRSteam_ResetAllStats, [bAchievementsToo])) return false;
return readBoolResponse();
}
public function getFileCount():int {
if(!callWrapper(AIRSteam_GetFileCount)) return 0;
return readIntResponse();
}
public function getFileSize(fileName:String):int {
if(!callWrapper(AIRSteam_GetFileSize, [fileName])) return 0;
return readIntResponse();
}
public function fileExists(fileName:String):Boolean {
if(!callWrapper(AIRSteam_FileExists, [fileName])) return false;
return readBoolResponse();
}
public function fileWrite(fileName:String, data:ByteArray):Boolean {
if(!callWrapper(AIRSteam_FileWrite, [fileName, data])) return false;
return readBoolResponse();
}
public function fileRead(fileName:String, data:ByteArray):Boolean {
if(!callWrapper(AIRSteam_FileRead, [fileName])) return false;
var success:Boolean = readBoolResponse();
if(success) {
var content:String = readStringResponse();
data.writeUTFBytes(content);
data.position = 0;
}
return success;
}
public function fileDelete(fileName:String):Boolean {
if(!callWrapper(AIRSteam_FileDelete, [fileName])) return false;
return readBoolResponse();
}
public function isCloudEnabledForApp():Boolean {
if(!callWrapper(AIRSteam_IsCloudEnabledForApp)) return false;
return readBoolResponse();
}
public function setCloudEnabledForApp(enabled:Boolean):Boolean {
if(!callWrapper(AIRSteam_SetCloudEnabledForApp, [enabled])) return false;
return readBoolResponse();
}
}
}
|
/*
* FRESteamWorks.as
* This file is part of FRESteamWorks.
*
* Created by Ventero <http://github.com/Ventero>
* Copyright (c) 2012-2013 Level Up Labs, LLC. All rights reserved.
*/
package com.amanitadesign.steam {
import flash.desktop.NativeProcess;
import flash.desktop.NativeProcessStartupInfo;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.StatusEvent;
import flash.filesystem.File;
import flash.utils.ByteArray;
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
import flash.utils.clearInterval;
import flash.utils.setInterval;
public class FRESteamWorks extends EventDispatcher {
[Event(name="steam_response", type="com.amanitadesign.steam.SteamEvent")]
private static const PATH:String = "NativeApps/Linux/APIWrapper";
private var _file:File;
private var _process:NativeProcess;
private var _tm:int;
private var _init:Boolean = false;
private var _error:Boolean = false;
private var _crashHandlerArgs:Array = null;
public var isReady:Boolean = false;
private static const AIRSteam_Init:int = 0;
private static const AIRSteam_RunCallbacks:int = 1;
private static const AIRSteam_RequestStats:int = 2;
private static const AIRSteam_SetAchievement:int = 3;
private static const AIRSteam_ClearAchievement:int = 4;
private static const AIRSteam_IsAchievement:int = 5;
private static const AIRSteam_GetStatInt:int = 6;
private static const AIRSteam_GetStatFloat:int = 7;
private static const AIRSteam_SetStatInt:int = 8;
private static const AIRSteam_SetStatFloat:int = 9;
private static const AIRSteam_StoreStats:int = 10;
private static const AIRSteam_ResetAllStats:int = 11;
private static const AIRSteam_GetFileCount:int = 12;
private static const AIRSteam_GetFileSize:int = 13;
private static const AIRSteam_FileExists:int = 14;
private static const AIRSteam_FileWrite:int = 15;
private static const AIRSteam_FileRead:int = 16;
private static const AIRSteam_FileDelete:int = 17;
private static const AIRSteam_IsCloudEnabledForApp:int = 18;
private static const AIRSteam_SetCloudEnabledForApp:int = 19;
private static const AIRSteam_GetUserID:int = 20;
private static const AIRSteam_GetPersonaName:int = 21;
private static const AIRSteam_UseCrashHandler:int = 22;
public function FRESteamWorks (target:IEventDispatcher = null) {
_file = File.applicationDirectory.resolvePath(PATH);
_process = new NativeProcess();
_process.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, eventDispatched);
_process.addEventListener(IOErrorEvent.STANDARD_INPUT_IO_ERROR, errorCallback);
super(target);
}
public function dispose():void {
if(_process.running) {
_process.closeInput();
_process.exit();
}
clearInterval(_tm);
isReady = false;
}
private function startProcess():void {
var startupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
startupInfo.executable = _file;
_process.start(startupInfo);
}
public function init():Boolean {
if(!_file.exists) return false;
try {
startProcess();
} catch(e:Error) {
return false;
}
// try to start the process a second time, but this time ignoring any
// potential errors since we will definitely get one about the process
// already running. this seems to give the runtime enough time to check
// for any stderr output of the initial call to startProcess(), so that we
// now can check if it actually started: in case it couldn't one of the
// libraries it depends on, it prints something like "error while loading
// shared libraries" to stderr, which we're trying to detect here.
// process.running is unreliable, in that it's always set to true,
// even if the process didn't start at all
try {
startProcess();
} catch(e:Error) {
// no-op
}
if(!_process.running) return false;
if(_process.standardError.bytesAvailable > 0) return false;
// initialization seems to be successful
_init = true;
// UseCrashHandler has to be called before Steam_Init
// but we still have to make sure the process is actually running
// so FRESteamWorks#useCrashHandler just sets _crashHandlerArgs
// and the actual call is handled here
if(_crashHandlerArgs) {
if(!callWrapper(AIRSteam_UseCrashHandler, _crashHandlerArgs))
return false;
}
if(!callWrapper(AIRSteam_Init)) return false;
isReady = readBoolResponse();
if(isReady) _tm = setInterval(runCallbacks, 100);
return isReady;
}
private function errorCallback(e:IOErrorEvent):void {
_error = true;
// the process doesn't accept our input anymore, so just stop it
clearInterval(_tm);
if(_process.running) {
try {
_process.closeInput();
} catch(e:*) {
// no-op
}
_process.exit();
}
}
private function callWrapper(funcName:int, params:Array = null):Boolean {
_error = false;
if(!_process.running) return false;
var stdin:IDataOutput = _process.standardInput;
stdin.writeUTFBytes(funcName + "\n");
if (params) {
for(var i:int = 0; i < params.length; ++i) {
if(params[i] is ByteArray) {
var length:uint = params[i].length;
// length + 1 for the added newline
stdin.writeUTFBytes(String(length + 1) + "\n");
stdin.writeBytes(params[i]);
stdin.writeUTFBytes("\n");
} else {
stdin.writeUTFBytes(String(params[i]) + "\n");
}
}
}
return !_error;
}
private function waitForData(output:IDataInput):uint {
while(!output.bytesAvailable) {
// wait
if(!_process.running) return 0;
}
return output.bytesAvailable;
}
private function readBoolResponse():Boolean {
if(!_process.running) return false;
var stdout:IDataInput = _process.standardOutput;
var avail:uint = waitForData(stdout);
var response:String = stdout.readUTFBytes(1);
return (response == "t");
}
private function readIntResponse():int {
if(!_process.running) return 0;
var stdout:IDataInput = _process.standardOutput;
var avail:uint = waitForData(stdout);
var response:String = stdout.readUTFBytes(avail);
return parseInt(response, 10);
}
private function readFloatResponse():Number {
if(!_process.running) return 0.0;
var stdout:IDataInput = _process.standardOutput;
var avail:uint = waitForData(stdout);
var response:String = stdout.readUTFBytes(avail)
return parseFloat(response);
}
private function readStringResponse():String {
if(!_process.running) return "";
var stdout:IDataInput = _process.standardOutput;
var avail:uint = waitForData(stdout);
var response:String = stdout.readUTFBytes(avail)
return response;
}
private function eventDispatched(e:ProgressEvent):void {
var stderr:IDataInput = _process.standardError;
var avail:uint = stderr.bytesAvailable;
var data:String = stderr.readUTFBytes(avail);
var pattern:RegExp = /__event__<(\d+),(\d+)>/g;
var result:Object;
while((result = pattern.exec(data))) {
var req_type:int = new int(result[1]);
var response:int = new int(result[2]);
var steamEvent:SteamEvent = new SteamEvent(SteamEvent.STEAM_RESPONSE, req_type, response);
dispatchEvent(steamEvent);
}
}
public function requestStats():Boolean {
if(!callWrapper(AIRSteam_RequestStats)) return false;
return readBoolResponse();
}
public function runCallbacks():Boolean {
if(!callWrapper(AIRSteam_RunCallbacks)) return false;
return true;
}
public function getUserID():String {
if(!callWrapper(AIRSteam_GetUserID)) return "";
return readStringResponse();
}
public function getPersonaName():String {
if(!callWrapper(AIRSteam_GetPersonaName)) return "";
return readStringResponse();
}
public function useCrashHandler(appID:uint, version:String, date:String, time:String):Boolean {
// only allow calls before SteamAPI_Init was called
if(_init) return false;
_crashHandlerArgs = [appID, version, date, time];
return true;
}
public function setAchievement(id:String):Boolean {
if(!callWrapper(AIRSteam_SetAchievement, [id])) return false;
return readBoolResponse();
}
public function clearAchievement(id:String):Boolean {
if(!callWrapper(AIRSteam_ClearAchievement, [id])) return false;
return readBoolResponse();
}
public function isAchievement(id:String):Boolean {
if(!callWrapper(AIRSteam_IsAchievement, [id])) return false;
return readBoolResponse();
}
public function getStatInt(id:String):int {
if(!callWrapper(AIRSteam_GetStatInt, [id])) return 0;
return readIntResponse();
}
public function getStatFloat(id:String):Number {
if(!callWrapper(AIRSteam_GetStatFloat, [id])) return 0.0;
return readFloatResponse();
}
public function setStatInt(id:String, value:int):Boolean {
if(!callWrapper(AIRSteam_SetStatInt, [id, value])) return false;
return readBoolResponse();
}
public function setStatFloat(id:String, value:Number):Boolean {
if(!callWrapper(AIRSteam_SetStatFloat, [id, value])) return false;
return readBoolResponse();
}
public function storeStats():Boolean {
if(!callWrapper(AIRSteam_StoreStats)) return false;
return readBoolResponse();
}
public function resetAllStats(bAchievementsToo:Boolean):Boolean {
if(!callWrapper(AIRSteam_ResetAllStats, [bAchievementsToo])) return false;
return readBoolResponse();
}
public function getFileCount():int {
if(!callWrapper(AIRSteam_GetFileCount)) return 0;
return readIntResponse();
}
public function getFileSize(fileName:String):int {
if(!callWrapper(AIRSteam_GetFileSize, [fileName])) return 0;
return readIntResponse();
}
public function fileExists(fileName:String):Boolean {
if(!callWrapper(AIRSteam_FileExists, [fileName])) return false;
return readBoolResponse();
}
public function fileWrite(fileName:String, data:ByteArray):Boolean {
if(!callWrapper(AIRSteam_FileWrite, [fileName, data])) return false;
return readBoolResponse();
}
public function fileRead(fileName:String, data:ByteArray):Boolean {
if(!callWrapper(AIRSteam_FileRead, [fileName])) return false;
var success:Boolean = readBoolResponse();
if(success) {
var content:String = readStringResponse();
data.writeUTFBytes(content);
data.position = 0;
}
return success;
}
public function fileDelete(fileName:String):Boolean {
if(!callWrapper(AIRSteam_FileDelete, [fileName])) return false;
return readBoolResponse();
}
public function isCloudEnabledForApp():Boolean {
if(!callWrapper(AIRSteam_IsCloudEnabledForApp)) return false;
return readBoolResponse();
}
public function setCloudEnabledForApp(enabled:Boolean):Boolean {
if(!callWrapper(AIRSteam_SetCloudEnabledForApp, [enabled])) return false;
return readBoolResponse();
}
}
}
|
Clarify comment
|
Clarify comment
|
ActionScript
|
bsd-2-clause
|
Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks
|
ad347a4c8d4dfeab7891e96402db7dbdb104f5d1
|
src/as/com/threerings/flash/TextFieldUtil.as
|
src/as/com/threerings/flash/TextFieldUtil.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 {
import flash.events.Event;
import flash.events.MouseEvent;
import flash.filters.GlowFilter;
import flash.system.Capabilities;
import flash.system.System;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFieldType;
import flash.text.TextFormat;
import flash.text.TextFormatAlign;
import com.threerings.util.Util;
public class TextFieldUtil
{
/** A fudge factor that must be added to a TextField's textWidth when setting the width. */
public static const WIDTH_PAD :int = 5;
/** A fudge factor that must be added to a TextField's textHeight when setting the height. */
public static const HEIGHT_PAD :int = 4;
/**
* Create a TextField.
*
* @param initProps contains properties with which to initialize the TextField.
* Additionally it may contain the following properties:
* outlineColor: uint
*
* initProps may be destructively modified.
*/
public static function createField (
text :String, initProps :Object = null, clazz :Class = null) :TextField
{
var tf :TextField = (clazz == null) ? new TextField() : TextField(new clazz());
if ("outlineColor" in initProps) {
tf.filters = [ new GlowFilter(uint(initProps["outlineColor"]), 1, 2, 2, 255) ];
}
Util.init(tf, initProps, null, MASK_FIELD_PROPS);
tf.text = text;
if (tf.autoSize != TextFieldAutoSize.NONE) {
tf.width = tf.textWidth + WIDTH_PAD;
tf.height = tf.textHeight + HEIGHT_PAD;
}
return tf;
}
/**
* Create a TextFormat using initProps.
* If unspecified, the following properties have default values:
* size: 18
* font: _sans
*/
public static function createFormat (initProps :Object) :TextFormat
{
var f :TextFormat = new TextFormat();
Util.init(f, initProps, DEFAULT_FORMAT_PROPS);
return f;
}
/**
* Include the specified TextField in a set of TextFields in which only
* one may have a selection at a time.
*/
public static function trackSingleSelectable (textField :TextField) :void
{
textField.addEventListener(MouseEvent.MOUSE_MOVE, handleTrackedSelection);
// immediately put the kibosh on any selection
textField.setSelection(0, 0);
}
/**
* Internal method related to tracking a single selectable TextField.
*/
protected static function handleTrackedSelection (event :MouseEvent) :void
{
if (event.buttonDown) {
var field :TextField = event.target as TextField;
if (field == _lastSelected) {
updateSelection(field);
} else if (field.selectionBeginIndex != field.selectionEndIndex) {
// clear the last one..
if (_lastSelected != null) {
handleLastSelectedRemoved();
}
_lastSelected = field;
_lastSelected.addEventListener(Event.REMOVED_FROM_STAGE, handleLastSelectedRemoved);
updateSelection(field);
}
}
}
/**
* Process the selection.
*/
protected static function updateSelection (field :TextField) :void
{
if (-1 != Capabilities.os.indexOf("Linux")) {
var str :String = field.text.substring(
field.selectionBeginIndex, field.selectionEndIndex);
System.setClipboard(str);
}
}
/**
* Internal method related to tracking a single selectable TextField.
*/
protected static function handleLastSelectedRemoved (... ignored) :void
{
_lastSelected.setSelection(0, 0);
_lastSelected.removeEventListener(Event.REMOVED_FROM_STAGE, handleLastSelectedRemoved);
_lastSelected = null;
}
/** The last tracked TextField to be selected. */
protected static var _lastSelected :TextField;
protected static const MASK_FIELD_PROPS :Object = { outlineColor: true };
protected static const DEFAULT_FORMAT_PROPS :Object = { size: 18, font: "_sans" };
}
}
|
//
// $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 {
import flash.events.Event;
import flash.events.MouseEvent;
import flash.filters.GlowFilter;
import flash.system.Capabilities;
import flash.system.System;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFieldType;
import flash.text.TextFormat;
import flash.text.TextFormatAlign;
import com.threerings.util.Util;
public class TextFieldUtil
{
/** A fudge factor that must be added to a TextField's textWidth when setting the width. */
public static const WIDTH_PAD :int = 5;
/** A fudge factor that must be added to a TextField's textHeight when setting the height. */
public static const HEIGHT_PAD :int = 4;
/**
* Create a TextField.
*
* @param initProps contains properties with which to initialize the TextField.
* Additionally it may contain the following properties:
* outlineColor: uint
* @param formatProps contains properties with which to initialize the defaultTextFormat.
*/
public static function createField (
text :String, initProps :Object = null, formatProps :Object = null, clazz :Class = null)
:TextField
{
var tf :TextField = (clazz == null) ? new TextField() : TextField(new clazz());
if ("outlineColor" in initProps) {
tf.filters = [ new GlowFilter(uint(initProps["outlineColor"]), 1, 2, 2, 255) ];
}
Util.init(tf, initProps, null, MASK_FIELD_PROPS);
if (formatProps != null) {
tf.defaultTextFormat = createFormat(formatProps);
}
tf.text = text;
if (tf.autoSize != TextFieldAutoSize.NONE) {
tf.width = tf.textWidth + WIDTH_PAD;
tf.height = tf.textHeight + HEIGHT_PAD;
}
return tf;
}
/**
* Create a TextFormat using initProps.
* If unspecified, the following properties have default values:
* size: 18
* font: _sans
*/
public static function createFormat (initProps :Object) :TextFormat
{
var f :TextFormat = new TextFormat();
Util.init(f, initProps, DEFAULT_FORMAT_PROPS);
return f;
}
/**
* Include the specified TextField in a set of TextFields in which only
* one may have a selection at a time.
*/
public static function trackSingleSelectable (textField :TextField) :void
{
textField.addEventListener(MouseEvent.MOUSE_MOVE, handleTrackedSelection);
// immediately put the kibosh on any selection
textField.setSelection(0, 0);
}
/**
* Internal method related to tracking a single selectable TextField.
*/
protected static function handleTrackedSelection (event :MouseEvent) :void
{
if (event.buttonDown) {
var field :TextField = event.target as TextField;
if (field == _lastSelected) {
updateSelection(field);
} else if (field.selectionBeginIndex != field.selectionEndIndex) {
// clear the last one..
if (_lastSelected != null) {
handleLastSelectedRemoved();
}
_lastSelected = field;
_lastSelected.addEventListener(Event.REMOVED_FROM_STAGE, handleLastSelectedRemoved);
updateSelection(field);
}
}
}
/**
* Process the selection.
*/
protected static function updateSelection (field :TextField) :void
{
if (-1 != Capabilities.os.indexOf("Linux")) {
var str :String = field.text.substring(
field.selectionBeginIndex, field.selectionEndIndex);
System.setClipboard(str);
}
}
/**
* Internal method related to tracking a single selectable TextField.
*/
protected static function handleLastSelectedRemoved (... ignored) :void
{
_lastSelected.setSelection(0, 0);
_lastSelected.removeEventListener(Event.REMOVED_FROM_STAGE, handleLastSelectedRemoved);
_lastSelected = null;
}
/** The last tracked TextField to be selected. */
protected static var _lastSelected :TextField;
protected static const MASK_FIELD_PROPS :Object = { outlineColor: true };
protected static const DEFAULT_FORMAT_PROPS :Object = { size: 18, font: "_sans" };
}
}
|
Allow the defaultTextFormat initProps to be specified more conveniently.
|
Allow the defaultTextFormat initProps to be specified more conveniently.
git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@478 ed5b42cb-e716-0410-a449-f6a68f950b19
|
ActionScript
|
lgpl-2.1
|
threerings/nenya,threerings/nenya
|
b7cc2b82506960df6900b9fac52f5aae3e1362c9
|
as3/xobjas3/src/com/rpath/xobj/XSmartURL.as
|
as3/xobjas3/src/com/rpath/xobj/XSmartURL.as
|
/*
# Copyright (c) 2008-2010 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 warranty; 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.Sort;
import flash.utils.Dictionary;
import mx.collections.SortField;
public class XSmartURL extends URL
{
public function XSmartURL(s:*=null)
{
// unwrap the URL passed in
if (s is XSmartURL)
{
s = (s as XSmartURL).baseURL;
}
super(s);
// keep track of the base URL distinct from
// our current value
baseURL = new URL(this.value);
}
public function get baseURL():URL
{
return _baseURL;
}
private var _baseURL:URL;
public function set baseURL(value:URL):void
{
_baseURL = value;
recomputeQualifiedURL();
}
/** descriptor provides the encoding chars to use
* which is a poor man's metadata right now
*/
[xobjTransient]
public var descriptor:XSmartURLDescriptor;
/** paging support
*/
[xobjTransient]
public var rangeRequest:Boolean;
[xobjTransient]
public var startIndex:Number;
[xobjTransient]
public var limit:Number;
[xobjTransient]
public var rangeUsingHeaders:Boolean;
/** filterTerms is an array of (field, operator, value) clauses
* that are assumed to be AND clauses
*/
private var _filterTerms:Array;
[xobjTransient]
public function get filterTerms():Array
{
return _filterTerms;
}
[xobjTransient]
public function set filterTerms(value:Array):void
{
_filterTerms = value;
recomputeQualifiedURL();
}
/** sortTerms are an ordered set of (asc, desc) fields to order by
*/
private var _sortTerms:Sort;
[xobjTransient]
public function get sortTerms():Sort
{
return _sortTerms;
}
[xobjTransient]
public function set sortTerms(value:Sort):void
{
_sortTerms = value;
recomputeQualifiedURL();
}
/** freeSearch is for google-like full text searching
*/
private var _freeSearch:String;
[xobjTransient]
public function get freeSearch():String
{
return _freeSearch;
}
[xobjTransient]
public function set freeSearch(value:String):void
{
_freeSearch = value;
recomputeQualifiedURL();
}
/** url takes the baseURL and modifies it to encode the query,
* page, etc. params requested
*/
// TODO: optimize this via setter/getter pairs on query terms
[xobjTransient]
[Bindable]
public function get qualifiedURL():String
{
return _qualifiedURL;
}
private var _qualifiedURL:String;
[xobjTransient]
public function set qualifiedURL(s:String):void
{
_qualifiedURL = s;
}
[xobjTransient]
public function recomputeQualifiedURL():void
{
if (!baseURL)
return;
var fullURL:String = baseURL.value;
var queryFrag:String = queryFragment();
if (queryFrag)
{
if (baseURL.hasQuery())
{
fullURL = fullURL + "&" + queryFrag;
}
else
{
fullURL = fullURL + "?" + queryFrag;
}
}
qualifiedURL = fullURL;
}
[xobjTransient]
public function queryFragment():String
{
var params:Dictionary = new Dictionary();
var query:String = "";
if (rangeRequest)
{
if (descriptor.rangeUsingHeaders)
{
// DAMN HTTPService won't pass RANGE header
setHeader("X-Range", "rows "+startIndex+"-"+(startIndex+ limit -1));
}
else
{
params[descriptor.startKey] = startIndex;
params[descriptor.limitKey] = limit;
}
}
// TODO: use descriptor to tell us how to express sort
if (sortTerms)
{
var terms:String = "";
if (sortTerms.fields && sortTerms.fields.length > 0)
{
var first:Boolean = true;
for each (var term:SortField in sortTerms.fields)
{
if (!term || !term.name)
continue;
terms = terms
+ (first ? "": descriptor.sortConjunction)
+ (term.descending ? descriptor.sortDescMarker: descriptor.sortAscMarker)
+ term.name;
first = false;
}
if (terms)
{
params[descriptor.sortKey] = terms;
}
}
}
if (filterTerms)
{
var search:String;
first = true;
for each (var searchTerm:FilterTerm in filterTerms)
{
search = search
+ (first ? "": descriptor.filterTermConjunction)
+ descriptor.filterTermStart
+ searchTerm.name + descriptor.filterTermSeperator+ searchTerm.operator +descriptor.filterTermSeperator + searchTerm.value
+ descriptor.filterTermEnd;
first = false;
}
if (search)
{
params[descriptor.filterKey] = search;
}
}
// Google like full text searching
if (freeSearch)
{
params[descriptor.searchKey] = freeSearch;
}
first = true;
for (var param:String in params)
{
query = query + (first ? "" : "&") + param + "=" + params[param];
first = false;
}
return query;
}
[xobjTransient]
public function addSearchTerm(term:FilterTerm):void
{
if (!filterTerms)
filterTerms = [];
filterTerms.push(term);
recomputeQualifiedURL();
}
/* TODO: decide if headers really belong on resource spec */
[xobjTransient]
public var headers:Dictionary;
[xobjTransient]
public var hasHeaders:Boolean;
[xobjTransient]
public function setHeader(name:String, value:String):void
{
headers[name] = value;
hasHeaders = true;
}
}
}
|
/*
# Copyright (c) 2008-2010 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 warranty; 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.Sort;
import flash.utils.Dictionary;
import mx.collections.SortField;
public class XSmartURL extends URL
{
public function XSmartURL(s:*=null)
{
// unwrap the URL passed in
if (s is XSmartURL)
{
s = (s as XSmartURL).baseURL;
}
super(s);
// keep track of the base URL distinct from
// our current value
baseURL = new URL(this.value);
}
public function get baseURL():URL
{
return _baseURL;
}
private var _baseURL:URL;
public function set baseURL(value:URL):void
{
_baseURL = value;
recomputeQualifiedURL();
}
/** descriptor provides the encoding chars to use
* which is a poor man's metadata right now
*/
[xobjTransient]
private var _descriptor:XSmartURLDescriptor;
public function get descriptor():XSmartURLDescriptor
{
return _descriptor;
}
public function set descriptor(value:XSmartURLDescriptor):void
{
_descriptor = value;
recomputeQualifiedURL();
}
/** paging support
*/
[xobjTransient]
public var rangeRequest:Boolean;
[xobjTransient]
public var startIndex:Number;
[xobjTransient]
public var limit:Number;
[xobjTransient]
public var rangeUsingHeaders:Boolean;
/** filterTerms is an array of (field, operator, value) clauses
* that are assumed to be AND clauses
*/
private var _filterTerms:Array;
[xobjTransient]
public function get filterTerms():Array
{
return _filterTerms;
}
[xobjTransient]
public function set filterTerms(value:Array):void
{
_filterTerms = value;
recomputeQualifiedURL();
}
/** sortTerms are an ordered set of (asc, desc) fields to order by
*/
private var _sortTerms:Sort;
[xobjTransient]
public function get sortTerms():Sort
{
return _sortTerms;
}
[xobjTransient]
public function set sortTerms(value:Sort):void
{
_sortTerms = value;
recomputeQualifiedURL();
}
/** freeSearch is for google-like full text searching
*/
private var _freeSearch:String;
[xobjTransient]
public function get freeSearch():String
{
return _freeSearch;
}
[xobjTransient]
public function set freeSearch(value:String):void
{
_freeSearch = value;
recomputeQualifiedURL();
}
/** url takes the baseURL and modifies it to encode the query,
* page, etc. params requested
*/
// TODO: optimize this via setter/getter pairs on query terms
[xobjTransient]
[Bindable]
public function get qualifiedURL():String
{
return _qualifiedURL;
}
private var _qualifiedURL:String;
[xobjTransient]
public function set qualifiedURL(s:String):void
{
_qualifiedURL = s;
}
[xobjTransient]
public function recomputeQualifiedURL():void
{
if (!baseURL)
return;
var fullURL:String = baseURL.value;
var queryFrag:String = queryFragment();
if (queryFrag)
{
if (baseURL.hasQuery())
{
fullURL = fullURL + "&" + queryFrag;
}
else
{
fullURL = fullURL + "?" + queryFrag;
}
}
qualifiedURL = fullURL;
}
[xobjTransient]
public function queryFragment():String
{
var params:Dictionary = new Dictionary();
var query:String = "";
if (!descriptor)
return query;
if (rangeRequest)
{
if (descriptor.rangeUsingHeaders)
{
// DAMN HTTPService won't pass RANGE header
setHeader("X-Range", "rows "+startIndex+"-"+(startIndex+ limit -1));
}
else
{
params[descriptor.startKey] = startIndex;
params[descriptor.limitKey] = limit;
}
}
// TODO: use descriptor to tell us how to express sort
if (sortTerms)
{
var terms:String = "";
if (sortTerms.fields && sortTerms.fields.length > 0)
{
var first:Boolean = true;
for each (var term:SortField in sortTerms.fields)
{
if (!term || !term.name)
continue;
terms = terms
+ (first ? "": descriptor.sortConjunction)
+ (term.descending ? descriptor.sortDescMarker: descriptor.sortAscMarker)
+ term.name;
first = false;
}
if (terms)
{
params[descriptor.sortKey] = terms;
}
}
}
if (filterTerms)
{
var search:String;
first = true;
for each (var searchTerm:FilterTerm in filterTerms)
{
search = search
+ (first ? "": descriptor.filterTermConjunction)
+ descriptor.filterTermStart
+ searchTerm.name + descriptor.filterTermSeperator+ searchTerm.operator +descriptor.filterTermSeperator + searchTerm.value
+ descriptor.filterTermEnd;
first = false;
}
if (search)
{
params[descriptor.filterKey] = search;
}
}
// Google like full text searching
if (freeSearch)
{
params[descriptor.searchKey] = freeSearch;
}
first = true;
for (var param:String in params)
{
query = query + (first ? "" : "&") + param + "=" + params[param];
first = false;
}
return query;
}
[xobjTransient]
public function addSearchTerm(term:FilterTerm):void
{
if (!filterTerms)
filterTerms = [];
filterTerms.push(term);
recomputeQualifiedURL();
}
/* TODO: decide if headers really belong on resource spec */
[xobjTransient]
public var headers:Dictionary;
[xobjTransient]
public var hasHeaders:Boolean;
[xobjTransient]
public function setHeader(name:String, value:String):void
{
headers[name] = value;
hasHeaders = true;
}
}
}
|
Handle disparate initialization patterns in XSmartURL
|
Handle disparate initialization patterns in XSmartURL
|
ActionScript
|
apache-2.0
|
sassoftware/xobj,sassoftware/xobj,sassoftware/xobj,sassoftware/xobj
|
a3d0ca1e2ac2887a21361f4504d41c3507e84090
|
src/aerys/minko/render/RenderTarget.as
|
src/aerys/minko/render/RenderTarget.as
|
package aerys.minko.render
{
import aerys.minko.render.resource.texture.ITextureResource;
import aerys.minko.render.resource.texture.TextureResource;
/**
* RenderTarget objects can be used to render in the backbuffer or
* in textures.
*
* @author Jean-Marc Le Roux
*
* @see aerys.minko.render.resource.texture.ITextureResource
*
*/
public final class RenderTarget
{
private var _width : uint = 0;
private var _height : uint = 0;
private var _resource : ITextureResource = null;
private var _surfaceSelector : uint = 0;
private var _useDepthAndStencil : Boolean = false;
private var _antiAliasing : int = 0;
private var _backgroundColor : uint = 0;
public function get width() : uint
{
return _width;
}
public function set width(value : uint) : void
{
_width = value;
if (_resource)
_resource.setSize(value, _height);
}
public function get height() : uint
{
return _height;
}
public function set height(value : uint) : void
{
_height = value;
if (_resource)
_resource.setSize(_width, value);
}
public function get textureResource() : ITextureResource
{
return _resource;
}
public function get surfaceSelector() : uint
{
return _surfaceSelector;
}
public function get useDepthAndStencil() : Boolean
{
return _useDepthAndStencil;
}
public function get antiAliasing() : int
{
return _antiAliasing;
}
public function get backgroundColor() : uint
{
return _backgroundColor;
}
public function set backgroundColor(value : uint) : void
{
_backgroundColor = value;
}
public function RenderTarget(width : uint,
height : uint,
resource : ITextureResource = null,
surfaceSelector : uint = 0,
backgroundColor : uint = 0,
useDepthAndStencil : Boolean = true,
antiAliasing : int = 0)
{
_width = width;
_height = height;
_resource = resource;
_surfaceSelector = surfaceSelector;
_backgroundColor = backgroundColor;
_useDepthAndStencil = useDepthAndStencil;
_antiAliasing = antiAliasing;
if (_resource && (_resource.width != _width || _resource.height != _height))
throw new Error(
'The texture resource and the render target must have the same size.'
);
}
public function resize(width : uint, height : uint) : void
{
_width = width;
_height = height;
if (_resource)
_resource.setSize(width, height);
}
}
}
|
package aerys.minko.render
{
import aerys.minko.render.resource.texture.ITextureResource;
import aerys.minko.render.resource.texture.TextureResource;
/**
* RenderTarget objects can be used to render in the backbuffer or
* in textures.
*
* @author Jean-Marc Le Roux
*
* @see aerys.minko.render.resource.texture.ITextureResource
*
*/
public final class RenderTarget
{
private var _width : uint = 0;
private var _height : uint = 0;
private var _resource : ITextureResource = null;
private var _surfaceSelector : uint = 0;
private var _useDepthAndStencil : Boolean = false;
private var _antiAliasing : int = 0;
private var _backgroundColor : uint = 0;
public function get width() : uint
{
return _width;
}
public function set width(value : uint) : void
{
_width = value;
_resource.setSize(value, _height);
}
public function get height() : uint
{
return _height;
}
public function set height(value : uint) : void
{
_height = value;
_resource.setSize(_width, value);
}
public function get textureResource() : ITextureResource
{
return _resource;
}
public function get surfaceSelector() : uint
{
return _surfaceSelector;
}
public function get useDepthAndStencil() : Boolean
{
return _useDepthAndStencil;
}
public function get antiAliasing() : int
{
return _antiAliasing;
}
public function get backgroundColor() : uint
{
return _backgroundColor;
}
public function set backgroundColor(value : uint) : void
{
_backgroundColor = value;
}
public function RenderTarget(width : uint,
height : uint,
resource : ITextureResource = null,
surfaceSelector : uint = 0,
backgroundColor : uint = 0,
useDepthAndStencil : Boolean = true,
antiAliasing : int = 0)
{
_width = width;
_height = height;
_resource = resource;
_surfaceSelector = surfaceSelector;
_backgroundColor = backgroundColor;
_useDepthAndStencil = useDepthAndStencil;
_antiAliasing = antiAliasing;
if (_resource && (_resource.width != _width || _resource.height != _height))
throw new Error(
'The texture resource and the render target must have the same size.'
);
}
public function resize(width : uint, height : uint) : void
{
_width = width;
_height = height;
if (_resource)
_resource.setSize(width, height);
}
}
}
|
remove useless check for _resource != null in RenderTarget.width and RenderTarget.height setters
|
remove useless check for _resource != null in RenderTarget.width and RenderTarget.height setters
|
ActionScript
|
mit
|
aerys/minko-as3
|
08e64434d1378633dcf8b7075bbb88fbd9dcff9f
|
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>;
/** NetConnection legacy stuff. **/
private var _connection:NetConnection;
/** 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 play time **/
private var _playback_start_time: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;
/** Reference to the video object. **/
private var _video:Object;
/** Create the buffer. **/
public function Buffer(hls:HLS, loader:FragmentLoader, video:Object):void {
_hls = hls;
_loader = loader;
_video = video;
_hls.addEventListener(HLSEvent.MANIFEST,_manifestHandler);
_connection = new NetConnection();
_connection.connect(null);
_transform = new SoundTransform();
_transform.volume = 0.9;
_setState(HLSStates.IDLE);
};
/** Check the bufferlength. **/
private function _checkBuffer():void {
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_time*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.getIOError() == 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) {
//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) {
_setState(HLSStates.BUFFERING);
}
} else if (_state == HLSStates.BUFFERING) {
_setState(HLSStates.PLAYING);
}
};
/** 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):void {
_buffer = _buffer.slice(_buffer_current_index);
_buffer_current_index = 0;
if (_playback_start_pts == Number.NEGATIVE_INFINITY) {
_playback_start_pts = min_pts;
_playlist_start_pts = _loader.getPlayListStartPTS();
_playback_start_time = (_playback_start_pts-_playlist_start_pts)/1000;
}
_buffer_last_pts = max_pts;
tags.sort(_sortTagsbyDTS);
for each (var t:Tag in tags) {
_buffer.push(t);
}
_buffer_next_time=_playback_start_time+(_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 = new NetStream(_connection);
_video.attachNetStream(_stream);
_stream.play(null);
_stream.soundTransform = _transform;
_stream.appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN);
_stream.appendBytes(FLV.getHeader());
seek(PlaybackStartPosition);
}
};
/** Toggle playback. **/
public function pause():void {
clearInterval(_interval);
if(_state == HLSStates.PAUSED) {
_setState(HLSStates.BUFFERING);
_stream.resume();
_interval = setInterval(_checkBuffer,100);
} else if(_state == HLSStates.PLAYING) {
_setState(HLSStates.PAUSED);
_stream.pause();
}
};
/** 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;
}
}
}
};
/** 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;
_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>;
/** NetConnection legacy stuff. **/
private var _connection:NetConnection;
/** 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;
/** Reference to the video object. **/
private var _video:Object;
/** Create the buffer. **/
public function Buffer(hls:HLS, loader:FragmentLoader, video:Object):void {
_hls = hls;
_loader = loader;
_video = video;
_hls.addEventListener(HLSEvent.MANIFEST,_manifestHandler);
_connection = new NetConnection();
_connection.connect(null);
_transform = new SoundTransform();
_transform.volume = 0.9;
_setState(HLSStates.IDLE);
};
/** Check the bufferlength. **/
private function _checkBuffer():void {
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.getIOError() == 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) {
//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) {
_setState(HLSStates.BUFFERING);
}
} else if (_state == HLSStates.BUFFERING) {
_setState(HLSStates.PLAYING);
}
};
/** 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):void {
// flush already injected Tags and restart index from 0
_buffer = _buffer.slice(_buffer_current_index);
_buffer_current_index = 0;
if (_playback_start_pts == Number.NEGATIVE_INFINITY) {
_playback_start_pts = min_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) {
_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 = new NetStream(_connection);
_video.attachNetStream(_stream);
_stream.play(null);
_stream.soundTransform = _transform;
_stream.appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN);
_stream.appendBytes(FLV.getHeader());
seek(PlaybackStartPosition);
}
};
/** Toggle playback. **/
public function pause():void {
clearInterval(_interval);
if(_state == HLSStates.PAUSED) {
_setState(HLSStates.BUFFERING);
_stream.resume();
_interval = setInterval(_checkBuffer,100);
} else if(_state == HLSStates.PLAYING) {
_setState(HLSStates.PAUSED);
_stream.pause();
}
};
/** 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;
}
}
}
};
/** 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;
_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;
}
};
}
}
|
rename variable for sake of clarity
|
rename variable for sake of clarity
|
ActionScript
|
mpl-2.0
|
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
|
d439e32db4f6b5bd440d8da4115eac4d815a248d
|
src/flash/src/Moxie.as
|
src/flash/src/Moxie.as
|
package
{
import com.*;
import com.errors.RuntimeError;
import com.events.*;
import flash.display.LoaderInfo;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.ProgressEvent;
import flash.external.ExternalInterface;
import flash.system.ApplicationDomain;
import flash.system.Security;
import flash.utils.*;
import mxi.Extend;
import mxi.Utils;
import mxi.events.ODataEvent;
import mxi.events.OErrorEvent;
import mxi.events.OProgressEvent;
[SWF(width='500', height='500')]
public class Moxie extends Sprite
{
public static var uid:String;
private var eventDispatcher:String = "moxie.core.EventTarget.instance.dispatchEvent";
public static var compFactory:ComponentFactory;
public static var stageOccupied:Boolean = false; // whether a display facility is already occupied
/**
* Main constructor for the Plupload class.
*/
public function Moxie()
{
if (stage) {
_init();
} else {
addEventListener(Event.ADDED_TO_STAGE, init);
}
}
/**
* Initialization event handler.
*
* @param e Event object.
*/
private function _init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, _init);
// Allow scripting on swf loaded from another domain
if (MXI::EnableCSS) {
Security.allowDomain("*");
}
// Align and scale stage
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.EXACT_FIT;
// use only FlashVars, ignore QueryString
var params:Object, url:String, urlParts:Object, pos:int, query:Object;
params = root.loaderInfo.parameters;
pos = root.loaderInfo.url.indexOf('?');
if (pos !== -1) {
return; // we do not allow anything from query sring, so if there's anything, we - quit
}
// Setup id
if (!params.hasOwnProperty("uid")) {
return; // we do not have uid, so we cannot fire error event - lets simply wait until it timeouts
}
Moxie.uid = Utils.sanitize(params["uid"]);
// Event dispatcher
if (params.hasOwnProperty("target") && /^[\w\.]+$/.test(params["target"])) {
eventDispatcher = params["target"];
}
//ExternalInterface.marshallExceptions = true; // propagate AS exceptions to JS and vice-versa
ExternalInterface.addCallback('exec', exec);
ExternalInterface.addCallback('isOccupied', isOccupied);
// initialize component factory
Moxie.compFactory = new ComponentFactory;
_fireEvent(Moxie.uid + "::Init");
}
public function exec(uid:String, compName:String, action:String, args:* = null) : *
{
// Moxie.log([uid, compName, action, args]);
uid = Utils.sanitize(uid); // make it safe
var comp:* = Moxie.compFactory.get(uid);
// Moxie.log([compName, action]);
try {
// initialize corresponding com
if (!comp) {
comp = Moxie.compFactory.create(this, uid, compName);
}
// execute the action if available
if (comp.hasOwnProperty(action)) {
return comp[action].apply(comp, args as Array);
}
} catch(err:*) { // re-route exceptions thrown by components (TODO: check marshallExceptions feature)
_fireEvent(Moxie.uid + "::Exception", {
name: err.name,
code: err.errorID,
message: compName + "::" + action
});
}
}
public function isOccupied() : Boolean {
return Moxie.stageOccupied;
}
/**
* Intercept component events and do some operations if required
*
* @param uid String unique identifier of the component throwing the event
* @param e mixed Event object
* @param exType String event type in mOxie format
*/
public function onComponentEvent(uid:String, e:*, exType:String) : void
{
var evt:Object = {};
var data:* = e.hasOwnProperty('data') ? e.data : null;
switch (e.type)
{
case ProgressEvent.PROGRESS:
case OProgressEvent.PROGRESS:
evt.loaded = e.bytesLoaded;
evt.total = e.bytesTotal;
break;
case OErrorEvent.ERROR:
data = e.code;
break;
}
evt.type = [uid, exType].join('::');
_fireEvent(evt, data);
}
/**
* Fires an event from the flash movie out to the page level JS.
*
* @param uid String unique identifier of the component throwing the event
* @param type Name of event to fire.
* @param obj Object with optional data.
*/
private function _fireEvent(evt:*, obj:* = null):void {
try {
ExternalInterface.call(eventDispatcher, evt, obj);
} catch(err:*) {
//_fireEvent("Exception", { name: 'RuntimeError', message: 4 });
// throwing an exception would be better here
}
}
public static function log(obj:*) : void {
ExternalInterface.call('console.info', obj);
}
}
}
|
package
{
import com.*;
import com.errors.RuntimeError;
import com.events.*;
import flash.display.LoaderInfo;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.ProgressEvent;
import flash.external.ExternalInterface;
import flash.system.ApplicationDomain;
import flash.system.Security;
import flash.utils.*;
import mxi.Extend;
import mxi.Utils;
import mxi.events.ODataEvent;
import mxi.events.OErrorEvent;
import mxi.events.OProgressEvent;
[SWF(width='500', height='500')]
public class Moxie extends Sprite
{
public static var uid:String;
private var eventDispatcher:String = "moxie.core.EventTarget.instance.dispatchEvent";
public static var compFactory:ComponentFactory;
public static var stageOccupied:Boolean = false; // whether a display facility is already occupied
/**
* Main constructor for the Plupload class.
*/
public function Moxie()
{
if (stage) {
_init();
} else {
addEventListener(Event.ADDED_TO_STAGE, init);
}
}
/**
* Initialization event handler.
*
* @param e Event object.
*/
private function _init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, _init);
// Allow scripting on swf loaded from another domain
if (MXI::EnableCSS) {
Security.allowDomain("*");
}
// Align and scale stage
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.EXACT_FIT;
// use only FlashVars, ignore QueryString
var params:Object = root.loaderInfo.parameters;
var url:String = root.loaderInfo.url;
var pos:int = url.indexOf('?');
if (pos !== -1 && !/^\?[\d\.ab]+$/.test(url.substr(pos))) {
return; // we do not allow anything from query sring, except the version (for caching purposes)
}
// Setup id
if (!params.hasOwnProperty("uid")) {
return; // we do not have uid, so we cannot fire error event - lets simply wait until it timeouts
}
Moxie.uid = Utils.sanitize(params["uid"]);
// Event dispatcher
if (params.hasOwnProperty("target") && /^[\w\.]+$/.test(params["target"])) {
eventDispatcher = params["target"];
}
//ExternalInterface.marshallExceptions = true; // propagate AS exceptions to JS and vice-versa
ExternalInterface.addCallback('exec', exec);
ExternalInterface.addCallback('isOccupied', isOccupied);
// initialize component factory
Moxie.compFactory = new ComponentFactory;
_fireEvent(Moxie.uid + "::Init");
}
public function exec(uid:String, compName:String, action:String, args:* = null) : *
{
// Moxie.log([uid, compName, action, args]);
uid = Utils.sanitize(uid); // make it safe
var comp:* = Moxie.compFactory.get(uid);
// Moxie.log([compName, action]);
try {
// initialize corresponding com
if (!comp) {
comp = Moxie.compFactory.create(this, uid, compName);
}
// execute the action if available
if (comp.hasOwnProperty(action)) {
return comp[action].apply(comp, args as Array);
}
} catch(err:*) { // re-route exceptions thrown by components (TODO: check marshallExceptions feature)
_fireEvent(Moxie.uid + "::Exception", {
name: err.name,
code: err.errorID,
message: compName + "::" + action
});
}
}
public function isOccupied() : Boolean {
return Moxie.stageOccupied;
}
/**
* Intercept component events and do some operations if required
*
* @param uid String unique identifier of the component throwing the event
* @param e mixed Event object
* @param exType String event type in mOxie format
*/
public function onComponentEvent(uid:String, e:*, exType:String) : void
{
var evt:Object = {};
var data:* = e.hasOwnProperty('data') ? e.data : null;
switch (e.type)
{
case ProgressEvent.PROGRESS:
case OProgressEvent.PROGRESS:
evt.loaded = e.bytesLoaded;
evt.total = e.bytesTotal;
break;
case OErrorEvent.ERROR:
data = e.code;
break;
}
evt.type = [uid, exType].join('::');
_fireEvent(evt, data);
}
/**
* Fires an event from the flash movie out to the page level JS.
*
* @param uid String unique identifier of the component throwing the event
* @param type Name of event to fire.
* @param obj Object with optional data.
*/
private function _fireEvent(evt:*, obj:* = null):void {
try {
ExternalInterface.call(eventDispatcher, evt, obj);
} catch(err:*) {
//_fireEvent("Exception", { name: 'RuntimeError', message: 4 });
// throwing an exception would be better here
}
}
public static function log(obj:*) : void {
ExternalInterface.call('console.info', obj);
}
}
}
|
Allow (only) version or timestamp in swf url.
|
Flash: Allow (only) version or timestamp in swf url.
|
ActionScript
|
agpl-3.0
|
moxiecode/moxie,moxiecode/moxie,moxiecode/moxie,moxiecode/moxie
|
c927d0cd15813e5f296a30b7b91ac330fd690469
|
src/com/merlinds/miracle_tool/controllers/PublishCommand.as
|
src/com/merlinds/miracle_tool/controllers/PublishCommand.as
|
/**
* User: MerlinDS
* Date: 18.07.2014
* Time: 15:14
*/
package com.merlinds.miracle_tool.controllers {
import com.merlinds.debug.log;
import com.merlinds.miracle.geom.Transformation;
import com.merlinds.miracle_tool.events.ActionEvent;
import com.merlinds.miracle_tool.events.DialogEvent;
import com.merlinds.miracle_tool.models.ProjectModel;
import com.merlinds.miracle_tool.models.vo.AnimationVO;
import com.merlinds.miracle_tool.models.vo.ElementVO;
import com.merlinds.miracle_tool.models.vo.FrameVO;
import com.merlinds.miracle_tool.models.vo.SourceVO;
import com.merlinds.miracle_tool.models.vo.TimelineVO;
import com.merlinds.miracle_tool.services.ActionService;
import com.merlinds.miracle_tool.services.FileSystemService;
import com.merlinds.miracle_tool.utils.MeshUtils;
import com.merlinds.unitls.Resolutions;
import flash.display.BitmapData;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.utils.ByteArray;
import org.robotlegs.mvcs.Command;
public class PublishCommand extends Command {
[Inject]
public var projectModel:ProjectModel;
[Inject]
public var fileSystemService:FileSystemService;
[Inject]
public var actionService:ActionService;
[Inject]
public var event:ActionEvent;
private var _mesh:ByteArray;
private var _png:ByteArray;
private var _animations:ByteArray;
private var _scale:Number;
private var _elements:Object;
//==============================================================================
//{region PUBLIC METHODS
public function PublishCommand() {
super();
}
override public function execute():void {
log(this, "execute");
if(event.body == null){
var data:Object = {
projectName:this.projectModel.name
};
this.actionService.addAcceptActions(new <String>[ActionEvent.PUBLISHING]);
this.dispatch(new DialogEvent(DialogEvent.PUBLISH_SETTINGS, data));
}else{
var projectName:String = event.body.projectName;
_scale = Resolutions.width(this.projectModel.targetResolution) /
Resolutions.width(this.projectModel.referenceResolution);
this.createOutput();
this.fileSystemService.writeTexture(projectName, _png, _mesh);
this.fileSystemService.writeAnimation(_animations);
}
}
//} endregion PUBLIC METHODS ===================================================
//==============================================================================
//{region PRIVATE\PROTECTED METHODS
private function createOutput():void{
var buffer:BitmapData = new BitmapData(this.projectModel.outputSize, this.projectModel.outputSize, true, 0x0);
_elements = {};
var meshes:Array = [];
var animations:Array = [];
var n:int = this.projectModel.sources.length;
for(var i:int = 0; i < n; i++){
var mesh:Array = [];
var source:SourceVO = this.projectModel.sources[i];
var m:int = source.elements.length;
for(var j:int = 0; j < m; j++){
//push element view to buffer
var element:ElementVO = source.elements[j];
var depth:Point = new Point(element.x + this.projectModel.boundsOffset,
element.y + this.projectModel.boundsOffset);
buffer.copyPixels(element.bitmapData, element.bitmapData.rect, depth);
//get mesh
mesh.push({
name:element.name,
vertexes:MeshUtils.flipToY(element.vertexes),
uv:MeshUtils.covertToRelative(element.uv, this.projectModel.outputSize),
indexes:element.indexes
});
//save mesh bounds to buffer for animation bounds calculation
_elements[element.name] = element.vertexes;
}
meshes.push({name:source.clearName, mesh:mesh});
//get animation
m = source.animations.length;
for(j = 0; j < m; j++){
var animation:Object = this.createAnimationOutput(source.animations[j], source.clearName);
animations.push(animation);
}
}
trace("mesh");
var json:String = JSON.stringify(meshes);
trace(json);
_mesh = new ByteArray();
_mesh.writeObject(meshes);
_png = PNGEncoder.encode(buffer);
_animations = new ByteArray();
_animations.writeObject(animations);
}
private function createAnimationOutput(animationVO:AnimationVO, meshPrefix:String):Object {
var data:Object = { name:meshPrefix + "." + animationVO.name,// name of the matrix
totalFrames:animationVO.totalFrames,// Total animation frames
layers:[]};
//scale bounds
var bounds:Rectangle = animationVO.bounds.clone();
bounds.x = bounds.x * _scale;
bounds.y = bounds.y * _scale;
bounds.width = bounds.width * _scale;
bounds.height = bounds.height * _scale;
data.bounds = bounds;
//calculate frames
var n:int = animationVO.timelines.length;
//find matrix sequence for current animation
for(var i:int = 0; i < n; i++){
var timelineVO:TimelineVO = animationVO.timelines[i];
var m:int = timelineVO.frames.length;
var layer:Layer = new Layer();
for(var j:int = 0; j < m; j++){
var frameVO:FrameVO = timelineVO.frames[j];
//create matrix
var transform:Transformation = frameVO.generateTransform(_scale,
//get previous frame transformation object
layer.matrixList.length > 0 ? layer.matrixList[ layer.matrixList.length - 1] : null
);
var index:int = transform == null ? -1 : layer.matrixList.push(transform) - 1;
var framesArray:Array = this.createFramesInfo(index, frameVO.name,
frameVO.duration, frameVO.type == "motion");
layer.framesList = layer.framesList.concat(framesArray);
}
data.layers.unshift(layer);
}
trace(JSON.stringify(data));
return data;
}
[Inline]
private function createFramesInfo(index:int, polygonName:String,
duration:int, motion:Boolean):Array {
var result:Array = new Array(duration);
if(duration < 2){
motion = false;
}
if(index > -1){
var t:Number = 1 / duration;
for(var i:int = 0; i < duration; i++){
var frameInfoData:FrameInfoData = new FrameInfoData();
frameInfoData.index = index;
frameInfoData.polygonName = polygonName;
frameInfoData.motion = motion;
frameInfoData.t = motion ? t * i : 0;
result[i] = frameInfoData;
}
}
return result;
}
//} endregion PRIVATE\PROTECTED METHODS ========================================
//==============================================================================
//{region EVENTS HANDLERS
//} endregion EVENTS HANDLERS ==================================================
//==============================================================================
//{region GETTERS/SETTERS
//} endregion GETTERS/SETTERS ==================================================
}
}
class Layer{
public var matrixList:Array;
public var framesList:Array;
public function Layer() {
this.framesList = [];
this.matrixList = [];
}
}
class FrameInfoData{
public var polygonName:String;
public var motion:Boolean;
public var index:int;
public var t:Number;
}
|
/**
* User: MerlinDS
* Date: 18.07.2014
* Time: 15:14
*/
package com.merlinds.miracle_tool.controllers {
import com.merlinds.debug.log;
import com.merlinds.miracle.geom.Transformation;
import com.merlinds.miracle_tool.events.ActionEvent;
import com.merlinds.miracle_tool.events.DialogEvent;
import com.merlinds.miracle_tool.models.ProjectModel;
import com.merlinds.miracle_tool.models.vo.AnimationVO;
import com.merlinds.miracle_tool.models.vo.ElementVO;
import com.merlinds.miracle_tool.models.vo.FrameVO;
import com.merlinds.miracle_tool.models.vo.SourceVO;
import com.merlinds.miracle_tool.models.vo.TimelineVO;
import com.merlinds.miracle_tool.services.ActionService;
import com.merlinds.miracle_tool.services.FileSystemService;
import com.merlinds.miracle_tool.utils.MeshUtils;
import com.merlinds.unitls.Resolutions;
import flash.display.BitmapData;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.utils.ByteArray;
import org.robotlegs.mvcs.Command;
public class PublishCommand extends Command {
[Inject]
public var projectModel:ProjectModel;
[Inject]
public var fileSystemService:FileSystemService;
[Inject]
public var actionService:ActionService;
[Inject]
public var event:ActionEvent;
private var _mesh:ByteArray;
private var _png:ByteArray;
private var _animations:ByteArray;
private var _scale:Number;
private var _elements:Object;
//==============================================================================
//{region PUBLIC METHODS
public function PublishCommand() {
super();
}
override public function execute():void {
log(this, "execute");
if(event.body == null){
var data:Object = {
projectName:this.projectModel.name
};
this.actionService.addAcceptActions(new <String>[ActionEvent.PUBLISHING]);
this.dispatch(new DialogEvent(DialogEvent.PUBLISH_SETTINGS, data));
}else{
var projectName:String = event.body.projectName;
_scale = Resolutions.width(this.projectModel.targetResolution) /
Resolutions.width(this.projectModel.referenceResolution);
this.createOutput();
this.fileSystemService.writeTexture(projectName, _png, _mesh);
this.fileSystemService.writeAnimation(_animations);
}
}
//} endregion PUBLIC METHODS ===================================================
//==============================================================================
//{region PRIVATE\PROTECTED METHODS
private function createOutput():void{
var buffer:BitmapData = new BitmapData(this.projectModel.outputSize, this.projectModel.outputSize, true, 0x0);
_elements = {};
var meshes:Array = [];
var animations:Array = [];
var n:int = this.projectModel.sources.length;
for(var i:int = 0; i < n; i++){
var mesh:Array = [];
var source:SourceVO = this.projectModel.sources[i];
var m:int = source.elements.length;
for(var j:int = 0; j < m; j++){
//push element view to buffer
var element:ElementVO = source.elements[j];
var depth:Point = new Point(element.x + this.projectModel.boundsOffset,
element.y + this.projectModel.boundsOffset);
buffer.copyPixels(element.bitmapData, element.bitmapData.rect, depth);
//get mesh
mesh.push({
name:element.name,
vertexes:MeshUtils.flipToY(element.vertexes),
uv:MeshUtils.covertToRelative(element.uv, this.projectModel.outputSize),
indexes:element.indexes
});
//save mesh bounds to buffer for animation bounds calculation
_elements[element.name] = element.vertexes;
}
meshes.push({name:source.clearName, mesh:mesh});
//get animation
m = source.animations.length;
for(j = 0; j < m; j++){
var animation:Object = this.createAnimationOutput(source.animations[j], source.clearName);
animations.push(animation);
}
}
trace("mesh");
var json:String = JSON.stringify(meshes);
trace(json);
_mesh = new ByteArray();
_mesh.writeObject(meshes);
_animations = new ByteArray();
_animations.writeObject(animations);
_animations.position = 0;
var test:Object = _animations.readObject();
_png = PNGEncoder.encode(buffer);
}
private function createAnimationOutput(animationVO:AnimationVO, meshPrefix:String):Object {
var data:Object = { name:meshPrefix + "." + animationVO.name,// name of the matrix
totalFrames:animationVO.totalFrames,// Total animation frames
layers:[]};
//scale bounds
var bounds:Rectangle = animationVO.bounds.clone();
bounds.x = bounds.x * _scale;
bounds.y = bounds.y * _scale;
bounds.width = bounds.width * _scale;
bounds.height = bounds.height * _scale;
data.bounds = bounds;
//calculate frames
var n:int = animationVO.timelines.length;
//find matrix sequence for current animation
for(var i:int = 0; i < n; i++){
var timelineVO:TimelineVO = animationVO.timelines[i];
var m:int = timelineVO.frames.length;
var layer:Layer = new Layer();
for(var j:int = 0; j < m; j++){
var frameVO:FrameVO = timelineVO.frames[j];
//create matrix
var transform:Transformation = frameVO.generateTransform(_scale,
//get previous frame transformation object
layer.matrixList.length > 0 ? layer.matrixList[ layer.matrixList.length - 1] : null
);
var index:int = transform == null ? -1 : layer.matrixList.push(transform) - 1;
var framesArray:Array = this.createFramesInfo(index, frameVO.name,
frameVO.duration, frameVO.type == "motion");
layer.framesList = layer.framesList.concat(framesArray);
}
data.layers.unshift(layer);
}
return data;
}
[Inline]
private function createFramesInfo(index:int, polygonName:String,
duration:int, motion:Boolean):Array {
var result:Array = new Array(duration);
if(duration < 2){
motion = false;
}
if(index > -1){
var t:Number = 1 / duration;
for(var i:int = 0; i < duration; i++){
var frameInfoData:FrameInfoData = new FrameInfoData();
frameInfoData.index = index;
frameInfoData.polygonName = polygonName;
frameInfoData.motion = motion;
frameInfoData.t = motion ? t * i : 0;
result[i] = frameInfoData;
}
}
return result;
}
//} endregion PRIVATE\PROTECTED METHODS ========================================
//==============================================================================
//{region EVENTS HANDLERS
//} endregion EVENTS HANDLERS ==================================================
//==============================================================================
//{region GETTERS/SETTERS
//} endregion GETTERS/SETTERS ==================================================
}
}
class Layer{
public var matrixList:Array;
public var framesList:Array;
public function Layer() {
this.framesList = [];
this.matrixList = [];
}
}
class FrameInfoData{
public var polygonName:String;
public var motion:Boolean;
public var index:int;
public var t:Number;
}
|
Add gestouch extension for miracle
|
Add gestouch extension for miracle
|
ActionScript
|
mit
|
MerlinDS/miracle_tool
|
1b86755aa733415d6ef5e63fb0635c2b27839abb
|
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 : Effect = 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,
effect : Effect = null,
...controllers)
{
super();
initialize(geometry, material, effect, controllers);
}
private function initialize(geometry : Geometry,
material : Material,
effect : Effect,
controllers : Array) : void
{
_bindings = new DataBindings(this);
this.properties = new DataProvider(properties, 'meshProperties', DataProviderUsage.EXCLUSIVE);
_geometry = geometry;
this.material = material || new BasicMaterial();
// _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 : Effect = 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 || new BasicMaterial();
// _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);
}
}
}
|
remove deprecated effect : Effect argument in Mesh constructor and Mesh.initialize()
|
remove deprecated effect : Effect argument in Mesh constructor and Mesh.initialize()
|
ActionScript
|
mit
|
aerys/minko-as3
|
10ce4a34926945f40defb226dd3c34f6bb52b12a
|
tamarin-central/thane/as3src/flash/utils/Timer.as
|
tamarin-central/thane/as3src/flash/utils/Timer.as
|
//
// $Id: $
package flash.utils {
import flash.events.EventDispatcher;
import flash.events.TimerEvent;
import de.polygonal.ds.Heap;
public class Timer extends EventDispatcher
{
public function Timer (delay :Number, repeatCount :int = 0)
{
if (_heap == null) {
_heap = new Heap(10000, compareTimers);
Thane.requestHeartbeat(heartbeat);
}
_delay = delay;
_repeatCount = repeatCount;
reset();
}
public function get currentCount () :int
{
return _currentCount;
}
public function get delay () :Number
{
return _delay;
}
public function set delay (value :Number) :void
{
_delay = value;
if (running) {
stop();
start();
}
}
public function get repeatCount () :int
{
return _repeatCount;
}
public function get running () :Boolean
{
return _buddy != null;
}
public function start () :void
{
if (_buddy != null) {
return;
}
enqueue(new Buddy(this, getTimer() + _delay));
}
public function stop () :void
{
// cut any current enqueued buddy adrift
if (_buddy != null) {
_buddy.budette = null;
_buddy = null;
}
}
public function reset () :void
{
stop();
_currentCount = 0;
}
protected function expire (buddy :Buddy) :void
{
if (buddy !== _buddy) {
// the timer was stopped since this buddy was enqueued
return;
}
_currentCount ++;
dispatchEvent(new TimerEvent(TimerEvent.TIMER));
if (_buddy == null) {
// the timer was stopped in the TIMER event itself - do not requeue!
return;
}
if (repeatCount == 0 || _currentCount < _repeatCount) {
buddy.expiration += _delay;
enqueue(buddy);
} else {
dispatchEvent(new TimerEvent(TimerEvent.TIMER_COMPLETE));
_buddy = null;
}
}
private function enqueue (buddy :Buddy) :void
{
_buddy = buddy;
if (_heap.enqueue(_buddy)) {
return;
}
// TODO: formalize this as a quota rather than an implementation deficiency?
throw new Error("Too many simultaneous running flash.utils.Timer objects");
}
private static function compareTimers (a :Buddy, b :Buddy) :int
{
// b-a rather than a-b so as to order low values before high
return b.expiration - a.expiration;
}
protected static function heartbeat () :void
{
var now :int = getTimer();
while (_heap.size > 0 && _heap.front.expiration <= now) {
var buddy :Buddy = _heap.dequeue();
if (buddy.budette != null) {
buddy.budette.expire(buddy);
}
}
}
static function createTimer (closure :Function, delay :Number,
timeout :Boolean, args :Array) :uint
{
var timer :Timer = new Timer(delay, timeout ? 1 : 0);
var thisIx = _timerIx;
var fun :Function = function (event :TimerEvent) :void {
if (timeout) {
destroyTimer(thisIx);
}
closure.apply(null, args);
};
timer.addEventListener(TimerEvent.TIMER, fun);
_timers[_timerIx] = [ timer, fun ];
timer.start();
return _timerIx ++;
}
static 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];
}
}
private var _currentCount :int;
private var _delay :Number;
private var _repeatCount :int;
private var _buddy :Buddy;
private static var _heap :Heap;
private static var _timers :Dictionary = new Dictionary();
private static var _timerIx :uint = 1;
}
}
import flash.utils.Timer;
class Buddy {
public var budette :Timer;
public var expiration :int;
public function Buddy (timer :Timer, expiration :int)
{
this.budette = timer;
this.expiration = expiration;
}
}
|
//
// $Id: $
package flash.utils {
import flash.events.EventDispatcher;
import flash.events.TimerEvent;
import de.polygonal.ds.Heap;
public class Timer extends EventDispatcher
{
public function Timer (delay :Number, repeatCount :int = 0)
{
if (_heap == null) {
_heap = new Heap(10000, compareTimers);
Thane.requestHeartbeat(heartbeat);
}
_delay = delay;
_repeatCount = repeatCount;
reset();
}
public function get currentCount () :int
{
return _currentCount;
}
public function get delay () :Number
{
return _delay;
}
public function set delay (value :Number) :void
{
_delay = value;
if (running) {
stop();
start();
}
}
public function get repeatCount () :int
{
return _repeatCount;
}
public function get running () :Boolean
{
return _buddy != null;
}
public function start () :void
{
if (_buddy != null) {
return;
}
scheduleBuddy(new Buddy(this));
}
public function stop () :void
{
// cut any current enqueued buddy adrift
if (_buddy != null) {
_buddy.budette = null;
_buddy = null;
}
}
public function reset () :void
{
stop();
_currentCount = 0;
}
protected function expire (buddy :Buddy) :void
{
if (buddy !== _buddy) {
// the timer was stopped since this buddy was enqueued
return;
}
_currentCount ++;
dispatchEvent(new TimerEvent(TimerEvent.TIMER));
if (_buddy == null) {
// the timer was stopped in the TIMER event itself - do not requeue!
return;
}
if (repeatCount == 0 || _currentCount < _repeatCount) {
scheduleBuddy(buddy);
} else {
dispatchEvent(new TimerEvent(TimerEvent.TIMER_COMPLETE));
_buddy = null;
}
}
private function scheduleBuddy (buddy :Buddy) :void
{
_buddy = buddy;
_buddy.expiration = getTimer() + Math.max(_delay, 5);
if (_heap.enqueue(_buddy)) {
return;
}
// TODO: formalize this as a quota rather than an implementation deficiency?
throw new Error("Too many simultaneous running flash.utils.Timer objects");
}
private static function compareTimers (a :Buddy, b :Buddy) :int
{
// b-a rather than a-b so as to order low values before high
return b.expiration - a.expiration;
}
protected static function heartbeat () :void
{
var now :int = getTimer();
// see if we should pop one timer off the queue and expire it; we could pop all the
// outstanding ones, but this solution puts the onus on developers to make their event
// handlers light-weight, and protects the socket code from starvation
if (_heap.size > 0 && _heap.front.expiration <= now) {
var buddy :Buddy = _heap.dequeue();
if (buddy.budette != null) {
buddy.budette.expire(buddy);
}
}
}
static function createTimer (closure :Function, delay :Number,
timeout :Boolean, args :Array) :uint
{
var timer :Timer = new Timer(delay, timeout ? 1 : 0);
var thisIx = _timerIx;
var fun :Function = function (event :TimerEvent) :void {
if (timeout) {
destroyTimer(thisIx);
}
closure.apply(null, args);
};
timer.addEventListener(TimerEvent.TIMER, fun);
_timers[_timerIx] = [ timer, fun ];
timer.start();
return _timerIx ++;
}
static 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];
}
}
private var _currentCount :int;
private var _delay :Number;
private var _repeatCount :int;
private var _buddy :Buddy;
private static var _heap :Heap;
private static var _timers :Dictionary = new Dictionary();
private static var _timerIx :uint = 1;
}
}
import flash.utils.Timer;
import flash.utils.getTimer;
class Buddy {
public var budette :Timer;
public var expiration :int;
public function Buddy (timer :Timer)
{
this.budette = timer;
}
}
|
Tweak the Timer implementation: first, schedule repeat expiration based on the current time, not when the timer was supposed to go off. Second, make 5 ms the minimum actual delay used on a timer. Third, Only pop one timer event off the queue in any Thane heartbeat. This last change is somewhere between audacious and questionable; it will definitely help prevent e.g. socket starvation and keep programmers honest. On the other hand it sacrifices some (admittedly bizarre) scenarios where multiple timers ought to fire simultaneously.
|
Tweak the Timer implementation: first, schedule repeat expiration based on the current time, not when the timer was supposed to go off. Second, make 5 ms the minimum actual delay used on a timer. Third, Only pop one timer event off the queue in any Thane heartbeat. This last change is somewhere between audacious and questionable; it will definitely help prevent e.g. socket starvation and keep programmers honest. On the other hand it sacrifices some (admittedly bizarre) scenarios where multiple timers ought to fire simultaneously.
|
ActionScript
|
bsd-2-clause
|
greyhavens/thane,greyhavens/thane,greyhavens/thane,greyhavens/thane,greyhavens/thane,greyhavens/thane,greyhavens/thane
|
ebcd3092126282266478ee0ddf83802fb0f6b8d5
|
examples/web/app/classes/server/FMSBridge.as
|
examples/web/app/classes/server/FMSBridge.as
|
package server {
import flash.events.EventDispatcher;
import flash.events.NetStatusEvent;
import flash.events.Event;
import flash.net.Responder;
public final class FMSBridge extends EventDispatcher {
public var connection:FMSConnection;
public var client:FMSClient;
public function FMSBridge(rtmpAddress:String = null, ...rest) {
connection = new FMSConnection();
connection.client = client = new FMSClient();
rtmpAddress && connect.apply(this, [rtmpAddress].concat(rest));
}
public function connect(rtmpAddress:String, ...rest):void {
connection.connect.apply(this, [rtmpAddress].concat(rest));
}
public function dispose():void {
connection.dispose();
}
public function close():void {
connection.close();
}
public function registerUser(token:String, email:String, player:String):void {
connection.call('registerUser', null, token, email, player);
}
public function signinUser(token:String):void {
connection.call('signinUser', null, token);
}
public function changePlayer(player:uint):void {
connection.call('changePlayer', null, player);
}
public function startGame():void {
connection.call('startGame', null);
}
public function updateScore(score:uint):void {
connection.call('updateScore', null, score);
}
}
}
|
package server {
import flash.events.EventDispatcher;
import flash.events.NetStatusEvent;
import flash.events.Event;
import flash.net.Responder;
public final class FMSBridge extends EventDispatcher {
public var connection:FMSConnection;
public var client:FMSClient;
public function FMSBridge(rtmpAddress:String = null, ...rest) {
connection = new FMSConnection();
connection.client = client = new FMSClient();
rtmpAddress && connect.apply(this, [rtmpAddress].concat(rest));
}
public function connect(rtmpAddress:String, ...rest):void {
connection.connect.apply(this, [rtmpAddress].concat(rest));
}
public function dispose():void {
connection.dispose();
}
public function close():void {
connection.close();
}
public function registerUser(token:String, email:String, player:uint):void {
connection.call('registerUser', null, token, email, player);
}
public function signinUser(token:String):void {
connection.call('signinUser', null, token);
}
public function changePlayer(player:uint):void {
connection.call('changePlayer', null, player);
}
public function startGame():void {
connection.call('startGame', null);
}
public function updateScore(score:uint):void {
connection.call('updateScore', null, score);
}
}
}
|
Update FMSBridge.as
|
Update FMSBridge.as
|
ActionScript
|
apache-2.0
|
adriancmiranda/flash-compiler,adriancmiranda/flash-compiler,adriancmiranda/flash-compiler,adriancmiranda/flash-compiler,adriancmiranda/flash-compiler,adriancmiranda/flash-compiler,adriancmiranda/flash-compiler,adriancmiranda/flash-compiler
|
d16a40bb3f1739a1858c08f1c461d8015ba8c2a4
|
src/aerys/minko/scene/controller/TransformController.as
|
src/aerys/minko/scene/controller/TransformController.as
|
package aerys.minko.scene.controller
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.Viewport;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.math.Matrix4x4;
import flash.display.BitmapData;
import flash.utils.Dictionary;
import mx.olap.aggregators.MaxAggregator;
use namespace minko_math;
/**
* The TransformController handles the batched update of all the local to world matrices
* of a sub-scene. As such, it will only be active on the root node of a sub-scene and will
* automatically disable itself on other nodes.
*
* @author Jean-Marc Le Roux
*
*/
public final class TransformController extends AbstractController
{
private static const INIT_NONE : uint = 0;
private static const INIT_LOCAL_TO_WORLD : uint = 1;
private static const INIT_WORLD_TO_LOCAL : uint = 2;
private var _target : ISceneNode;
private var _invalidList : Boolean;
private var _nodeToId : Dictionary;
private var _idToNode : Vector.<ISceneNode>
private var _transforms : Vector.<Matrix4x4>;
private var _initialized : Vector.<uint>;
private var _localToWorldTransforms : Vector.<Matrix4x4>;
private var _worldToLocalTransforms : Vector.<Matrix4x4>;
private var _numChildren : Vector.<uint>;
private var _firstChildId : Vector.<uint>;
private var _parentId : Vector.<int>;
public function TransformController()
{
super();
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function renderingBeginHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : Number) : void
{
if (_invalidList)
updateTransformsList();
if (_transforms.length)
updateLocalToWorld();
}
private function updateLocalToWorld(nodeId : uint = 0, subtreeOnly : Boolean = false) : void
{
var numNodes : uint = _transforms.length;
var childrenOffset : uint = 1;
var rootLocalToWorld : Matrix4x4 = _localToWorldTransforms[nodeId];
var rootTransform : Matrix4x4 = _transforms[nodeId];
var root : ISceneNode = _idToNode[childId];
var subtreeMax : uint = nodeId;
if (rootTransform._hasChanged || _initialized[nodeId] == INIT_NONE)
{
rootLocalToWorld.copyFrom(rootTransform);
if (nodeId != 0)
rootLocalToWorld.append(_localToWorldTransforms[_parentId[nodeId]]);
rootTransform._hasChanged = false;
_initialized[nodeId] = INIT_LOCAL_TO_WORLD;
root.localToWorldTransformChanged.execute(root, rootLocalToWorld);
}
if (lastChildId > subtreeMax)
subtreeMax = lastChildId;
while (nodeId < numNodes)
{
var localToWorld : Matrix4x4 = _localToWorldTransforms[nodeId];
var numChildren : uint = _numChildren[nodeId];
var firstChildId : uint = _firstChildId[nodeId];
var lastChildId : uint = firstChildId + numChildren;
var isDirty : Boolean = localToWorld._hasChanged;
localToWorld._hasChanged = false;
for (var childId : uint = firstChildId; childId < lastChildId; ++childId)
{
var childTransform : Matrix4x4 = _transforms[childId];
var childLocalToWorld : Matrix4x4 = _localToWorldTransforms[childId];
var childIsDirty : Boolean = isDirty || childTransform._hasChanged
|| !_initialized[childId];
if (childIsDirty)
{
var child : ISceneNode = _idToNode[childId];
childLocalToWorld
.copyFrom(childTransform)
.append(localToWorld);
childTransform._hasChanged = false;
_initialized[childId] = INIT_LOCAL_TO_WORLD;
child.localToWorldTransformChanged.execute(child, childLocalToWorld);
}
}
if (subtreeOnly && nodeId && nodeId >= subtreeMax)
{
var parentId : uint = _parentId[nodeId];
nodeId = _firstChildId[parentId];
while (!_numChildren[nodeId] && nodeId < subtreeMax)
++nodeId;
if (nodeId >= subtreeMax)
return ;
nodeId = _firstChildId[nodeId];
}
else
++nodeId;
}
}
private function updateAncestorsAndSelfLocalToWorld(nodeId : int) : void
{
var dirtyRoot : int = -1;
while (nodeId >= 0)
{
if ((_transforms[nodeId] as Matrix4x4)._hasChanged || !_initialized[nodeId])
dirtyRoot = nodeId;
nodeId = _parentId[nodeId];
}
if (dirtyRoot >= 0)
updateLocalToWorld(dirtyRoot, true);
}
private function targetAddedHandler(ctrl : TransformController,
target : ISceneNode) : void
{
if (_target)
throw new Error('The TransformController cannot have more than one target.');
_target = target;
_invalidList = true;
if (target is Scene)
{
(target as Scene).renderingBegin.add(renderingBeginHandler);
return;
}
if (target is Group)
{
var targetGroup : Group = target as Group;
targetGroup.descendantAdded.add(descendantAddedHandler);
targetGroup.descendantRemoved.add(descendantRemovedHandler);
}
target.added.add(addedHandler);
}
private function targetRemovedHandler(ctrl : TransformController,
target : ISceneNode) : void
{
target.added.remove(addedHandler);
if (target is Group)
{
var targetGroup : Group = target as Group;
targetGroup.descendantAdded.remove(descendantAddedHandler);
targetGroup.descendantRemoved.remove(descendantRemovedHandler);
}
_invalidList = false;
_target = null;
_nodeToId = null;
_transforms = null;
_initialized = null;
_localToWorldTransforms = null;
_worldToLocalTransforms = null;
_numChildren = null;
_idToNode = null;
_parentId = null;
}
private function addedHandler(target : ISceneNode, ancestor : Group) : void
{
// the controller will remove itself from the node when it's not its own root anymore
// but it will watch for the 'removed' signal to add itself back if the node becomes
// its own root again
_target.removed.add(removedHandler);
_target.removeController(this);
}
private function removedHandler(target : ISceneNode, ancestor : Group) : void
{
if (target.root == target)
{
target.removed.remove(removedHandler);
target.addController(this);
}
}
private function descendantAddedHandler(root : Group,
descendant : ISceneNode) : void
{
_invalidList = true;
}
private function descendantRemovedHandler(root : Group,
descendant : ISceneNode) : void
{
_invalidList = true;
}
private function updateTransformsList() : void
{
var root : ISceneNode = _target.root;
var nodes : Vector.<ISceneNode> = new <ISceneNode>[root];
var nodeId : uint = 0;
var oldNodeToId : Dictionary = _nodeToId;
var oldInitialized : Vector.<uint> = _initialized;
var oldLocalToWorldTransforms : Vector.<Matrix4x4> = _localToWorldTransforms;
var oldWorldToLocalTransform : Vector.<Matrix4x4> = _worldToLocalTransforms;
_nodeToId = new Dictionary(true);
_transforms = new <Matrix4x4>[];
_initialized = new <uint>[];
_localToWorldTransforms = new <Matrix4x4>[];
_worldToLocalTransforms = new <Matrix4x4>[];
_numChildren = new <uint>[];
_firstChildId = new <uint>[];
_idToNode = new <ISceneNode>[];
_parentId = new <int>[-1];
while (nodes.length)
{
var node : ISceneNode = nodes.shift();
var group : Group = node as Group;
_nodeToId[node] = nodeId;
_idToNode[nodeId] = node;
_transforms[nodeId] = node.transform;
if (oldNodeToId && node in oldNodeToId)
{
var oldNodeId : uint = oldNodeToId[node];
_localToWorldTransforms[nodeId] = oldLocalToWorldTransforms[oldNodeId];
_worldToLocalTransforms[nodeId] = oldWorldToLocalTransform[oldNodeId];
_initialized[nodeId] = oldInitialized[oldNodeId];
}
else
{
_localToWorldTransforms[nodeId] = new Matrix4x4().lock();
_worldToLocalTransforms[nodeId] = null;
_initialized[nodeId] = INIT_NONE;
}
if (group)
{
var numChildren : uint = group.numChildren;
var firstChildId : uint = nodeId + nodes.length + 1;
_numChildren[nodeId] = numChildren;
_firstChildId[nodeId] = firstChildId;
for (var childId : uint = 0; childId < numChildren; ++childId)
{
_parentId[uint(firstChildId + childId)] = nodeId;
nodes.push(group.getChildAt(childId));
}
}
else
{
_numChildren[nodeId] = 0;
_firstChildId[nodeId] = 0;
}
++nodeId;
}
_worldToLocalTransforms.length = _localToWorldTransforms.length;
_invalidList = false;
}
public function getLocalToWorldTransform(node : ISceneNode,
forceUpdate : Boolean = false) : Matrix4x4
{
if (_invalidList || _nodeToId[node] == undefined)
updateTransformsList();
var nodeId : uint = _nodeToId[node];
if (forceUpdate)
updateAncestorsAndSelfLocalToWorld(nodeId);
return _localToWorldTransforms[nodeId];
}
public function getWorldToLocalTransform(node : ISceneNode,
forceUpdate : Boolean = false) : Matrix4x4
{
if (_invalidList || _nodeToId[node] == undefined)
updateTransformsList();
var nodeId : uint = _nodeToId[node];
var worldToLocalTransform : Matrix4x4 = _worldToLocalTransforms[nodeId];
if (!worldToLocalTransform)
{
_worldToLocalTransforms[nodeId] = worldToLocalTransform = new Matrix4x4();
if (!forceUpdate)
{
worldToLocalTransform.copyFrom(_localToWorldTransforms[nodeId]).invert();
_initialized[nodeId] |= INIT_WORLD_TO_LOCAL;
}
}
if (forceUpdate)
updateAncestorsAndSelfLocalToWorld(nodeId);
if (!(_initialized[nodeId] & INIT_WORLD_TO_LOCAL))
{
_initialized[nodeId] |= INIT_WORLD_TO_LOCAL;
worldToLocalTransform
.copyFrom(_localToWorldTransforms[nodeId])
.invert();
}
return worldToLocalTransform;
}
}
}
|
package aerys.minko.scene.controller
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.Viewport;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.math.Matrix4x4;
import flash.display.BitmapData;
import flash.utils.Dictionary;
import mx.olap.aggregators.MaxAggregator;
use namespace minko_math;
/**
* The TransformController handles the batched update of all the local to world matrices
* of a sub-scene. As such, it will only be active on the root node of a sub-scene and will
* automatically disable itself on other nodes.
*
* @author Jean-Marc Le Roux
*
*/
public final class TransformController extends AbstractController
{
private static const INIT_NONE : uint = 0;
private static const INIT_LOCAL_TO_WORLD : uint = 1;
private static const INIT_WORLD_TO_LOCAL : uint = 2;
private var _target : ISceneNode;
private var _invalidList : Boolean;
private var _nodeToId : Dictionary;
private var _idToNode : Vector.<ISceneNode>
private var _transforms : Vector.<Matrix4x4>;
private var _initialized : Vector.<uint>;
private var _localToWorldTransforms : Vector.<Matrix4x4>;
private var _worldToLocalTransforms : Vector.<Matrix4x4>;
private var _numChildren : Vector.<uint>;
private var _firstChildId : Vector.<uint>;
private var _parentId : Vector.<int>;
public function TransformController()
{
super();
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function renderingBeginHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : Number) : void
{
if (_invalidList)
updateTransformsList();
if (_transforms.length)
updateLocalToWorld();
}
private function updateLocalToWorld(nodeId : uint = 0, subtreeOnly : Boolean = false) : void
{
var numNodes : uint = _transforms.length;
var childrenOffset : uint = 1;
var rootLocalToWorld : Matrix4x4 = _localToWorldTransforms[nodeId];
var rootTransform : Matrix4x4 = _transforms[nodeId];
var root : ISceneNode = _idToNode[nodeId];
var subtreeMax : uint = nodeId;
if (rootTransform._hasChanged || _initialized[nodeId] == INIT_NONE)
{
rootLocalToWorld.copyFrom(rootTransform);
if (nodeId != 0)
rootLocalToWorld.append(_localToWorldTransforms[_parentId[nodeId]]);
rootTransform._hasChanged = false;
_initialized[nodeId] = INIT_LOCAL_TO_WORLD;
root.localToWorldTransformChanged.execute(root, rootLocalToWorld);
}
if (lastChildId > subtreeMax)
subtreeMax = lastChildId;
while (nodeId < numNodes)
{
var localToWorld : Matrix4x4 = _localToWorldTransforms[nodeId];
var numChildren : uint = _numChildren[nodeId];
var firstChildId : uint = _firstChildId[nodeId];
var lastChildId : uint = firstChildId + numChildren;
var isDirty : Boolean = localToWorld._hasChanged;
localToWorld._hasChanged = false;
for (var childId : uint = firstChildId; childId < lastChildId; ++childId)
{
var childTransform : Matrix4x4 = _transforms[childId];
var childLocalToWorld : Matrix4x4 = _localToWorldTransforms[childId];
var childIsDirty : Boolean = isDirty || childTransform._hasChanged
|| !_initialized[childId];
if (childIsDirty)
{
var child : ISceneNode = _idToNode[childId];
childLocalToWorld
.copyFrom(childTransform)
.append(localToWorld);
childTransform._hasChanged = false;
_initialized[childId] = INIT_LOCAL_TO_WORLD;
child.localToWorldTransformChanged.execute(child, childLocalToWorld);
}
}
if (subtreeOnly && nodeId && nodeId >= subtreeMax)
{
var parentId : uint = _parentId[nodeId];
nodeId = _firstChildId[parentId];
while (!_numChildren[nodeId] && nodeId < subtreeMax)
++nodeId;
if (nodeId >= subtreeMax)
return ;
nodeId = _firstChildId[nodeId];
}
else
++nodeId;
}
}
private function updateAncestorsAndSelfLocalToWorld(nodeId : int) : void
{
var dirtyRoot : int = -1;
while (nodeId >= 0)
{
if ((_transforms[nodeId] as Matrix4x4)._hasChanged || !_initialized[nodeId])
dirtyRoot = nodeId;
nodeId = _parentId[nodeId];
}
if (dirtyRoot >= 0)
updateLocalToWorld(dirtyRoot, true);
}
private function targetAddedHandler(ctrl : TransformController,
target : ISceneNode) : void
{
if (_target)
throw new Error('The TransformController cannot have more than one target.');
_target = target;
_invalidList = true;
if (target is Scene)
{
(target as Scene).renderingBegin.add(renderingBeginHandler);
return;
}
if (target is Group)
{
var targetGroup : Group = target as Group;
targetGroup.descendantAdded.add(descendantAddedHandler);
targetGroup.descendantRemoved.add(descendantRemovedHandler);
}
target.added.add(addedHandler);
}
private function targetRemovedHandler(ctrl : TransformController,
target : ISceneNode) : void
{
target.added.remove(addedHandler);
if (target is Group)
{
var targetGroup : Group = target as Group;
targetGroup.descendantAdded.remove(descendantAddedHandler);
targetGroup.descendantRemoved.remove(descendantRemovedHandler);
}
_invalidList = false;
_target = null;
_nodeToId = null;
_transforms = null;
_initialized = null;
_localToWorldTransforms = null;
_worldToLocalTransforms = null;
_numChildren = null;
_idToNode = null;
_parentId = null;
}
private function addedHandler(target : ISceneNode, ancestor : Group) : void
{
// the controller will remove itself from the node when it's not its own root anymore
// but it will watch for the 'removed' signal to add itself back if the node becomes
// its own root again
_target.removed.add(removedHandler);
_target.removeController(this);
}
private function removedHandler(target : ISceneNode, ancestor : Group) : void
{
if (target.root == target)
{
target.removed.remove(removedHandler);
target.addController(this);
}
}
private function descendantAddedHandler(root : Group,
descendant : ISceneNode) : void
{
_invalidList = true;
}
private function descendantRemovedHandler(root : Group,
descendant : ISceneNode) : void
{
_invalidList = true;
}
private function updateTransformsList() : void
{
var root : ISceneNode = _target.root;
var nodes : Vector.<ISceneNode> = new <ISceneNode>[root];
var nodeId : uint = 0;
var oldNodeToId : Dictionary = _nodeToId;
var oldInitialized : Vector.<uint> = _initialized;
var oldLocalToWorldTransforms : Vector.<Matrix4x4> = _localToWorldTransforms;
var oldWorldToLocalTransform : Vector.<Matrix4x4> = _worldToLocalTransforms;
_nodeToId = new Dictionary(true);
_transforms = new <Matrix4x4>[];
_initialized = new <uint>[];
_localToWorldTransforms = new <Matrix4x4>[];
_worldToLocalTransforms = new <Matrix4x4>[];
_numChildren = new <uint>[];
_firstChildId = new <uint>[];
_idToNode = new <ISceneNode>[];
_parentId = new <int>[-1];
while (nodes.length)
{
var node : ISceneNode = nodes.shift();
var group : Group = node as Group;
_nodeToId[node] = nodeId;
_idToNode[nodeId] = node;
_transforms[nodeId] = node.transform;
if (oldNodeToId && node in oldNodeToId)
{
var oldNodeId : uint = oldNodeToId[node];
_localToWorldTransforms[nodeId] = oldLocalToWorldTransforms[oldNodeId];
_worldToLocalTransforms[nodeId] = oldWorldToLocalTransform[oldNodeId];
_initialized[nodeId] = oldInitialized[oldNodeId];
}
else
{
_localToWorldTransforms[nodeId] = new Matrix4x4().lock();
_worldToLocalTransforms[nodeId] = null;
_initialized[nodeId] = INIT_NONE;
}
if (group)
{
var numChildren : uint = group.numChildren;
var firstChildId : uint = nodeId + nodes.length + 1;
_numChildren[nodeId] = numChildren;
_firstChildId[nodeId] = firstChildId;
for (var childId : uint = 0; childId < numChildren; ++childId)
{
_parentId[uint(firstChildId + childId)] = nodeId;
nodes.push(group.getChildAt(childId));
}
}
else
{
_numChildren[nodeId] = 0;
_firstChildId[nodeId] = 0;
}
++nodeId;
}
_worldToLocalTransforms.length = _localToWorldTransforms.length;
_invalidList = false;
}
public function getLocalToWorldTransform(node : ISceneNode,
forceUpdate : Boolean = false) : Matrix4x4
{
if (_invalidList || _nodeToId[node] == undefined)
updateTransformsList();
var nodeId : uint = _nodeToId[node];
if (forceUpdate)
updateAncestorsAndSelfLocalToWorld(nodeId);
return _localToWorldTransforms[nodeId];
}
public function getWorldToLocalTransform(node : ISceneNode,
forceUpdate : Boolean = false) : Matrix4x4
{
if (_invalidList || _nodeToId[node] == undefined)
updateTransformsList();
var nodeId : uint = _nodeToId[node];
var worldToLocalTransform : Matrix4x4 = _worldToLocalTransforms[nodeId];
if (!worldToLocalTransform)
{
_worldToLocalTransforms[nodeId] = worldToLocalTransform = new Matrix4x4();
if (!forceUpdate)
{
worldToLocalTransform.copyFrom(_localToWorldTransforms[nodeId]).invert();
_initialized[nodeId] |= INIT_WORLD_TO_LOCAL;
}
}
if (forceUpdate)
updateAncestorsAndSelfLocalToWorld(nodeId);
if (!(_initialized[nodeId] & INIT_WORLD_TO_LOCAL))
{
_initialized[nodeId] |= INIT_WORLD_TO_LOCAL;
worldToLocalTransform
.copyFrom(_localToWorldTransforms[nodeId])
.invert();
}
return worldToLocalTransform;
}
}
}
|
fix TransformController.updateLocalToWorld() init. of root to _idToNode[nodeId] instead of _idToNode[childId]
|
fix TransformController.updateLocalToWorld() init. of root to _idToNode[nodeId] instead of _idToNode[childId]
|
ActionScript
|
mit
|
aerys/minko-as3
|
b85d020ba519ce95fb2496a65aa6d59ed81bd999
|
swfcat.as
|
swfcat.as
|
package
{
import flash.display.Sprite;
import flash.text.TextField;
import flash.net.Socket;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.utils.ByteArray;
import flash.utils.setTimeout;
public class swfcat extends Sprite
{
/* David's relay (nickname 3VXRyxz67OeRoqHn) that also serves a
crossdomain policy. */
private const DEFAULT_TOR_ADDR:Object = {
host: "173.255.221.44",
port: 9001
};
// Milliseconds.
private const FACILITATOR_POLL_INTERVAL:int = 10000;
// Socket to facilitator.
private var s_f:Socket;
private var output_text:TextField;
private var fac_addr:Object;
public function puts(s:String):void
{
output_text.appendText(s + "\n");
output_text.scrollV = output_text.maxScrollV;
}
public function swfcat()
{
output_text = new TextField();
output_text.width = 400;
output_text.height = 300;
output_text.background = true;
output_text.backgroundColor = 0x001f0f;
output_text.textColor = 0x44CC44;
addChild(output_text);
puts("Starting.");
// Wait until the query string parameters are loaded.
this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete);
}
private function loaderinfo_complete(e:Event):void
{
var fac_spec:String;
puts("Parameters loaded.");
fac_spec = this.loaderInfo.parameters["facilitator"];
if (!fac_spec) {
puts("Error: no \"facilitator\" specification provided.");
return;
}
puts("Facilitator spec: \"" + fac_spec + "\"");
fac_addr = parse_addr_spec(fac_spec);
if (!fac_addr) {
puts("Error: Facilitator spec must be in the form \"host:port\".");
return;
}
main();
}
/* The main logic begins here, after start-up issues are taken care of. */
private function main():void
{
s_f = new Socket();
s_f.addEventListener(Event.CONNECT, fac_connected);
s_f.addEventListener(Event.CLOSE, function (e:Event):void {
puts("Facilitator: closed connection.");
setTimeout(main, FACILITATOR_POLL_INTERVAL);
});
s_f.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("Facilitator: I/O error: " + e.text + ".");
});
s_f.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Facilitator: security error: " + e.text + ".");
});
puts("Facilitator: connecting to " + fac_addr.host + ":" + fac_addr.port + ".");
s_f.connect(fac_addr.host, fac_addr.port);
}
private function fac_connected(e:Event):void
{
puts("Facilitator: connected.");
s_f.addEventListener(ProgressEvent.SOCKET_DATA, fac_data);
s_f.writeUTFBytes("GET / HTTP/1.0\r\n\r\n");
}
private function fac_data(e:ProgressEvent):void
{
var client_spec:String;
var client_addr:Object;
var proxy_pair:Object;
client_spec = s_f.readMultiByte(e.bytesLoaded, "utf-8");
puts("Facilitator: got \"" + client_spec + "\"");
client_addr = parse_addr_spec(client_spec);
if (!client_addr) {
puts("Error: Client spec must be in the form \"host:port\".");
return;
}
if (client_addr.host == "0.0.0.0" && client_addr.port == 0) {
puts("Error: Facilitator has no clients.");
return;
}
proxy_pair = new ProxyPair(this, client_addr, DEFAULT_TOR_ADDR);
proxy_pair.connect();
}
/* Parse an address in the form "host:port". Returns an Object with
keys "host" (String) and "port" (int). Returns null on error. */
private static function parse_addr_spec(spec:String):Object
{
var parts:Array;
var addr:Object;
parts = spec.split(":", 2);
if (parts.length != 2 || !parseInt(parts[1]))
return null;
addr = {}
addr.host = parts[0];
addr.port = parseInt(parts[1]);
return addr;
}
}
}
import flash.display.Sprite;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.Socket;
import flash.utils.ByteArray;
/* An instance of a client-relay connection. */
class ProxyPair
{
// Address ({host, port}) of client.
private var addr_c:Object;
// Address ({host, port}) of relay.
private var addr_r:Object;
// Socket to client.
private var s_c:Socket;
// Socket to relay.
private var s_r:Socket;
// Parent swfcat, for UI updates.
private var ui:swfcat;
private function log(msg:String):void
{
ui.puts(id() + ": " + msg)
}
// String describing this pair for output.
private function id():String
{
return "<" + this.addr_c.host + ":" + this.addr_c.port +
"," + this.addr_r.host + ":" + this.addr_r.port + ">";
}
public function ProxyPair(ui:swfcat, addr_c:Object, addr_r:Object)
{
this.ui = ui;
this.addr_c = addr_c;
this.addr_r = addr_r;
}
public function connect():void
{
s_r = new Socket();
s_r.addEventListener(Event.CONNECT, tor_connected);
s_r.addEventListener(Event.CLOSE, function (e:Event):void {
log("Tor: closed.");
if (s_c.connected)
s_c.close();
});
s_r.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
log("Tor: I/O error: " + e.text + ".");
if (s_c.connected)
s_c.close();
});
s_r.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
log("Tor: security error: " + e.text + ".");
if (s_c.connected)
s_c.close();
});
log("Tor: connecting to " + addr_r.host + ":" + addr_r.port + ".");
s_r.connect(addr_r.host, addr_r.port);
}
private function tor_connected(e:Event):void
{
log("Tor: connected.");
s_c = new Socket();
s_c.addEventListener(Event.CONNECT, client_connected);
s_c.addEventListener(Event.CLOSE, function (e:Event):void {
log("Client: closed.");
if (s_r.connected)
s_r.close();
});
s_c.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
log("Client: I/O error: " + e.text + ".");
if (s_r.connected)
s_r.close();
});
s_c.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
log("Client: security error: " + e.text + ".");
if (s_r.connected)
s_r.close();
});
log("Client: connecting to " + addr_c.host + ":" + addr_c.port + ".");
s_c.connect(addr_c.host, addr_c.port);
}
private function client_connected(e:Event):void
{
log("Client: connected.");
s_r.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
var bytes:ByteArray = new ByteArray();
s_r.readBytes(bytes, 0, e.bytesLoaded);
log("Tor: read " + bytes.length + ".");
s_c.writeBytes(bytes);
});
s_c.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
var bytes:ByteArray = new ByteArray();
s_c.readBytes(bytes, 0, e.bytesLoaded);
log("Client: read " + bytes.length + ".");
s_r.writeBytes(bytes);
});
}
}
|
package
{
import flash.display.Sprite;
import flash.text.TextField;
import flash.net.Socket;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.utils.ByteArray;
import flash.utils.setTimeout;
public class swfcat extends Sprite
{
/* David's bridge (nickname eRYaZuvY02FpExln) that also serves a
crossdomain policy. */
private const DEFAULT_TOR_ADDR:Object = {
// host: "173.255.221.44", 3VXRyxz67OeRoqHn
host: "69.164.193.231",
port: 9001
};
// Milliseconds.
private const FACILITATOR_POLL_INTERVAL:int = 10000;
// Socket to facilitator.
private var s_f:Socket;
private var output_text:TextField;
private var fac_addr:Object;
public function puts(s:String):void
{
output_text.appendText(s + "\n");
output_text.scrollV = output_text.maxScrollV;
}
public function swfcat()
{
output_text = new TextField();
output_text.width = 400;
output_text.height = 300;
output_text.background = true;
output_text.backgroundColor = 0x001f0f;
output_text.textColor = 0x44CC44;
addChild(output_text);
puts("Starting.");
// Wait until the query string parameters are loaded.
this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete);
}
private function loaderinfo_complete(e:Event):void
{
var fac_spec:String;
puts("Parameters loaded.");
fac_spec = this.loaderInfo.parameters["facilitator"];
if (!fac_spec) {
puts("Error: no \"facilitator\" specification provided.");
return;
}
puts("Facilitator spec: \"" + fac_spec + "\"");
fac_addr = parse_addr_spec(fac_spec);
if (!fac_addr) {
puts("Error: Facilitator spec must be in the form \"host:port\".");
return;
}
main();
}
/* The main logic begins here, after start-up issues are taken care of. */
private function main():void
{
s_f = new Socket();
s_f.addEventListener(Event.CONNECT, fac_connected);
s_f.addEventListener(Event.CLOSE, function (e:Event):void {
puts("Facilitator: closed connection.");
setTimeout(main, FACILITATOR_POLL_INTERVAL);
});
s_f.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("Facilitator: I/O error: " + e.text + ".");
});
s_f.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Facilitator: security error: " + e.text + ".");
});
puts("Facilitator: connecting to " + fac_addr.host + ":" + fac_addr.port + ".");
s_f.connect(fac_addr.host, fac_addr.port);
}
private function fac_connected(e:Event):void
{
puts("Facilitator: connected.");
s_f.addEventListener(ProgressEvent.SOCKET_DATA, fac_data);
s_f.writeUTFBytes("GET / HTTP/1.0\r\n\r\n");
}
private function fac_data(e:ProgressEvent):void
{
var client_spec:String;
var client_addr:Object;
var proxy_pair:Object;
client_spec = s_f.readMultiByte(e.bytesLoaded, "utf-8");
puts("Facilitator: got \"" + client_spec + "\"");
client_addr = parse_addr_spec(client_spec);
if (!client_addr) {
puts("Error: Client spec must be in the form \"host:port\".");
return;
}
if (client_addr.host == "0.0.0.0" && client_addr.port == 0) {
puts("Error: Facilitator has no clients.");
return;
}
proxy_pair = new ProxyPair(this, client_addr, DEFAULT_TOR_ADDR);
proxy_pair.connect();
}
/* Parse an address in the form "host:port". Returns an Object with
keys "host" (String) and "port" (int). Returns null on error. */
private static function parse_addr_spec(spec:String):Object
{
var parts:Array;
var addr:Object;
parts = spec.split(":", 2);
if (parts.length != 2 || !parseInt(parts[1]))
return null;
addr = {}
addr.host = parts[0];
addr.port = parseInt(parts[1]);
return addr;
}
}
}
import flash.display.Sprite;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.Socket;
import flash.utils.ByteArray;
/* An instance of a client-relay connection. */
class ProxyPair
{
// Address ({host, port}) of client.
private var addr_c:Object;
// Address ({host, port}) of relay.
private var addr_r:Object;
// Socket to client.
private var s_c:Socket;
// Socket to relay.
private var s_r:Socket;
// Parent swfcat, for UI updates.
private var ui:swfcat;
private function log(msg:String):void
{
ui.puts(id() + ": " + msg)
}
// String describing this pair for output.
private function id():String
{
return "<" + this.addr_c.host + ":" + this.addr_c.port +
"," + this.addr_r.host + ":" + this.addr_r.port + ">";
}
public function ProxyPair(ui:swfcat, addr_c:Object, addr_r:Object)
{
this.ui = ui;
this.addr_c = addr_c;
this.addr_r = addr_r;
}
public function connect():void
{
s_r = new Socket();
s_r.addEventListener(Event.CONNECT, tor_connected);
s_r.addEventListener(Event.CLOSE, function (e:Event):void {
log("Tor: closed.");
if (s_c.connected)
s_c.close();
});
s_r.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
log("Tor: I/O error: " + e.text + ".");
if (s_c.connected)
s_c.close();
});
s_r.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
log("Tor: security error: " + e.text + ".");
if (s_c.connected)
s_c.close();
});
log("Tor: connecting to " + addr_r.host + ":" + addr_r.port + ".");
s_r.connect(addr_r.host, addr_r.port);
}
private function tor_connected(e:Event):void
{
log("Tor: connected.");
s_c = new Socket();
s_c.addEventListener(Event.CONNECT, client_connected);
s_c.addEventListener(Event.CLOSE, function (e:Event):void {
log("Client: closed.");
if (s_r.connected)
s_r.close();
});
s_c.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
log("Client: I/O error: " + e.text + ".");
if (s_r.connected)
s_r.close();
});
s_c.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
log("Client: security error: " + e.text + ".");
if (s_r.connected)
s_r.close();
});
log("Client: connecting to " + addr_c.host + ":" + addr_c.port + ".");
s_c.connect(addr_c.host, addr_c.port);
}
private function client_connected(e:Event):void
{
log("Client: connected.");
s_r.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
var bytes:ByteArray = new ByteArray();
s_r.readBytes(bytes, 0, e.bytesLoaded);
log("Tor: read " + bytes.length + ".");
s_c.writeBytes(bytes);
});
s_c.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
var bytes:ByteArray = new ByteArray();
s_c.readBytes(bytes, 0, e.bytesLoaded);
log("Client: read " + bytes.length + ".");
s_r.writeBytes(bytes);
});
}
}
|
Change to my bridge instead of my relay.
|
Change to my bridge instead of my relay.
The relay started hibernating today; it seems that this causes it to
drop out of the directory consensus and the Tor client doesn't want to
reconnect to it.
|
ActionScript
|
mit
|
arlolra/flashproxy,infinity0/flashproxy,infinity0/flashproxy,infinity0/flashproxy,arlolra/flashproxy,glamrock/flashproxy,glamrock/flashproxy,arlolra/flashproxy,infinity0/flashproxy,glamrock/flashproxy,infinity0/flashproxy,infinity0/flashproxy,arlolra/flashproxy,glamrock/flashproxy,arlolra/flashproxy,glamrock/flashproxy,arlolra/flashproxy,arlolra/flashproxy,glamrock/flashproxy
|
f0683bc243d7ee7bd31308203ceac0f127e779df
|
swfcat.as
|
swfcat.as
|
package
{
import flash.display.Sprite;
import flash.text.TextField;
import flash.net.Socket;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.utils.ByteArray;
import flash.utils.setTimeout;
public class swfcat extends Sprite
{
/* David's relay (nickname 3VXRyxz67OeRoqHn) that also serves a
crossdomain policy. */
private const DEFAULT_TOR_ADDR:Object = {
host: "173.255.221.44",
port: 9001
};
// Milliseconds.
private const FACILITATOR_POLL_INTERVAL:int = 1000;
// Socket to facilitator.
private var s_f:Socket;
private var output_text:TextField;
private var fac_addr:Object;
public function puts(s:String):void
{
output_text.appendText(s + "\n");
output_text.scrollV = output_text.maxScrollV;
}
public function swfcat()
{
output_text = new TextField();
output_text.width = 400;
output_text.height = 300;
output_text.background = true;
output_text.backgroundColor = 0x001f0f;
output_text.textColor = 0x44CC44;
addChild(output_text);
puts("Starting.");
// Wait until the query string parameters are loaded.
this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete);
}
private function loaderinfo_complete(e:Event):void
{
var fac_spec:String;
puts("Parameters loaded.");
fac_spec = this.loaderInfo.parameters["facilitator"];
if (!fac_spec) {
puts("Error: no \"facilitator\" specification provided.");
return;
}
puts("Facilitator spec: \"" + fac_spec + "\"");
fac_addr = parse_addr_spec(fac_spec);
if (!fac_addr) {
puts("Error: Facilitator spec must be in the form \"host:port\".");
return;
}
main();
}
/* The main logic begins here, after start-up issues are taken care of. */
private function main():void
{
s_f = new Socket();
s_f.addEventListener(Event.CONNECT, fac_connected);
s_f.addEventListener(Event.CLOSE, function (e:Event):void {
puts("Facilitator: closed connection.");
setTimeout(main, FACILITATOR_POLL_INTERVAL);
});
s_f.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("Facilitator: I/O error: " + e.text + ".");
});
s_f.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Facilitator: security error: " + e.text + ".");
});
puts("Facilitator: connecting to " + fac_addr.host + ":" + fac_addr.port + ".");
s_f.connect(fac_addr.host, fac_addr.port);
}
private function fac_connected(e:Event):void
{
puts("Facilitator: connected.");
s_f.addEventListener(ProgressEvent.SOCKET_DATA, fac_data);
s_f.writeUTFBytes("GET / HTTP/1.0\r\n\r\n");
}
private function fac_data(e:ProgressEvent):void
{
var client_spec:String;
var client_addr:Object;
var proxy_pair:Object;
client_spec = s_f.readMultiByte(e.bytesLoaded, "utf-8");
puts("Facilitator: got \"" + client_spec + "\"");
client_addr = parse_addr_spec(client_spec);
if (!client_addr) {
puts("Error: Client spec must be in the form \"host:port\".");
return;
}
if (client_addr.host == "0.0.0.0" && client_addr.port == 0) {
puts("Error: Facilitator has no clients.");
return;
}
proxy_pair = new ProxyPair(this, client_addr, DEFAULT_TOR_ADDR);
proxy_pair.connect();
}
/* Parse an address in the form "host:port". Returns an Object with
keys "host" (String) and "port" (int). Returns null on error. */
private static function parse_addr_spec(spec:String):Object
{
var parts:Array;
var addr:Object;
parts = spec.split(":", 2);
if (parts.length != 2 || !parseInt(parts[1]))
return null;
addr = {}
addr.host = parts[0];
addr.port = parseInt(parts[1]);
return addr;
}
}
}
import flash.display.Sprite;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.Socket;
import flash.utils.ByteArray;
/* An instance of a client-relay connection. */
class ProxyPair
{
// Address ({host, port}) of client.
private var addr_c:Object;
// Address ({host, port}) of relay.
private var addr_r:Object;
// Socket to client.
private var s_c:Socket;
// Socket to relay.
private var s_r:Socket;
// Parent swfcat, for UI updates.
private var ui:swfcat;
private function log(msg:String):void
{
ui.puts(id() + ": " + msg)
}
// String describing this pair for output.
private function id():String
{
return "<" + this.addr_c.host + ":" + this.addr_c.port +
"," + this.addr_r.host + ":" + this.addr_r.port + ">";
}
public function ProxyPair(ui:swfcat, addr_c:Object, addr_r:Object)
{
this.ui = ui;
this.addr_c = addr_c;
this.addr_r = addr_r;
}
public function connect():void
{
s_r = new Socket();
s_r.addEventListener(Event.CONNECT, tor_connected);
s_r.addEventListener(Event.CLOSE, function (e:Event):void {
log("Tor: closed.");
if (s_c.connected)
s_c.close();
});
s_r.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
log("Tor: I/O error: " + e.text + ".");
if (s_c.connected)
s_c.close();
});
s_r.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
log("Tor: security error: " + e.text + ".");
if (s_c.connected)
s_c.close();
});
log("Tor: connecting to " + addr_r.host + ":" + addr_r.port + ".");
s_r.connect(addr_r.host, addr_r.port);
}
private function tor_connected(e:Event):void
{
log("Tor: connected.");
s_c = new Socket();
s_c.addEventListener(Event.CONNECT, client_connected);
s_c.addEventListener(Event.CLOSE, function (e:Event):void {
log("Client: closed.");
if (s_r.connected)
s_r.close();
});
s_c.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
log("Client: I/O error: " + e.text + ".");
if (s_r.connected)
s_r.close();
});
s_c.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
log("Client: security error: " + e.text + ".");
if (s_r.connected)
s_r.close();
});
log("Client: connecting to " + addr_c.host + ":" + addr_c.port + ".");
s_c.connect(addr_c.host, addr_c.port);
}
private function client_connected(e:Event):void
{
log("Client: connected.");
s_r.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
var bytes:ByteArray = new ByteArray();
s_r.readBytes(bytes, 0, e.bytesLoaded);
log("Tor: read " + bytes.length + ".");
s_c.writeBytes(bytes);
});
s_c.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
var bytes:ByteArray = new ByteArray();
s_c.readBytes(bytes, 0, e.bytesLoaded);
log("Client: read " + bytes.length + ".");
s_r.writeBytes(bytes);
});
}
}
|
package
{
import flash.display.Sprite;
import flash.text.TextField;
import flash.net.Socket;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.utils.ByteArray;
import flash.utils.setTimeout;
public class swfcat extends Sprite
{
/* David's relay (nickname 3VXRyxz67OeRoqHn) that also serves a
crossdomain policy. */
private const DEFAULT_TOR_ADDR:Object = {
host: "173.255.221.44",
port: 9001
};
// Milliseconds.
private const FACILITATOR_POLL_INTERVAL:int = 10000;
// Socket to facilitator.
private var s_f:Socket;
private var output_text:TextField;
private var fac_addr:Object;
public function puts(s:String):void
{
output_text.appendText(s + "\n");
output_text.scrollV = output_text.maxScrollV;
}
public function swfcat()
{
output_text = new TextField();
output_text.width = 400;
output_text.height = 300;
output_text.background = true;
output_text.backgroundColor = 0x001f0f;
output_text.textColor = 0x44CC44;
addChild(output_text);
puts("Starting.");
// Wait until the query string parameters are loaded.
this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete);
}
private function loaderinfo_complete(e:Event):void
{
var fac_spec:String;
puts("Parameters loaded.");
fac_spec = this.loaderInfo.parameters["facilitator"];
if (!fac_spec) {
puts("Error: no \"facilitator\" specification provided.");
return;
}
puts("Facilitator spec: \"" + fac_spec + "\"");
fac_addr = parse_addr_spec(fac_spec);
if (!fac_addr) {
puts("Error: Facilitator spec must be in the form \"host:port\".");
return;
}
main();
}
/* The main logic begins here, after start-up issues are taken care of. */
private function main():void
{
s_f = new Socket();
s_f.addEventListener(Event.CONNECT, fac_connected);
s_f.addEventListener(Event.CLOSE, function (e:Event):void {
puts("Facilitator: closed connection.");
setTimeout(main, FACILITATOR_POLL_INTERVAL);
});
s_f.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("Facilitator: I/O error: " + e.text + ".");
});
s_f.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Facilitator: security error: " + e.text + ".");
});
puts("Facilitator: connecting to " + fac_addr.host + ":" + fac_addr.port + ".");
s_f.connect(fac_addr.host, fac_addr.port);
}
private function fac_connected(e:Event):void
{
puts("Facilitator: connected.");
s_f.addEventListener(ProgressEvent.SOCKET_DATA, fac_data);
s_f.writeUTFBytes("GET / HTTP/1.0\r\n\r\n");
}
private function fac_data(e:ProgressEvent):void
{
var client_spec:String;
var client_addr:Object;
var proxy_pair:Object;
client_spec = s_f.readMultiByte(e.bytesLoaded, "utf-8");
puts("Facilitator: got \"" + client_spec + "\"");
client_addr = parse_addr_spec(client_spec);
if (!client_addr) {
puts("Error: Client spec must be in the form \"host:port\".");
return;
}
if (client_addr.host == "0.0.0.0" && client_addr.port == 0) {
puts("Error: Facilitator has no clients.");
return;
}
proxy_pair = new ProxyPair(this, client_addr, DEFAULT_TOR_ADDR);
proxy_pair.connect();
}
/* Parse an address in the form "host:port". Returns an Object with
keys "host" (String) and "port" (int). Returns null on error. */
private static function parse_addr_spec(spec:String):Object
{
var parts:Array;
var addr:Object;
parts = spec.split(":", 2);
if (parts.length != 2 || !parseInt(parts[1]))
return null;
addr = {}
addr.host = parts[0];
addr.port = parseInt(parts[1]);
return addr;
}
}
}
import flash.display.Sprite;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.Socket;
import flash.utils.ByteArray;
/* An instance of a client-relay connection. */
class ProxyPair
{
// Address ({host, port}) of client.
private var addr_c:Object;
// Address ({host, port}) of relay.
private var addr_r:Object;
// Socket to client.
private var s_c:Socket;
// Socket to relay.
private var s_r:Socket;
// Parent swfcat, for UI updates.
private var ui:swfcat;
private function log(msg:String):void
{
ui.puts(id() + ": " + msg)
}
// String describing this pair for output.
private function id():String
{
return "<" + this.addr_c.host + ":" + this.addr_c.port +
"," + this.addr_r.host + ":" + this.addr_r.port + ">";
}
public function ProxyPair(ui:swfcat, addr_c:Object, addr_r:Object)
{
this.ui = ui;
this.addr_c = addr_c;
this.addr_r = addr_r;
}
public function connect():void
{
s_r = new Socket();
s_r.addEventListener(Event.CONNECT, tor_connected);
s_r.addEventListener(Event.CLOSE, function (e:Event):void {
log("Tor: closed.");
if (s_c.connected)
s_c.close();
});
s_r.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
log("Tor: I/O error: " + e.text + ".");
if (s_c.connected)
s_c.close();
});
s_r.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
log("Tor: security error: " + e.text + ".");
if (s_c.connected)
s_c.close();
});
log("Tor: connecting to " + addr_r.host + ":" + addr_r.port + ".");
s_r.connect(addr_r.host, addr_r.port);
}
private function tor_connected(e:Event):void
{
log("Tor: connected.");
s_c = new Socket();
s_c.addEventListener(Event.CONNECT, client_connected);
s_c.addEventListener(Event.CLOSE, function (e:Event):void {
log("Client: closed.");
if (s_r.connected)
s_r.close();
});
s_c.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
log("Client: I/O error: " + e.text + ".");
if (s_r.connected)
s_r.close();
});
s_c.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
log("Client: security error: " + e.text + ".");
if (s_r.connected)
s_r.close();
});
log("Client: connecting to " + addr_c.host + ":" + addr_c.port + ".");
s_c.connect(addr_c.host, addr_c.port);
}
private function client_connected(e:Event):void
{
log("Client: connected.");
s_r.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
var bytes:ByteArray = new ByteArray();
s_r.readBytes(bytes, 0, e.bytesLoaded);
log("Tor: read " + bytes.length + ".");
s_c.writeBytes(bytes);
});
s_c.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
var bytes:ByteArray = new ByteArray();
s_c.readBytes(bytes, 0, e.bytesLoaded);
log("Client: read " + bytes.length + ".");
s_r.writeBytes(bytes);
});
}
}
|
Include FACILITATOR_POLL_INTERVAL to 10 s.
|
Include FACILITATOR_POLL_INTERVAL to 10 s.
|
ActionScript
|
mit
|
infinity0/flashproxy,infinity0/flashproxy,glamrock/flashproxy,arlolra/flashproxy,infinity0/flashproxy,infinity0/flashproxy,arlolra/flashproxy,glamrock/flashproxy,infinity0/flashproxy,arlolra/flashproxy,glamrock/flashproxy,arlolra/flashproxy,infinity0/flashproxy,arlolra/flashproxy,arlolra/flashproxy,glamrock/flashproxy,glamrock/flashproxy,arlolra/flashproxy,glamrock/flashproxy
|
7253a8b05498cc079f4f6e56bfa5740c8114f748
|
src/aerys/minko/scene/controller/TransformController.as
|
src/aerys/minko/scene/controller/TransformController.as
|
package aerys.minko.scene.controller
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.Viewport;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.math.Matrix4x4;
import flash.display.BitmapData;
import flash.utils.Dictionary;
use namespace minko_math;
/**
* The TransformController handles the batched update of all the local to world matrices
* of a sub-scene. As such, it will only be active on the root node of a sub-scene and will
* automatically disable itself on other nodes.
*
* @author Jean-Marc Le Roux
*
*/
public final class TransformController extends AbstractController
{
private var _target : ISceneNode;
private var _invalidList : Boolean;
private var _nodeToId : Dictionary;
private var _idToNode : Vector.<ISceneNode>
private var _transforms : Vector.<Matrix4x4>;
private var _localToWorldTransforms : Vector.<Matrix4x4>;
private var _numChildren : Vector.<uint>;
private var _firstChildId : Vector.<uint>
private var _parentId : Vector.<int>
public function TransformController()
{
super();
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function renderingBeginHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : Number) : void
{
if (_invalidList)
updateTransformsList();
if (_transforms.length)
{
var rootTransform : Matrix4x4 = _transforms[0];
var isDirty : Boolean = rootTransform._hasChanged;
if (isDirty)
{
_localToWorldTransforms[0].copyFrom(rootTransform);
rootTransform._hasChanged = false;
}
updateLocalToWorld();
}
}
private function updateLocalToWorld(nodeId : uint = 0) : void
{
var numNodes : uint = _transforms.length;
var childrenOffset : uint = 1;
var rootLocalToWorld : Matrix4x4 = _localToWorldTransforms[nodeId];
var rootTransform : Matrix4x4 = _transforms[nodeId];
var root : ISceneNode = _idToNode[childId];
if (rootTransform._hasChanged)
{
rootLocalToWorld.copyFrom(rootTransform);
if (nodeId != 0)
rootLocalToWorld.append(_transforms[_parentId]);
root.localToWorldTransformChanged.execute(root, rootLocalToWorld);
}
for (; nodeId < numNodes; ++nodeId)
{
var localToWorld : Matrix4x4 = _localToWorldTransforms[nodeId];
var numChildren : uint = _numChildren[nodeId];
var isDirty : Boolean = localToWorld._hasChanged;
var firstChildId : uint = _firstChildId[nodeId];
var lastChildId : uint = firstChildId + numChildren;
localToWorld._hasChanged = false;
for (var childId : uint = firstChildId; childId < lastChildId; ++childId)
{
var childTransform : Matrix4x4 = _transforms[childId];
var childLocalToWorld : Matrix4x4 = _localToWorldTransforms[childId];
var childIsDirty : Boolean = isDirty || childTransform._hasChanged;
if (childIsDirty)
{
var child : ISceneNode = _idToNode[childId];
childLocalToWorld
.copyFrom(childTransform)
.append(localToWorld);
childTransform._hasChanged = false;
child.localToWorldTransformChanged.execute(child, childLocalToWorld);
}
}
}
}
private function updateAncestorsAndSelfLocalToWorld(nodeId : int) : void
{
var dirtyRoot : int = nodeId;
while (nodeId >= 0)
{
if ((_transforms[nodeId] as Matrix4x4)._hasChanged)
dirtyRoot = nodeId;
nodeId = _parentId[nodeId];
}
if (dirtyRoot >= 0)
updateLocalToWorld(dirtyRoot);
}
private function targetAddedHandler(ctrl : TransformController,
target : ISceneNode) : void
{
if (_target)
throw new Error('The TransformController cannot have more than one target.');
_target = target;
_invalidList = true;
if (target is Scene)
{
(target as Scene).renderingBegin.add(renderingBeginHandler);
return;
}
if (target is Group)
{
var targetGroup : Group = target as Group;
targetGroup.descendantAdded.add(descendantAddedHandler);
targetGroup.descendantRemoved.add(descendantRemovedHandler);
}
target.added.add(addedHandler);
}
private function targetRemovedHandler(ctrl : TransformController,
target : ISceneNode) : void
{
target.added.remove(addedHandler);
if (target is Group)
{
var targetGroup : Group = target as Group;
targetGroup.descendantAdded.remove(descendantAddedHandler);
targetGroup.descendantRemoved.remove(descendantRemovedHandler);
}
_invalidList = false;
_target = null;
_nodeToId = null;
_transforms = null;
_localToWorldTransforms = null;
_numChildren = null;
_idToNode = null;
_parentId = null;
}
private function addedHandler(target : ISceneNode, ancestor : Group) : void
{
// the controller will remove itself from the node when it's not its own root anymore
// but it will watch for the 'removed' signal to add itself back if the node becomes
// its own root again
_target.removed.add(removedHandler);
_target.removeController(this);
}
private function removedHandler(target : ISceneNode, ancestor : Group) : void
{
if (target.root == target)
{
target.removed.remove(removedHandler);
target.addController(this);
}
}
private function descendantAddedHandler(root : Group,
descendant : ISceneNode) : void
{
_invalidList = true;
}
private function descendantRemovedHandler(root : Group,
descendant : ISceneNode) : void
{
_invalidList = true;
}
private function updateTransformsList() : void
{
var root : ISceneNode = _target.root;
var nodes : Vector.<ISceneNode> = new <ISceneNode>[root];
var nodeId : uint = 0;
_nodeToId = new Dictionary(true);
_transforms = new <Matrix4x4>[];
_localToWorldTransforms = new <Matrix4x4>[];
_numChildren = new <uint>[];
_firstChildId = new <uint>[];
_idToNode = new <ISceneNode>[];
_parentId = new <int>[-1];
while (nodes.length)
{
var node : ISceneNode = nodes.shift();
var group : Group = node as Group;
_nodeToId[node] = nodeId;
_idToNode[nodeId] = node;
_transforms[nodeId] = node.transform;
_localToWorldTransforms[nodeId] = new Matrix4x4().lock();
if (group)
{
var numChildren : uint = group.numChildren;
var firstChildId : uint = nodeId + nodes.length + 1;
_numChildren[nodeId] = numChildren;
_firstChildId[nodeId] = firstChildId;
for (var childId : uint = 0; childId < numChildren; ++childId)
{
_parentId[uint(firstChildId + childId)] = nodeId;
nodes.push(group.getChildAt(childId));
}
}
else
{
_numChildren[nodeId] = 0;
_firstChildId[nodeId] = 0;
}
++nodeId;
}
_invalidList = false;
}
public function getLocalToWorldTransform(node : ISceneNode,
forceUpdate : Boolean = false) : Matrix4x4
{
if (_invalidList || _nodeToId[node] == undefined)
updateTransformsList();
var nodeId : uint = _nodeToId[node];
if (forceUpdate)
updateAncestorsAndSelfLocalToWorld(nodeId);
return _localToWorldTransforms[nodeId];
}
}
}
|
package aerys.minko.scene.controller
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.Viewport;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.math.Matrix4x4;
import flash.display.BitmapData;
import flash.utils.Dictionary;
use namespace minko_math;
/**
* The TransformController handles the batched update of all the local to world matrices
* of a sub-scene. As such, it will only be active on the root node of a sub-scene and will
* automatically disable itself on other nodes.
*
* @author Jean-Marc Le Roux
*
*/
public final class TransformController extends AbstractController
{
private var _target : ISceneNode;
private var _invalidList : Boolean;
private var _nodeToId : Dictionary;
private var _idToNode : Vector.<ISceneNode>
private var _transforms : Vector.<Matrix4x4>;
private var _localToWorldTransforms : Vector.<Matrix4x4>;
private var _numChildren : Vector.<uint>;
private var _firstChildId : Vector.<uint>
private var _parentId : Vector.<int>
public function TransformController()
{
super();
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function renderingBeginHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : Number) : void
{
if (_invalidList)
updateTransformsList();
if (_transforms.length)
{
var rootTransform : Matrix4x4 = _transforms[0];
var isDirty : Boolean = rootTransform._hasChanged;
if (isDirty)
{
_localToWorldTransforms[0].copyFrom(rootTransform);
rootTransform._hasChanged = false;
}
updateLocalToWorld();
}
}
private function updateLocalToWorld(nodeId : uint = 0) : void
{
var numNodes : uint = _transforms.length;
var childrenOffset : uint = 1;
var rootLocalToWorld : Matrix4x4 = _localToWorldTransforms[nodeId];
var rootTransform : Matrix4x4 = _transforms[nodeId];
var root : ISceneNode = _idToNode[childId];
if (rootTransform._hasChanged)
{
rootLocalToWorld.copyFrom(rootTransform);
if (nodeId != 0)
rootLocalToWorld.append(_transforms[_parentId[nodeId]]);
root.localToWorldTransformChanged.execute(root, rootLocalToWorld);
}
for (; nodeId < numNodes; ++nodeId)
{
var localToWorld : Matrix4x4 = _localToWorldTransforms[nodeId];
var numChildren : uint = _numChildren[nodeId];
var isDirty : Boolean = localToWorld._hasChanged;
var firstChildId : uint = _firstChildId[nodeId];
var lastChildId : uint = firstChildId + numChildren;
localToWorld._hasChanged = false;
for (var childId : uint = firstChildId; childId < lastChildId; ++childId)
{
var childTransform : Matrix4x4 = _transforms[childId];
var childLocalToWorld : Matrix4x4 = _localToWorldTransforms[childId];
var childIsDirty : Boolean = isDirty || childTransform._hasChanged;
if (childIsDirty)
{
var child : ISceneNode = _idToNode[childId];
childLocalToWorld
.copyFrom(childTransform)
.append(localToWorld);
childTransform._hasChanged = false;
child.localToWorldTransformChanged.execute(child, childLocalToWorld);
}
}
}
}
private function updateAncestorsAndSelfLocalToWorld(nodeId : int) : void
{
var dirtyRoot : int = nodeId;
while (nodeId >= 0)
{
if ((_transforms[nodeId] as Matrix4x4)._hasChanged)
dirtyRoot = nodeId;
nodeId = _parentId[nodeId];
}
if (dirtyRoot >= 0)
updateLocalToWorld(dirtyRoot);
}
private function targetAddedHandler(ctrl : TransformController,
target : ISceneNode) : void
{
if (_target)
throw new Error('The TransformController cannot have more than one target.');
_target = target;
_invalidList = true;
if (target is Scene)
{
(target as Scene).renderingBegin.add(renderingBeginHandler);
return;
}
if (target is Group)
{
var targetGroup : Group = target as Group;
targetGroup.descendantAdded.add(descendantAddedHandler);
targetGroup.descendantRemoved.add(descendantRemovedHandler);
}
target.added.add(addedHandler);
}
private function targetRemovedHandler(ctrl : TransformController,
target : ISceneNode) : void
{
target.added.remove(addedHandler);
if (target is Group)
{
var targetGroup : Group = target as Group;
targetGroup.descendantAdded.remove(descendantAddedHandler);
targetGroup.descendantRemoved.remove(descendantRemovedHandler);
}
_invalidList = false;
_target = null;
_nodeToId = null;
_transforms = null;
_localToWorldTransforms = null;
_numChildren = null;
_idToNode = null;
_parentId = null;
}
private function addedHandler(target : ISceneNode, ancestor : Group) : void
{
// the controller will remove itself from the node when it's not its own root anymore
// but it will watch for the 'removed' signal to add itself back if the node becomes
// its own root again
_target.removed.add(removedHandler);
_target.removeController(this);
}
private function removedHandler(target : ISceneNode, ancestor : Group) : void
{
if (target.root == target)
{
target.removed.remove(removedHandler);
target.addController(this);
}
}
private function descendantAddedHandler(root : Group,
descendant : ISceneNode) : void
{
_invalidList = true;
}
private function descendantRemovedHandler(root : Group,
descendant : ISceneNode) : void
{
_invalidList = true;
}
private function updateTransformsList() : void
{
var root : ISceneNode = _target.root;
var nodes : Vector.<ISceneNode> = new <ISceneNode>[root];
var nodeId : uint = 0;
_nodeToId = new Dictionary(true);
_transforms = new <Matrix4x4>[];
_localToWorldTransforms = new <Matrix4x4>[];
_numChildren = new <uint>[];
_firstChildId = new <uint>[];
_idToNode = new <ISceneNode>[];
_parentId = new <int>[-1];
while (nodes.length)
{
var node : ISceneNode = nodes.shift();
var group : Group = node as Group;
_nodeToId[node] = nodeId;
_idToNode[nodeId] = node;
_transforms[nodeId] = node.transform;
_localToWorldTransforms[nodeId] = new Matrix4x4().lock();
if (group)
{
var numChildren : uint = group.numChildren;
var firstChildId : uint = nodeId + nodes.length + 1;
_numChildren[nodeId] = numChildren;
_firstChildId[nodeId] = firstChildId;
for (var childId : uint = 0; childId < numChildren; ++childId)
{
_parentId[uint(firstChildId + childId)] = nodeId;
nodes.push(group.getChildAt(childId));
}
}
else
{
_numChildren[nodeId] = 0;
_firstChildId[nodeId] = 0;
}
++nodeId;
}
_invalidList = false;
}
public function getLocalToWorldTransform(node : ISceneNode,
forceUpdate : Boolean = false) : Matrix4x4
{
if (_invalidList || _nodeToId[node] == undefined)
updateTransformsList();
var nodeId : uint = _nodeToId[node];
if (forceUpdate)
updateAncestorsAndSelfLocalToWorld(nodeId);
return _localToWorldTransforms[nodeId];
}
}
}
|
Fix update of root localToWorldTransform.
|
Fix update of root localToWorldTransform.
|
ActionScript
|
mit
|
aerys/minko-as3
|
e94ec76c18d50881454839ffac87ee19e75acede
|
src/aerys/minko/scene/controller/mesh/MeshController.as
|
src/aerys/minko/scene/controller/mesh/MeshController.as
|
package aerys.minko.scene.controller.mesh
{
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.Mesh;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.math.Matrix4x4;
public final class MeshController extends AbstractController
{
private var _data : DataProvider;
private var _worldToLocal : Matrix4x4;
public function MeshController()
{
super(Mesh);
initialize();
}
private function initialize() : void
{
_worldToLocal = new Matrix4x4();
targetAdded.add(targetAddedHandler);
}
private function targetAddedHandler(ctrl : MeshController,
target : Mesh) : void
{
target.added.add(addedHandler);
target.removed.add(removedHandler);
}
private function addedHandler(target : Mesh,
ancestor : Group) : void
{
if (!target.scene)
return ;
_data = new DataProvider();
_data.setProperty('localToWorld', target.getLocalToWorldTransform());
_data.setProperty('worldToLocal', target.getWorldToLocalTransform(_worldToLocal));
target.bindings.addProvider(_data);
target.localToWorldTransformChanged.add(localToWorldChangedHandler);
}
private function removedHandler(target : Mesh,
ancestor : Group) : void
{
if (!ancestor.scene)
return ;
target.localToWorldTransformChanged.remove(localToWorldChangedHandler);
target.bindings.removeProvider(_data);
_data = null;
}
private function localToWorldChangedHandler(mesh : Mesh, localToWorld : Matrix4x4) : void
{
_data.setProperty('localToWorld', localToWorld);
_data.setProperty('worldToLocal', _worldToLocal.copyFrom(localToWorld).invert());
}
}
}
|
package aerys.minko.scene.controller.mesh
{
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.Mesh;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.enum.DataProviderUsage;
import aerys.minko.type.math.Matrix4x4;
public final class MeshController extends AbstractController
{
private var _data : DataProvider;
private var _worldToLocal : Matrix4x4;
public function MeshController()
{
super(Mesh);
initialize();
}
private function initialize() : void
{
_worldToLocal = new Matrix4x4();
targetAdded.add(targetAddedHandler);
}
private function targetAddedHandler(ctrl : MeshController,
target : Mesh) : void
{
target.added.add(addedHandler);
target.removed.add(removedHandler);
}
private function addedHandler(target : Mesh,
ancestor : Group) : void
{
if (!target.scene)
return ;
_data = new DataProvider(
null, target.name + '_transforms', DataProviderUsage.EXCLUSIVE
);
_data.setProperty('localToWorld', target.getLocalToWorldTransform());
_data.setProperty('worldToLocal', target.getWorldToLocalTransform(false, _worldToLocal));
target.bindings.addProvider(_data);
target.localToWorldTransformChanged.add(localToWorldChangedHandler);
}
private function removedHandler(target : Mesh,
ancestor : Group) : void
{
if (!ancestor.scene)
return ;
target.localToWorldTransformChanged.remove(localToWorldChangedHandler);
target.bindings.removeProvider(_data);
_data = null;
}
private function localToWorldChangedHandler(mesh : Mesh, localToWorld : Matrix4x4) : void
{
_data.setProperty('localToWorld', localToWorld);
_data.setProperty('worldToLocal', _worldToLocal.copyFrom(localToWorld).invert());
}
}
}
|
fix MeshController to create the mesh transforms data provider with the DataProviderUsage.EXCLUSIVE usage in order to avoid having it added twice on cloned meshes
|
fix MeshController to create the mesh transforms data provider with the DataProviderUsage.EXCLUSIVE usage in order to avoid having it added twice on cloned meshes
|
ActionScript
|
mit
|
aerys/minko-as3
|
8f0c69708168aeb7f57cd08c9f889aebc6943a8b
|
src/aerys/minko/scene/controller/mesh/skinning/AbstractSkinningHelper.as
|
src/aerys/minko/scene/controller/mesh/skinning/AbstractSkinningHelper.as
|
package aerys.minko.scene.controller.mesh.skinning
{
import aerys.minko.Minko;
import aerys.minko.ns.minko_math;
import aerys.minko.render.geometry.stream.format.VertexComponent;
import aerys.minko.render.geometry.stream.format.VertexFormat;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.Mesh;
import aerys.minko.type.animation.SkinningMethod;
import aerys.minko.type.log.DebugLevel;
import flash.geom.Matrix3D;
import flash.geom.Vector3D;
internal class AbstractSkinningHelper
{
use namespace minko_math;
private static const WORLD_SKELETON_MATRIX : Matrix3D = new Matrix3D();
private static const TMP_SKINNING_MATRIX : Matrix3D = new Matrix3D();
protected var _targets : Vector.<Mesh> = new Vector.<Mesh>();
protected var _matrices : Vector.<Number> = new <Number>[];
protected var _dqn : Vector.<Number> = new <Number>[];
protected var _dqd : Vector.<Number> = new <Number>[];
protected var _method : uint;
protected var _bindShape : Matrix3D;
protected var _invBindMatrices : Vector.<Matrix3D>;
public function AbstractSkinningHelper(method : uint,
bindShape : Matrix3D,
invBindMatrices : Vector.<Matrix3D>)
{
_method = method;
_bindShape = bindShape;
_invBindMatrices = invBindMatrices;
Minko.log(DebugLevel.SKINNING,
'Creating SkinningController with method ' + method + ' and '
+ invBindMatrices.length + ' bones.'
);
}
public function addMesh(mesh : Mesh) : void
{
_targets.push(mesh);
}
public function removeMesh(mesh : Mesh) : void
{
_targets.splice(_targets.indexOf(mesh), 1);
}
public function removeAllMeshes() : void
{
while (_targets.length != 0)
removeMesh(_targets[0]);
}
public function update(skeletonRoot : Group,
joints : Vector.<Group>) : void
{
throw new Error('Must be overriden');
}
protected final function getInfluenceStrides(format : VertexFormat, out : Vector.<uint>) : void
{
var numInfluences : uint = getNumInfluences(format);
var roundedNumInfluences : uint = (numInfluences >> 1) << 1;
if (out.length != numInfluences)
out.length = numInfluences;
for (var influenceId : uint = 0; influenceId < roundedNumInfluences; ++influenceId)
out[influenceId] =
format.getBytesOffsetForComponent(VertexComponent.BONES[influenceId >> 1])
+ ((influenceId & 0x1) << 3);
if (numInfluences % 2 != 0)
out[numInfluences - 1] =
format.getBytesOffsetForComponent(VertexComponent.BONE_S);
}
protected final function getNumInfluences(format : VertexFormat) : uint
{
return uint(format.hasComponent(VertexComponent.BONE_S))
+ 2 * (
uint(format.hasComponent(VertexComponent.BONE_0_1))
+ uint(format.hasComponent(VertexComponent.BONE_2_3))
+ uint(format.hasComponent(VertexComponent.BONE_4_5))
+ uint(format.hasComponent(VertexComponent.BONE_6_7))
+ uint(format.hasComponent(VertexComponent.BONE_8_9))
+ uint(format.hasComponent(VertexComponent.BONE_10_11))
);
}
protected final function writeMatrices(skeletonRoot : Group,
joints : Vector.<Group>) : void
{
var numJoints : int = joints.length;
WORLD_SKELETON_MATRIX.copyFrom(skeletonRoot.localToWorld._matrix);
WORLD_SKELETON_MATRIX.invert();
for (var jointIndex : int = 0; jointIndex < numJoints; ++jointIndex)
{
var joint : Group = joints[jointIndex];
var invBindMatrix : Matrix3D = _invBindMatrices[jointIndex];
TMP_SKINNING_MATRIX.copyFrom(_bindShape);
TMP_SKINNING_MATRIX.append(invBindMatrix);
TMP_SKINNING_MATRIX.append(joint.localToWorld._matrix);
TMP_SKINNING_MATRIX.append(WORLD_SKELETON_MATRIX);
TMP_SKINNING_MATRIX.copyRawDataTo(_matrices, jointIndex * 16, true);
}
}
protected final function writeDualQuaternions() : void
{
var numQuaternions : int = _matrices.length / 16;
_dqd.length = _dqn.length = numQuaternions * 4;
for (var quaternionId : int = 0; quaternionId < numQuaternions; ++quaternionId)
{
var matrixOffset : int = quaternionId * 16;
var quaternionOffset : int = quaternionId * 4;
var m00 : Number = _matrices[matrixOffset];
var m03 : Number = _matrices[uint(matrixOffset + 3)];
var m05 : Number = _matrices[uint(matrixOffset + 5)];
var m07 : Number = _matrices[uint(matrixOffset + 7)];
var m10 : Number = _matrices[uint(matrixOffset + 10)];
var m11 : Number = _matrices[uint(matrixOffset + 11)];
var mTrace : Number = m00 + m05 + _matrices[uint(matrixOffset + 10)];
var s : Number = 0.;
var nw : Number = 0.;
var nx : Number = 0.;
var ny : Number = 0.;
var nz : Number = 0.;
if (mTrace > 0)
{
s = 2.0 * Math.sqrt(mTrace + 1.0);
nw = 0.25 * s;
nx = (_matrices[uint(matrixOffset + 9)] - _matrices[uint(matrixOffset + 6)]) / s;
ny = (_matrices[uint(matrixOffset + 2)] - _matrices[uint(matrixOffset + 8)]) / s;
nz = (_matrices[uint(matrixOffset + 4)] - _matrices[uint(matrixOffset + 1)]) / s;
}
else if (m00 > m05 && m00 > m10)
{
s = 2.0 * Math.sqrt(1.0 + m00 - m05 - m10);
nw = (_matrices[uint(matrixOffset + 9)] - _matrices[uint(matrixOffset + 6)]) / s
nx = 0.25 * s;
ny = (_matrices[uint(matrixOffset + 1)] + _matrices[uint(matrixOffset + 4)]) / s;
nz = (_matrices[uint(matrixOffset + 2)] + _matrices[uint(matrixOffset + 8)]) / s;
}
else if (m05 > m10)
{
s = 2.0 * Math.sqrt(1.0 + m05 - m00 - m10);
nw = (_matrices[uint(matrixOffset + 2)] - _matrices[uint(matrixOffset + 8)]) / s;
nx = (_matrices[uint(matrixOffset + 1)] + _matrices[uint(matrixOffset + 4)]) / s;
ny = 0.25 * s;
nz = (_matrices[uint(matrixOffset + 6)] + _matrices[uint(matrixOffset + 9)]) / s;
}
else
{
s = 2.0 * Math.sqrt(1.0 + m10 - m00 - m05);
nw = (_matrices[uint(matrixOffset + 4)] - _matrices[uint(matrixOffset + 1)]) / s;
nx = (_matrices[uint(matrixOffset + 2)] + _matrices[uint(matrixOffset + 8)]) / s;
ny = (_matrices[uint(matrixOffset + 6)] + _matrices[uint(matrixOffset + 9)]) / s;
nz = 0.25 * s;
}
_dqd[quaternionOffset] = 0.5 * ( m03 * nw + m07 * nz - m11 * ny);
_dqd[uint(quaternionOffset + 1)] = 0.5 * (-m03 * nz + m07 * nw + m11 * nx);
_dqd[uint(quaternionOffset + 2)] = 0.5 * ( m03 * ny - m07 * nx + m11 * nw);
_dqd[uint(quaternionOffset + 3)] = -0.5 * ( m03 * nx + m07 * ny + m11 * nz);
_dqn[quaternionOffset] = nx;
_dqn[uint(quaternionOffset + 1)] = ny;
_dqn[uint(quaternionOffset + 2)] = nz;
_dqn[uint(quaternionOffset + 3)] = nw;
}
}
}
}
|
package aerys.minko.scene.controller.mesh.skinning
{
import aerys.minko.Minko;
import aerys.minko.ns.minko_math;
import aerys.minko.render.geometry.stream.format.VertexComponent;
import aerys.minko.render.geometry.stream.format.VertexFormat;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.Mesh;
import aerys.minko.type.animation.SkinningMethod;
import aerys.minko.type.log.DebugLevel;
import flash.geom.Matrix3D;
import flash.geom.Vector3D;
internal class AbstractSkinningHelper
{
use namespace minko_math;
private static const WORLD_SKELETON_MATRIX : Matrix3D = new Matrix3D();
private static const TMP_SKINNING_MATRIX : Matrix3D = new Matrix3D();
protected var _targets : Vector.<Mesh> = new Vector.<Mesh>();
protected var _matrices : Vector.<Number> = new <Number>[];
protected var _dqn : Vector.<Number> = new <Number>[];
protected var _dqd : Vector.<Number> = new <Number>[];
protected var _method : uint;
protected var _bindShape : Matrix3D;
protected var _invBindMatrices : Vector.<Matrix3D>;
public function get numMeshes() : uint
{
return _targets.length;
}
public function AbstractSkinningHelper(method : uint,
bindShape : Matrix3D,
invBindMatrices : Vector.<Matrix3D>)
{
_method = method;
_bindShape = bindShape;
_invBindMatrices = invBindMatrices;
Minko.log(DebugLevel.SKINNING,
'Creating SkinningController with method ' + method + ' and '
+ invBindMatrices.length + ' bones.'
);
}
public function addMesh(mesh : Mesh) : void
{
_targets.push(mesh);
}
public function removeMesh(mesh : Mesh) : void
{
_targets.splice(_targets.indexOf(mesh), 1);
}
public function removeAllMeshes() : void
{
while (_targets.length != 0)
removeMesh(_targets[0]);
}
public function update(skeletonRoot : Group,
joints : Vector.<Group>) : void
{
throw new Error('Must be overriden');
}
protected final function getInfluenceStrides(format : VertexFormat, out : Vector.<uint>) : void
{
var numInfluences : uint = getNumInfluences(format);
var roundedNumInfluences : uint = (numInfluences >> 1) << 1;
if (out.length != numInfluences)
out.length = numInfluences;
for (var influenceId : uint = 0; influenceId < roundedNumInfluences; ++influenceId)
out[influenceId] =
format.getBytesOffsetForComponent(VertexComponent.BONES[influenceId >> 1])
+ ((influenceId & 0x1) << 3);
if (numInfluences % 2 != 0)
out[numInfluences - 1] =
format.getBytesOffsetForComponent(VertexComponent.BONE_S);
}
protected final function getNumInfluences(format : VertexFormat) : uint
{
return uint(format.hasComponent(VertexComponent.BONE_S))
+ 2 * (
uint(format.hasComponent(VertexComponent.BONE_0_1))
+ uint(format.hasComponent(VertexComponent.BONE_2_3))
+ uint(format.hasComponent(VertexComponent.BONE_4_5))
+ uint(format.hasComponent(VertexComponent.BONE_6_7))
+ uint(format.hasComponent(VertexComponent.BONE_8_9))
+ uint(format.hasComponent(VertexComponent.BONE_10_11))
);
}
protected final function writeMatrices(skeletonRoot : Group,
joints : Vector.<Group>) : void
{
var numJoints : int = joints.length;
WORLD_SKELETON_MATRIX.copyFrom(skeletonRoot.localToWorld._matrix);
WORLD_SKELETON_MATRIX.invert();
for (var jointIndex : int = 0; jointIndex < numJoints; ++jointIndex)
{
var joint : Group = joints[jointIndex];
var invBindMatrix : Matrix3D = _invBindMatrices[jointIndex];
TMP_SKINNING_MATRIX.copyFrom(_bindShape);
TMP_SKINNING_MATRIX.append(invBindMatrix);
TMP_SKINNING_MATRIX.append(joint.localToWorld._matrix);
TMP_SKINNING_MATRIX.append(WORLD_SKELETON_MATRIX);
TMP_SKINNING_MATRIX.copyRawDataTo(_matrices, jointIndex * 16, true);
}
}
protected final function writeDualQuaternions() : void
{
var numQuaternions : int = _matrices.length / 16;
_dqd.length = _dqn.length = numQuaternions * 4;
for (var quaternionId : int = 0; quaternionId < numQuaternions; ++quaternionId)
{
var matrixOffset : int = quaternionId * 16;
var quaternionOffset : int = quaternionId * 4;
var m00 : Number = _matrices[matrixOffset];
var m03 : Number = _matrices[uint(matrixOffset + 3)];
var m05 : Number = _matrices[uint(matrixOffset + 5)];
var m07 : Number = _matrices[uint(matrixOffset + 7)];
var m10 : Number = _matrices[uint(matrixOffset + 10)];
var m11 : Number = _matrices[uint(matrixOffset + 11)];
var mTrace : Number = m00 + m05 + _matrices[uint(matrixOffset + 10)];
var s : Number = 0.;
var nw : Number = 0.;
var nx : Number = 0.;
var ny : Number = 0.;
var nz : Number = 0.;
if (mTrace > 0)
{
s = 2.0 * Math.sqrt(mTrace + 1.0);
nw = 0.25 * s;
nx = (_matrices[uint(matrixOffset + 9)] - _matrices[uint(matrixOffset + 6)]) / s;
ny = (_matrices[uint(matrixOffset + 2)] - _matrices[uint(matrixOffset + 8)]) / s;
nz = (_matrices[uint(matrixOffset + 4)] - _matrices[uint(matrixOffset + 1)]) / s;
}
else if (m00 > m05 && m00 > m10)
{
s = 2.0 * Math.sqrt(1.0 + m00 - m05 - m10);
nw = (_matrices[uint(matrixOffset + 9)] - _matrices[uint(matrixOffset + 6)]) / s
nx = 0.25 * s;
ny = (_matrices[uint(matrixOffset + 1)] + _matrices[uint(matrixOffset + 4)]) / s;
nz = (_matrices[uint(matrixOffset + 2)] + _matrices[uint(matrixOffset + 8)]) / s;
}
else if (m05 > m10)
{
s = 2.0 * Math.sqrt(1.0 + m05 - m00 - m10);
nw = (_matrices[uint(matrixOffset + 2)] - _matrices[uint(matrixOffset + 8)]) / s;
nx = (_matrices[uint(matrixOffset + 1)] + _matrices[uint(matrixOffset + 4)]) / s;
ny = 0.25 * s;
nz = (_matrices[uint(matrixOffset + 6)] + _matrices[uint(matrixOffset + 9)]) / s;
}
else
{
s = 2.0 * Math.sqrt(1.0 + m10 - m00 - m05);
nw = (_matrices[uint(matrixOffset + 4)] - _matrices[uint(matrixOffset + 1)]) / s;
nx = (_matrices[uint(matrixOffset + 2)] + _matrices[uint(matrixOffset + 8)]) / s;
ny = (_matrices[uint(matrixOffset + 6)] + _matrices[uint(matrixOffset + 9)]) / s;
nz = 0.25 * s;
}
_dqd[quaternionOffset] = 0.5 * ( m03 * nw + m07 * nz - m11 * ny);
_dqd[uint(quaternionOffset + 1)] = 0.5 * (-m03 * nz + m07 * nw + m11 * nx);
_dqd[uint(quaternionOffset + 2)] = 0.5 * ( m03 * ny - m07 * nx + m11 * nw);
_dqd[uint(quaternionOffset + 3)] = -0.5 * ( m03 * nx + m07 * ny + m11 * nz);
_dqn[quaternionOffset] = nx;
_dqn[uint(quaternionOffset + 1)] = ny;
_dqn[uint(quaternionOffset + 2)] = nz;
_dqn[uint(quaternionOffset + 3)] = nw;
}
}
}
}
|
add AbstractSkinningHelper.numMeshes property
|
add AbstractSkinningHelper.numMeshes property
|
ActionScript
|
mit
|
aerys/minko-as3
|
0f6983b3fe0ee1cc6028d2ec6bc493ada5873673
|
bin/Data/Scripts/33_Urho2DSpriterAnimation.as
|
bin/Data/Scripts/33_Urho2DSpriterAnimation.as
|
// Urho2D sprite example.
// This sample demonstrates:
// - Creating a 2D scene with spriter animation
// - Displaying the scene using the Renderer subsystem
// - Handling keyboard to move and zoom 2D camera
#include "Scripts/Utilities/Sample.as"
Node@ spriterNode;
int spriterAnimationIndex = 0;
void Start()
{
// Execute the common startup for samples
SampleStart();
// Create the scene content
CreateScene();
// Create the UI content
CreateInstructions();
// Setup the viewport for displaying the scene
SetupViewport();
// Hook up to the frame update events
SubscribeToEvents();
}
void CreateScene()
{
scene_ = Scene();
// Create the Octree component to the scene. This is required before adding any drawable components, or else nothing will
// show up. The default octree volume will be from (-1000, -1000, -1000) to (1000, 1000, 1000) in world coordinates; it
// is also legal to place objects outside the volume but their visibility can then not be checked in a hierarchically
// optimizing manner
scene_.CreateComponent("Octree");
// Create a scene node for the camera, which we will move around
// The camera will use default settings (1000 far clip distance, 45 degrees FOV, set aspect ratio automatically)
cameraNode = scene_.CreateChild("Camera");
// Set an initial position for the camera scene node above the plane
cameraNode.position = Vector3(0.0f, 0.0f, -10.0f);
Camera@ camera = cameraNode.CreateComponent("Camera");
camera.orthographic = true;
camera.orthoSize = graphics.height * PIXEL_SIZE;
camera.zoom = 1.5f * Min(graphics.width / 1280.0f, graphics.height / 800.0f); // Set zoom according to user's resolution to ensure full visibility (initial zoom (1.5) is set for full visibility at 1280x800 resolution)
AnimationSet2D@ spriterAnimationSet = cache.GetResource("AnimationSet2D", "Urho2D/imp/imp.scml");
if (spriterAnimationSet is null)
return;
spriterNode = scene_.CreateChild("SpriterAnimation");
AnimatedSprite2D@ animatedSprite = spriterNode.CreateComponent("AnimatedSprite2D");
animatedSprite.SetAnimation(spriterAnimationSet, spriterAnimationSet.GetAnimation(spriterAnimationIndex), LM_FORCE_LOOPED);
}
void CreateInstructions()
{
// Construct new Text object, set string to display and font to use
Text@ instructionText = ui.root.CreateChild("Text");
instructionText.text = "Mouse click to play next animation, \nUse WASD keys to move, use PageUp PageDown keys to zoom.";
instructionText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15);
instructionText.textAlignment = HA_CENTER; // Center rows in relation to each other
// Position the text relative to the screen center
instructionText.horizontalAlignment = HA_CENTER;
instructionText.verticalAlignment = VA_CENTER;
instructionText.SetPosition(0, ui.root.height / 4);
}
void SetupViewport()
{
// Set up a viewport to the Renderer subsystem so that the 3D scene can be seen. We need to define the scene and the camera
// at minimum. Additionally we could configure the viewport screen size and the rendering path (eg. forward / deferred) to
// use, but now we just use full screen and default render path configured in the engine command line options
Viewport@ viewport = Viewport(scene_, cameraNode.GetComponent("Camera"));
renderer.viewports[0] = viewport;
}
void MoveCamera(float timeStep)
{
// Do not move if the UI has a focused element (the console)
if (ui.focusElement !is null)
return;
// Movement speed as world units per second
const float MOVE_SPEED = 4.0f;
// Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
if (input.keyDown['W'])
cameraNode.Translate(Vector3(0.0f, 1.0f, 0.0f) * MOVE_SPEED * timeStep);
if (input.keyDown['S'])
cameraNode.Translate(Vector3(0.0f, -1.0f, 0.0f) * MOVE_SPEED * timeStep);
if (input.keyDown['A'])
cameraNode.Translate(Vector3(-1.0f, 0.0f, 0.0f) * MOVE_SPEED * timeStep);
if (input.keyDown['D'])
cameraNode.Translate(Vector3(1.0f, 0.0f, 0.0f) * MOVE_SPEED * timeStep);
if (input.keyDown[KEY_PAGEUP])
{
Camera@ camera = cameraNode.GetComponent("Camera");
camera.zoom = camera.zoom * 1.01f;
}
if (input.keyDown[KEY_PAGEDOWN])
{
Camera@ camera = cameraNode.GetComponent("Camera");
camera.zoom = camera.zoom * 0.99f;
}
}
void SubscribeToEvents()
{
// Subscribe HandleUpdate() function for processing update events
SubscribeToEvent("Update", "HandleUpdate");
SubscribeToEvent("MouseButtonDown", "HandleMouseButtonDown");
// Unsubscribe the SceneUpdate event from base class to prevent camera pitch and yaw in 2D sample
UnsubscribeFromEvent("SceneUpdate");
}
void HandleUpdate(StringHash eventType, VariantMap& eventData)
{
// Take the frame time step, which is stored as a float
float timeStep = eventData["TimeStep"].GetFloat();
// Move the camera, scale movement with time step
MoveCamera(timeStep);
}
void HandleMouseButtonDown(StringHash eventType, VariantMap& eventData)
{
AnimatedSprite2D@ spriterAnimatedSprite = spriterNode.GetComponent("AnimatedSprite2D");
AnimationSet2D@ spriterAnimationSet = spriterAnimatedSprite.animationSet;
spriterAnimationIndex = (spriterAnimationIndex + 1) % spriterAnimationSet.numAnimations;
spriterAnimatedSprite.SetAnimation(spriterAnimationSet.GetAnimation(spriterAnimationIndex), LM_FORCE_LOOPED);
}
// Create XML patch instructions for screen joystick layout specific to this sample app
String patchInstructions =
"<patch>" +
" <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" +
" <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Zoom In</replace>" +
" <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" +
" <element type=\"Text\">" +
" <attribute name=\"Name\" value=\"KeyBinding\" />" +
" <attribute name=\"Text\" value=\"PAGEUP\" />" +
" </element>" +
" </add>" +
" <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" +
" <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Zoom Out</replace>" +
" <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" +
" <element type=\"Text\">" +
" <attribute name=\"Name\" value=\"KeyBinding\" />" +
" <attribute name=\"Text\" value=\"PAGEDOWN\" />" +
" </element>" +
" </add>" +
"</patch>";
|
// Urho2D sprite example.
// This sample demonstrates:
// - Creating a 2D scene with spriter animation
// - Displaying the scene using the Renderer subsystem
// - Handling keyboard to move and zoom 2D camera
#include "Scripts/Utilities/Sample.as"
Node@ spriterNode;
int spriterAnimationIndex = 0;
void Start()
{
// Execute the common startup for samples
SampleStart();
// Create the scene content
CreateScene();
// Create the UI content
CreateInstructions();
// Setup the viewport for displaying the scene
SetupViewport();
// Hook up to the frame update events
SubscribeToEvents();
}
void CreateScene()
{
scene_ = Scene();
// Create the Octree component to the scene. This is required before adding any drawable components, or else nothing will
// show up. The default octree volume will be from (-1000, -1000, -1000) to (1000, 1000, 1000) in world coordinates; it
// is also legal to place objects outside the volume but their visibility can then not be checked in a hierarchically
// optimizing manner
scene_.CreateComponent("Octree");
// Create a scene node for the camera, which we will move around
// The camera will use default settings (1000 far clip distance, 45 degrees FOV, set aspect ratio automatically)
cameraNode = scene_.CreateChild("Camera");
// Set an initial position for the camera scene node above the plane
cameraNode.position = Vector3(0.0f, 0.0f, -10.0f);
Camera@ camera = cameraNode.CreateComponent("Camera");
camera.orthographic = true;
camera.orthoSize = graphics.height * PIXEL_SIZE;
camera.zoom = 1.5f * Min(graphics.width / 1280.0f, graphics.height / 800.0f); // Set zoom according to user's resolution to ensure full visibility (initial zoom (1.5) is set for full visibility at 1280x800 resolution)
AnimationSet2D@ spriterAnimationSet = cache.GetResource("AnimationSet2D", "Urho2D/imp/imp.scml");
if (spriterAnimationSet is null)
return;
spriterNode = scene_.CreateChild("SpriterAnimation");
AnimatedSprite2D@ spriterAnimatedSprite = spriterNode.CreateComponent("AnimatedSprite2D");
spriterAnimatedSprite.SetAnimation(spriterAnimationSet, spriterAnimationSet.GetAnimation(spriterAnimationIndex), LM_FORCE_LOOPED);
}
void CreateInstructions()
{
// Construct new Text object, set string to display and font to use
Text@ instructionText = ui.root.CreateChild("Text");
instructionText.text = "Mouse click to play next animation, \nUse WASD keys to move, use PageUp PageDown keys to zoom.";
instructionText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15);
instructionText.textAlignment = HA_CENTER; // Center rows in relation to each other
// Position the text relative to the screen center
instructionText.horizontalAlignment = HA_CENTER;
instructionText.verticalAlignment = VA_CENTER;
instructionText.SetPosition(0, ui.root.height / 4);
}
void SetupViewport()
{
// Set up a viewport to the Renderer subsystem so that the 3D scene can be seen. We need to define the scene and the camera
// at minimum. Additionally we could configure the viewport screen size and the rendering path (eg. forward / deferred) to
// use, but now we just use full screen and default render path configured in the engine command line options
Viewport@ viewport = Viewport(scene_, cameraNode.GetComponent("Camera"));
renderer.viewports[0] = viewport;
}
void MoveCamera(float timeStep)
{
// Do not move if the UI has a focused element (the console)
if (ui.focusElement !is null)
return;
// Movement speed as world units per second
const float MOVE_SPEED = 4.0f;
// Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
if (input.keyDown['W'])
cameraNode.Translate(Vector3(0.0f, 1.0f, 0.0f) * MOVE_SPEED * timeStep);
if (input.keyDown['S'])
cameraNode.Translate(Vector3(0.0f, -1.0f, 0.0f) * MOVE_SPEED * timeStep);
if (input.keyDown['A'])
cameraNode.Translate(Vector3(-1.0f, 0.0f, 0.0f) * MOVE_SPEED * timeStep);
if (input.keyDown['D'])
cameraNode.Translate(Vector3(1.0f, 0.0f, 0.0f) * MOVE_SPEED * timeStep);
if (input.keyDown[KEY_PAGEUP])
{
Camera@ camera = cameraNode.GetComponent("Camera");
camera.zoom = camera.zoom * 1.01f;
}
if (input.keyDown[KEY_PAGEDOWN])
{
Camera@ camera = cameraNode.GetComponent("Camera");
camera.zoom = camera.zoom * 0.99f;
}
}
void SubscribeToEvents()
{
// Subscribe HandleUpdate() function for processing update events
SubscribeToEvent("Update", "HandleUpdate");
SubscribeToEvent("MouseButtonDown", "HandleMouseButtonDown");
// Unsubscribe the SceneUpdate event from base class to prevent camera pitch and yaw in 2D sample
UnsubscribeFromEvent("SceneUpdate");
}
void HandleUpdate(StringHash eventType, VariantMap& eventData)
{
// Take the frame time step, which is stored as a float
float timeStep = eventData["TimeStep"].GetFloat();
// Move the camera, scale movement with time step
MoveCamera(timeStep);
}
void HandleMouseButtonDown(StringHash eventType, VariantMap& eventData)
{
AnimatedSprite2D@ spriterAnimatedSprite = spriterNode.GetComponent("AnimatedSprite2D");
AnimationSet2D@ spriterAnimationSet = spriterAnimatedSprite.animationSet;
spriterAnimationIndex = (spriterAnimationIndex + 1) % spriterAnimationSet.numAnimations;
spriterAnimatedSprite.SetAnimation(spriterAnimationSet.GetAnimation(spriterAnimationIndex), LM_FORCE_LOOPED);
}
// Create XML patch instructions for screen joystick layout specific to this sample app
String patchInstructions =
"<patch>" +
" <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" +
" <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Zoom In</replace>" +
" <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" +
" <element type=\"Text\">" +
" <attribute name=\"Name\" value=\"KeyBinding\" />" +
" <attribute name=\"Text\" value=\"PAGEUP\" />" +
" </element>" +
" </add>" +
" <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" +
" <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Zoom Out</replace>" +
" <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" +
" <element type=\"Text\">" +
" <attribute name=\"Name\" value=\"KeyBinding\" />" +
" <attribute name=\"Text\" value=\"PAGEDOWN\" />" +
" </element>" +
" </add>" +
"</patch>";
|
rename variable.
|
rename variable.
|
ActionScript
|
mit
|
MonkeyFirst/Urho3D,helingping/Urho3D,299299/Urho3D,rokups/Urho3D,tommy3/Urho3D,kostik1337/Urho3D,victorholt/Urho3D,henu/Urho3D,SuperWangKai/Urho3D,rokups/Urho3D,orefkov/Urho3D,cosmy1/Urho3D,fire/Urho3D-1,PredatorMF/Urho3D,eugeneko/Urho3D,xiliu98/Urho3D,eugeneko/Urho3D,fire/Urho3D-1,urho3d/Urho3D,299299/Urho3D,rokups/Urho3D,tommy3/Urho3D,henu/Urho3D,MeshGeometry/Urho3D,victorholt/Urho3D,299299/Urho3D,SuperWangKai/Urho3D,MonkeyFirst/Urho3D,c4augustus/Urho3D,cosmy1/Urho3D,c4augustus/Urho3D,abdllhbyrktr/Urho3D,iainmerrick/Urho3D,weitjong/Urho3D,weitjong/Urho3D,xiliu98/Urho3D,SuperWangKai/Urho3D,tommy3/Urho3D,MonkeyFirst/Urho3D,bacsmar/Urho3D,helingping/Urho3D,rokups/Urho3D,kostik1337/Urho3D,luveti/Urho3D,codedash64/Urho3D,MonkeyFirst/Urho3D,299299/Urho3D,urho3d/Urho3D,carnalis/Urho3D,orefkov/Urho3D,SuperWangKai/Urho3D,c4augustus/Urho3D,MeshGeometry/Urho3D,rokups/Urho3D,bacsmar/Urho3D,eugeneko/Urho3D,weitjong/Urho3D,c4augustus/Urho3D,PredatorMF/Urho3D,victorholt/Urho3D,orefkov/Urho3D,fire/Urho3D-1,codemon66/Urho3D,SirNate0/Urho3D,SirNate0/Urho3D,codedash64/Urho3D,carnalis/Urho3D,henu/Urho3D,SirNate0/Urho3D,iainmerrick/Urho3D,fire/Urho3D-1,helingping/Urho3D,codedash64/Urho3D,299299/Urho3D,codedash64/Urho3D,299299/Urho3D,victorholt/Urho3D,carnalis/Urho3D,iainmerrick/Urho3D,cosmy1/Urho3D,eugeneko/Urho3D,luveti/Urho3D,henu/Urho3D,urho3d/Urho3D,iainmerrick/Urho3D,victorholt/Urho3D,carnalis/Urho3D,kostik1337/Urho3D,abdllhbyrktr/Urho3D,SirNate0/Urho3D,PredatorMF/Urho3D,helingping/Urho3D,MeshGeometry/Urho3D,luveti/Urho3D,cosmy1/Urho3D,tommy3/Urho3D,orefkov/Urho3D,xiliu98/Urho3D,MonkeyFirst/Urho3D,SuperWangKai/Urho3D,c4augustus/Urho3D,tommy3/Urho3D,codemon66/Urho3D,bacsmar/Urho3D,codedash64/Urho3D,carnalis/Urho3D,abdllhbyrktr/Urho3D,helingping/Urho3D,iainmerrick/Urho3D,fire/Urho3D-1,rokups/Urho3D,kostik1337/Urho3D,cosmy1/Urho3D,abdllhbyrktr/Urho3D,xiliu98/Urho3D,kostik1337/Urho3D,weitjong/Urho3D,xiliu98/Urho3D,MeshGeometry/Urho3D,weitjong/Urho3D,abdllhbyrktr/Urho3D,bacsmar/Urho3D,PredatorMF/Urho3D,luveti/Urho3D,codemon66/Urho3D,luveti/Urho3D,codemon66/Urho3D,urho3d/Urho3D,SirNate0/Urho3D,codemon66/Urho3D,MeshGeometry/Urho3D,henu/Urho3D
|
9d1c3a8c70e249275ae6c1fc556e2acaf4293a68
|
dolly-framework/src/test/actionscript/dolly/ClonerTest.as
|
dolly-framework/src/test/actionscript/dolly/ClonerTest.as
|
package dolly {
import dolly.core.dolly_internal;
import dolly.data.ClassLevelCloneable;
import dolly.data.PropertyLevelCloneable;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertNotNull;
import org.flexunit.asserts.assertNull;
use namespace dolly_internal;
public class ClonerTest {
private var classLevelCloneable:ClassLevelCloneable;
private var classLevelCloneableType:Type;
private var propertyLevelCloneable:PropertyLevelCloneable;
private var propertyLevelCloneableType:Type;
[Before]
public function before():void {
classLevelCloneable = new ClassLevelCloneable();
classLevelCloneable.property1 = "value 1";
classLevelCloneable.property2 = "value 2";
classLevelCloneable.property3 = "value 3";
classLevelCloneable.writableField = "value 4";
propertyLevelCloneable = new PropertyLevelCloneable();
propertyLevelCloneable.property1 = "value 1";
propertyLevelCloneable.property2 = "value 2";
propertyLevelCloneable.property3 = "value 3";
propertyLevelCloneable.writableField = "value 4";
classLevelCloneableType = Type.forInstance(classLevelCloneable);
propertyLevelCloneableType = Type.forInstance(propertyLevelCloneable);
}
[After]
public function after():void {
classLevelCloneable = null;
propertyLevelCloneable = null;
classLevelCloneableType = null;
propertyLevelCloneableType = null;
}
[Test]
public function testGetCloneableFieldsForType():void {
var cloneableFields:Vector.<Field> = Cloner.getCloneableFieldsForType(classLevelCloneableType);
assertNotNull(cloneableFields);
assertEquals(4, cloneableFields.length);
cloneableFields = Cloner.getCloneableFieldsForType(propertyLevelCloneableType);
assertNotNull(cloneableFields);
assertEquals(3, cloneableFields.length);
}
[Test]
public function testCloneWithClassLevelMetadata():void {
const clone:ClassLevelCloneable = Cloner.clone(classLevelCloneable) as ClassLevelCloneable;
assertNotNull(clone);
assertNotNull(clone.property1);
assertEquals(clone.property1, classLevelCloneable.property1);
assertNotNull(clone.property2);
assertEquals(clone.property2, classLevelCloneable.property2);
assertNotNull(clone.property3);
assertEquals(clone.property3, classLevelCloneable.property3);
assertNotNull(clone.writableField);
assertEquals(clone.writableField, classLevelCloneable.writableField);
}
[Test]
public function testCloneWithPropertyLevelMetadata():void {
const clone:PropertyLevelCloneable = Cloner.clone(
propertyLevelCloneable
) as PropertyLevelCloneable;
assertNotNull(clone);
assertNull(clone.property1);
assertNotNull(clone.property2);
assertEquals(clone.property2, propertyLevelCloneable.property2);
assertNotNull(clone.property3);
assertEquals(clone.property3, propertyLevelCloneable.property3);
assertNotNull(clone.writableField);
assertEquals(clone.writableField, propertyLevelCloneable.writableField);
}
}
}
|
package dolly {
import dolly.core.dolly_internal;
import dolly.data.ClassLevelCloneable;
import dolly.data.ClassLevelCopyableCloneable;
import dolly.data.PropertyLevelCloneable;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertNotNull;
import org.flexunit.asserts.assertNull;
use namespace dolly_internal;
public class ClonerTest {
private var classLevelCloneable:ClassLevelCloneable;
private var classLevelCloneableType:Type;
private var classLevelCopyableCloneable:ClassLevelCopyableCloneable;
private var classLevelCopyableCloneableType:Type;
private var propertyLevelCloneable:PropertyLevelCloneable;
private var propertyLevelCloneableType:Type;
[Before]
public function before():void {
classLevelCloneable = new ClassLevelCloneable();
classLevelCloneable.property1 = "value 1";
classLevelCloneable.property2 = "value 2";
classLevelCloneable.property3 = "value 3";
classLevelCloneable.writableField = "value 4";
classLevelCloneableType = Type.forInstance(classLevelCloneable);
classLevelCopyableCloneable = new ClassLevelCopyableCloneable();
classLevelCopyableCloneable.property1 = "value 1";
classLevelCopyableCloneable.property2 = "value 2";
classLevelCopyableCloneable.property3 = "value 3";
classLevelCopyableCloneable.writableField = "value 4";
classLevelCopyableCloneableType = Type.forInstance(classLevelCopyableCloneable);
propertyLevelCloneable = new PropertyLevelCloneable();
propertyLevelCloneable.property1 = "value 1";
propertyLevelCloneable.property2 = "value 2";
propertyLevelCloneable.property3 = "value 3";
propertyLevelCloneable.writableField = "value 4";
propertyLevelCloneableType = Type.forInstance(propertyLevelCloneable);
}
[After]
public function after():void {
classLevelCloneable = null;
classLevelCloneableType = null;
classLevelCopyableCloneable = null;
classLevelCopyableCloneableType = null;
propertyLevelCloneable = null;
propertyLevelCloneableType = null;
}
[Test]
public function testGetCloneableFieldsForType():void {
var cloneableFields:Vector.<Field> = Cloner.getCloneableFieldsForType(classLevelCloneableType);
assertNotNull(cloneableFields);
assertEquals(4, cloneableFields.length);
cloneableFields = Cloner.getCloneableFieldsForType(classLevelCloneableType);
assertNotNull(cloneableFields);
assertEquals(4, cloneableFields.length);
cloneableFields = Cloner.getCloneableFieldsForType(propertyLevelCloneableType);
assertNotNull(cloneableFields);
assertEquals(3, cloneableFields.length);
}
[Test]
public function testCloneWithClassLevelMetadata():void {
const clone:ClassLevelCloneable = Cloner.clone(classLevelCloneable) as ClassLevelCloneable;
assertNotNull(clone);
assertNotNull(clone.property1);
assertEquals(clone.property1, classLevelCloneable.property1);
assertNotNull(clone.property2);
assertEquals(clone.property2, classLevelCloneable.property2);
assertNotNull(clone.property3);
assertEquals(clone.property3, classLevelCloneable.property3);
assertNotNull(clone.writableField);
assertEquals(clone.writableField, classLevelCloneable.writableField);
}
[Test]
public function testCloneWithPropertyLevelMetadata():void {
const clone:PropertyLevelCloneable = Cloner.clone(
propertyLevelCloneable
) as PropertyLevelCloneable;
assertNotNull(clone);
assertNull(clone.property1);
assertNotNull(clone.property2);
assertEquals(clone.property2, propertyLevelCloneable.property2);
assertNotNull(clone.property3);
assertEquals(clone.property3, propertyLevelCloneable.property3);
assertNotNull(clone.writableField);
assertEquals(clone.writableField, propertyLevelCloneable.writableField);
}
}
}
|
Test ClassLevelCopyableCloneable class in ClonerTest.
|
Test ClassLevelCopyableCloneable class in ClonerTest.
|
ActionScript
|
mit
|
Yarovoy/dolly
|
8f68e30bb0f8bfefdaf5a0d2d12193cdf58ba3f6
|
src/widgets/supportClasses/ResultAttributes.as
|
src/widgets/supportClasses/ResultAttributes.as
|
package widgets.supportClasses
{
import com.esri.ags.FeatureSet;
import com.esri.ags.Graphic;
import com.esri.ags.layers.FeatureLayer;
import com.esri.ags.layers.supportClasses.CodedValue;
import com.esri.ags.layers.supportClasses.CodedValueDomain;
import com.esri.ags.layers.supportClasses.FeatureType;
import com.esri.ags.layers.supportClasses.Field;
import com.esri.ags.layers.supportClasses.LayerDetails;
import mx.core.FlexGlobals;
import mx.core.LayoutDirection;
import mx.formatters.DateFormatter;
[Bindable]
public class ResultAttributes
{
public var attributes:Object;
public var title:String;
public var content:String;
public var link:String;
public var linkAlias:String;
public static function toResultAttributes(fields:XMLList,
graphic:Graphic = null,
featureSet:FeatureSet = null,
layer:FeatureLayer = null,
layerDetails:LayerDetails = null,
fallbackTitle:String = null,
titleField:String = null,
linkField:String = null,
linkAlias:String = null):ResultAttributes
{
var resultAttributes:ResultAttributes = new ResultAttributes;
var value:String = "";
var title:String = "";
var content:String = "";
var link:String = "";
var linkAlias:String;
var fieldsXMLList:XMLList = fields ? fields.field : null;
if (fields && fields[0].@all[0] == "true")
{
if (layerDetails.fields)
{
for each (var field:Field in layerDetails.fields)
{
if (field.name in graphic.attributes)
{
displayFields(field.name, getFieldXML(field.name, fieldsXMLList), field);
}
}
}
else
{
for (var fieldName:String in graphic.attributes)
{
displayFields(fieldName, getFieldXML(fieldName, fieldsXMLList), null);
}
}
}
else
{
for each (var fieldXML:XML in fieldsXMLList) // display the fields in the same order as specified
{
if (fieldXML.@name[0] in graphic.attributes)
{
displayFields(fieldXML.@name[0], fieldXML, getField(layer, fieldXML.@name[0]));
}
}
}
resultAttributes.attributes = graphic.attributes;
resultAttributes.title = title ? title : fallbackTitle;
resultAttributes.content = content;
resultAttributes.link = link ? link : null;
resultAttributes.linkAlias = linkAlias;
function displayFields(fieldName:String, fieldXML:XML, field:Field):void
{
var fieldNameTextValue:String = graphic.attributes[fieldName];
value = fieldNameTextValue ? fieldNameTextValue : "";
if (value)
{
var isDateField:Boolean;
var useUTC:Boolean;
var dateFormat:String;
if (fieldXML)
{
useUTC = fieldXML.format.@useutc[0] || fieldXML.@useutc[0] == "true";
dateFormat = fieldXML.format.@dateformat[0] || fieldXML.@dateformat[0];
if (dateFormat)
{
isDateField = true;
}
}
if (!isDateField && field)
{
isDateField = field.type == Field.TYPE_DATE;
}
if (isDateField)
{
var dateMS:Number = Number(value);
if (!isNaN(dateMS))
{
value = msToDate(dateMS, dateFormat, useUTC);
}
}
else
{
var typeID:String = layerDetails.typeIdField ? graphic.attributes[layerDetails.typeIdField] : null;
if (fieldName == layerDetails.typeIdField)
{
var featureType:FeatureType = getFeatureType(layer, typeID);
if (featureType && featureType.name)
{
value = featureType.name;
}
}
else
{
var codedValue:CodedValue = getCodedValue(layer, fieldName, value, typeID);
if (codedValue)
{
value = codedValue.name;
}
}
}
}
if (titleField && fieldName.toUpperCase() == titleField.toUpperCase())
{
title = value;
}
else if (linkField && fieldName.toUpperCase() == linkField.toUpperCase())
{
link = value;
linkAlias = linkAlias;
}
else if (fieldName.toUpperCase() != "SHAPE_LENGTH" && fieldName.toUpperCase() != "SHAPE_AREA")
{
var fieldLabel:String;
if (fieldXML && fieldXML.@alias[0])
{
fieldLabel = fieldXML.@alias[0];
}
else
{
fieldLabel = featureSet.fieldAliases[fieldName];
}
if (FlexGlobals.topLevelApplication.layoutDirection == LayoutDirection.RTL)
{
content += value + " :" + fieldLabel + "\n";
}
else
{
content += fieldLabel + ": " + value + "\n";
}
}
}
return resultAttributes;
}
private static function getFieldXML(fieldName:String, fields:XMLList):XML
{
var result:XML;
for each (var fieldXML:XML in fields)
{
if (fieldName == fieldXML.@name[0])
{
result = fieldXML;
break;
}
}
return result;
}
private static function getField(layer:FeatureLayer, fieldName:String):Field
{
var result:Field;
if (layer)
{
for each (var field:Field in layer.layerDetails.fields)
{
if (fieldName == field.name)
{
result = field;
break;
}
}
}
return result;
}
private static function getFeatureType(layer:FeatureLayer, typeID:String):FeatureType
{
var result:FeatureType;
if (layer)
{
for each (var featureType:FeatureType in layer.layerDetails.types)
{
if (typeID == featureType.id)
{
result = featureType;
break;
}
}
}
return result;
}
private static function msToDate(ms:Number, dateFormat:String, useUTC:Boolean):String
{
var date:Date = new Date(ms);
if (date.milliseconds == 999) // workaround for REST bug
{
date.milliseconds++;
}
if (useUTC)
{
date.minutes += date.timezoneOffset;
}
if (dateFormat)
{
var dateFormatter:DateFormatter = new DateFormatter();
dateFormatter.formatString = dateFormat;
var result:String = dateFormatter.format(date);
if (result)
{
return result;
}
else
{
return dateFormatter.error;
}
}
else
{
return date.toLocaleString();
}
}
private static function getCodedValue(layer:FeatureLayer, fieldName:String, fieldValue:String, typeID:String):CodedValue
{
var result:CodedValue;
var codedValueDomain:CodedValueDomain;
if (typeID)
{
var featureType:FeatureType = getFeatureType(layer, typeID);
if (featureType)
{
codedValueDomain = featureType.domains[fieldName] as CodedValueDomain;
}
}
else
{
var field:Field = getField(layer, fieldName);
if (field)
{
codedValueDomain = field.domain as CodedValueDomain;
}
}
if (codedValueDomain)
{
for each (var codedValue:CodedValue in codedValueDomain.codedValues)
{
if (fieldValue == codedValue.code)
{
result = codedValue;
break;
}
}
}
return result;
}
}
}
|
package widgets.supportClasses
{
import com.esri.ags.FeatureSet;
import com.esri.ags.Graphic;
import com.esri.ags.layers.FeatureLayer;
import com.esri.ags.layers.supportClasses.CodedValue;
import com.esri.ags.layers.supportClasses.CodedValueDomain;
import com.esri.ags.layers.supportClasses.FeatureType;
import com.esri.ags.layers.supportClasses.Field;
import com.esri.ags.layers.supportClasses.LayerDetails;
import mx.core.FlexGlobals;
import mx.core.LayoutDirection;
import mx.formatters.DateFormatter;
[Bindable]
public class ResultAttributes
{
public var attributes:Object;
public var title:String;
public var content:String;
public var link:String;
public var linkAlias:String;
public static function toResultAttributes(fields:XMLList,
graphic:Graphic = null,
featureSet:FeatureSet = null,
layer:FeatureLayer = null,
layerDetails:LayerDetails = null,
fallbackTitle:String = null,
titleField:String = null,
linkField:String = null,
linkAlias:String = null):ResultAttributes
{
var resultAttributes:ResultAttributes = new ResultAttributes;
var value:String = "";
var title:String = "";
var content:String = "";
var link:String = "";
var linkAlias:String;
var fieldsXMLList:XMLList = fields ? fields.field : null;
if (fields && fields[0].@all[0] == "true")
{
if (layerDetails.fields)
{
for each (var field:Field in layerDetails.fields)
{
if (field.name in graphic.attributes)
{
displayFields(field.name, getFieldXML(field.name, fieldsXMLList), field);
}
}
}
else
{
for (var fieldName:String in graphic.attributes)
{
displayFields(fieldName, getFieldXML(fieldName, fieldsXMLList), null);
}
}
}
else
{
for each (var fieldXML:XML in fieldsXMLList) // display the fields in the same order as specified
{
if (fieldXML.@name[0] in graphic.attributes)
{
displayFields(fieldXML.@name[0], fieldXML, getField(layer, fieldXML.@name[0]));
}
}
}
resultAttributes.attributes = graphic.attributes;
resultAttributes.title = title ? title : fallbackTitle;
resultAttributes.content = content.replace(/\n$/, '');
resultAttributes.link = link ? link : null;
resultAttributes.linkAlias = linkAlias;
function displayFields(fieldName:String, fieldXML:XML, field:Field):void
{
var fieldNameTextValue:String = graphic.attributes[fieldName];
value = fieldNameTextValue ? fieldNameTextValue : "";
if (value)
{
var isDateField:Boolean;
var useUTC:Boolean;
var dateFormat:String;
if (fieldXML)
{
useUTC = fieldXML.format.@useutc[0] || fieldXML.@useutc[0] == "true";
dateFormat = fieldXML.format.@dateformat[0] || fieldXML.@dateformat[0];
if (dateFormat)
{
isDateField = true;
}
}
if (!isDateField && field)
{
isDateField = field.type == Field.TYPE_DATE;
}
if (isDateField)
{
var dateMS:Number = Number(value);
if (!isNaN(dateMS))
{
value = msToDate(dateMS, dateFormat, useUTC);
}
}
else
{
var typeID:String = layerDetails.typeIdField ? graphic.attributes[layerDetails.typeIdField] : null;
if (fieldName == layerDetails.typeIdField)
{
var featureType:FeatureType = getFeatureType(layer, typeID);
if (featureType && featureType.name)
{
value = featureType.name;
}
}
else
{
var codedValue:CodedValue = getCodedValue(layer, fieldName, value, typeID);
if (codedValue)
{
value = codedValue.name;
}
}
}
}
if (titleField && fieldName.toUpperCase() == titleField.toUpperCase())
{
title = value;
}
else if (linkField && fieldName.toUpperCase() == linkField.toUpperCase())
{
link = value;
linkAlias = linkAlias;
}
else if (fieldName.toUpperCase() != "SHAPE_LENGTH" && fieldName.toUpperCase() != "SHAPE_AREA")
{
var fieldLabel:String;
if (fieldXML && fieldXML.@alias[0])
{
fieldLabel = fieldXML.@alias[0];
}
else
{
fieldLabel = featureSet.fieldAliases[fieldName];
}
if (FlexGlobals.topLevelApplication.layoutDirection == LayoutDirection.RTL)
{
content += value + " :" + fieldLabel + "\n";
}
else
{
content += fieldLabel + ": " + value + "\n";
}
}
}
return resultAttributes;
}
private static function getFieldXML(fieldName:String, fields:XMLList):XML
{
var result:XML;
for each (var fieldXML:XML in fields)
{
if (fieldName == fieldXML.@name[0])
{
result = fieldXML;
break;
}
}
return result;
}
private static function getField(layer:FeatureLayer, fieldName:String):Field
{
var result:Field;
if (layer)
{
for each (var field:Field in layer.layerDetails.fields)
{
if (fieldName == field.name)
{
result = field;
break;
}
}
}
return result;
}
private static function getFeatureType(layer:FeatureLayer, typeID:String):FeatureType
{
var result:FeatureType;
if (layer)
{
for each (var featureType:FeatureType in layer.layerDetails.types)
{
if (typeID == featureType.id)
{
result = featureType;
break;
}
}
}
return result;
}
private static function msToDate(ms:Number, dateFormat:String, useUTC:Boolean):String
{
var date:Date = new Date(ms);
if (date.milliseconds == 999) // workaround for REST bug
{
date.milliseconds++;
}
if (useUTC)
{
date.minutes += date.timezoneOffset;
}
if (dateFormat)
{
var dateFormatter:DateFormatter = new DateFormatter();
dateFormatter.formatString = dateFormat;
var result:String = dateFormatter.format(date);
if (result)
{
return result;
}
else
{
return dateFormatter.error;
}
}
else
{
return date.toLocaleString();
}
}
private static function getCodedValue(layer:FeatureLayer, fieldName:String, fieldValue:String, typeID:String):CodedValue
{
var result:CodedValue;
var codedValueDomain:CodedValueDomain;
if (typeID)
{
var featureType:FeatureType = getFeatureType(layer, typeID);
if (featureType)
{
codedValueDomain = featureType.domains[fieldName] as CodedValueDomain;
}
}
else
{
var field:Field = getField(layer, fieldName);
if (field)
{
codedValueDomain = field.domain as CodedValueDomain;
}
}
if (codedValueDomain)
{
for each (var codedValue:CodedValue in codedValueDomain.codedValues)
{
if (fieldValue == codedValue.code)
{
result = codedValue;
break;
}
}
}
return result;
}
}
}
|
Remove trailing ResultAttributes#toResultAttributes() content newlines.
|
Remove trailing ResultAttributes#toResultAttributes() content newlines.
|
ActionScript
|
apache-2.0
|
Esri/arcgis-viewer-flex,CanterburyRegionalCouncil/arcgis-viewer-flex,CanterburyRegionalCouncil/arcgis-viewer-flex,CanterburyRegionalCouncil/arcgis-viewer-flex,Esri/arcgis-viewer-flex
|
f75d46f75fbad01f2955a6a880f49db98c6bc68e
|
src/as/com/threerings/io/Streamer.as
|
src/as/com/threerings/io/Streamer.as
|
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2009 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.io {
import flash.utils.ByteArray;
import flash.utils.Dictionary;
import com.threerings.util.ByteEnum;
import com.threerings.util.ClassUtil;
import com.threerings.util.Enum;
import com.threerings.io.streamers.ArrayStreamer;
import com.threerings.io.streamers.ByteArrayStreamer;
import com.threerings.io.streamers.ByteEnumStreamer;
import com.threerings.io.streamers.EnumStreamer;
import com.threerings.io.streamers.NumberStreamer;
import com.threerings.io.streamers.StringStreamer;
public class Streamer
{
public static function getStreamer (obj :Object) :Streamer
{
var jname :String;
if (obj is TypedArray) {
jname = TypedArray(obj).getJavaType();
} else {
jname = Translations.getToServer(ClassUtil.getClassName(obj));
}
return getStreamerByJavaName(jname);
}
public static function getStreamerByJavaName (jname :String) :Streamer
{
initStreamers();
// unstream lists as simple arrays
if (jname == "java.util.List" || jname == "java.util.ArrayList") {
jname = "[Ljava.lang.Object;";
}
// see if we have a streamer for it
var streamer :Streamer = _byJName[jname] as Streamer;
if (streamer != null) {
return streamer;
}
// see if it's an array that we unstream using an ArrayStreamer
if (jname.charAt(0) === "[") {
streamer = new ArrayStreamer(jname);
} else {
// otherwise see if it represents a Streamable
// usually this is called from ObjectInputStream, but when it's called from
// ObjectOutputStream it's a bit annoying, because we started with a class/object.
// But: the code is smaller, so that wins
var clazz :Class = ClassUtil.getClassByName(Translations.getFromServer(jname));
if (ClassUtil.isAssignableAs(Enum, clazz)) {
streamer = ClassUtil.isAssignableAs(ByteEnum, clazz) ?
new ByteEnumStreamer(clazz, jname) : new EnumStreamer(clazz, jname);
} else if (ClassUtil.isAssignableAs(Streamable, clazz)) {
streamer = new Streamer(clazz, jname);
} else {
return null;
}
}
// add the good new streamer
registerStreamer(streamer);
return streamer;
}
/** This should be a protected constructor. */
public function Streamer (targ :Class, jname :String = null)
//throws IOError
{
_target = targ;
_jname = (jname != null) ? jname : Translations.getToServer(ClassUtil.getClassName(targ));
}
/**
* Return the String to use to identify the class that we're streaming.
*/
public function getJavaClassName () :String
{
return _jname;
}
public function writeObject (obj :Object, out :ObjectOutputStream) :void
//throws IOError
{
(obj as Streamable).writeObject(out);
}
public function createObject (ins :ObjectInputStream) :Object
//throws IOError
{
// actionscript is so fucked up
return new _target();
}
public function readObject (obj :Object, ins :ObjectInputStream) :void
//throws IOError
{
(obj as Streamable).readObject(ins);
}
protected static function registerStreamer (st :Streamer) :void
{
_byJName[st.getJavaClassName()] = st;
}
/**
* Initialize our streamers. This cannot simply be done statically
* because we cannot instantiate a subclass when this class is still
* being created. Fucking actionscript.
*/
private static function initStreamers () :void
{
if (_byJName != null) {
return;
}
_byJName = new Dictionary();
for each (var c :Class in
[ StringStreamer, NumberStreamer, ArrayStreamer, ByteArrayStreamer ]) {
registerStreamer(Streamer(new c()));
}
}
protected var _target :Class;
protected var _jname :String;
protected static var _byJName :Dictionary;
}
}
|
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2009 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.io {
import flash.utils.ByteArray;
import flash.utils.Dictionary;
import com.threerings.util.ByteEnum;
import com.threerings.util.ClassUtil;
import com.threerings.util.Enum;
import com.threerings.io.streamers.ArrayStreamer;
import com.threerings.io.streamers.ByteArrayStreamer;
import com.threerings.io.streamers.ByteEnumStreamer;
import com.threerings.io.streamers.EnumStreamer;
import com.threerings.io.streamers.NumberStreamer;
import com.threerings.io.streamers.StringStreamer;
public class Streamer
{
public static function getStreamer (obj :Object) :Streamer
{
var jname :String;
if (obj is TypedArray) {
jname = TypedArray(obj).getJavaType();
} else {
jname = Translations.getToServer(ClassUtil.getClassName(obj));
}
return getStreamerByJavaName(jname);
}
public static function getStreamerByJavaName (jname :String) :Streamer
{
initStreamers();
// unstream lists as simple arrays
if (jname == "java.util.List" || jname == "java.util.ArrayList") {
jname = "[Ljava.lang.Object;";
}
// see if we have a streamer for it
var streamer :Streamer = _byJName[jname] as Streamer;
if (streamer != null) {
return streamer;
}
// see if it's an array that we unstream using an ArrayStreamer
if (jname.charAt(0) === "[") {
streamer = new ArrayStreamer(jname);
} else {
// otherwise see if it represents a Streamable
// usually this is called from ObjectInputStream, but when it's called from
// ObjectOutputStream it's a bit annoying, because we started with a class/object.
// But: the code is smaller, so that wins
var clazz :Class = ClassUtil.getClassByName(Translations.getFromServer(jname));
if (ClassUtil.isAssignableAs(Enum, clazz)) {
streamer = ClassUtil.isAssignableAs(ByteEnum, clazz) ?
new ByteEnumStreamer(clazz, jname) : new EnumStreamer(clazz, jname);
} else if (ClassUtil.isAssignableAs(Streamable, clazz)) {
streamer = new Streamer(clazz, jname);
} else {
return null;
}
}
// add the good new streamer
registerStreamer(streamer);
return streamer;
}
/** This should be a protected constructor. */
public function Streamer (targ :Class, jname :String = null)
//throws IOError
{
_target = targ;
_jname = (jname != null) ? jname : Translations.getToServer(ClassUtil.getClassName(targ));
}
/**
* Return the String to use to identify the class that we're streaming.
*/
public function getJavaClassName () :String
{
return _jname;
}
public function writeObject (obj :Object, out :ObjectOutputStream) :void
//throws IOError
{
(obj as Streamable).writeObject(out);
}
public function createObject (ins :ObjectInputStream) :Object
//throws IOError
{
// actionscript is so fucked up
return new _target();
}
public function readObject (obj :Object, ins :ObjectInputStream) :void
//throws IOError
{
(obj as Streamable).readObject(ins);
}
public function toString () :String
{
return "[Streamer(" + _jname + ")]";
}
protected static function registerStreamer (st :Streamer) :void
{
_byJName[st.getJavaClassName()] = st;
}
/**
* Initialize our streamers. This cannot simply be done statically
* because we cannot instantiate a subclass when this class is still
* being created. Fucking actionscript.
*/
private static function initStreamers () :void
{
if (_byJName != null) {
return;
}
_byJName = new Dictionary();
for each (var c :Class in
[ StringStreamer, NumberStreamer, ArrayStreamer, ByteArrayStreamer ]) {
registerStreamer(Streamer(new c()));
}
}
protected var _target :Class;
protected var _jname :String;
protected static var _byJName :Dictionary;
}
}
|
Add a better toString, for debugging.
|
Add a better toString, for debugging.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@5963 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
2b9e77607fecc9bf970419f81d78569d95f2e4ad
|
src/com/pivotshare/hls/loader/FragmentStream.as
|
src/com/pivotshare/hls/loader/FragmentStream.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 com.pivotshare.hls.loader {
import flash.display.DisplayObject;
import flash.events.*;
import flash.net.*;
import flash.utils.ByteArray;
import flash.utils.getTimer;
import flash.utils.Timer;
import org.mangui.hls.constant.HLSLoaderTypes;
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.model.Fragment;
import org.mangui.hls.model.FragmentData;
import org.mangui.hls.utils.AES;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
import org.mangui.hls.utils.Hex;
}
/**
* HLS Fragment Streamer, which also handles decryption.
* Tries to parallel URLStream design pattern, but is incomplete.
*
* See [Reading and writing a ByteArray](http://help.adobe.com/en_US/as3/dev/WS5b3ccc516d4fbf351e63e3d118666ade46-7d54.html)
*
* @class FragmentStream
* @extends EventDispatcher
* @author HGPA
*/
public class FragmentStream extends EventDispatcher {
/*
* DisplayObject needed by AES decrypter.
*/
private var _displayObject : DisplayObject;
/*
* Fragment being loaded.
*/
private var _fragment : Fragment;
/*
* URLStream used to download current Fragment.
*/
private var _fragmentURLStream : URLStream;
/**
* Create a FragmentStream.
*
* This constructor takes a reference to main DisplayObject, e.g. stage,
* necessary for AES decryption control.
*
* TODO: It would be more appropriate to create a factory that itself
* takes the DisplayObject (or a more flexible version of AES).
*
* @constructor
* @param {DisplayObject} displayObject
*/
public function FragmentStream(displayObject : DisplayObject) : void {
_displayObject = displayObject;
};
/*
* Return FragmentData of Fragment currently being downloaded.
* Of immediate interest is the `bytes` field.
*
* @method getFragment
* @return {Fragment}
*/
public function getFragment() : Fragment {
return _fragment;
}
/*
* Close the stream.
*
* @method close
*/
public function close() : void {
if (_fragmentURLStream && _fragmentURLStream.connected) {
_fragmentURLStream.close();
}
if (_fragment) {
if (_fragment.data.decryptAES) {
_fragment.data.decryptAES.cancel();
_fragment.data.decryptAES = null;
}
// Explicitly release memory
// http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/utils/ByteArray.html#clear()
_fragment.data.bytes.clear();
_fragment.data.bytes = null;
}
}
/**
* Load a Fragment.
*
* This class/methods DOES NOT user reference of parameter. Instead it
* clones the Fragment and manipulates this internally.
*
* @method load
* @param {Fragment} fragment - Fragment with details (cloned)
* @param {ByteArray} key - Encryption Key
* @return {HLSLoadMetrics}
*/
public function load(fragment : Fragment, key : ByteArray) : HLSLoadMetrics {
// Clone Fragment, with new initilizations of deep fields
// Passing around references is what is causing problems.
// FragmentData is initialized as part of construction
_fragment = new Fragment(
fragment.url,
fragment.duration,
fragment.level,
fragment.seqnum,
fragment.start_time,
fragment.continuity,
fragment.program_date,
fragment.decrypt_url,
fragment.decrypt_iv, // We need this reference
fragment.byterange_start_offset,
fragment.byterange_end_offset,
new Vector.<String>()
)
_fragmentURLStream = new URLStream();
// START (LOADING) METRICS
// Event listener callbacks enclose _metrics
var _metrics : HLSLoadMetrics = new HLSLoadMetrics(HLSLoaderTypes.FRAGMENT_MAIN);
_metrics.level = _fragment.level;
_metrics.id = _fragment.seqnum;
_metrics.loading_request_time = getTimer();
// String used to identify fragment in debug messages
CONFIG::LOGGING {
var fragmentString : String = "Fragment[" + _fragment.level + "][" + _fragment.seqnum + "]";
}
//
// See `onLoadProgress` first.
//
/*
* Called when Fragment is processing which may inclue decryption.
*
* To access data, call `Fragment.getFragment`, which will include
* all bytes loaded to this point, with FragmentData's ByteArray
* having the expected position
*
* NOTE: This was `FragmentLoader._fragDecryptProgressHandler` before refactor.
*
* @method onProcess
* @param {ByteArray} data - *Portion* of data that finished processing
*/
var onProcess : Function = function onProcess(data : ByteArray) : void {
// Ensure byte array pointer starts at beginning
data.position = 0;
var bytes : ByteArray = _fragment.data.bytes;
// Byte Range Business
// TODO: Confirm this is still working
if (_fragment.byterange_start_offset != -1) {
_fragment.data.bytes.position = _fragment.data.bytes.length;
_fragment.data.bytes.writeBytes(data);
// if we have retrieved all the data, disconnect loader and notify fragment complete
if (_fragment.data.bytes.length >= _fragment.byterange_end_offset) {
if (_fragmentURLStream.connected) {
_fragmentURLStream.close();
onProcessComplete(null);
}
}
} else {
// Append data to Fragment, but then reset position to mimic
// expected pattern of URLStream
var fragmentPosition : int = _fragment.data.bytes.position;
_fragment.data.bytes.position = _fragment.data.bytes.length;
_fragment.data.bytes.writeBytes(data);
_fragment.data.bytes.position = fragmentPosition;
}
var progressEvent : ProgressEvent = new ProgressEvent(
ProgressEvent.PROGRESS,
false,
false,
_fragment.data.bytes.length, // bytesLoaded
_fragment.data.bytesTotal // bytesTotal
);
dispatchEvent(progressEvent);
}
/*
* Called when Fragment has completed processing.
* May or may not include decryption.
*
* NOTE: This was `FragmentLoader._fragDecryptCompleteHandler`
* before refactor.
*
* @method onProcessComplete
* @param {ByteArray} data - Portion of data finished processing
*/
var onProcessComplete : Function = function onProcessComplete() : void {
// END DECRYPTION METRICS
// garbage collect AES decrypter
if (_fragment.data.decryptAES) {
_metrics.decryption_end_time = getTimer();
var decrypt_duration : Number = _metrics.decryption_end_time - _metrics.decryption_begin_time;
CONFIG::LOGGING {
Log.debug("FragmentStream#onProcessComplete: Decrypted duration/length/speed:" +
decrypt_duration + "/" + _fragment.data.bytesLoaded + "/" +
Math.round((8000 * _fragment.data.bytesLoaded / decrypt_duration) / 1024) + " kb/s");
}
_fragment.data.decryptAES = null;
}
var completeEvent : Event = new ProgressEvent(Event.COMPLETE);
dispatchEvent(completeEvent);
}
/*
* Called when URLStream has download a portion of the file fragment.
* This event callback delegates to decrypter if necessary.
* Eventually onProcess is called when the downloaded portion has
* finished processing.
*
* NOTE: Was `_fragLoadCompleteHandler` before refactor
*
* @param {ProgressEvent} evt - Portion of data finished processing
*/
var onLoadProgress : Function = function onProgress(evt : ProgressEvent) : void {
// First call of onProgress for this Fragment
// Initilize fields in Fragment and FragmentData
if (_fragment.data.bytes == null) {
_fragment.data.bytes = new ByteArray();
_fragment.data.bytesLoaded = 0;
_fragment.data.bytesTotal = evt.bytesTotal;
_fragment.data.flushTags();
// NOTE: This may be wrong, as it is only called after data
// has been loaded.
_metrics.loading_begin_time = getTimer();
CONFIG::LOGGING {
Log.debug("FragmentStream#onLoadProgress: Downloaded " +
fragmentString + "'s first " + evt.bytesLoaded +
" bytes of " + evt.bytesTotal + " Total");
}
// decrypt data if needed
if (_fragment.decrypt_url != null) {
// START DECRYPTION METRICS
_metrics.decryption_begin_time = getTimer();
CONFIG::LOGGING {
Log.debug("FragmentStream#onLoadProgress: " + fragmentString + " needs to be decrypted");
}
_fragment.data.decryptAES = new AES(
_displayObject,
key,
_fragment.decrypt_iv,
onProcess,
onProcessComplete
);
} else {
_fragment.data.decryptAES = null;
}
}
if (evt.bytesLoaded > _fragment.data.bytesLoaded && _fragmentURLStream.bytesAvailable > 0) { // prevent EOF error race condition
// bytes from URLStream
var data : ByteArray = new ByteArray();
_fragmentURLStream.readBytes(data);
// Mark that bytes have been loaded, but do not store these
// bytes yet
_fragment.data.bytesLoaded += data.length;
if (_fragment.data.decryptAES != null) {
_fragment.data.decryptAES.append(data);
} else {
onProcess(data);
}
}
}
/*
* Called when URLStream had completed downloading.
*
* @param {Event} evt - Portion of data finished processing
*/
var onLoadComplete : Function = function onLoadComplete(evt : Event) : void {
// load complete, reset retry counter
//_fragRetryCount = 0;
//_fragRetryTimeout = 1000;
if (_fragment.data.bytes == null) {
CONFIG::LOGGING {
Log.warn("FragmentStream#onLoadComplete: " + fragmentString +
" size is null, invalidate it and load next one");
}
//_levels[_hls.loadLevel].updateFragment(_fragCurrent.seqnum, false);
//_loadingState = LOADING_IDLE;
// TODO: Dispatch an error
return;
}
CONFIG::LOGGING {
Log.debug("FragmentStream#onLoadComplete: " + fragmentString +
" has finished downloading, but may still be decrypting");
}
// TODO: ???
//_fragSkipping = false;
// END LOADING METRICS
_metrics.loading_end_time = getTimer();
_metrics.size = _fragment.data.bytesLoaded;
var _loading_duration : uint = _metrics.loading_end_time - _metrics.loading_request_time;
CONFIG::LOGGING {
Log.debug("FragmentStream#onLoadComplete: Loading duration/RTT/length/speed:" +
_loading_duration + "/" +
(_metrics.loading_begin_time - _metrics.loading_request_time) + "/" +
_metrics.size + "/" +
Math.round((8000 * _metrics.size / _loading_duration) / 1024) + " kb/s");
}
if (_fragment.data.decryptAES) {
_fragment.data.decryptAES.notifycomplete(); // Calls onProcessComplete by proxy
} else {
onProcessComplete();
}
}
/*
* Called when URLStream has Errored.
* @param {ErrorEvent} evt - Portion of data finished processing
*/
var onLoadError : Function = function onLoadError(evt : ErrorEvent) : void {
CONFIG::LOGGING {
Log.error("FragmentStream#onLoadError: " + evt.text);
}
// Forward error
dispatchEvent(evt);
}
_fragmentURLStream.addEventListener(IOErrorEvent.IO_ERROR, onLoadError);
_fragmentURLStream.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onLoadError);
_fragmentURLStream.addEventListener(ProgressEvent.PROGRESS, onLoadProgress);
_fragmentURLStream.addEventListener(Event.COMPLETE, onLoadComplete);
_fragmentURLStream.load(new URLRequest(fragment.url));
return _metrics;
}
}
}
|
/* 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 com.pivotshare.hls.loader {
import flash.display.DisplayObject;
import flash.events.*;
import flash.net.*;
import flash.utils.ByteArray;
import flash.utils.getTimer;
import flash.utils.Timer;
import org.mangui.hls.constant.HLSLoaderTypes;
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.model.Fragment;
import org.mangui.hls.model.FragmentData;
import org.mangui.hls.utils.AES;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
import org.mangui.hls.utils.Hex;
}
/**
* HLS Fragment Streamer, which also handles decryption.
* Tries to parallel URLStream design pattern, but is incomplete.
*
* See [Reading and writing a ByteArray](http://help.adobe.com/en_US/as3/dev/WS5b3ccc516d4fbf351e63e3d118666ade46-7d54.html)
*
* @class FragmentStream
* @extends EventDispatcher
* @author HGPA
*/
public class FragmentStream extends EventDispatcher {
/*
* DisplayObject needed by AES decrypter.
*/
private var _displayObject : DisplayObject;
/*
* Fragment being loaded.
*/
private var _fragment : Fragment;
/*
* URLStream used to download current Fragment.
*/
private var _fragmentURLStream : URLStream;
/**
* Create a FragmentStream.
*
* This constructor takes a reference to main DisplayObject, e.g. stage,
* necessary for AES decryption control.
*
* TODO: It would be more appropriate to create a factory that itself
* takes the DisplayObject (or a more flexible version of AES).
*
* @constructor
* @param {DisplayObject} displayObject
*/
public function FragmentStream(displayObject : DisplayObject) : void {
_displayObject = displayObject;
};
/*
* Return FragmentData of Fragment currently being downloaded.
* Of immediate interest is the `bytes` field.
*
* @method getFragment
* @return {Fragment}
*/
public function getFragment() : Fragment {
return _fragment;
}
/*
* Close the stream.
*
* @method close
*/
public function close() : void {
if (_fragmentURLStream && _fragmentURLStream.connected) {
_fragmentURLStream.close();
}
if (_fragment && _fragment.data) {
if (_fragment.data.decryptAES) {
_fragment.data.decryptAES.cancel();
_fragment.data.decryptAES = null;
}
// Explicitly release memory
// http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/utils/ByteArray.html#clear()
if (_fragment.data.bytes) {
_fragment.data.bytes.clear();
_fragment.data.bytes = null;
}
}
}
/**
* Load a Fragment.
*
* This class/methods DOES NOT user reference of parameter. Instead it
* clones the Fragment and manipulates this internally.
*
* @method load
* @param {Fragment} fragment - Fragment with details (cloned)
* @param {ByteArray} key - Encryption Key
* @return {HLSLoadMetrics}
*/
public function load(fragment : Fragment, key : ByteArray) : HLSLoadMetrics {
// Clone Fragment, with new initilizations of deep fields
// Passing around references is what is causing problems.
// FragmentData is initialized as part of construction
_fragment = new Fragment(
fragment.url,
fragment.duration,
fragment.level,
fragment.seqnum,
fragment.start_time,
fragment.continuity,
fragment.program_date,
fragment.decrypt_url,
fragment.decrypt_iv, // We need this reference
fragment.byterange_start_offset,
fragment.byterange_end_offset,
new Vector.<String>()
)
_fragmentURLStream = new URLStream();
// START (LOADING) METRICS
// Event listener callbacks enclose _metrics
var _metrics : HLSLoadMetrics = new HLSLoadMetrics(HLSLoaderTypes.FRAGMENT_MAIN);
_metrics.level = _fragment.level;
_metrics.id = _fragment.seqnum;
_metrics.loading_request_time = getTimer();
// String used to identify fragment in debug messages
CONFIG::LOGGING {
var fragmentString : String = "Fragment[" + _fragment.level + "][" + _fragment.seqnum + "]";
}
//
// See `onLoadProgress` first.
//
/*
* Called when Fragment is processing which may inclue decryption.
*
* To access data, call `Fragment.getFragment`, which will include
* all bytes loaded to this point, with FragmentData's ByteArray
* having the expected position
*
* NOTE: This was `FragmentLoader._fragDecryptProgressHandler` before refactor.
*
* @method onProcess
* @param {ByteArray} data - *Portion* of data that finished processing
*/
var onProcess : Function = function onProcess(data : ByteArray) : void {
// Ensure byte array pointer starts at beginning
data.position = 0;
var bytes : ByteArray = _fragment.data.bytes;
// Byte Range Business
// TODO: Confirm this is still working
if (_fragment.byterange_start_offset != -1) {
_fragment.data.bytes.position = _fragment.data.bytes.length;
_fragment.data.bytes.writeBytes(data);
// if we have retrieved all the data, disconnect loader and notify fragment complete
if (_fragment.data.bytes.length >= _fragment.byterange_end_offset) {
if (_fragmentURLStream.connected) {
_fragmentURLStream.close();
onProcessComplete(null);
}
}
} else {
// Append data to Fragment, but then reset position to mimic
// expected pattern of URLStream
var fragmentPosition : int = _fragment.data.bytes.position;
_fragment.data.bytes.position = _fragment.data.bytes.length;
_fragment.data.bytes.writeBytes(data);
_fragment.data.bytes.position = fragmentPosition;
}
var progressEvent : ProgressEvent = new ProgressEvent(
ProgressEvent.PROGRESS,
false,
false,
_fragment.data.bytes.length, // bytesLoaded
_fragment.data.bytesTotal // bytesTotal
);
dispatchEvent(progressEvent);
}
/*
* Called when Fragment has completed processing.
* May or may not include decryption.
*
* NOTE: This was `FragmentLoader._fragDecryptCompleteHandler`
* before refactor.
*
* @method onProcessComplete
* @param {ByteArray} data - Portion of data finished processing
*/
var onProcessComplete : Function = function onProcessComplete() : void {
// END DECRYPTION METRICS
// garbage collect AES decrypter
if (_fragment.data.decryptAES) {
_metrics.decryption_end_time = getTimer();
var decrypt_duration : Number = _metrics.decryption_end_time - _metrics.decryption_begin_time;
CONFIG::LOGGING {
Log.debug("FragmentStream#onProcessComplete: Decrypted duration/length/speed:" +
decrypt_duration + "/" + _fragment.data.bytesLoaded + "/" +
Math.round((8000 * _fragment.data.bytesLoaded / decrypt_duration) / 1024) + " kb/s");
}
_fragment.data.decryptAES = null;
}
var completeEvent : Event = new ProgressEvent(Event.COMPLETE);
dispatchEvent(completeEvent);
}
/*
* Called when URLStream has download a portion of the file fragment.
* This event callback delegates to decrypter if necessary.
* Eventually onProcess is called when the downloaded portion has
* finished processing.
*
* NOTE: Was `_fragLoadCompleteHandler` before refactor
*
* @param {ProgressEvent} evt - Portion of data finished processing
*/
var onLoadProgress : Function = function onProgress(evt : ProgressEvent) : void {
// First call of onProgress for this Fragment
// Initilize fields in Fragment and FragmentData
if (_fragment.data.bytes == null) {
_fragment.data.bytes = new ByteArray();
_fragment.data.bytesLoaded = 0;
_fragment.data.bytesTotal = evt.bytesTotal;
_fragment.data.flushTags();
// NOTE: This may be wrong, as it is only called after data
// has been loaded.
_metrics.loading_begin_time = getTimer();
CONFIG::LOGGING {
Log.debug("FragmentStream#onLoadProgress: Downloaded " +
fragmentString + "'s first " + evt.bytesLoaded +
" bytes of " + evt.bytesTotal + " Total");
}
// decrypt data if needed
if (_fragment.decrypt_url != null) {
// START DECRYPTION METRICS
_metrics.decryption_begin_time = getTimer();
CONFIG::LOGGING {
Log.debug("FragmentStream#onLoadProgress: " + fragmentString + " needs to be decrypted");
}
_fragment.data.decryptAES = new AES(
_displayObject,
key,
_fragment.decrypt_iv,
onProcess,
onProcessComplete
);
} else {
_fragment.data.decryptAES = null;
}
}
if (evt.bytesLoaded > _fragment.data.bytesLoaded && _fragmentURLStream.bytesAvailable > 0) { // prevent EOF error race condition
// bytes from URLStream
var data : ByteArray = new ByteArray();
_fragmentURLStream.readBytes(data);
// Mark that bytes have been loaded, but do not store these
// bytes yet
_fragment.data.bytesLoaded += data.length;
if (_fragment.data.decryptAES != null) {
_fragment.data.decryptAES.append(data);
} else {
onProcess(data);
}
}
}
/*
* Called when URLStream had completed downloading.
*
* @param {Event} evt - Portion of data finished processing
*/
var onLoadComplete : Function = function onLoadComplete(evt : Event) : void {
// load complete, reset retry counter
//_fragRetryCount = 0;
//_fragRetryTimeout = 1000;
if (_fragment.data.bytes == null) {
CONFIG::LOGGING {
Log.warn("FragmentStream#onLoadComplete: " + fragmentString +
" size is null, invalidate it and load next one");
}
//_levels[_hls.loadLevel].updateFragment(_fragCurrent.seqnum, false);
//_loadingState = LOADING_IDLE;
// TODO: Dispatch an error
return;
}
CONFIG::LOGGING {
Log.debug("FragmentStream#onLoadComplete: " + fragmentString +
" has finished downloading, but may still be decrypting");
}
// TODO: ???
//_fragSkipping = false;
// END LOADING METRICS
_metrics.loading_end_time = getTimer();
_metrics.size = _fragment.data.bytesLoaded;
var _loading_duration : uint = _metrics.loading_end_time - _metrics.loading_request_time;
CONFIG::LOGGING {
Log.debug("FragmentStream#onLoadComplete: Loading duration/RTT/length/speed:" +
_loading_duration + "/" +
(_metrics.loading_begin_time - _metrics.loading_request_time) + "/" +
_metrics.size + "/" +
Math.round((8000 * _metrics.size / _loading_duration) / 1024) + " kb/s");
}
if (_fragment.data.decryptAES) {
_fragment.data.decryptAES.notifycomplete(); // Calls onProcessComplete by proxy
} else {
onProcessComplete();
}
}
/*
* Called when URLStream has Errored.
* @param {ErrorEvent} evt - Portion of data finished processing
*/
var onLoadError : Function = function onLoadError(evt : ErrorEvent) : void {
CONFIG::LOGGING {
Log.error("FragmentStream#onLoadError: " + evt.text);
}
// Forward error
dispatchEvent(evt);
}
_fragmentURLStream.addEventListener(IOErrorEvent.IO_ERROR, onLoadError);
_fragmentURLStream.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onLoadError);
_fragmentURLStream.addEventListener(ProgressEvent.PROGRESS, onLoadProgress);
_fragmentURLStream.addEventListener(Event.COMPLETE, onLoadComplete);
_fragmentURLStream.load(new URLRequest(fragment.url));
return _metrics;
}
}
}
|
Fix destruction
|
[FragmentStream] Fix destruction
|
ActionScript
|
mpl-2.0
|
codex-corp/flashls,codex-corp/flashls
|
28d1f6d8d8dc317921e036178742ccf765ed92d3
|
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.mesh.MeshController;
import aerys.minko.scene.controller.mesh.MeshVisibilityController;
import aerys.minko.scene.controller.mesh.skinning.SkinningController;
public class CloneOptions
{
private var _clonedControllerTypes : Vector.<Class> = new <Class>[];
private var _ignoredControllerTypes : Vector.<Class> = new <Class>[];
private var _reassignedControllerTypes : Vector.<Class> = new <Class>[];
private var _defaultControllerAction : uint = ControllerCloneAction.REASSIGN;
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()
{
}
public static function get defaultOptions() : CloneOptions
{
var cloneOptions : CloneOptions = new CloneOptions();
cloneOptions._clonedControllerTypes.push(
AnimationController,
SkinningController
);
cloneOptions._ignoredControllerTypes.push(
MeshController,
MeshVisibilityController,
CameraController,
TransformController
);
cloneOptions._defaultControllerAction = ControllerCloneAction.REASSIGN;
return cloneOptions;
}
public static function get cloneAllOptions() : CloneOptions
{
var cloneOptions : CloneOptions = new CloneOptions();
cloneOptions._ignoredControllerTypes.push(
MeshController,
MeshVisibilityController,
CameraController,
TransformController
);
cloneOptions._defaultControllerAction = ControllerCloneAction.CLONE;
return cloneOptions;
}
public function addControllerAction(controllerClass : Class, action : uint) : void
{
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.');
}
}
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.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
);
cloneOptions._defaultControllerAction = ControllerCloneAction.REASSIGN;
return cloneOptions;
}
public static function get cloneAllOptions() : CloneOptions
{
var cloneOptions : CloneOptions = new CloneOptions();
cloneOptions._ignoredControllerTypes.push(
MeshController,
MeshVisibilityController,
CameraController,
TransformController
);
cloneOptions._defaultControllerAction = ControllerCloneAction.CLONE;
return cloneOptions;
}
public function addControllerAction(controllerClass : Class, action : uint) : void
{
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.');
}
}
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 coding style
|
fix coding style
|
ActionScript
|
mit
|
aerys/minko-as3
|
4ac697f36077555a98b82699a8948e29eaca4f44
|
src/aerys/minko/render/resource/texture/TextureResource.as
|
src/aerys/minko/render/resource/texture/TextureResource.as
|
package aerys.minko.render.resource.texture
{
import aerys.minko.render.resource.Context3DResource;
import flash.display.BitmapData;
import flash.display3D.Context3DTextureFormat;
import flash.display3D.textures.Texture;
import flash.display3D.textures.TextureBase;
import flash.geom.Matrix;
import flash.utils.ByteArray;
/**
* @inheritdoc
* @author Jean-Marc Le Roux
*
*/
public final class TextureResource implements ITextureResource
{
private static const MAX_SIZE : uint = 2048;
private static const TMP_MATRIX : Matrix = new Matrix();
private static const FORMAT_BGRA : String = Context3DTextureFormat.BGRA
private static const FORMAT_COMPRESSED : String = Context3DTextureFormat.COMPRESSED;
private var _texture : Texture = null;
private var _mipmap : Boolean = false;
private var _bitmapData : BitmapData = null;
private var _atf : ByteArray = null;
private var _atfFormat : uint = 0;
private var _width : Number = 0;
private var _height : Number = 0;
private var _update : Boolean = false;
private var _resize : Boolean = false;
public function get width() : uint
{
return _width;
}
public function get height() : uint
{
return _height;
}
public function TextureResource(width : int = 0, height : int = 0)
{
if (width != 0 && height != 0)
setSize(width, height);
}
public function setSize(width : uint, height : uint) : void
{
//http://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2
if (!(width && !(width & (width - 1)))
|| !(height && !(height & (height - 1))))
{
throw new Error('The size must be a power of 2.');
}
_width = width;
_height = height;
_resize = true;
}
public function setContentFromBitmapData(bitmapData : BitmapData,
mipmap : Boolean,
downSample : Boolean = false) : void
{
var bitmapWidth : uint = bitmapData.width;
var bitmapHeight : uint = bitmapData.height;
var w : int = 0;
var h : int = 0;
if (downSample)
{
w = 1 << Math.floor(Math.log(bitmapWidth) * Math.LOG2E);
h = 1 << Math.floor(Math.log(bitmapHeight) * Math.LOG2E);
}
else
{
w = 1 << Math.ceil(Math.log(bitmapWidth) * Math.LOG2E);
h = 1 << Math.ceil(Math.log(bitmapHeight) * Math.LOG2E);
}
if (w > MAX_SIZE)
w = MAX_SIZE;
if (h > MAX_SIZE)
h = MAX_SIZE;
if (_bitmapData == null || _bitmapData.width != w || _bitmapData.height != h)
_bitmapData = new BitmapData(w, h, bitmapData.transparent, 0);
if (w != bitmapWidth || h != bitmapHeight)
{
TMP_MATRIX.identity();
TMP_MATRIX.scale(w / bitmapWidth, h / bitmapHeight);
_bitmapData.draw(bitmapData, TMP_MATRIX);
}
else
{
_bitmapData.draw(bitmapData);
}
if (_texture
&& (mipmap != _mipmap
|| bitmapData.width != _width
|| bitmapData.height != _height))
{
_texture.dispose();
_texture = null;
}
_width = _bitmapData.width;
_height = _bitmapData.height;
_mipmap = mipmap;
_update = true;
}
public function setContentFromATF(atf : ByteArray) : void
{
_atf = atf;
_update = true;
atf.position = 6;
_atfFormat = atf.readUnsignedByte() & 3;
_width = 1 << atf.readUnsignedByte();
_height = 1 << atf.readUnsignedByte();
_mipmap = atf.readUnsignedByte() > 1;
atf.position = 0;
}
public function getNativeTexture(context : Context3DResource) : TextureBase
{
if ((!_texture || _resize) && _width && _height)
{
_resize = false;
if (_texture)
_texture.dispose();
_texture = context.createTexture(
_width,
_height,
_atf && _atfFormat == 2 ? FORMAT_COMPRESSED : FORMAT_BGRA,
_bitmapData == null && _atf == null
);
_update = true;
}
if (_update)
{
_update = false;
uploadTextureWithMipMaps();
}
_atf = null;
_bitmapData = null;
if (_texture == null)
throw new Error();
return _texture;
}
private function uploadTextureWithMipMaps() : void
{
if (_bitmapData)
{
if (_mipmap)
{
var level : int = 0;
var size : int = _width > _height ? _width : _height;
var transparent : Boolean = _bitmapData.transparent;
var transform : Matrix = new Matrix();
var tmp : BitmapData = new BitmapData(
size,
size,
transparent,
0
);
while (size >= 1)
{
tmp.draw(_bitmapData, transform, null, null, null, true);
_texture.uploadFromBitmapData(tmp, level);
transform.scale(.5, .5);
level++;
size >>= 1;
if (tmp.transparent)
tmp.fillRect(tmp.rect, 0);
}
tmp.dispose();
}
else
{
_texture.uploadFromBitmapData(_bitmapData, 0);
}
_bitmapData.dispose();
}
else if (_atf)
{
_texture.uploadCompressedTextureFromByteArray(_atf, 0, false);
}
}
public function dispose() : void
{
if (_texture)
{
_texture.dispose();
_texture = null;
}
}
}
}
|
package aerys.minko.render.resource.texture
{
import aerys.minko.render.resource.Context3DResource;
import flash.display.BitmapData;
import flash.display3D.Context3DTextureFormat;
import flash.display3D.textures.Texture;
import flash.display3D.textures.TextureBase;
import flash.geom.Matrix;
import flash.utils.ByteArray;
/**
* @inheritdoc
* @author Jean-Marc Le Roux
*
*/
public final class TextureResource implements ITextureResource
{
private static const MAX_SIZE : uint = 2048;
private static const TMP_MATRIX : Matrix = new Matrix();
private static const FORMAT_BGRA : String = Context3DTextureFormat.BGRA
private static const FORMAT_COMPRESSED : String = Context3DTextureFormat.COMPRESSED;
private var _texture : Texture = null;
private var _mipmap : Boolean = false;
private var _bitmapData : BitmapData = null;
private var _atf : ByteArray = null;
private var _atfFormat : uint = 0;
private var _width : Number = 0;
private var _height : Number = 0;
private var _update : Boolean = false;
private var _resize : Boolean = false;
public function get width() : uint
{
return _width;
}
public function get height() : uint
{
return _height;
}
public function TextureResource(width : int = 0, height : int = 0)
{
if (width != 0 && height != 0)
setSize(width, height);
}
public function setSize(width : uint, height : uint) : void
{
//http://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2
if (!(width && !(width & (width - 1)))
|| !(height && !(height & (height - 1))))
{
throw new Error('The size must be a power of 2.');
}
_width = width;
_height = height;
_resize = true;
}
public function setContentFromBitmapData(bitmapData : BitmapData,
mipmap : Boolean,
downSample : Boolean = false) : void
{
var bitmapWidth : uint = bitmapData.width;
var bitmapHeight : uint = bitmapData.height;
var w : int = 0;
var h : int = 0;
if (downSample)
{
w = 1 << Math.floor(Math.log(bitmapWidth) * Math.LOG2E);
h = 1 << Math.floor(Math.log(bitmapHeight) * Math.LOG2E);
}
else
{
w = 1 << Math.ceil(Math.log(bitmapWidth) * Math.LOG2E);
h = 1 << Math.ceil(Math.log(bitmapHeight) * Math.LOG2E);
}
if (w > MAX_SIZE)
w = MAX_SIZE;
if (h > MAX_SIZE)
h = MAX_SIZE;
if (_bitmapData == null || _bitmapData.width != w || _bitmapData.height != h)
_bitmapData = new BitmapData(w, h, bitmapData.transparent, 0);
if (w != bitmapWidth || h != bitmapHeight)
{
TMP_MATRIX.identity();
TMP_MATRIX.scale(w / bitmapWidth, h / bitmapHeight);
_bitmapData.draw(bitmapData, TMP_MATRIX);
}
else
{
_bitmapData.draw(bitmapData);
}
if (_texture
&& (mipmap != _mipmap
|| bitmapData.width != _width
|| bitmapData.height != _height))
{
_texture.dispose();
_texture = null;
}
_width = _bitmapData.width;
_height = _bitmapData.height;
_mipmap = mipmap;
_update = true;
}
public function setContentFromATF(atf : ByteArray) : void
{
_atf = atf;
_bitmapData = null;
_update = true;
atf.position = 6;
_atfFormat = atf.readUnsignedByte() & 3;
_width = 1 << atf.readUnsignedByte();
_height = 1 << atf.readUnsignedByte();
_mipmap = atf.readUnsignedByte() > 1;
atf.position = 0;
}
public function getNativeTexture(context : Context3DResource) : TextureBase
{
if ((!_texture || _resize) && _width && _height)
{
_resize = false;
if (_texture)
_texture.dispose();
_texture = context.createTexture(
_width,
_height,
_atf && _atfFormat == 2 ? FORMAT_COMPRESSED : FORMAT_BGRA,
_bitmapData == null && _atf == null
);
_update = true;
}
if (_update)
{
_update = false;
uploadTextureWithMipMaps();
}
_atf = null;
_bitmapData = null;
if (_texture == null)
throw new Error();
return _texture;
}
private function uploadTextureWithMipMaps() : void
{
if (_bitmapData)
{
if (_mipmap)
{
var level : int = 0;
var size : int = _width > _height ? _width : _height;
var transparent : Boolean = _bitmapData.transparent;
var transform : Matrix = new Matrix();
var tmp : BitmapData = new BitmapData(
size,
size,
transparent,
0
);
while (size >= 1)
{
tmp.draw(_bitmapData, transform, null, null, null, true);
_texture.uploadFromBitmapData(tmp, level);
transform.scale(.5, .5);
level++;
size >>= 1;
if (tmp.transparent)
tmp.fillRect(tmp.rect, 0);
}
tmp.dispose();
}
else
{
_texture.uploadFromBitmapData(_bitmapData, 0);
}
_bitmapData.dispose();
}
else if (_atf)
{
_texture.uploadCompressedTextureFromByteArray(_atf, 0, false);
}
}
public function dispose() : void
{
if (_texture)
{
_texture.dispose();
_texture = null;
}
}
}
}
|
Fix for broken TextureResource.setContentForATF()
|
Fix for broken TextureResource.setContentForATF()
|
ActionScript
|
mit
|
aerys/minko-as3
|
adcc38dd58f0129912334d0a682119990452facb
|
src/com/esri/builder/controllers/supportClasses/WidgetTypeLoader.as
|
src/com/esri/builder/controllers/supportClasses/WidgetTypeLoader.as
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2016 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.CustomWidgetType;
import com.esri.builder.model.WidgetType;
import com.esri.builder.supportClasses.FileUtil;
import com.esri.builder.supportClasses.LogUtil;
import flash.events.EventDispatcher;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.utils.ByteArray;
import modules.IBuilderModule;
import modules.supportClasses.CustomXMLModule;
import mx.core.FlexGlobals;
import mx.events.ModuleEvent;
import mx.logging.ILogger;
import mx.logging.Log;
import mx.modules.IModuleInfo;
import mx.modules.ModuleManager;
public class WidgetTypeLoader extends EventDispatcher
{
private static const LOG:ILogger = LogUtil.createLogger(WidgetTypeLoader);
internal static var loadedModuleInfos:Array = [];
private var swf:File;
private var config:File;
//need reference when loading to avoid being garbage collected before load completes
private var moduleInfo:IModuleInfo;
//requires either swf or config
public function WidgetTypeLoader(swf:File = null, config:File = null)
{
this.swf = swf;
this.config = config;
}
public function get name():String
{
var fileName:String;
if (swf && swf.exists)
{
fileName = FileUtil.getFileName(swf);
}
else if (config && config.exists)
{
fileName = FileUtil.getFileName(config);
}
return fileName;
}
public function load():void
{
if (swf && swf.exists)
{
loadModule();
}
else if (!swf.exists && config.exists)
{
loadConfigModule();
}
else
{
dispatchError();
}
}
private function loadConfigModule():void
{
if (Log.isInfo())
{
LOG.info('Loading XML module: {0}', config.url);
}
var moduleConfig:XML = readModuleConfig(config);
if (moduleConfig)
{
var customWidgetType:CustomWidgetType = parseCustomWidgetType(moduleConfig);
if (customWidgetType)
{
dispatchComplete(customWidgetType);
return;
}
}
dispatchError();
}
private function loadModule():void
{
if (Log.isInfo())
{
LOG.info('Loading SWF module: {0}', swf.url);
}
moduleInfo = ModuleManager.getModule(swf.url);
if (moduleInfo.ready)
{
if (Log.isInfo())
{
LOG.info('Unloading module: {0}', swf.url);
}
moduleInfo.addEventListener(ModuleEvent.UNLOAD, moduleInfo_unloadHandler);
moduleInfo.release();
moduleInfo.unload();
}
else
{
if (Log.isInfo())
{
LOG.info('Loading module: {0}', swf.url);
}
var fileBytes:ByteArray = new ByteArray();
var fileStream:FileStream = new FileStream();
fileStream.open(swf, FileMode.READ);
fileStream.readBytes(fileBytes);
fileStream.close();
moduleInfo.addEventListener(ModuleEvent.READY, moduleInfo_readyHandler);
moduleInfo.addEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler);
moduleInfo.load(null, null, fileBytes, FlexGlobals.topLevelApplication.moduleFactory);
}
}
private function moduleInfo_unloadHandler(event:ModuleEvent):void
{
if (Log.isInfo())
{
LOG.info('Module unloaded: {0}', swf.url);
}
var moduleInfo:IModuleInfo = event.module;
moduleInfo.removeEventListener(ModuleEvent.UNLOAD, moduleInfo_unloadHandler);
var moduleInfoIndex:int = loadedModuleInfos.indexOf(moduleInfo);
if (moduleInfoIndex > -1)
{
loadedModuleInfos.splice(moduleInfoIndex, 1);
}
this.moduleInfo = null;
FlexGlobals.topLevelApplication.callLater(loadModule);
}
private function moduleInfo_readyHandler(event:ModuleEvent):void
{
if (Log.isInfo())
{
LOG.info('Module loaded: {0}', swf.url);
}
var moduleInfo:IModuleInfo = event.currentTarget as IModuleInfo;
moduleInfo.removeEventListener(ModuleEvent.READY, moduleInfo_readyHandler);
moduleInfo.removeEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler);
if (config && config.exists)
{
if (Log.isInfo())
{
LOG.info('Reading module config: {0}', config.url);
}
var moduleConfig:XML = readModuleConfig(config);
}
const builderModule:IBuilderModule = event.module.factory.create() as IBuilderModule;
if (builderModule)
{
if (Log.isInfo())
{
LOG.info('Widget type created for module: {0}', swf.url);
}
var widgetType:WidgetType = getWidgetType(moduleInfo, builderModule, moduleConfig);
}
loadedModuleInfos.push(moduleInfo);
this.moduleInfo = null;
dispatchComplete(widgetType);
}
private function dispatchComplete(widgetType:WidgetType):void
{
if (Log.isInfo())
{
LOG.info('Module load complete: {0}', name);
}
dispatchEvent(new WidgetTypeLoaderEvent(WidgetTypeLoaderEvent.LOAD_COMPLETE, widgetType));
}
private function getWidgetType(moduleInfo:IModuleInfo, builderModule:IBuilderModule, moduleConfig:XML):WidgetType
{
var customModulesDirectoryURL:String = WellKnownDirectories.getInstance().customModules.url;
var isCustomModule:Boolean = (moduleInfo.url.indexOf(customModulesDirectoryURL) > -1);
if (moduleConfig)
{
var configXML:XML = moduleConfig.configuration[0];
var version:String = moduleConfig.widgetversion[0];
}
return isCustomModule ?
new CustomWidgetType(builderModule, version, configXML) :
new WidgetType(builderModule);
}
private function readModuleConfig(configFile:File):XML
{
var configXML:XML;
var fileStream:FileStream = new FileStream();
try
{
fileStream.open(configFile, FileMode.READ);
configXML = XML(fileStream.readUTFBytes(fileStream.bytesAvailable));
}
catch (e:Error)
{
//ignore
if (Log.isInfo())
{
LOG.info('Could not read module config: {0}', e.toString());
}
}
finally
{
fileStream.close();
}
return configXML;
}
private function moduleInfo_errorHandler(event:ModuleEvent):void
{
var moduleInfo:IModuleInfo = event.module;
moduleInfo.removeEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler);
moduleInfo.removeEventListener(ModuleEvent.READY, moduleInfo_readyHandler);
this.moduleInfo = null;
dispatchError();
}
private function dispatchError():void
{
if (Log.isInfo())
{
LOG.info('Module load failed: {0}', name);
}
dispatchEvent(new WidgetTypeLoaderEvent(WidgetTypeLoaderEvent.LOAD_ERROR));
}
private function parseCustomWidgetType(configXML:XML):CustomWidgetType
{
if (Log.isInfo())
{
LOG.info('Creating widget type from XML: {0}', configXML);
}
var customModule:CustomXMLModule = new CustomXMLModule();
customModule.widgetName = configXML.name;
customModule.isOpenByDefault = (configXML.openbydefault == 'true');
var widgetLabel:String = configXML.label[0];
var widgetDescription:String = configXML.description[0];
var widgetHelpURL:String = configXML.helpurl[0];
var widgetConfiguration:XML = configXML.configuration[0] ? configXML.configuration[0] : <configuration/>;
var widgetVersion:String = configXML.widgetversion[0];
customModule.widgetIconLocation = createWidgetIconPath(configXML.icon[0], customModule.widgetName);
customModule.widgetLabel = widgetLabel ? widgetLabel : customModule.widgetName;
customModule.widgetDescription = widgetDescription ? widgetDescription : "";
customModule.widgetHelpURL = widgetHelpURL ? widgetHelpURL : "";
return new CustomWidgetType(customModule, widgetVersion, widgetConfiguration);
}
private function createWidgetIconPath(iconPath:String, widgetName:String):String
{
var widgetIconPath:String;
if (iconPath)
{
widgetIconPath = "widgets/" + widgetName + "/" + iconPath;
}
else
{
widgetIconPath = "assets/images/i_widget.png";
}
return widgetIconPath;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2016 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.CustomWidgetType;
import com.esri.builder.model.WidgetType;
import com.esri.builder.supportClasses.FileUtil;
import com.esri.builder.supportClasses.LogUtil;
import flash.events.EventDispatcher;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.utils.ByteArray;
import modules.IBuilderModule;
import modules.supportClasses.CustomXMLModule;
import mx.core.FlexGlobals;
import mx.events.ModuleEvent;
import mx.logging.ILogger;
import mx.logging.Log;
import mx.modules.IModuleInfo;
import mx.modules.ModuleManager;
public class WidgetTypeLoader extends EventDispatcher
{
private static const LOG:ILogger = LogUtil.createLogger(WidgetTypeLoader);
internal static var loadedModuleInfos:Array = [];
private var swf:File;
private var config:File;
//need reference when loading to avoid being garbage collected before load completes
private var moduleInfo:IModuleInfo;
//requires either swf or config
public function WidgetTypeLoader(swf:File = null, config:File = null)
{
this.swf = swf;
this.config = config;
}
public function get name():String
{
var fileName:String;
if (swf && swf.exists)
{
fileName = FileUtil.getFileName(swf);
}
else if (config && config.exists)
{
fileName = FileUtil.getFileName(config);
}
return fileName;
}
public function load():void
{
if (swf && swf.exists)
{
loadModule();
}
else if (config && config.exists)
{
loadConfigModule();
}
else
{
dispatchError();
}
}
private function loadConfigModule():void
{
if (Log.isInfo())
{
LOG.info('Loading XML module: {0}', config.url);
}
var moduleConfig:XML = readModuleConfig(config);
if (moduleConfig)
{
var customWidgetType:CustomWidgetType = parseCustomWidgetType(moduleConfig);
if (customWidgetType)
{
dispatchComplete(customWidgetType);
return;
}
}
dispatchError();
}
private function loadModule():void
{
if (Log.isInfo())
{
LOG.info('Loading SWF module: {0}', swf.url);
}
moduleInfo = ModuleManager.getModule(swf.url);
if (moduleInfo.ready)
{
if (Log.isInfo())
{
LOG.info('Unloading module: {0}', swf.url);
}
moduleInfo.addEventListener(ModuleEvent.UNLOAD, moduleInfo_unloadHandler);
moduleInfo.release();
moduleInfo.unload();
}
else
{
if (Log.isInfo())
{
LOG.info('Loading module: {0}', swf.url);
}
var fileBytes:ByteArray = new ByteArray();
var fileStream:FileStream = new FileStream();
fileStream.open(swf, FileMode.READ);
fileStream.readBytes(fileBytes);
fileStream.close();
moduleInfo.addEventListener(ModuleEvent.READY, moduleInfo_readyHandler);
moduleInfo.addEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler);
moduleInfo.load(null, null, fileBytes, FlexGlobals.topLevelApplication.moduleFactory);
}
}
private function moduleInfo_unloadHandler(event:ModuleEvent):void
{
if (Log.isInfo())
{
LOG.info('Module unloaded: {0}', swf.url);
}
var moduleInfo:IModuleInfo = event.module;
moduleInfo.removeEventListener(ModuleEvent.UNLOAD, moduleInfo_unloadHandler);
var moduleInfoIndex:int = loadedModuleInfos.indexOf(moduleInfo);
if (moduleInfoIndex > -1)
{
loadedModuleInfos.splice(moduleInfoIndex, 1);
}
this.moduleInfo = null;
FlexGlobals.topLevelApplication.callLater(loadModule);
}
private function moduleInfo_readyHandler(event:ModuleEvent):void
{
if (Log.isInfo())
{
LOG.info('Module loaded: {0}', swf.url);
}
var moduleInfo:IModuleInfo = event.currentTarget as IModuleInfo;
moduleInfo.removeEventListener(ModuleEvent.READY, moduleInfo_readyHandler);
moduleInfo.removeEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler);
if (config && config.exists)
{
if (Log.isInfo())
{
LOG.info('Reading module config: {0}', config.url);
}
var moduleConfig:XML = readModuleConfig(config);
}
const builderModule:IBuilderModule = event.module.factory.create() as IBuilderModule;
if (builderModule)
{
if (Log.isInfo())
{
LOG.info('Widget type created for module: {0}', swf.url);
}
var widgetType:WidgetType = getWidgetType(moduleInfo, builderModule, moduleConfig);
}
loadedModuleInfos.push(moduleInfo);
this.moduleInfo = null;
dispatchComplete(widgetType);
}
private function dispatchComplete(widgetType:WidgetType):void
{
if (Log.isInfo())
{
LOG.info('Module load complete: {0}', name);
}
dispatchEvent(new WidgetTypeLoaderEvent(WidgetTypeLoaderEvent.LOAD_COMPLETE, widgetType));
}
private function getWidgetType(moduleInfo:IModuleInfo, builderModule:IBuilderModule, moduleConfig:XML):WidgetType
{
var customModulesDirectoryURL:String = WellKnownDirectories.getInstance().customModules.url;
var isCustomModule:Boolean = (moduleInfo.url.indexOf(customModulesDirectoryURL) > -1);
if (moduleConfig)
{
var configXML:XML = moduleConfig.configuration[0];
var version:String = moduleConfig.widgetversion[0];
}
return isCustomModule ?
new CustomWidgetType(builderModule, version, configXML) :
new WidgetType(builderModule);
}
private function readModuleConfig(configFile:File):XML
{
var configXML:XML;
var fileStream:FileStream = new FileStream();
try
{
fileStream.open(configFile, FileMode.READ);
configXML = XML(fileStream.readUTFBytes(fileStream.bytesAvailable));
}
catch (e:Error)
{
//ignore
if (Log.isInfo())
{
LOG.info('Could not read module config: {0}', e.toString());
}
}
finally
{
fileStream.close();
}
return configXML;
}
private function moduleInfo_errorHandler(event:ModuleEvent):void
{
var moduleInfo:IModuleInfo = event.module;
moduleInfo.removeEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler);
moduleInfo.removeEventListener(ModuleEvent.READY, moduleInfo_readyHandler);
this.moduleInfo = null;
dispatchError();
}
private function dispatchError():void
{
if (Log.isInfo())
{
LOG.info('Module load failed: {0}', name);
}
dispatchEvent(new WidgetTypeLoaderEvent(WidgetTypeLoaderEvent.LOAD_ERROR));
}
private function parseCustomWidgetType(configXML:XML):CustomWidgetType
{
if (Log.isInfo())
{
LOG.info('Creating widget type from XML: {0}', configXML);
}
var customModule:CustomXMLModule = new CustomXMLModule();
customModule.widgetName = configXML.name;
customModule.isOpenByDefault = (configXML.openbydefault == 'true');
var widgetLabel:String = configXML.label[0];
var widgetDescription:String = configXML.description[0];
var widgetHelpURL:String = configXML.helpurl[0];
var widgetConfiguration:XML = configXML.configuration[0] ? configXML.configuration[0] : <configuration/>;
var widgetVersion:String = configXML.widgetversion[0];
customModule.widgetIconLocation = createWidgetIconPath(configXML.icon[0], customModule.widgetName);
customModule.widgetLabel = widgetLabel ? widgetLabel : customModule.widgetName;
customModule.widgetDescription = widgetDescription ? widgetDescription : "";
customModule.widgetHelpURL = widgetHelpURL ? widgetHelpURL : "";
return new CustomWidgetType(customModule, widgetVersion, widgetConfiguration);
}
private function createWidgetIconPath(iconPath:String, widgetName:String):String
{
var widgetIconPath:String;
if (iconPath)
{
widgetIconPath = "widgets/" + widgetName + "/" + iconPath;
}
else
{
widgetIconPath = "assets/images/i_widget.png";
}
return widgetIconPath;
}
}
}
|
Fix typo when checking for custom widget config existence.
|
Fix typo when checking for custom widget config existence.
|
ActionScript
|
apache-2.0
|
Esri/arcgis-viewer-builder-flex
|
756aeac1c0ccc267c6e3e1bf7ba9c822eaa927f0
|
src/as/com/threerings/util/EmbeddedSwfLoader.as
|
src/as/com/threerings/util/EmbeddedSwfLoader.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.display.DisplayObject;
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.errors.IllegalOperationError;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.utils.ByteArray;
import flash.system.ApplicationDomain;
import flash.system.LoaderContext;
/**
* Allows you to load an embeded SWF stored as a Byte Array then access any stored classes
* within the SWF.
* Embed your swf like:
* [Embed(source="foo.swf", mimeType="application/octet-stream"]
* Then, instantiate that class and pass it to load() as a ByteArray.
*
* An Event.COMPLETE will be dispatched upon the successful completion of a call to
* {@link load}. IOErrorEvent.IO_ERROR will be dispatched if there's a problem reading the
* ByteArray.
*
* @deprecated Content packs are coming, and symbols can be embedded directly
* by using [Embed(source="foo.swf#somesymbol")]
*/
public class EmbeddedSwfLoader extends EventDispatcher
{
public function EmbeddedSwfLoader ()
{
_loader = new Loader();
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, dispatchEvent);
_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, dispatchEvent);
}
// This doesn't work. We cannot write parameters to the contentLoaderInfo.
// So: there is no way to pass parameters to content loaded using loadBytes,
// and there's no way to pass parameters to any other content without
// destroying caching (because you must append them to the url). Stupid flash.
// /**
// * Set a parameter accessible to the loaded content.
// */
// public function setParameter (name :String, val :String) :void
// {
// _loader.contentLoaderInfo.parameters[name] = val;
// }
/**
* Load the SWF from a Byte Array. A CLASS_LOADED event will be dispatched on successful
* completion of the load. If any errors occur, a LOAD_ERROR event will be dispatched.
*/
public function load (byteArray :ByteArray) :void
{
var context :LoaderContext = new LoaderContext();
context.applicationDomain = ApplicationDomain.currentDomain;
_loader.loadBytes(byteArray, context);
}
/**
* Get the top-level display object defined in the loaded SWF.
*/
public function getContent () :DisplayObject
{
checkLoaded();
return _loader.content;
}
/**
* Retrieves a class definition from the loaded swf.
*
* @throws IllegalOperationError when the swf has not completed loading or the class does
* not exist
*/
public function getClass (className :String) :Class
{
return getSymbol(className) as Class;
}
/**
* Retrieves a Function definition from the loaded swf.
*
* @throws IllegalOperationError when the swf has not completed loading or the class does
* not exist
*/
public function getFunction (functionName :String) :Function
{
return getSymbol(functionName) as Function;
}
/**
* Retrieves a symbol definition from the loaded swf.
*
* @throws IllegalOperationError when the swf has not completed loading or the class does
* not exist
*/
public function getSymbol (symbolName :String) :Object
{
checkLoaded();
try {
return _loader.contentLoaderInfo.applicationDomain.getDefinition(symbolName);
} catch (e: Error) {
throw new IllegalOperationError(symbolName + " definition not found");
}
return null;
}
/**
* Checks if a symbol exists in the library.
*
* @throws IllegalOperationError when the swf has not completed loading.
*/
public function isSymbol (className :String) :Boolean
{
checkLoaded();
return _loader.contentLoaderInfo.applicationDomain.hasDefinition(className);
}
/**
* Validate that the load operation is complete.
*/
protected function checkLoaded () :void
{
var loaderInfo :LoaderInfo = _loader.contentLoaderInfo;
if (loaderInfo.bytesTotal == 0 || loaderInfo.bytesLoaded != loaderInfo.bytesTotal) {
throw new IllegalOperationError("SWF has not completed loading");
}
}
protected var _loader :Loader;
}
}
|
//
// $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.display.DisplayObject;
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.errors.IllegalOperationError;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.utils.ByteArray;
import flash.system.ApplicationDomain;
import flash.system.LoaderContext;
/**
* Allows you to load an embeded SWF stored as a Byte Array then access any stored classes
* within the SWF.
* Embed your swf like:
* [Embed(source="foo.swf", mimeType="application/octet-stream"]
* Then, instantiate that class and pass it to load() as a ByteArray.
*
* An Event.COMPLETE will be dispatched upon the successful completion of a call to
* {@link load}. IOErrorEvent.IO_ERROR will be dispatched if there's a problem reading the
* ByteArray.
*
* @deprecated Content packs are coming, and symbols can be embedded directly
* by using [Embed(source="foo.swf#somesymbol")]
*/
public class EmbeddedSwfLoader extends EventDispatcher
{
public function EmbeddedSwfLoader (useSubDomain :Boolean = false)
{
_useSubDomain = useSubDomain;
_loader = new Loader();
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, dispatchEvent);
_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, dispatchEvent);
}
// This doesn't work. We cannot write parameters to the contentLoaderInfo.
// So: there is no way to pass parameters to content loaded using loadBytes,
// and there's no way to pass parameters to any other content without
// destroying caching (because you must append them to the url). Stupid flash.
// /**
// * Set a parameter accessible to the loaded content.
// */
// public function setParameter (name :String, val :String) :void
// {
// _loader.contentLoaderInfo.parameters[name] = val;
// }
/**
* Load the SWF from a Byte Array. A CLASS_LOADED event will be dispatched on successful
* completion of the load. If any errors occur, a LOAD_ERROR event will be dispatched.
*/
public function load (byteArray :ByteArray) :void
{
var context :LoaderContext = new LoaderContext();
context.applicationDomain = _useSubDomain ?
new ApplicationDomain(ApplicationDomain.currentDomain) :
ApplicationDomain.currentDomain;
_loader.loadBytes(byteArray, context);
}
/**
* Get the top-level display object defined in the loaded SWF.
*/
public function getContent () :DisplayObject
{
checkLoaded();
return _loader.content;
}
/**
* Retrieves a class definition from the loaded swf.
*
* @throws IllegalOperationError when the swf has not completed loading or the class does
* not exist
*/
public function getClass (className :String) :Class
{
return getSymbol(className) as Class;
}
/**
* Retrieves a Function definition from the loaded swf.
*
* @throws IllegalOperationError when the swf has not completed loading or the class does
* not exist
*/
public function getFunction (functionName :String) :Function
{
return getSymbol(functionName) as Function;
}
/**
* Retrieves a symbol definition from the loaded swf.
*
* @throws IllegalOperationError when the swf has not completed loading or the class does
* not exist
*/
public function getSymbol (symbolName :String) :Object
{
checkLoaded();
try {
return _loader.contentLoaderInfo.applicationDomain.getDefinition(symbolName);
} catch (e: Error) {
throw new IllegalOperationError(symbolName + " definition not found");
}
return null;
}
/**
* Checks if a symbol exists in the library.
*
* @throws IllegalOperationError when the swf has not completed loading.
*/
public function isSymbol (className :String) :Boolean
{
checkLoaded();
return _loader.contentLoaderInfo.applicationDomain.hasDefinition(className);
}
/**
* Validate that the load operation is complete.
*/
protected function checkLoaded () :void
{
var loaderInfo :LoaderInfo = _loader.contentLoaderInfo;
if (loaderInfo.bytesTotal == 0 || loaderInfo.bytesLoaded != loaderInfo.bytesTotal) {
throw new IllegalOperationError("SWF has not completed loading");
}
}
protected var _loader :Loader;
protected var _useSubDomain :Boolean;
}
}
|
allow the use of subdomains, if wished
|
allow the use of subdomains, if wished
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4614 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
f6803d5d744cbf4a75fcf82a5e5563816cae91f2
|
exporter/src/main/as/flump/export/ExportConf.as
|
exporter/src/main/as/flump/export/ExportConf.as
|
//
// Flump - Copyright 2013 Flump Authors
package flump.export {
import aspire.util.Log;
import aspire.util.Set;
import aspire.util.Sets;
import aspire.util.StringUtil;
import flash.display.StageQuality;
import flash.filesystem.File;
import flump.mold.AtlasMold;
import flump.mold.optional;
import flump.mold.require;
import flump.xfl.XflLibrary;
public class ExportConf
{
public static const OPTIMIZE_MEMORY :String = "Memory";
public static const OPTIMIZE_SPEED :String = "Speed";
public var name :String = "default";
public var format :String = JSONZipFormat.NAME;
public var scale :Number = 1;
/** The size of the border around each texture in an atlas, in pixels */
public var textureBorder :int = 1;
/** The maximum size of the width and height of a generated texture atlas */
public var maxAtlasSize :int = 2048;
/** Additional scaleFactors to output */
public var additionalScaleFactors :Array = [];
/** The optimization strategy. */
public var optimize :String = OPTIMIZE_SPEED;
/** The stage quality setting (StageQuality). */
public var quality :String = StageQuality.BEST;
/** Whether or not to pretty print the library. */
public var prettyPrint :Boolean = false;
public function get scaleFactorsString () :String {
return this.additionalScaleFactors.join(",");
}
public function set scaleFactorsString (str :String) :void {
var strings :Array = str.split(",");
var values :Set = Sets.newSetOf(int);
for each (var num :String in str.split(",")) {
try {
// additional scale factors must be integers > 1
var scale :int = StringUtil.parseUnsignedInteger(StringUtil.trim(num));
if (scale > 1) {
values.add(scale);
}
} catch (e :Error) {}
}
this.additionalScaleFactors = values.toArray();
this.additionalScaleFactors.sort();
}
public function get description () :String {
const scaleString :String = (this.scale * 100).toFixed(0) + "%";
var scaleFactors :String = "";
for each (var scaleFactor :int in this.additionalScaleFactors) {
scaleFactors += ", " + AtlasMold.scaleFactorSuffix(scaleFactor);
}
return "'" + this.name + "' (" + this.format + ", " + scaleString + scaleFactors + ")";
}
public static function fromJSON (o :Object) :ExportConf {
const conf :ExportConf = new ExportConf();
conf.name = require(o, "name");
conf.scale = require(o, "scale");
conf.format = require(o, "format");
conf.textureBorder = optional(o, "textureBorder", 1);
conf.maxAtlasSize = optional(o, "maxAtlasSize", 2048);
conf.additionalScaleFactors = optional(o, "additionalScaleFactors", []);
conf.optimize = optional(o, "optimize", OPTIMIZE_MEMORY);
conf.quality = optional(o, "quality", StageQuality.BEST);
conf.prettyPrint = optional(o, "prettyPrint", false);
return conf;
}
public function createPublishFormat (exportDir :File, lib :XflLibrary) :PublishFormat {
var formatClass :Class;
switch (format.toLowerCase()) {
case JSONFormat.NAME.toLowerCase(): formatClass = JSONFormat; break;
case JSONZipFormat.NAME.toLowerCase(): formatClass = JSONZipFormat; break;
case XMLFormat.NAME.toLowerCase(): formatClass = XMLFormat; break;
default:
log.error("Invalid publish format", "name", format);
formatClass = JSONZipFormat;
break;
}
return new formatClass(exportDir, lib, this);
}
protected static const log :Log = Log.getLog(ExportConf);
}
}
|
//
// Flump - Copyright 2013 Flump Authors
package flump.export {
import aspire.util.Log;
import aspire.util.Set;
import aspire.util.Sets;
import aspire.util.StringUtil;
import flash.display.StageQuality;
import flash.filesystem.File;
import flump.mold.AtlasMold;
import flump.mold.optional;
import flump.mold.require;
import flump.xfl.XflLibrary;
public class ExportConf
{
public static const OPTIMIZE_MEMORY :String = "Memory";
public static const OPTIMIZE_SPEED :String = "Speed";
public var name :String = "default";
public var format :String = JSONZipFormat.NAME;
public var scale :Number = 1;
/** The size of the border around each texture in an atlas, in pixels */
public var textureBorder :int = 1;
/** The maximum size of the width and height of a generated texture atlas */
public var maxAtlasSize :int = 2048;
/** Additional scaleFactors to output */
public var additionalScaleFactors :Array = [];
/** The optimization strategy. */
public var optimize :String = OPTIMIZE_SPEED;
/** The stage quality setting (StageQuality). */
public var quality :String = StageQuality.BEST;
/** Whether or not to pretty print the library. */
public var prettyPrint :Boolean = false;
public function get scaleFactorsString () :String {
return this.additionalScaleFactors.join(",");
}
public function set scaleFactorsString (str :String) :void {
var values :Set = Sets.newSetOf(int);
for each (var num :String in str.split(",")) {
try {
// additional scale factors must be integers > 1
var scale :int = StringUtil.parseUnsignedInteger(StringUtil.trim(num));
if (scale > 1) {
values.add(scale);
}
} catch (e :Error) {}
}
this.additionalScaleFactors = values.toArray();
this.additionalScaleFactors.sort();
}
public function get description () :String {
const scaleString :String = (this.scale * 100).toFixed(0) + "%";
var scaleFactors :String = "";
for each (var scaleFactor :int in this.additionalScaleFactors) {
scaleFactors += ", " + AtlasMold.scaleFactorSuffix(scaleFactor);
}
return "'" + this.name + "' (" + this.format + ", " + scaleString + scaleFactors + ")";
}
public static function fromJSON (o :Object) :ExportConf {
const conf :ExportConf = new ExportConf();
conf.name = require(o, "name");
conf.scale = require(o, "scale");
conf.format = require(o, "format");
conf.textureBorder = optional(o, "textureBorder", 1);
conf.maxAtlasSize = optional(o, "maxAtlasSize", 2048);
conf.additionalScaleFactors = optional(o, "additionalScaleFactors", []);
conf.optimize = optional(o, "optimize", OPTIMIZE_MEMORY);
conf.quality = optional(o, "quality", StageQuality.BEST);
conf.prettyPrint = optional(o, "prettyPrint", false);
return conf;
}
public function createPublishFormat (exportDir :File, lib :XflLibrary) :PublishFormat {
var formatClass :Class;
switch (format.toLowerCase()) {
case JSONFormat.NAME.toLowerCase(): formatClass = JSONFormat; break;
case JSONZipFormat.NAME.toLowerCase(): formatClass = JSONZipFormat; break;
case XMLFormat.NAME.toLowerCase(): formatClass = XMLFormat; break;
default:
log.error("Invalid publish format", "name", format);
formatClass = JSONZipFormat;
break;
}
return new formatClass(exportDir, lib, this);
}
protected static const log :Log = Log.getLog(ExportConf);
}
}
|
Remove unused code
|
Remove unused code
|
ActionScript
|
mit
|
funkypandagame/flump,mathieuanthoine/flump,tconkling/flump,tconkling/flump,mathieuanthoine/flump,funkypandagame/flump,mathieuanthoine/flump
|
c6baab42b3de3e9651be5a9ef0fa0a59135c77e1
|
test/unit/Suite.as
|
test/unit/Suite.as
|
package {
import asunit.framework.TestSuite;
public class Suite extends TestSuite {
public function Suite() {
super();
addTest(new PlayerTest("testPass"));
}
}
}
|
package {
import asunit.framework.TestSuite;
public class Suite extends TestSuite {
public function Suite() {
super();
addTest(new PlayerTest("testPass"));
addTest(new UriTest("test_isSafe"));
}
}
}
|
Add URI tests to the asunit test suite
|
Add URI tests to the asunit test suite
|
ActionScript
|
mit
|
cameronhunter/divine-player-swf
|
ae517a93d90625f083e58135c9e9bd0ea61559b1
|
src/as/com/threerings/flex/CommandCheckBox.as
|
src/as/com/threerings/flex/CommandCheckBox.as
|
//
// $Id: CommandButton.as 408 2008-02-06 01:03:55Z ray $
//
// 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.events.MouseEvent;
import mx.controls.CheckBox;
import com.threerings.util.CommandEvent;
/**
* A checkbox that dispatches a command (or calls a function) when it is toggled.
*/
public class CommandCheckBox extends CheckBox
{
/**
* Create a command button.
*
* @param label the label text for the button.
* @param cmdOrFn either a String, which will be the CommandEvent command to dispatch,
* or a function, which will be called when clicked.
* @param arg the argument for the CommentEvent or the function. If the arg is an Array
* then those parameters are used for calling the function.
* Note that if arg is null, the actual argument passed will be the 'selected' state of the
* button. If you really want to call a method with no args, specify arg as an emtpy Array.
*/
public function CommandCheckBox (label :String = null, cmdOrFn :* = null, arg :Object = null)
{
CommandButton.validateCmd(cmdOrFn);
this.label = label;
_cmdOrFn = cmdOrFn;
_arg = arg;
}
/**
* Set the command and argument to be issued when this button is pressed.
*/
public function setCommand (cmd :String, arg :Object = null) :void
{
_cmdOrFn = cmd;
_arg = arg;
}
/**
* Set a callback function to call when the button is pressed.
*/
public function setCallback (fn :Function, arg :Object = null) :void
{
_cmdOrFn = fn;
_arg = arg;
}
override protected function clickHandler (event :MouseEvent) :void
{
super.clickHandler(event);
CommandButton.processCommandClick(this, event, _cmdOrFn, _arg);
}
/** The command (String) to submit, or the function (Function) to call
* when clicked, */
protected var _cmdOrFn :Object;
/** The argument that accompanies our command. */
protected var _arg :Object;
}
}
|
//
// $Id: CommandButton.as 408 2008-02-06 01:03:55Z ray $
//
// 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.events.MouseEvent;
import mx.controls.CheckBox;
import com.threerings.util.CommandEvent;
/**
* A checkbox that dispatches a command (or calls a function) when it is toggled.
*/
public class CommandCheckBox extends CheckBox
{
/**
* Create a command checkbox.
*
* @param label the label text for the checkbox.
* @param cmdOrFn either a String, which will be the CommandEvent command to dispatch,
* or a function, which will be called when clicked.
* @param arg the argument for the CommentEvent or the function. If the arg is an Array
* then those parameters are used for calling the function.
* Note that if arg is null, the actual argument passed will be the 'selected' state of the
* checkbox. If you really want to call a method with no args, specify arg as an emtpy Array.
*/
public function CommandCheckBox (label :String = null, cmdOrFn :* = null, arg :Object = null)
{
CommandButton.validateCmd(cmdOrFn);
this.label = label;
_cmdOrFn = cmdOrFn;
_arg = arg;
}
/**
* Set the command and argument to be issued when this button is pressed.
*/
public function setCommand (cmd :String, arg :Object = null) :void
{
_cmdOrFn = cmd;
_arg = arg;
}
/**
* Set a callback function to call when the button is pressed.
*/
public function setCallback (fn :Function, arg :Object = null) :void
{
_cmdOrFn = fn;
_arg = arg;
}
override protected function clickHandler (event :MouseEvent) :void
{
super.clickHandler(event);
CommandButton.processCommandClick(this, event, _cmdOrFn, _arg);
}
/** The command (String) to submit, or the function (Function) to call
* when clicked, */
protected var _cmdOrFn :Object;
/** The argument that accompanies our command. */
protected var _arg :Object;
}
}
|
Comment tweak.
|
Comment tweak.
git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@736 ed5b42cb-e716-0410-a449-f6a68f950b19
|
ActionScript
|
lgpl-2.1
|
threerings/nenya,threerings/nenya
|
de8e3fac5d98a2aa87d52d9d98330a310577b64b
|
src/aerys/minko/render/shader/part/environment/EnvironmentMappingShaderPart.as
|
src/aerys/minko/render/shader/part/environment/EnvironmentMappingShaderPart.as
|
package aerys.minko.render.shader.part.environment
{
import aerys.minko.render.material.environment.EnvironmentMappingProperties;
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.render.shader.part.BlendingShaderPart;
import aerys.minko.render.shader.part.phong.LightAwareShaderPart;
import aerys.minko.render.shader.part.projection.BlinnNewellProjectionShaderPart;
import aerys.minko.render.shader.part.projection.ProbeProjectionShaderPart;
import aerys.minko.type.enum.Blending;
import aerys.minko.type.enum.EnvironmentMappingType;
import aerys.minko.type.enum.SamplerDimension;
import aerys.minko.type.enum.SamplerFiltering;
import aerys.minko.type.enum.SamplerFormat;
import aerys.minko.type.enum.SamplerMipMapping;
import aerys.minko.type.enum.SamplerWrapping;
import flash.geom.Rectangle;
public class EnvironmentMappingShaderPart extends LightAwareShaderPart
{
private var _blinnNewellProjectionPart : BlinnNewellProjectionShaderPart;
private var _probeProjectionPart : ProbeProjectionShaderPart;
private var _blending : BlendingShaderPart;
public function EnvironmentMappingShaderPart(main : Shader)
{
super(main);
_blinnNewellProjectionPart = new BlinnNewellProjectionShaderPart(main);
_probeProjectionPart = new ProbeProjectionShaderPart(main);
_blending = new BlendingShaderPart(main);
}
public function getEnvironmentColor() : SFloat
{
if (!meshBindings.propertyExists(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE)
|| !meshBindings.propertyExists(EnvironmentMappingProperties.ENVIRONMENT_MAP))
return float4(0, 0, 0, 0);
// compute reflected vector
var cWorldCameraPosition : SFloat = this.cameraPosition;
var vsWorldVertexToCamera : SFloat = normalize(subtract(cWorldCameraPosition, vsWorldPosition));
var reflected : SFloat = normalize(interpolate(reflect(vsWorldVertexToCamera.xyzz, vsWorldNormal.xyzz)));
var reflectionType : int = meshBindings.getProperty(
EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE
);
var reflectionMap : SFloat = getEnvironmentMap(reflectionType);
// retrieve reflection color from reflection map
var reflectionMapUV : SFloat;
var reflectionColor : SFloat;
switch (reflectionType)
{
case EnvironmentMappingType.NONE:
reflectionColor = float4(0, 0, 0, 0);
break;
case EnvironmentMappingType.PROBE:
reflectionMapUV = _probeProjectionPart.projectVector(reflected, new Rectangle(0, 0, 1, 1));
reflectionColor = sampleTexture(reflectionMap, reflectionMapUV);
break;
case EnvironmentMappingType.BLINN_NEWELL:
reflectionMapUV = _blinnNewellProjectionPart.projectVector(reflected, new Rectangle(0, 0, 1, 1));
reflectionColor = sampleTexture(reflectionMap, reflectionMapUV);
break;
case EnvironmentMappingType.CUBE:
reflectionColor = sampleTexture(reflectionMap, reflected);
break;
default:
throw new Error('Unsupported reflection type');
}
// modifify alpha color
if (meshBindings.propertyExists(EnvironmentMappingProperties.REFLECTIVITY))
{
var reflectivity : SFloat = meshBindings.getParameter(
EnvironmentMappingProperties.REFLECTIVITY, 1
);
reflectionColor = float4(reflectionColor.xyz, multiply(reflectionColor.w, reflectivity));
}
return reflectionColor;
}
public function getEnvironmentMap(environmentMappingType : uint = 0) : SFloat
{
if (!environmentMappingType)
meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE);
return meshBindings.getTextureParameter(
EnvironmentMappingProperties.ENVIRONMENT_MAP,
meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FILTERING, SamplerFiltering.NEAREST),
meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_MIPMAPPING, SamplerMipMapping.DISABLE),
meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_WRAPPING, SamplerWrapping.CLAMP),
environmentMappingType == EnvironmentMappingType.CUBE ? SamplerDimension.CUBE : SamplerDimension.FLAT,
meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FORMAT, SamplerFormat.RGBA)
);
}
public function applyEnvironmentMapping(diffuse : SFloat) : SFloat
{
if (!meshBindings.propertyExists(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE))
return diffuse;
return _blending.blend(
getEnvironmentColor(),
diffuse,
meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_BLENDING, Blending.ALPHA)
);
}
}
}
|
package aerys.minko.render.shader.part.environment
{
import aerys.minko.render.material.environment.EnvironmentMappingProperties;
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.render.shader.part.BlendingShaderPart;
import aerys.minko.render.shader.part.phong.LightAwareShaderPart;
import aerys.minko.render.shader.part.projection.BlinnNewellProjectionShaderPart;
import aerys.minko.render.shader.part.projection.ProbeProjectionShaderPart;
import aerys.minko.type.enum.Blending;
import aerys.minko.type.enum.EnvironmentMappingType;
import aerys.minko.type.enum.SamplerDimension;
import aerys.minko.type.enum.SamplerFiltering;
import aerys.minko.type.enum.SamplerFormat;
import aerys.minko.type.enum.SamplerMipMapping;
import aerys.minko.type.enum.SamplerWrapping;
import flash.geom.Rectangle;
public class EnvironmentMappingShaderPart extends LightAwareShaderPart
{
private var _blinnNewellProjectionPart : BlinnNewellProjectionShaderPart;
private var _probeProjectionPart : ProbeProjectionShaderPart;
private var _blending : BlendingShaderPart;
public function EnvironmentMappingShaderPart(main : Shader)
{
super(main);
_blinnNewellProjectionPart = new BlinnNewellProjectionShaderPart(main);
_probeProjectionPart = new ProbeProjectionShaderPart(main);
_blending = new BlendingShaderPart(main);
}
public function getEnvironmentColor() : SFloat
{
if (!meshBindings.propertyExists(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE)
|| !meshBindings.propertyExists(EnvironmentMappingProperties.ENVIRONMENT_MAP))
return float4(0, 0, 0, 0);
// compute reflected vector
var cWorldCameraPosition : SFloat = this.cameraPosition;
var vsWorldVertexToCamera : SFloat = normalize(subtract(cWorldCameraPosition, vsWorldPosition));
var reflected : SFloat = normalize(interpolate(reflect(vsWorldNormal.xyzz, vsWorldVertexToCamera.xyzz)));
var reflectionType : int = meshBindings.getProperty(
EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE
);
var reflectionMap : SFloat = getEnvironmentMap(reflectionType);
// retrieve reflection color from reflection map
var reflectionMapUV : SFloat;
var reflectionColor : SFloat;
switch (reflectionType)
{
case EnvironmentMappingType.NONE:
reflectionColor = float4(0, 0, 0, 0);
break;
case EnvironmentMappingType.PROBE:
reflectionMapUV = _probeProjectionPart.projectVector(reflected, new Rectangle(0, 0, 1, 1));
reflectionColor = sampleTexture(reflectionMap, reflectionMapUV);
break;
case EnvironmentMappingType.BLINN_NEWELL:
reflectionMapUV = _blinnNewellProjectionPart.projectVector(reflected, new Rectangle(0, 0, 1, 1));
reflectionColor = sampleTexture(reflectionMap, reflectionMapUV);
break;
case EnvironmentMappingType.CUBE:
reflectionColor = sampleTexture(reflectionMap, reflected);
break;
default:
throw new Error('Unsupported reflection type');
}
// modifify alpha color
if (meshBindings.propertyExists(EnvironmentMappingProperties.REFLECTIVITY))
{
var reflectivity : SFloat = meshBindings.getParameter(
EnvironmentMappingProperties.REFLECTIVITY, 1
);
reflectionColor = float4(reflectionColor.xyz, multiply(reflectionColor.w, reflectivity));
}
return reflectionColor;
}
public function getEnvironmentMap(environmentMappingType : uint = 0) : SFloat
{
if (!environmentMappingType)
meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE);
return meshBindings.getTextureParameter(
EnvironmentMappingProperties.ENVIRONMENT_MAP,
meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FILTERING, SamplerFiltering.NEAREST),
meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_MIPMAPPING, SamplerMipMapping.DISABLE),
meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_WRAPPING, SamplerWrapping.CLAMP),
environmentMappingType == EnvironmentMappingType.CUBE ? SamplerDimension.CUBE : SamplerDimension.FLAT,
meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FORMAT, SamplerFormat.RGBA)
);
}
public function applyEnvironmentMapping(diffuse : SFloat) : SFloat
{
if (!meshBindings.propertyExists(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE))
return diffuse;
return _blending.blend(
getEnvironmentColor(),
diffuse,
meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_BLENDING, Blending.ALPHA)
);
}
}
}
|
Fix flipped env map
|
Fix flipped env map
|
ActionScript
|
mit
|
aerys/minko-as3
|
47f3fb62a868e9556a2ec5b335d58cac3da86caf
|
frameworks/projects/Core/as/src/org/apache/flex/events/EventDispatcher.as
|
frameworks/projects/Core/as/src/org/apache/flex/events/EventDispatcher.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.events
{
COMPILE::JS
{
import goog.events.EventTarget;
}
COMPILE::AS3
{
import flash.events.EventDispatcher;
}
/**
* This class simply wraps flash.events.EventDispatcher so that
* no flash packages are needed on the JS side.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
COMPILE::AS3
public class EventDispatcher extends flash.events.EventDispatcher implements IEventDispatcher
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function EventDispatcher()
{
super();
}
}
COMPILE::JS
public class EventDispatcher extends goog.events.EventTarget implements IEventDispatcher
{
override public function addEventListener(type:String, handler:Object, opt_capture:Boolean = false, opt_handlerScope:Object = null):void
{
super.addEventListener(type, handler, opt_capture, opt_handlerScope);
const that:* = this;
var source:* = this;
if (that.element && that.element.nodeName &&
that.element.nodeName.toLowerCase() !== 'div' &&
that.element.nodeName.toLowerCase() !== 'body')
{
source = that.element;
}
else if (ElementEvents.elementEvents[type])
{
// mouse and keyboard events also dispatch off the element.
source = that.element;
}
goog.events.listen(source, type, handler);
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.events
{
COMPILE::JS
{
import goog.events;
import goog.events.EventTarget;
}
COMPILE::AS3
{
import flash.events.EventDispatcher;
}
/**
* This class simply wraps flash.events.EventDispatcher so that
* no flash packages are needed on the JS side.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
COMPILE::AS3
public class EventDispatcher extends flash.events.EventDispatcher implements IEventDispatcher
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function EventDispatcher()
{
super();
}
}
COMPILE::JS
public class EventDispatcher extends goog.events.EventTarget implements IEventDispatcher
{
override public function addEventListener(type:String, handler:Object, opt_capture:Boolean = false, opt_handlerScope:Object = null):void
{
super.addEventListener(type, handler, opt_capture, opt_handlerScope);
const that:* = this;
var source:* = this;
if (that.element && that.element.nodeName &&
that.element.nodeName.toLowerCase() !== 'div' &&
that.element.nodeName.toLowerCase() !== 'body')
{
source = that.element;
}
else if (ElementEvents.elementEvents[type])
{
// mouse and keyboard events also dispatch off the element.
source = that.element;
}
goog.events.listen(source, type, handler);
}
}
}
|
use goog.events class
|
use goog.events class
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
8ccdf19a42846313b25a994b4ca625cdaefb0e32
|
src/as/com/threerings/util/Util.as
|
src/as/com/threerings/util/Util.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.ByteArray;
public class Util
{
/**
* Initialize the target object with values present in the initProps object and the defaults
* object. Neither initProps nor defaults will be modified.
* @throws ReferenceError if a property cannot be set on the target object.
*
* @param target any object or class instance.
* @param initProps a plain Object hash containing names and properties to set on the target
* object.
* @param defaults a plain Object hash containing names and properties to set on the target
* object, only if the same property name does not exist in initProps.
* @param maskProps a plain Object hash containing names of properties to omit setting
* from the initProps object. This allows you to add custom properties to
* initProps without having to modify the value from your callers.
*/
public static function init (
target :Object, initProps :Object, defaults :Object = null, maskProps :Object = null) :void
{
var prop :String;
for (prop in initProps) {
if (maskProps == null || !(prop in maskProps)) {
target[prop] = initProps[prop];
}
}
if (defaults != null) {
for (prop in defaults) {
if (!(prop in initProps)) {
target[prop] = defaults[prop];
}
}
}
}
/**
* Is the specified object 'simple': one of the basic built-in flash types.
*/
public static function isSimple (obj :Object) :Boolean
{
var type :String = typeof(obj);
switch (type) {
case "number":
case "string":
case "boolean":
return true;
case "object":
return (obj is Date) || (obj is Array);
default:
return false;
}
}
/**
* Parse the 'value' object into XML safely. This is equivalent to <code>new XML(value)</code>
* but offers protection from other code that may have changing the default settings
* used for parsing XML. Also, if you would like to use non-standard parsing settings
* this method will protect other code from being broken by you.
*
* @param value the value to parse into XML.
* @param settings an Object containing your desired non-standard XML parsing settings.
* @see XML#setSettings()
*/
public static function newXML (value :Object, settings :Object = null) :XML
{
return safeXMLOp(function () :* {
return new XML(value);
}, settings) as XML;
}
/**
* Call toString() on the specified XML object safely. This is equivalent to
* <code>xml.toString()</code> but offers protection from other code that may have changed
* the default settings used for stringing XML. Also, if you would like to use the
* non-standard printing settings this method will protect other code from being
* broken by you.
*
* @param xml the xml value to Stringify.
* @param settings an Object containing
* @see XML#toString()
* @see XML#setSettings()
*/
public static function XMLtoString (xml :XML, settings :Object = null) :String
{
return safeXMLOp(function () :* {
return xml.toString();
}, settings) as String;
}
/**
* Call toXMLString() on the specified XML object safely. This is equivalent to
* <code>xml.toXMLString()</code> but offers protection from other code that may have changed
* the default settings used for stringing XML. Also, if you would like to use the
* non-standard printing settings this method will protect other code from being
* broken by you.
*
* @param xml the xml value to Stringify.
* @param settings an Object containing
* @see XML#toXMLString()
* @see XML#setSettings()
*/
public static function XMLtoXMLString (xml :XML, settings :Object = null) :String
{
return safeXMLOp(function () :* {
return xml.toXMLString();
}, settings) as String;
}
/**
* Perform an operation on XML that takes place using the specified settings, and
* restores the XML settings to their previous values.
*
* @param fn a function to be called with no arguments.
* @param settings any custom XML settings, or null to use the defaults.
*
* @return the return value of your function, if any.
* @see XML#setSettings()
* @see XML#settings()
*/
public static function safeXMLOp (fn :Function, settings :Object = null) :*
{
var oldSettings :Object = XML.settings();
try {
XML.setSettings(settings);
return fn();
} finally {
XML.setSettings(oldSettings);
}
}
/**
* A nice utility method for testing equality in a better way.
* If the objects are Equalable, then that will be tested. Arrays
* and ByteArrays are also compared and are equal if they have
* elements that are equals (deeply).
*/
public static function equals (obj1 :Object, obj2 :Object) :Boolean
{
// catch various common cases (both primitive or null)
if (obj1 === obj2) {
return true;
} else if (obj1 is Equalable) {
// if obj1 is Equalable, then that decides it
return (obj1 as Equalable).equals(obj2);
} else if ((obj1 is Array) && (obj2 is Array)) {
return ArrayUtil.equals(obj1 as Array, obj2 as Array);
} else if ((obj1 is ByteArray) && (obj2 is ByteArray)) {
var ba1 :ByteArray = (obj1 as ByteArray);
var ba2 :ByteArray = (obj2 as ByteArray);
if (ba1.length != ba2.length) {
return false;
}
for (var ii :int = 0; ii < ba1.length; ii++) {
if (ba1[ii] != ba2[ii]) {
return false;
}
}
return true;
}
return false;
}
/**
* If you call a varargs method by passing it an array, the array
* will end up being arg 1.
*/
public static function unfuckVarargs (args :Array) :Array
{
return (args.length == 1 && (args[0] is Array)) ? (args[0] as Array)
: args;
}
}
}
|
//
// $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.ByteArray;
public class Util
{
/**
* Initialize the target object with values present in the initProps object and the defaults
* object. Neither initProps nor defaults will be modified.
* @throws ReferenceError if a property cannot be set on the target object.
*
* @param target any object or class instance.
* @param initProps a plain Object hash containing names and properties to set on the target
* object.
* @param defaults a plain Object hash containing names and properties to set on the target
* object, only if the same property name does not exist in initProps.
* @param maskProps a plain Object hash containing names of properties to omit setting
* from the initProps object. This allows you to add custom properties to
* initProps without having to modify the value from your callers.
*/
public static function init (
target :Object, initProps :Object, defaults :Object = null, maskProps :Object = null) :void
{
var prop :String;
for (prop in initProps) {
if (maskProps == null || !(prop in maskProps)) {
target[prop] = initProps[prop];
}
}
if (defaults != null) {
for (prop in defaults) {
if (!(prop in initProps)) {
target[prop] = defaults[prop];
}
}
}
}
/**
* Is the specified object 'simple': one of the basic built-in flash types.
*/
public static function isSimple (obj :Object) :Boolean
{
var type :String = typeof(obj);
switch (type) {
case "number":
case "string":
case "boolean":
return true;
case "object":
return (obj is Date) || (obj is Array);
default:
return false;
}
}
/**
* Parse the 'value' object into XML safely. This is equivalent to <code>new XML(value)</code>
* but offers protection from other code that may have changing the default settings
* used for parsing XML. Also, if you would like to use non-standard parsing settings
* this method will protect other code from being broken by you.
*
* @param value the value to parse into XML.
* @param settings an Object containing your desired XML settings, or null (or omitted) to
* use the default settings.
* @see XML#setSettings()
*/
public static function newXML (value :Object, settings :Object = null) :XML
{
return safeXMLOp(function () :* {
return new XML(value);
}, settings) as XML;
}
/**
* Call toString() on the specified XML object safely. This is equivalent to
* <code>xml.toString()</code> but offers protection from other code that may have changed
* the default settings used for stringing XML. Also, if you would like to use the
* non-standard printing settings this method will protect other code from being
* broken by you.
*
* @param xml the xml value to Stringify.
* @param settings an Object containing your desired XML settings, or null (or omitted) to
* use the default settings.
* @see XML#toString()
* @see XML#setSettings()
*/
public static function XMLtoString (xml :XML, settings :Object = null) :String
{
return safeXMLOp(function () :* {
return xml.toString();
}, settings) as String;
}
/**
* Call toXMLString() on the specified XML object safely. This is equivalent to
* <code>xml.toXMLString()</code> but offers protection from other code that may have changed
* the default settings used for stringing XML. Also, if you would like to use the
* non-standard printing settings this method will protect other code from being
* broken by you.
*
* @param xml the xml value to Stringify.
* @param settings an Object containing your desired XML settings, or null (or omitted) to
* use the default settings.
* @see XML#toXMLString()
* @see XML#setSettings()
*/
public static function XMLtoXMLString (xml :XML, settings :Object = null) :String
{
return safeXMLOp(function () :* {
return xml.toXMLString();
}, settings) as String;
}
/**
* Perform an operation on XML that takes place using the specified settings, and
* restores the XML settings to their previous values.
*
* @param fn a function to be called with no arguments.
* @param settings an Object containing your desired XML settings, or null (or omitted) to
* use the default settings.
*
* @return the return value of your function, if any.
* @see XML#setSettings()
* @see XML#settings()
*/
public static function safeXMLOp (fn :Function, settings :Object = null) :*
{
var oldSettings :Object = XML.settings();
try {
XML.setSettings(settings); // setting to null resets to all the defaults
return fn();
} finally {
XML.setSettings(oldSettings);
}
}
/**
* A nice utility method for testing equality in a better way.
* If the objects are Equalable, then that will be tested. Arrays
* and ByteArrays are also compared and are equal if they have
* elements that are equals (deeply).
*/
public static function equals (obj1 :Object, obj2 :Object) :Boolean
{
// catch various common cases (both primitive or null)
if (obj1 === obj2) {
return true;
} else if (obj1 is Equalable) {
// if obj1 is Equalable, then that decides it
return (obj1 as Equalable).equals(obj2);
} else if ((obj1 is Array) && (obj2 is Array)) {
return ArrayUtil.equals(obj1 as Array, obj2 as Array);
} else if ((obj1 is ByteArray) && (obj2 is ByteArray)) {
var ba1 :ByteArray = (obj1 as ByteArray);
var ba2 :ByteArray = (obj2 as ByteArray);
if (ba1.length != ba2.length) {
return false;
}
for (var ii :int = 0; ii < ba1.length; ii++) {
if (ba1[ii] != ba2[ii]) {
return false;
}
}
return true;
}
return false;
}
/**
* If you call a varargs method by passing it an array, the array
* will end up being arg 1.
*/
public static function unfuckVarargs (args :Array) :Array
{
return (args.length == 1 && (args[0] is Array)) ? (args[0] as Array)
: args;
}
}
}
|
Fix docs, clarify.
|
Fix docs, clarify.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4934 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
4c15dd4ee1405d6559f2df409924ffb629375989
|
src/aerys/minko/render/shader/part/DiffuseShaderPart.as
|
src/aerys/minko/render/shader/part/DiffuseShaderPart.as
|
package aerys.minko.render.shader.part
{
import aerys.minko.render.material.basic.BasicProperties;
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.type.enum.SamplerFiltering;
import aerys.minko.type.enum.SamplerMipMapping;
import aerys.minko.type.enum.SamplerWrapping;
public class DiffuseShaderPart extends ShaderPart
{
/**
* The shader part to use a diffuse map or fallback and use a solid color.
*
* @param main
*
*/
public function DiffuseShaderPart(main : Shader)
{
super(main);
}
public function getDiffuseColor() : SFloat
{
var diffuseColor : SFloat = null;
if (meshBindings.propertyExists(BasicProperties.DIFFUSE_MAP))
{
var uv : SFloat = vertexUV.xy;
var diffuseMap : SFloat = meshBindings.getTextureParameter(
BasicProperties.DIFFUSE_MAP,
meshBindings.getConstant(BasicProperties.DIFFUSE_FILTERING, SamplerFiltering.LINEAR),
meshBindings.getConstant(BasicProperties.DIFFUSE_MIPMAPPING, SamplerMipMapping.LINEAR),
meshBindings.getConstant(BasicProperties.DIFFUSE_WRAPPING, SamplerWrapping.REPEAT)
);
if (meshBindings.propertyExists(BasicProperties.DIFFUSE_UV_SCALE))
uv.scaleBy(meshBindings.getParameter(BasicProperties.DIFFUSE_UV_SCALE, 2));
if (meshBindings.propertyExists(BasicProperties.DIFFUSE_UV_OFFSET))
uv.incrementBy(meshBindings.getParameter(BasicProperties.DIFFUSE_UV_OFFSET, 2));
diffuseColor = sampleTexture(diffuseMap,interpolate(uv));
}
else if (meshBindings.propertyExists(BasicProperties.DIFFUSE_COLOR))
{
diffuseColor = meshBindings.getParameter(BasicProperties.DIFFUSE_COLOR, 4);
}
else
{
diffuseColor = float4(0., 0., 0., 1.);
}
// Apply HLSA modifiers
if (meshBindings.propertyExists(BasicProperties.DIFFUSE_TRANSFORM))
{
diffuseColor = multiply4x4(
diffuseColor,
meshBindings.getParameter(BasicProperties.DIFFUSE_TRANSFORM, 16)
);
}
if (meshBindings.propertyExists(BasicProperties.ALPHA_THRESHOLD))
{
var alphaThreshold : SFloat = meshBindings.getParameter(
BasicProperties.ALPHA_THRESHOLD, 1
);
kill(subtract(0.5, lessThan(diffuseColor.w, alphaThreshold)));
}
return diffuseColor;
}
}
}
|
package aerys.minko.render.shader.part
{
import aerys.minko.render.material.basic.BasicProperties;
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.type.enum.SamplerFiltering;
import aerys.minko.type.enum.SamplerMipMapping;
import aerys.minko.type.enum.SamplerWrapping;
public class DiffuseShaderPart extends ShaderPart
{
/**
* The shader part to use a diffuse map or fallback and use a solid color.
*
* @param main
*
*/
public function DiffuseShaderPart(main : Shader)
{
super(main);
}
public function getDiffuseColor(killOnAlphaThreshold : Boolean = true) : SFloat
{
var diffuseColor : SFloat = null;
if (meshBindings.propertyExists(BasicProperties.DIFFUSE_MAP))
{
var uv : SFloat = vertexUV.xy;
var diffuseMap : SFloat = meshBindings.getTextureParameter(
BasicProperties.DIFFUSE_MAP,
meshBindings.getConstant(BasicProperties.DIFFUSE_FILTERING, SamplerFiltering.LINEAR),
meshBindings.getConstant(BasicProperties.DIFFUSE_MIPMAPPING, SamplerMipMapping.LINEAR),
meshBindings.getConstant(BasicProperties.DIFFUSE_WRAPPING, SamplerWrapping.REPEAT)
);
if (meshBindings.propertyExists(BasicProperties.DIFFUSE_UV_SCALE))
uv.scaleBy(meshBindings.getParameter(BasicProperties.DIFFUSE_UV_SCALE, 2));
if (meshBindings.propertyExists(BasicProperties.DIFFUSE_UV_OFFSET))
uv.incrementBy(meshBindings.getParameter(BasicProperties.DIFFUSE_UV_OFFSET, 2));
diffuseColor = sampleTexture(diffuseMap,interpolate(uv));
}
else if (meshBindings.propertyExists(BasicProperties.DIFFUSE_COLOR))
{
diffuseColor = meshBindings.getParameter(BasicProperties.DIFFUSE_COLOR, 4);
}
else
{
diffuseColor = float4(0., 0., 0., 1.);
}
// Apply HLSA modifiers
if (meshBindings.propertyExists(BasicProperties.DIFFUSE_TRANSFORM))
{
diffuseColor = multiply4x4(
diffuseColor,
meshBindings.getParameter(BasicProperties.DIFFUSE_TRANSFORM, 16)
);
}
if (killOnAlphaThreshold && meshBindings.propertyExists(BasicProperties.ALPHA_THRESHOLD))
{
var alphaThreshold : SFloat = meshBindings.getParameter(
BasicProperties.ALPHA_THRESHOLD, 1
);
kill(subtract(0.5, lessThan(diffuseColor.w, alphaThreshold)));
}
return diffuseColor;
}
}
}
|
add a killOnAlphaThreshold : Boolean argument to DiffuseShaderPart.getDiffuseColor() to enable/disable the kill that is sometime done at a later stage (cf. wireframe)
|
add a killOnAlphaThreshold : Boolean argument to DiffuseShaderPart.getDiffuseColor() to enable/disable the kill that is sometime done at a later stage (cf. wireframe)
|
ActionScript
|
mit
|
aerys/minko-as3
|
47d8ed1d631603599abb588515371f3280d43ea3
|
src/as/com/threerings/flex/CommandMenu.as
|
src/as/com/threerings/flex/CommandMenu.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.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.geom.Rectangle;
import mx.controls.Menu;
import mx.core.mx_internal;
import mx.core.Application;
import mx.core.ScrollPolicy;
import mx.events.MenuEvent;
import mx.utils.ObjectUtil;
import flexlib.controls.ScrollableArrowMenu;
import com.threerings.util.CommandEvent;
use namespace mx_internal;
/**
* A pretty standard menu that can submit CommandEvents if menu items
* have "command" and possibly "arg" properties. Commands are submitted to
* controllers for processing. Alternatively, you may specify
* "callback" properties that specify a function closure to call, with the
* "arg" property containing either a single arg or an array of args.
*
* Example dataProvider array:
* [ { label: "Go home", icon: homeIconClass,
* command: Controller.GO_HOME, arg: homeId },
* { type: "separator"},
{ label: "Crazytown", callback: setCrazy, arg: [ true, false ] },
* { label: "Other places", children: subMenuArray }
* ];
*
* See "Defining menu structure and data" in the Flex manual for the
* full list.
*/
public class CommandMenu extends ScrollableArrowMenu
{
public function CommandMenu ()
{
super();
verticalScrollPolicy = ScrollPolicy.OFF;
addEventListener(MenuEvent.ITEM_CLICK, itemClicked);
}
/**
* Factory method to create a command menu.
*
* @param items an array of menu items.
*/
public static function createMenu (items :Array) :CommandMenu
{
var menu :CommandMenu = new CommandMenu();
menu.owner = DisplayObjectContainer(Application.application);
menu.tabEnabled = false;
menu.showRoot = true;
Menu.popUpMenu(menu, null, items);
return menu;
}
/**
* Actually pop up the menu. This can be used instead of show().
*/
public function popUp (
trigger :DisplayObject, popUpwards :Boolean = false) :void
{
var r :Rectangle = trigger.getBounds(trigger.stage);
if (popUpwards) {
show(r.x, 0);
// then, reposition the y once we know our size
y = r.y - getExplicitOrMeasuredHeight();
} else {
// position it below the trigger
show(r.x, r.y + r.height);
}
}
/**
* Just like our superclass's show(), except that when invoked
* with no args, causes the menu to show at the current mouse location
* instead of the top-left corner of the application.
*/
override public function show (xShow :Object = null, yShow :Object = null) :void
{
if (xShow == null) {
xShow = DisplayObject(Application.application).mouseX;
}
if (yShow == null) {
yShow = DisplayObject(Application.application).mouseY;
}
super.show(xShow, yShow);
}
/**
* Callback for MenuEvent.ITEM_CLICK.
*/
protected function itemClicked (event :MenuEvent) :void
{
var arg :Object = getItemProp(event.item, "arg");
var cmdOrFn :Object = getItemProp(event.item, "command");
if (cmdOrFn == null) {
cmdOrFn = getItemProp(event.item, "callback");
}
if (cmdOrFn != null) {
event.stopImmediatePropagation();
CommandEvent.dispatch(mx_internal::parentDisplayObject, cmdOrFn, arg)
}
// else: no warning. There may be non-command menu items mixed in.
}
/**
* Get the specified property for the specified item, if any.
* Somewhat similar to bits in the DefaultDataDescriptor.
*/
protected function getItemProp (item :Object, prop :String) :Object
{
try {
if (item is XML) {
return String((item as XML).attribute(prop));
} else if (prop in item) {
return item[prop];
}
} catch (e :Error) {
// alas; fall through
}
return null;
}
}
}
|
//
// $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.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.events.IEventDispatcher;
import flash.geom.Rectangle;
import mx.controls.Menu;
import mx.core.mx_internal;
import mx.core.Application;
import mx.core.ScrollPolicy;
import mx.events.MenuEvent;
import mx.utils.ObjectUtil;
import flexlib.controls.ScrollableArrowMenu;
import com.threerings.util.CommandEvent;
use namespace mx_internal;
/**
* A pretty standard menu that can submit CommandEvents if menu items have "command" and possibly
* "arg" properties. Commands are submitted to controllers for processing. Alternatively, you may
* specify "callback" properties that specify a function closure to call, with the "arg" property
* containing either a single arg or an array of args.
*
* Example dataProvider array:
* [ { label: "Go home", icon: homeIconClass,
* command: Controller.GO_HOME, arg: homeId },
* { type: "separator"},
{ label: "Crazytown", callback: setCrazy, arg: [ true, false ] },
* { label: "Other places", children: subMenuArray }
* ];
*
* See "Defining menu structure and data" in the Flex manual for the full list.
*/
public class CommandMenu extends ScrollableArrowMenu
{
/**
* Factory method to create a command menu.
*
* @param items an array of menu items.
*/
public static function createMenu (items :Array) :CommandMenu
{
var menu :CommandMenu = new CommandMenu();
menu.owner = DisplayObjectContainer(Application.application);
menu.tabEnabled = false;
menu.showRoot = true;
Menu.popUpMenu(menu, null, items);
return menu;
}
public function CommandMenu ()
{
super();
verticalScrollPolicy = ScrollPolicy.OFF;
addEventListener(MenuEvent.ITEM_CLICK, itemClicked);
}
/**
* Configures the event dispatcher to be used when dispatching this menu's events. By default
* they will be dispatched on the stage.
*/
public function setDispatcher (dispatcher :IEventDispatcher) :void
{
_dispatcher = dispatcher;
}
/**
* Actually pop up the menu. This can be used instead of show().
*/
public function popUp (
trigger :DisplayObject, popUpwards :Boolean = false) :void
{
var r :Rectangle = trigger.getBounds(trigger.stage);
if (popUpwards) {
show(r.x, 0);
// then, reposition the y once we know our size
y = r.y - getExplicitOrMeasuredHeight();
} else {
// position it below the trigger
show(r.x, r.y + r.height);
}
}
/**
* Just like our superclass's show(), except that when invoked with no args, causes the menu to
* show at the current mouse location instead of the top-left corner of the application.
*/
override public function show (xShow :Object = null, yShow :Object = null) :void
{
if (xShow == null) {
xShow = DisplayObject(Application.application).mouseX;
}
if (yShow == null) {
yShow = DisplayObject(Application.application).mouseY;
}
super.show(xShow, yShow);
}
/**
* Callback for MenuEvent.ITEM_CLICK.
*/
protected function itemClicked (event :MenuEvent) :void
{
var arg :Object = getItemProp(event.item, "arg");
var cmdOrFn :Object = getItemProp(event.item, "command");
if (cmdOrFn == null) {
cmdOrFn = getItemProp(event.item, "callback");
}
if (cmdOrFn != null) {
event.stopImmediatePropagation();
CommandEvent.dispatch(_dispatcher == null ? mx_internal::parentDisplayObject :
_dispatcher, cmdOrFn, arg);
}
// else: no warning. There may be non-command menu items mixed in.
}
/**
* Get the specified property for the specified item, if any. Somewhat similar to bits in the
* DefaultDataDescriptor.
*/
protected function getItemProp (item :Object, prop :String) :Object
{
try {
if (item is XML) {
return String((item as XML).attribute(prop));
} else if (prop in item) {
return item[prop];
}
} catch (e :Error) {
// alas; fall through
}
return null;
}
protected var _dispatcher :IEventDispatcher;
}
}
|
Allow a custom dispatcher to be provided because the default (dispatching on the stage) only routes commands to the global controller, bypassing the controller for the current place view.
|
Allow a custom dispatcher to be provided because the default (dispatching on
the stage) only routes commands to the global controller, bypassing the
controller for the current place view.
git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@190 ed5b42cb-e716-0410-a449-f6a68f950b19
|
ActionScript
|
lgpl-2.1
|
threerings/nenya,threerings/nenya
|
8c502aba9254a0930ab08996f93eb78940b0c687
|
src/com/google/analytics/core/BrowserInfo.as
|
src/com/google/analytics/core/BrowserInfo.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.core
{
import com.google.analytics.utils.Environment;
import com.google.analytics.utils.Variables;
import com.google.analytics.utils.Version;
import com.google.analytics.v4.Configuration;
/**
* The BrowserInfo class.
*/
public class BrowserInfo
{
private var _config:Configuration;
private var _info:Environment;
/**
* Creates a new BrowserInfo instance.
* @param info The Environment reference of the BrowserInfo instance.
*/
public function BrowserInfo( config:Configuration, info:Environment )
{
_config = config;
_info = info;
}
/**
* Language encoding for the browser.
* <p>Some browsers don't set this, in which case it is set to "-".</p>
* <p>Example : <b>utmcs=ISO-8859-1</b></p>
*/
public function get utmcs():String
{
return _info.languageEncoding;
}
/**
* The Screen resolution
* <p>Example : <b>utmsr=2400x1920</b></p>
*/
public function get utmsr():String
{
return _info.screenWidth + "x" + _info.screenHeight;
}
/**
* Screen color depth
* <p>Example :<b>utmsc=24-bit</b></p>
*/
public function get utmsc():String
{
return _info.screenColorDepth + "-bit";
}
/**
* Browser language.
* <p>Example :<b>utmul=pt-br</b></p>
*/
public function get utmul():String
{
return _info.language.toLowerCase();
}
/**
* Indicates if browser is Java-enabled.
* <p>Example :<b>utmje=1</b></p>
*/
public function get utmje():String
{
return "0"; //not supported
}
/**
* Flash Version.
* <p>Example :<b>utmfl=9.0%20r48</b></p>
*/
public function get utmfl():String
{
if( _config.detectFlash )
{
var v:Version = _info.flashVersion;
return v.major+"."+v.minor+" r"+v.build;
}
return "-";
}
/**
* Returns a Variables object representation.
* @return a Variables object representation.
*/
public function toVariables():Variables
{
var variables:Variables = new Variables();
variables.URIencode = true;
variables.utmcs = utmcs;
variables.utmsr = utmsr;
variables.utmsc = utmsc;
variables.utmul = utmul;
variables.utmje = utmje;
variables.utmfl = utmfl;
return variables;
}
/**
* Returns the url String representation of the object.
* @return the url String representation of the object.
*/
public function toURLString():String
{
var v:Variables = toVariables();
return v.toString();
}
}
}
|
/*
* 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.core
{
import com.google.analytics.utils.Environment;
import com.google.analytics.utils.Variables;
import com.google.analytics.v4.Configuration;
import core.version;
public class BrowserInfo
{
private var _config:Configuration;
private var _info:Environment;
/**
* Creates a new BrowserInfo instance.
* @param info The Environment reference of the BrowserInfo instance.
*/
public function BrowserInfo( config:Configuration, info:Environment )
{
_config = config;
_info = info;
}
/**
* Language encoding for the browser.
* <p>Some browsers don't set this, in which case it is set to "-".</p>
* <p>Example : <b>utmcs=ISO-8859-1</b></p>
*/
public function get utmcs():String
{
return _info.languageEncoding;
}
/**
* The Screen resolution
* <p>Example : <b>utmsr=2400x1920</b></p>
*/
public function get utmsr():String
{
return _info.screenWidth + "x" + _info.screenHeight;
}
/**
* Screen color depth
* <p>Example :<b>utmsc=24-bit</b></p>
*/
public function get utmsc():String
{
return _info.screenColorDepth + "-bit";
}
/**
* Browser language.
* <p>Example :<b>utmul=pt-br</b></p>
*/
public function get utmul():String
{
return _info.language.toLowerCase();
}
/**
* Indicates if browser is Java-enabled.
* <p>Example :<b>utmje=1</b></p>
*/
public function get utmje():String
{
return "0"; //not supported
}
/**
* Flash Version.
* <p>Example :<b>utmfl=9.0%20r48</b></p>
*/
public function get utmfl():String
{
if( _config.detectFlash )
{
var v:version = _info.flashVersion;
return v.major+"."+v.minor+" r"+v.build;
}
return "-";
}
/**
* Returns a Variables object representation.
* @return a Variables object representation.
*/
public function toVariables():Variables
{
var variables:Variables = new Variables();
variables.URIencode = true;
variables.utmcs = utmcs;
variables.utmsr = utmsr;
variables.utmsc = utmsc;
variables.utmul = utmul;
variables.utmje = utmje;
variables.utmfl = utmfl;
return variables;
}
/**
* Returns the url String representation of the object.
* @return the url String representation of the object.
*/
public function toURLString():String
{
var v:Variables = toVariables();
return v.toString();
}
}
}
|
replace class Version by core.version
|
replace class Version by core.version
|
ActionScript
|
apache-2.0
|
dli-iclinic/gaforflash,mrthuanvn/gaforflash,drflash/gaforflash,drflash/gaforflash,Miyaru/gaforflash,jisobkim/gaforflash,dli-iclinic/gaforflash,Miyaru/gaforflash,Vigmar/gaforflash,mrthuanvn/gaforflash,jisobkim/gaforflash,jeremy-wischusen/gaforflash,DimaBaliakin/gaforflash,Vigmar/gaforflash,soumavachakraborty/gaforflash,jeremy-wischusen/gaforflash,soumavachakraborty/gaforflash,DimaBaliakin/gaforflash
|
fd57d48acf7a14f0bbc5ecfb6677487f9e83703e
|
tests/test_ad/src/net/iab/vpaid/core/AdData.as
|
tests/test_ad/src/net/iab/vpaid/core/AdData.as
|
package net.iab.vpaid.core
{
/**
* Contains ad configuration parameters
* @author Andrei Andreev
*/
public class AdData extends Object
{
private var _params:Object = {};
/**
*
* @param params at runtime typically LoaderInfo.parameters
*/
public function AdData(params:Object = null)
{
init(params);
}
private function init(params:Object = null):void
{
var url:String = escape("http://services.mediamind.com/instream/IAB/videos/ad-video-canal.mp4");
_params.advideo = unescape(url);
_params.skipOffset = 5;
_params.ovvBeaconURL = "http://localhost/iab/OVVBeacon.swf";
this.params = params;
}
/**
* Iterates through argument properties and stored key/value pairs. Passing of null does not nullify individual properties.
*/
public function set params(value:Object):void
{
for (var property:String in value)
_params[property] = unescape(value[property]);
}
/**
* Looks up property by proeprty name and returns corresponding value as a primitive Object. It is consumer's responsibility to validate/cast to specific value data type.
* @param property name of the key in key/value pair
* @return primitive typeless Object
*/
public function getParam(property:String):Object
{
return _params[property];
}
}
}
|
package net.iab.vpaid.core
{
/**
* Contains ad configuration parameters
* @author Andrei Andreev
*/
public class AdData extends Object
{
private var _params:Object = {};
/**
*
* @param params at runtime typically LoaderInfo.parameters
*/
public function AdData(params:Object = null)
{
init(params);
}
private function init(params:Object = null):void
{
var url:String = escape("http://services.mediamind.com/instream/IAB/videos/ad-video-canal.mp4");
_params.advideo = unescape(url);
_params.skipOffset = 5;
//_params.ovvBeaconURL = "http://localhost/iab/OVVBeacon.swf";
_params.ovvBeaconURL = "/ad/OVVBeacon.swf";
this.params = params;
}
/**
* Iterates through argument properties and stored key/value pairs. Passing of null does not nullify individual properties.
*/
public function set params(value:Object):void
{
for (var property:String in value)
_params[property] = unescape(value[property]);
}
/**
* Looks up property by proeprty name and returns corresponding value as a primitive Object. It is consumer's responsibility to validate/cast to specific value data type.
* @param property name of the key in key/value pair
* @return primitive typeless Object
*/
public function getParam(property:String):Object
{
return _params[property];
}
}
}
|
Recompile for default OVVBeacon location
|
Recompile for default OVVBeacon location
|
ActionScript
|
bsd-3-clause
|
OBSLabs/openvv,OBSLabs/openvv,jdreetz/openvv,jdreetz/openvv,OBSLabs/openvv,jdreetz/openvv
|
bbfcf85775ef70d36207687e835ca65040bf621f
|
src/as/com/threerings/ezgame/client/EZGamePanel.as
|
src/as/com/threerings/ezgame/client/EZGamePanel.as
|
package com.threerings.ezgame.client {
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.events.Event;
import flash.utils.Dictionary;
import mx.containers.Canvas;
import mx.containers.VBox;
import mx.core.Container;
import mx.core.IChildList;
import mx.utils.DisplayUtil;
import com.threerings.util.MediaContainer;
import com.threerings.mx.controls.ChatDisplayBox;
import com.threerings.crowd.client.PlaceView;
import com.threerings.crowd.data.PlaceObject;
import com.threerings.crowd.util.CrowdContext;
import com.threerings.ezgame.data.EZGameConfig;
import com.threerings.ezgame.data.EZGameObject;
import com.threerings.ezgame.Game;
public class EZGamePanel extends VBox
implements PlaceView
{
public function EZGamePanel (ctx :CrowdContext, ctrl :EZGameController)
{
_ctx = ctx;
_ctrl = ctrl;
// add a listener so that we hear about all new children
addEventListener(Event.ADDED, childAdded);
addEventListener(Event.REMOVED, childRemoved);
var cfg :EZGameConfig = (ctrl.getPlaceConfig() as EZGameConfig);
_gameView = new MediaContainer(cfg.configData); // TODO
addChild(_gameView);
addChild(new ChatDisplayBox(ctx));
}
// from PlaceView
public function willEnterPlace (plobj :PlaceObject) :void
{
// don't start notifying anything of the game until we've
// notified the game manager that we're in the game
// (done in GameController, and it uses callLater, so we do it twice!)
_ctx.getClient().callLater(function () :void {
_ctx.getClient().callLater(function () :void {
_ezObj = (plobj as EZGameObject);
notifyOfGame(_gameView);
});
});
}
// from PlaceView
public function didLeavePlace (plobj :PlaceObject) :void
{
removeListeners(_gameView);
_ezObj = null;
}
/**
* Handle ADDED events.
*/
protected function childAdded (event :Event) :void
{
if (_ezObj != null) {
notifyOfGame(event.target as DisplayObject);
}
}
/**
* Handle REMOVED events.
*/
protected function childRemoved (event :Event) :void
{
if (_ezObj != null) {
removeListeners(event.target as DisplayObject);
}
}
/**
* Find any children of the specified object that implement
* com.metasoy.game.Game and provide them with the GameObject.
*/
protected function notifyOfGame (root :DisplayObject) :void
{
DisplayUtil.walkDisplayObjects(root,
function (disp :DisplayObject) :void
{
if (disp is Game) {
// only notify the Game if we haven't seen it before
if (null == _seenGames[disp]) {
(disp as Game).setGameObject(_ctrl.gameObjImpl);
_seenGames[disp] = true;
}
}
// always check to see if it's a listener
_ctrl.gameObjImpl.registerListener(disp);
});
}
protected function removeListeners (root :DisplayObject) :void
{
DisplayUtil.walkDisplayObjects(root,
function (disp :DisplayObject) :void
{
_ctrl.gameObjImpl.unregisterListener(disp);
});
}
protected var _ctx :CrowdContext;
protected var _ctrl :EZGameController;
protected var _gameView :MediaContainer;
/** A weak-key hash of the Game interfaces we've already seen. */
protected var _seenGames :Dictionary = new Dictionary(true);
protected var _ezObj :EZGameObject;
}
}
|
package com.threerings.ezgame.client {
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.events.Event;
import flash.utils.Dictionary;
import mx.containers.Canvas;
import mx.containers.VBox;
import mx.core.Container;
import mx.core.IChildList;
import mx.utils.DisplayUtil;
import com.threerings.util.MediaContainer;
import com.threerings.mx.controls.ChatDisplayBox;
import com.threerings.crowd.client.PlaceView;
import com.threerings.crowd.data.PlaceObject;
import com.threerings.crowd.util.CrowdContext;
import com.threerings.ezgame.data.EZGameConfig;
import com.threerings.ezgame.data.EZGameObject;
import com.threerings.ezgame.Game;
public class EZGamePanel extends VBox
implements PlaceView
{
public function EZGamePanel (ctx :CrowdContext, ctrl :EZGameController)
{
_ctx = ctx;
_ctrl = ctrl;
// add a listener so that we hear about all new children
addEventListener(Event.ADDED, childAdded);
addEventListener(Event.REMOVED, childRemoved);
var cfg :EZGameConfig = (ctrl.getPlaceConfig() as EZGameConfig);
_gameView = new MediaContainer(cfg.configData); // TODO
addChild(_gameView);
//addChild(new ChatDisplayBox(ctx));
}
// from PlaceView
public function willEnterPlace (plobj :PlaceObject) :void
{
// don't start notifying anything of the game until we've
// notified the game manager that we're in the game
// (done in GameController, and it uses callLater, so we do it twice!)
_ctx.getClient().callLater(function () :void {
_ctx.getClient().callLater(function () :void {
_ezObj = (plobj as EZGameObject);
notifyOfGame(_gameView);
});
});
}
// from PlaceView
public function didLeavePlace (plobj :PlaceObject) :void
{
removeListeners(_gameView);
_ezObj = null;
}
/**
* Handle ADDED events.
*/
protected function childAdded (event :Event) :void
{
if (_ezObj != null) {
notifyOfGame(event.target as DisplayObject);
}
}
/**
* Handle REMOVED events.
*/
protected function childRemoved (event :Event) :void
{
if (_ezObj != null) {
removeListeners(event.target as DisplayObject);
}
}
/**
* Find any children of the specified object that implement
* com.metasoy.game.Game and provide them with the GameObject.
*/
protected function notifyOfGame (root :DisplayObject) :void
{
DisplayUtil.walkDisplayObjects(root,
function (disp :DisplayObject) :void
{
if (disp is Game) {
// only notify the Game if we haven't seen it before
if (null == _seenGames[disp]) {
(disp as Game).setGameObject(_ctrl.gameObjImpl);
_seenGames[disp] = true;
}
}
// always check to see if it's a listener
_ctrl.gameObjImpl.registerListener(disp);
});
}
protected function removeListeners (root :DisplayObject) :void
{
DisplayUtil.walkDisplayObjects(root,
function (disp :DisplayObject) :void
{
_ctrl.gameObjImpl.unregisterListener(disp);
});
}
protected var _ctx :CrowdContext;
protected var _ctrl :EZGameController;
protected var _gameView :MediaContainer;
/** A weak-key hash of the Game interfaces we've already seen. */
protected var _seenGames :Dictionary = new Dictionary(true);
protected var _ezObj :EZGameObject;
}
}
|
Remove giant obnoxious game-blocking chat display.
|
Remove giant obnoxious game-blocking chat display.
git-svn-id: a3e1eb16dde062992de22c830ed8045c8013209a@134 c613c5cb-e716-0410-b11b-feb51c14d237
|
ActionScript
|
lgpl-2.1
|
threerings/vilya,threerings/vilya
|
b7da2fa190965d58316f10cb6a70288ea0867305
|
src/as/com/threerings/media/image/ClassRecord.as
|
src/as/com/threerings/media/image/ClassRecord.as
|
//
// Nenya library - tools for developing networked games
// Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/nenya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.media.image {
import com.threerings.util.Log;
import com.threerings.util.Map;
import com.threerings.util.Maps;
import com.threerings.util.RandomUtil;
import com.threerings.util.StringUtil;
public class ClassRecord
{
private const log :Log = Log.getLog(ClassRecord);
/** An integer identifier for this class. */
public var classId :int;
/** The name of the color class. */
public var name :String;
/** The source color to use when recoloring colors in this class. */
public var source :uint;
/** Data identifying the range of colors around the source color
* that will be recolored when recoloring using this class. */
public var range :Array;
/** The default starting legality value for this color class. See
* {@link ColorRecord#starter}. */
public var starter :Boolean;
/** The default colorId to use for recoloration in this class, or
* 0 if there is no default defined. */
public var defaultId :int;
/** A table of target colors included in this class. */
public var colors :Map = Maps.newMapOf(int);
/** Used when parsing the color definitions. */
public function addColor (record :ColorRecord) :void
{
// validate the color id
if (record.colorId > 127) {
log.warning("Refusing to add color record; colorId > 127",
"class", this, "record", record);
} else if (colors.containsKey(record.colorId)) {
log.warning("Refusing to add duplicate colorId",
"class", this, "record", record, "existing", colors.get(record.colorId));
} else {
record.cclass = this;
colors.put(record.colorId, record);
}
}
/**
* Translates a color identified in string form into the id that should be used to look up
* its information. Throws an exception if no color could be found that associates with
* that name.
*/
public function getColorId (name :String) :int
{
// Check if the string is itself a number
var id :int = name as int;
if (colors.containsKey(id)) {
return id;
}
// Look for name matches among all colors
for each (var color :ColorRecord in colors) {
if (StringUtil.compareIgnoreCase(color.name, name) == 0) {
return color.colorId;
}
}
// That input wasn't a color
throw new Error("No color named '" + name + "'", 0);
}
/** Returns a random starting id from the entries in this class. */
public function randomStartingColor () :ColorRecord
{
// figure out our starter ids if we haven't already
if (_starters == null) {
_starters = [];
for each (var color :ColorRecord in colors) {
if (color.starter) {
_starters.push(color);
}
}
}
// sanity check
if (_starters.length < 1) {
log.warning("Requested random starting color from colorless component class",
"class", this);
return null;
}
// return a random entry from the array
return RandomUtil.pickRandom(_starters);
}
/**
* Get the default ColorRecord defined for this color class, or
* null if none.
*/
public function getDefault () :ColorRecord
{
return colors.get(defaultId);
}
public function toString () :String
{
return "[id=" + classId + ", name=" + name + ", source=#" +
StringUtil.toHex(source & 0xFFFFFF, 6) +
", range=" + StringUtil.toString(range) +
", starter=" + starter + ", colors=" +
StringUtil.toString(colors.values()) + "]";
}
public static function fromXml (xml :XML) :ClassRecord
{
var rec :ClassRecord = new ClassRecord();
rec.classId = xml.@classId;
for each (var colorXml :XML in xml.color) {
rec.colors.put(int(colorXml.@colorId), ColorRecord.fromXml(colorXml, rec));
}
rec.name = xml.@name;
var srcStr :String = xml.@source;
rec.source = parseInt(srcStr.substr(1, srcStr.length - 1), 16);
rec.range = toNumArray(xml.@range);
rec.defaultId = xml.@defaultId;
return rec;
}
protected static function toNumArray (str :String) :Array
{
if (str == null) {
return null;
}
return str.split(",").map(function(element :*, index :int, arr :Array) :Number {
return Number(element);
});
}
protected var _starters :Array;
}
}
|
//
// Nenya library - tools for developing networked games
// Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/nenya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.media.image {
import com.threerings.util.Log;
import com.threerings.util.Map;
import com.threerings.util.Maps;
import com.threerings.util.RandomUtil;
import com.threerings.util.StringUtil;
public class ClassRecord
{
private const log :Log = Log.getLog(ClassRecord);
/** An integer identifier for this class. */
public var classId :int;
/** The name of the color class. */
public var name :String;
/** The source color to use when recoloring colors in this class. */
public var source :uint;
/** Data identifying the range of colors around the source color
* that will be recolored when recoloring using this class. */
public var range :Array;
/** The default starting legality value for this color class. See
* {@link ColorRecord#starter}. */
public var starter :Boolean;
/** The default colorId to use for recoloration in this class, or
* 0 if there is no default defined. */
public var defaultId :int;
/** A table of target colors included in this class. */
public var colors :Map = Maps.newMapOf(int);
/** Used when parsing the color definitions. */
public function addColor (record :ColorRecord) :void
{
// validate the color id
if (record.colorId > 127) {
log.warning("Refusing to add color record; colorId > 127",
"class", this, "record", record);
} else if (colors.containsKey(record.colorId)) {
log.warning("Refusing to add duplicate colorId",
"class", this, "record", record, "existing", colors.get(record.colorId));
} else {
record.cclass = this;
colors.put(record.colorId, record);
}
}
/**
* Translates a color identified in string form into the id that should be used to look up
* its information. Throws an exception if no color could be found that associates with
* that name.
*/
public function getColorId (name :String) :int
{
// Check if the string is itself a number
var id :int = name as int;
if (colors.containsKey(id)) {
return id;
}
// Look for name matches among all colors
for each (var color :ColorRecord in colors.values()) {
if (StringUtil.compareIgnoreCase(color.name, name) == 0) {
return color.colorId;
}
}
// That input wasn't a color
throw new Error("No color named '" + name + "'", 0);
}
/** Returns a random starting id from the entries in this class. */
public function randomStartingColor () :ColorRecord
{
// figure out our starter ids if we haven't already
if (_starters == null) {
_starters = [];
for each (var color :ColorRecord in colors) {
if (color.starter) {
_starters.push(color);
}
}
}
// sanity check
if (_starters.length < 1) {
log.warning("Requested random starting color from colorless component class",
"class", this);
return null;
}
// return a random entry from the array
return RandomUtil.pickRandom(_starters);
}
/**
* Get the default ColorRecord defined for this color class, or
* null if none.
*/
public function getDefault () :ColorRecord
{
return colors.get(defaultId);
}
public function toString () :String
{
return "[id=" + classId + ", name=" + name + ", source=#" +
StringUtil.toHex(source & 0xFFFFFF, 6) +
", range=" + StringUtil.toString(range) +
", starter=" + starter + ", colors=" +
StringUtil.toString(colors.values()) + "]";
}
public static function fromXml (xml :XML) :ClassRecord
{
var rec :ClassRecord = new ClassRecord();
rec.classId = xml.@classId;
for each (var colorXml :XML in xml.color) {
rec.colors.put(int(colorXml.@colorId), ColorRecord.fromXml(colorXml, rec));
}
rec.name = xml.@name;
var srcStr :String = xml.@source;
rec.source = parseInt(srcStr.substr(1, srcStr.length - 1), 16);
rec.range = toNumArray(xml.@range);
rec.defaultId = xml.@defaultId;
return rec;
}
protected static function toNumArray (str :String) :Array
{
if (str == null) {
return null;
}
return str.split(",").map(function(element :*, index :int, arr :Array) :Number {
return Number(element);
});
}
protected var _starters :Array;
}
}
|
Fix bug in getting colorizations by name.
|
Fix bug in getting colorizations by name.
git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@967 ed5b42cb-e716-0410-a449-f6a68f950b19
|
ActionScript
|
lgpl-2.1
|
threerings/nenya,threerings/nenya
|
18950503cdfa37b4cbf25544d98475875c20d6ff
|
Game/Resources/VoltageScene/Scripts/Mastermind.as
|
Game/Resources/VoltageScene/Scripts/Mastermind.as
|
class Mastermind {
Hub @hub;
Entity @self;
Entity@ slot1 = null;
Entity@ slot2 = null;
Entity@ slot3 = null;
Entity@ slot4 = null;
Entity@ slot1Key;
Entity@ slot2Key;
Entity@ slot3Key;
Entity@ slot4Key;
Entity @light1;
Entity @light2;
Entity @light3;
Entity @light4;
Entity @flickeringLights;
Entity @roundabout;
Mastermind(Entity @entity){
@hub = Managers();
@self = @entity;
@slot1Key = GetEntityByGUID(1511964701); // GreenPropp
@slot2Key = GetEntityByGUID(1511964823); // RedPropp
@slot3Key = GetEntityByGUID(1511964915); // YellowPropp
@slot4Key = GetEntityByGUID(1511964754); // PinkPropp
// Remove this if updates are not desired.
RegisterUpdate();
}
// Called by the engine for each frame.
void Update(float deltaTime) {
if (puzzleSolved)
return;
CheckSolution();
for(int i = 0; i < correct; i++){
TurnOnLight(100, vec3(0,255,0));
}
for(int i = 0; i < rightColors; i++){
TurnOnLight(100, vec3(255,0,0));
}
if(puzzleSolved){
}
else{
}
}
bool puzzleSolved = false;
int correct = 0;
int rightColors = 0;
void CheckSolution(){
correct = 0;
rightColors = 0;
puzzleSolved = false;
TurnOffLights();
if (@slot1 != null && @slot2 != null && @slot3 != null && @slot4 != null) {
if (slot1 is slot1Key)
correct = correct + 1;
else if (slot1 is slot2Key || slot1 is slot3Key || slot1 is slot4Key)
rightColors = rightColors + 1;
if (slot2 is slot2Key)
correct = correct + 1;
else if (slot2 is slot1Key || slot2 is slot3Key || slot2 is slot4Key)
rightColors = rightColors + 1;
if (slot3 is slot3Key)
correct = correct + 1;
else if (slot3 is slot1Key || slot3 is slot2Key || slot3 is slot4Key)
rightColors = rightColors + 1;
if (slot4 is slot4Key)
correct = correct + 1;
else if (slot4 is slot1Key || slot4 is slot2Key || slot4 is slot3Key)
rightColors = rightColors + 1;
if (correct == 4) {
puzzleSolved = true;
SendMessage(roundabout, 2);
}
}
}
void TurnOnLight(int intensity, vec3 lightColor){
if(light1.GetSpotLight().intensity == 0){
light1.GetSpotLight().intensity = intensity;
light1.GetSpotLight().color = lightColor;
}
else if(light2.GetSpotLight().intensity == 0){
light2.GetSpotLight().intensity = intensity;
light2.GetSpotLight().color = lightColor;
}
else if(light3.GetSpotLight().intensity == 0){
light3.GetSpotLight().intensity = intensity;
light3.GetSpotLight().color = lightColor;
}
else if(light4.GetSpotLight().intensity == 0){
light4.GetSpotLight().intensity = intensity;
light4.GetSpotLight().color = lightColor;
}
}
void TurnOffLights(){
light1.GetSpotLight().intensity = 0;
light2.GetSpotLight().intensity = 0;
light3.GetSpotLight().intensity = 0;
light4.GetSpotLight().intensity = 0;
}
void ReceiveMessage(Entity @sender, int signal) {
if(signal < 4)
AddToSlot(signal, sender);
else
RemoveFromSlot(signal - 4);
}
void AddToSlot(int slot, Entity@ fuse) {
// First remove any existing fuse in this slot.
RemoveFromSlot(slot);
switch(slot){
case 0: {
@slot1 = @fuse;
break;
}
case 1: {
@slot2 = @fuse;
break;
}
case 2: {
@slot3 = @fuse;
break;
}
case 3: {
@slot4 = @fuse;
break;
}
}
}
void RemoveFromSlot(int slot){
switch(slot){
case 0: {
if (@slot1 != null) {
SendMessage(slot1, 0);
}
@slot1 = null;
break;
}
case 1: {
if (@slot2 != null) {
SendMessage(slot2, 0);
}
@slot2 = null;
break;
}
case 2: {
if (@slot3 != null) {
SendMessage(slot3, 0);
}
@slot3 = null;
break;
}
case 3: {
if (@slot4 != null) {
SendMessage(slot4, 0);
}
@slot4 = null;
break;
}
}
}
}
|
class Mastermind {
Hub @hub;
Entity @self;
Entity@ slot1 = null;
Entity@ slot2 = null;
Entity@ slot3 = null;
Entity@ slot4 = null;
Entity@ slot1Key;
Entity@ slot2Key;
Entity@ slot3Key;
Entity@ slot4Key;
Entity @light1;
Entity @light2;
Entity @light3;
Entity @light4;
Entity @flickeringLights;
Entity @roundabout;
bool puzzleSolved = false;
int correct = 0;
int rightColors = 0;
Mastermind(Entity @entity) {
@hub = Managers();
@self = @entity;
@slot1Key = GetEntityByGUID(1511964701); // GreenPropp
@slot2Key = GetEntityByGUID(1511964823); // RedPropp
@slot3Key = GetEntityByGUID(1511964915); // YellowPropp
@slot4Key = GetEntityByGUID(1511964754); // PinkPropp
// Remove this if updates are not desired.
RegisterUpdate();
}
// Called by the engine for each frame.
void Update(float deltaTime) {
if (puzzleSolved)
return;
CheckSolution();
for (int i = 0; i < correct; i++) {
TurnOnLight(100, vec3(0, 255, 0));
}
for (int i = 0; i < rightColors; i++) {
TurnOnLight(100, vec3(255, 0, 0));
}
}
void CheckSolution() {
correct = 0;
rightColors = 0;
puzzleSolved = false;
TurnOffLights();
if (@slot1 != null && @slot2 != null && @slot3 != null && @slot4 != null) {
if (slot1 is slot1Key)
correct = correct + 1;
else if (slot1 is slot2Key || slot1 is slot3Key || slot1 is slot4Key)
rightColors = rightColors + 1;
if (slot2 is slot2Key)
correct = correct + 1;
else if (slot2 is slot1Key || slot2 is slot3Key || slot2 is slot4Key)
rightColors = rightColors + 1;
if (slot3 is slot3Key)
correct = correct + 1;
else if (slot3 is slot1Key || slot3 is slot2Key || slot3 is slot4Key)
rightColors = rightColors + 1;
if (slot4 is slot4Key)
correct = correct + 1;
else if (slot4 is slot1Key || slot4 is slot2Key || slot4 is slot3Key)
rightColors = rightColors + 1;
if (correct == 4) {
puzzleSolved = true;
SendMessage(roundabout, 2);
}
}
}
void TurnOnLight(int intensity, vec3 lightColor) {
if (light1.GetSpotLight().intensity == 0) {
light1.GetSpotLight().intensity = intensity;
light1.GetSpotLight().color = lightColor;
}
else if (light2.GetSpotLight().intensity == 0) {
light2.GetSpotLight().intensity = intensity;
light2.GetSpotLight().color = lightColor;
}
else if (light3.GetSpotLight().intensity == 0) {
light3.GetSpotLight().intensity = intensity;
light3.GetSpotLight().color = lightColor;
}
else if (light4.GetSpotLight().intensity == 0) {
light4.GetSpotLight().intensity = intensity;
light4.GetSpotLight().color = lightColor;
}
}
void TurnOffLights() {
light1.GetSpotLight().intensity = 0;
light2.GetSpotLight().intensity = 0;
light3.GetSpotLight().intensity = 0;
light4.GetSpotLight().intensity = 0;
}
void ReceiveMessage(Entity @sender, int signal) {
if (signal < 4)
AddToSlot(signal, sender);
else
RemoveFromSlot(signal - 4);
}
void AddToSlot(int slot, Entity@ fuse) {
// First remove any existing fuse in this slot.
RemoveFromSlot(slot);
switch(slot) {
case 0: {
@slot1 = @fuse;
break;
}
case 1: {
@slot2 = @fuse;
break;
}
case 2: {
@slot3 = @fuse;
break;
}
case 3: {
@slot4 = @fuse;
break;
}
}
}
void RemoveFromSlot(int slot) {
switch(slot) {
case 0: {
if (@slot1 != null) {
SendMessage(slot1, 0);
}
@slot1 = null;
break;
}
case 1: {
if (@slot2 != null) {
SendMessage(slot2, 0);
}
@slot2 = null;
break;
}
case 2: {
if (@slot3 != null) {
SendMessage(slot3, 0);
}
@slot3 = null;
break;
}
case 3: {
if (@slot4 != null) {
SendMessage(slot4, 0);
}
@slot4 = null;
break;
}
}
}
}
|
Clean mastermind script in terms of tabs, spacing, and newlines.
|
Clean mastermind script in terms of tabs, spacing, and newlines.
|
ActionScript
|
mit
|
Chainsawkitten/LargeGameProjectEngine,Chainsawkitten/LargeGameProjectEngine
|
3a9b5e2c3fe3971e98283bfe35edc363a3686108
|
as3/com/netease/protobuf/BaseFieldDescriptor.as
|
as3/com/netease/protobuf/BaseFieldDescriptor.as
|
// vim: tabstop=4 shiftwidth=4
// Copyright (c) 2011 , 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.IllegalOperationError
import flash.utils.getDefinitionByName;
import flash.utils.IDataInput
/**
* @private
*/
public class BaseFieldDescriptor implements IFieldDescriptor {
public var fullName:String
protected var _name:String
public final function get name():String {
return _name
}
protected var tag:uint
public final function get tagNumber():uint {
return tag >>> 7
}
public function get type():Class {
throw new IllegalOperationError("Not Implemented!")
}
public function readSingleField(input:IDataInput):* {
throw new IllegalOperationError("Not Implemented!")
}
public function writeSingleField(output:WritingBuffer, value:*):void {
throw new IllegalOperationError("Not Implemented!")
}
public function write(destination:WritingBuffer, source:Message):void {
throw new IllegalOperationError("Not Implemented!")
}
private static const ACTIONSCRIPT_KEYWORDS:Object = {
"as" : true, "break" : true, "case" : true,
"catch" : true, "class" : true, "const" : true,
"continue" : true, "default" : true, "delete" : true,
"do" : true, "else" : true, "extends" : true,
"false" : true, "finally" : true, "for" : true,
"function" : true, "if" : true, "implements" : true,
"import" : true, "in" : true, "instanceof" : true,
"interface" : true, "internal" : true, "is" : true,
"native" : true, "new" : true, "null" : true,
"package" : true, "private" : true, "protected" : true,
"public" : true, "return" : true, "super" : true,
"switch" : true, "this" : true, "throw" : true,
"to" : true, "true" : true, "try" : true,
"typeof" : true, "use" : true, "var" : true,
"void" : true, "while" : true, "with" : true
}
public function toString():String {
return name
}
internal static function getExtensionByName(
name:String):BaseFieldDescriptor {
const fieldPosition:int = name.lastIndexOf('/')
if (fieldPosition == -1) {
return BaseFieldDescriptor(getDefinitionByName(name))
} else {
return getDefinitionByName(name.substring(0, fieldPosition))[
name.substring(fieldPosition + 1)]
}
}
}
}
function regexToUpperCase(matched:String, index:int, whole:String):String {
return matched.charAt(1).toUpperCase()
}
|
// vim: tabstop=4 shiftwidth=4
// Copyright (c) 2011 , 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.IllegalOperationError
import flash.utils.getDefinitionByName;
import flash.utils.IDataInput
/**
* @private
*/
public class BaseFieldDescriptor implements IFieldDescriptor {
public var fullName:String
protected var _name:String
public final function get name():String {
return _name
}
protected var tag:uint
public final function get tagNumber():uint {
return tag >>> 3
}
public function get type():Class {
throw new IllegalOperationError("Not Implemented!")
}
public function readSingleField(input:IDataInput):* {
throw new IllegalOperationError("Not Implemented!")
}
public function writeSingleField(output:WritingBuffer, value:*):void {
throw new IllegalOperationError("Not Implemented!")
}
public function write(destination:WritingBuffer, source:Message):void {
throw new IllegalOperationError("Not Implemented!")
}
private static const ACTIONSCRIPT_KEYWORDS:Object = {
"as" : true, "break" : true, "case" : true,
"catch" : true, "class" : true, "const" : true,
"continue" : true, "default" : true, "delete" : true,
"do" : true, "else" : true, "extends" : true,
"false" : true, "finally" : true, "for" : true,
"function" : true, "if" : true, "implements" : true,
"import" : true, "in" : true, "instanceof" : true,
"interface" : true, "internal" : true, "is" : true,
"native" : true, "new" : true, "null" : true,
"package" : true, "private" : true, "protected" : true,
"public" : true, "return" : true, "super" : true,
"switch" : true, "this" : true, "throw" : true,
"to" : true, "true" : true, "try" : true,
"typeof" : true, "use" : true, "var" : true,
"void" : true, "while" : true, "with" : true
}
public function toString():String {
return name
}
internal static function getExtensionByName(
name:String):BaseFieldDescriptor {
const fieldPosition:int = name.lastIndexOf('/')
if (fieldPosition == -1) {
return BaseFieldDescriptor(getDefinitionByName(name))
} else {
return getDefinitionByName(name.substring(0, fieldPosition))[
name.substring(fieldPosition + 1)]
}
}
}
}
function regexToUpperCase(matched:String, index:int, whole:String):String {
return matched.charAt(1).toUpperCase()
}
|
修复bug:tagID应该右移3位
|
修复bug:tagID应该右移3位
|
ActionScript
|
bsd-2-clause
|
tconkling/protoc-gen-as3
|
892fd753bdf2dec6a2ee62366cf4033da4e1132e
|
frameworks/projects/Graphics/as/src/org/apache/flex/core/graphics/GradientBase.as
|
frameworks/projects/Graphics/as/src/org/apache/flex/core/graphics/GradientBase.as
|
/**
* 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.apache.flex.core.graphics
{
import org.apache.flex.core.graphics.utils.CompoundTransform;
public class GradientBase
{
protected var colors:Array /* of uint */ = [];
protected var ratios:Array /* of Number */ = [];
protected var alphas:Array /* of Number */ = [];
/**
* Holds the matrix and the convenience transform properties (<code>x</code>, <code>y</code>, and <code>rotation</code>).
* The compoundTransform is only created when the <code>matrix</code> property is set.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
*/
protected var compoundTransform:CompoundTransform;
/**
* Value of the width and height of the untransformed gradient
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
*/
public static const GRADIENT_DIMENSION:Number = 1638.4;
/**
* Storage for the angle property.
*/
private var _angle:Number;
/**
* By default, the LinearGradientStroke defines a transition
* from left to right across the control.
* Use the <code>angle</code> property to control the transition direction.
* For example, a value of 180.0 causes the transition
* to occur from right to left, rather than from left to right.
*
* @default 0.0
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
*/
public function get angle():Number
{
return _angle / Math.PI * 180;
}
/**
* @private
*/
public function set angle(value:Number):void
{
_angle = value / 180 * Math.PI;
}
/**
* Storage for the entries property.
*/
private var _entries:Array = [];
/**
* @private
* Storage for the rotation property.
*/
private var _rotation:Number = 0.0;
/**
* An Array of GradientEntry objects
* defining the fill patterns for the gradient fill.
*
*/
public function get entries():Array
{
return _entries;
}
/**
* @private
*/
public function set entries(value:Array):void
{
_entries = value;
processEntries();
}
/**
* By default, the LinearGradientStroke defines a transition
* from left to right across the control.
* Use the <code>rotation</code> property to control the transition direction.
* For example, a value of 180.0 causes the transition
* to occur from right to left, rather than from left to right.
*
* @default 0.0
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get rotation():Number
{
return _rotation;
}
/**
* @private
*/
public function set rotation(value:Number):void
{
_rotation = value;
}
private var _x:Number = 0;
/**
* The distance by which to translate each point along the x axis.
*/
public function get x():Number
{
return _x;
}
/**
* @private
*/
public function set x(value:Number):void
{
_x = value;
}
private var _y:Number = 0;
/**
* The distance by which to translate each point along the y axis.
*/
public function get y():Number
{
return _y;
}
/**
* @private
*/
public function set y(value:Number):void
{
_y = value;
}
protected function toRad(a:Number):Number {
return a*Math.PI/180;
}
protected function get rotationInRadians():Number
{
return rotation / 180 * Math.PI;
}
/**
* @private
* Extract the gradient information in the public <code>entries</code>
* Array into the internal <code>colors</code>, <code>ratios</code>,
* and <code>alphas</code> arrays.
*/
private function processEntries():void
{
colors = [];
ratios = [];
alphas = [];
if (!_entries || _entries.length == 0)
return;
var ratioConvert:Number = 255;
var i:int;
var n:int = _entries.length;
for (i = 0; i < n; i++)
{
var e:GradientEntry = _entries[i];
colors.push(e.color);
alphas.push(e.alpha);
ratios.push(e.ratio * ratioConvert);
}
if (isNaN(ratios[0]))
ratios[0] = 0;
if (isNaN(ratios[n - 1]))
ratios[n - 1] = 255;
i = 1;
while (true)
{
while (i < n && !isNaN(ratios[i]))
{
i++;
}
if (i == n)
break;
var start:int = i - 1;
while (i < n && isNaN(ratios[i]))
{
i++;
}
var br:Number = ratios[start];
var tr:Number = ratios[i];
for (var j:int = 1; j < i - start; j++)
{
ratios[j] = br + j * (tr - br) / (i - start);
}
}
}
}
}
|
/**
* 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.apache.flex.core.graphics
{
import org.apache.flex.core.graphics.utils.CompoundTransform;
public class GradientBase
{
protected var colors:Array /* of uint */ = [];
protected var ratios:Array /* of Number */ = [];
protected var alphas:Array /* of Number */ = [];
/**
* Holds the matrix and the convenience transform properties (<code>x</code>, <code>y</code>, and <code>rotation</code>).
* The compoundTransform is only created when the <code>matrix</code> property is set.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
*/
protected var compoundTransform:CompoundTransform;
/**
* Value of the width and height of the untransformed gradient
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 1.5
*/
public static const GRADIENT_DIMENSION:Number = 1638.4;
/**
* Storage for the entries property.
*/
private var _entries:Array = [];
/**
* @private
* Storage for the rotation property.
*/
private var _rotation:Number = 0.0;
/**
* An Array of GradientEntry objects
* defining the fill patterns for the gradient fill.
*
*/
public function get entries():Array
{
return _entries;
}
/**
* @private
*/
public function set entries(value:Array):void
{
_entries = value;
processEntries();
}
/**
* By default, the LinearGradientStroke defines a transition
* from left to right across the control.
* Use the <code>rotation</code> property to control the transition direction.
* For example, a value of 180.0 causes the transition
* to occur from right to left, rather than from left to right.
*
* @default 0.0
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get rotation():Number
{
return _rotation;
}
/**
* @private
*/
public function set rotation(value:Number):void
{
_rotation = value;
}
private var _x:Number = 0;
/**
* The distance by which to translate each point along the x axis.
*/
public function get x():Number
{
return _x;
}
/**
* @private
*/
public function set x(value:Number):void
{
_x = value;
}
private var _y:Number = 0;
/**
* The distance by which to translate each point along the y axis.
*/
public function get y():Number
{
return _y;
}
/**
* @private
*/
public function set y(value:Number):void
{
_y = value;
}
protected function toRad(a:Number):Number {
return a*Math.PI/180;
}
protected function get rotationInRadians():Number
{
return rotation / 180 * Math.PI;
}
/**
* @private
* Extract the gradient information in the public <code>entries</code>
* Array into the internal <code>colors</code>, <code>ratios</code>,
* and <code>alphas</code> arrays.
*/
private function processEntries():void
{
colors = [];
ratios = [];
alphas = [];
if (!_entries || _entries.length == 0)
return;
var ratioConvert:Number = 255;
var i:int;
var n:int = _entries.length;
for (i = 0; i < n; i++)
{
var e:GradientEntry = _entries[i];
colors.push(e.color);
alphas.push(e.alpha);
ratios.push(e.ratio * ratioConvert);
}
if (isNaN(ratios[0]))
ratios[0] = 0;
if (isNaN(ratios[n - 1]))
ratios[n - 1] = 255;
i = 1;
while (true)
{
while (i < n && !isNaN(ratios[i]))
{
i++;
}
if (i == n)
break;
var start:int = i - 1;
while (i < n && isNaN(ratios[i]))
{
i++;
}
var br:Number = ratios[start];
var tr:Number = ratios[i];
for (var j:int = 1; j < i - start; j++)
{
ratios[j] = br + j * (tr - br) / (i - start);
}
}
}
}
}
|
Remove angle property and its getter/setter. The rotation property should be used to specify the gradient's rotation.
|
Remove angle property and its getter/setter. The rotation property should be used to specify the gradient's rotation.
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
fa808d61710ce4afc2d7e6d584a51ec8bc0e774b
|
FlexUnit4/src/org/flexunit/runners/Parameterized.as
|
FlexUnit4/src/org/flexunit/runners/Parameterized.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 Alan Stearns - [email protected]
* Michael Labriola - [email protected]
* David Wolever - [email protected]
* @version
*
**/
package org.flexunit.runners
{
import flex.lang.reflect.Field;
import org.flexunit.constants.AnnotationConstants;
import org.flexunit.internals.dependency.ExternalDependencyResolver;
import org.flexunit.internals.dependency.IExternalDependencyResolver;
import org.flexunit.internals.dependency.IExternalRunnerDependencyWatcher;
import org.flexunit.internals.runners.ErrorReportingRunner;
import org.flexunit.internals.runners.InitializationError;
import org.flexunit.internals.runners.statements.IAsyncStatement;
import org.flexunit.runner.IDescription;
import org.flexunit.runner.IRunner;
import org.flexunit.runner.external.IExternalDependencyRunner;
import org.flexunit.runner.notification.IRunNotifier;
import org.flexunit.runner.notification.StoppedByUserException;
import org.flexunit.runners.model.FrameworkMethod;
import org.flexunit.runners.model.IRunnerBuilder;
import org.flexunit.token.AsyncTestToken;
public class Parameterized extends ParentRunner implements IExternalDependencyRunner {
private var runners:Array;
private var klass:Class;
private var dr:IExternalDependencyResolver;
private var _dependencyWatcher:IExternalRunnerDependencyWatcher;
private var dependencyDataWatchers:Array;
private var _externalDependencyError:String;
private var externalError:Boolean = false;
public function set dependencyWatcher( value:IExternalRunnerDependencyWatcher ):void {
_dependencyWatcher = value;
if ( value && dr ) {
value.watchDependencyResolver( dr );
}
}
public function set externalDependencyError( value:String ):void {
externalError = true;
_externalDependencyError = value;
}
//Blank constructor means the old 0/1 error
public function Parameterized(klass:Class) {
super(klass);
this.klass = klass;
dr = new ExternalDependencyResolver( klass, this );
dr.resolveDependencies();
}
private function buildErrorRunner( message:String ):Array {
return [new ErrorReportingRunner( klass, new Error("There was an error retrieving the parameters for the testcase: cause " + message ) ) ];
}
private function buildRunners():Array {
var runners:Array = new Array();
try {
var parametersList:Array = getParametersList(klass);
if ( parametersList.length == 0 ) {
runners.push(new TestClassRunnerForParameters(klass));
} else {
for (var i:int= 0; i < parametersList.length; i++) {
runners.push(new TestClassRunnerForParameters(klass,parametersList, i));
}
}
}
catch ( error:Error ) {
runners = buildErrorRunner( error.message );
}
return runners;
}
private function getParametersList(klass:Class):Array {
var allParams:Array = new Array();
var frameworkMethod:FrameworkMethod;
var field:Field;
var methods:Array = getParametersMethods(klass);
var fields:Array = getParametersFields(klass);
var data:Array;
for ( var i:int=0; i<methods.length; i++ ) {
frameworkMethod = methods[ i ];
data = frameworkMethod.invokeExplosively(klass) as Array;
allParams = allParams.concat( data );
}
for ( var j:int=0; j<fields.length; j++ ) {
field = fields[ j ];
data = field.getObj( null ) as Array;
allParams = allParams.concat( data );
}
return allParams;
}
private function getParametersMethods(klass:Class):Array {
var methods:Array = testClass.getMetaDataMethods( AnnotationConstants.PARAMETERS );
return methods;
}
private function getParametersFields(klass:Class):Array {
var fields:Array = testClass.getMetaDataFields( AnnotationConstants.PARAMETERS, true );
return fields;
}
// begin Items copied from Suite
override protected function get children():Array {
if ( !runners ) {
if ( !externalError ) {
runners = buildRunners();
} else {
runners = buildErrorRunner( _externalDependencyError );
}
}
return runners;
}
override protected function describeChild( child:* ):IDescription {
return IRunner( child ).description;
}
override public function pleaseStop():void {
super.pleaseStop();
if ( runners ) {
for ( var i:int=0; i<runners.length; i++ ) {
( runners[ i ] as IRunner ).pleaseStop();
}
}
}
override protected function runChild( child:*, notifier:IRunNotifier, childRunnerToken:AsyncTestToken ):void {
if ( stopRequested ) {
childRunnerToken.sendResult( new StoppedByUserException() );
return;
}
IRunner( child ).run( notifier, childRunnerToken );
}
// end Items copied from Suite
}
}
import flex.lang.reflect.Field;
import flex.lang.reflect.Klass;
import flex.lang.reflect.Method;
import flex.lang.reflect.metadata.MetaDataAnnotation;
import flex.lang.reflect.metadata.MetaDataArgument;
import org.flexunit.constants.AnnotationArgumentConstants;
import org.flexunit.constants.AnnotationConstants;
import org.flexunit.internals.runners.InitializationError;
import org.flexunit.internals.runners.statements.IAsyncStatement;
import org.flexunit.runner.Description;
import org.flexunit.runner.IDescription;
import org.flexunit.runner.notification.IRunNotifier;
import org.flexunit.runners.BlockFlexUnit4ClassRunner;
import org.flexunit.runners.model.FrameworkMethod;
import org.flexunit.runners.model.ParameterizedMethod;
import org.flexunit.token.AsyncTestToken;
class TestClassRunnerForParameters extends BlockFlexUnit4ClassRunner {
private var klassInfo:Klass;
private var expandedTestList:Array;
private var parameterSetNumber:int;
private var parameterList:Array;
private var constructorParameterized:Boolean = false;
private function buildExpandedTestList():Array {
var testMethods:Array = testClass.getMetaDataMethods( AnnotationConstants.TEST );
var finalArray:Array = new Array();
for ( var i:int=0; i<testMethods.length; i++ ) {
var fwMethod:FrameworkMethod = testMethods[ i ];
var argument:MetaDataArgument = fwMethod.method.getMetaData( AnnotationConstants.TEST ).getArgument( AnnotationArgumentConstants.DATAPROVIDER );
var classMethod:Method;
var field:Field;
var results:Array;
var paramMethod:ParameterizedMethod;
if ( argument ) {
classMethod = klassInfo.getMethod( argument.value );
if ( classMethod ) {
results = classMethod.invoke( testClass ) as Array;
} else {
field = klassInfo.getField( argument.value );
if ( field ) {
var ar:Array = field.getObj(null) as Array;
results = new Array();
results = results.concat( ar );
}
}
for ( var j:int=0; j<results.length; j++ ) {
var method:Method = applyOrderToParameterizedTestMethod( fwMethod.method, j, results.length );
paramMethod = new ParameterizedMethod( method, results[ j ] );
finalArray.push( paramMethod );
}
} else {
finalArray.push( fwMethod );
}
}
return finalArray;
}
protected function applyOrderToParameterizedTestMethod( method : Method, dataSetIndex : int, totalMethods : int ) : Method
{
var xmlCopy:XML = method.methodXML.copy();
var a:MetaDataAnnotation = method.getMetaData( AnnotationConstants.TEST );
var arg:MetaDataArgument;
if ( a )
arg = a.getArgument( AnnotationArgumentConstants.ORDER );
else // CJP: If the method doesn't contain a "TEST" metadata tag, we probably shouldn't be in here anyway... throw Error?
return method;
if ( !arg )
xmlCopy.metadata.(@name=="Test").appendChild( <arg key="order" value="0"/> );
var orderValueDec : Number = (dataSetIndex + 1) / ( Math.pow( 10, totalMethods ) );
var newOrderValue : Number = xmlCopy.metadata.(@name=="Test").arg.( @key == "order" ).attribute( "value" ) + orderValueDec;
xmlCopy.metadata.(@name=="Test").arg.( @key == "order" ).( @value = newOrderValue );
var newMethod:Method = new Method( xmlCopy );
return newMethod;
}
override protected function computeTestMethods():Array {
//OPTIMIZATION POINT
if ( !expandedTestList ) {
expandedTestList = buildExpandedTestList();
}
return expandedTestList;
}
override protected function validatePublicVoidNoArgMethods( metaDataTag:String, isStatic:Boolean, errors:Array ):void {
//Only validate the ones that do not have a dataProvider attribute for these rules
var methods:Array = testClass.getMetaDataMethods( metaDataTag );
var annotation:MetaDataAnnotation;
var argument:MetaDataArgument;
var eachTestMethod:FrameworkMethod;
for ( var i:int=0; i<methods.length; i++ ) {
eachTestMethod = methods[ i ] as FrameworkMethod;
annotation = eachTestMethod.method.getMetaData( AnnotationConstants.TEST );
if ( annotation ) {
//Does it have a dataProvider?
argument = annotation.getArgument( AnnotationArgumentConstants.DATAPROVIDER );
}
//If there is an argument, we need to punt on verification of arguments until later when we know how many there actually are
if ( !argument ) {
eachTestMethod.validatePublicVoidNoArg( isStatic, errors );
}
}
}
override protected function describeChild( child:* ):IDescription {
if ( !constructorParameterized ) {
return super.describeChild( child );
}
var params:Array = computeParams();
/* if ( !params ) {
throw new InitializationError( "Parameterized runner has not been provided data" );
}*/
var paramName:String = params?params.join ( "_" ):"Missing Params";
var method:FrameworkMethod = FrameworkMethod( child );
return Description.createTestDescription( testClass.asClass, method.name + '_' + paramName, method.metadata );
}
private function computeParams():Array {
return parameterList?parameterList[parameterSetNumber]:null;
}
override protected function createTest():Object {
var args:Array = computeParams();
if ( args && args.length > 0 ) {
return testClass.klassInfo.constructor.newInstanceApply( args );
} else {
return testClass.klassInfo.constructor.newInstance();
}
}
//we don't want the BeforeClass and AfterClass on this run to execute, this will be handled by Parameterized
override protected function classBlock( notifier:IRunNotifier ):IAsyncStatement {
return childrenInvoker( notifier );
}
public function TestClassRunnerForParameters(klass:Class, parameterList:Array=null, i:int=0) {
klassInfo = new Klass( klass );
super(klass);
this.parameterList = parameterList;
this.parameterSetNumber = i;
if ( parameterList && parameterList.length > 0 ) {
constructorParameterized = true;
}
}
}
|
/**
* 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 Alan Stearns - [email protected]
* Michael Labriola - [email protected]
* David Wolever - [email protected]
* @version
*
**/
package org.flexunit.runners
{
import flex.lang.reflect.Field;
import org.flexunit.constants.AnnotationConstants;
import org.flexunit.internals.dependency.ExternalDependencyResolver;
import org.flexunit.internals.dependency.IExternalDependencyResolver;
import org.flexunit.internals.dependency.IExternalRunnerDependencyWatcher;
import org.flexunit.internals.runners.ErrorReportingRunner;
import org.flexunit.internals.runners.InitializationError;
import org.flexunit.internals.runners.statements.IAsyncStatement;
import org.flexunit.runner.IDescription;
import org.flexunit.runner.IRunner;
import org.flexunit.runner.external.IExternalDependencyRunner;
import org.flexunit.runner.notification.IRunNotifier;
import org.flexunit.runner.notification.StoppedByUserException;
import org.flexunit.runners.model.FrameworkMethod;
import org.flexunit.runners.model.IRunnerBuilder;
import org.flexunit.token.AsyncTestToken;
public class Parameterized extends ParentRunner implements IExternalDependencyRunner {
private var runners:Array;
private var klass:Class;
private var dr:IExternalDependencyResolver;
private var _dependencyWatcher:IExternalRunnerDependencyWatcher;
private var dependencyDataWatchers:Array;
private var _externalDependencyError:String;
private var externalError:Boolean = false;
public function set dependencyWatcher( value:IExternalRunnerDependencyWatcher ):void {
_dependencyWatcher = value;
if ( value && dr ) {
value.watchDependencyResolver( dr );
}
}
public function set externalDependencyError( value:String ):void {
externalError = true;
_externalDependencyError = value;
}
//Blank constructor means the old 0/1 error
public function Parameterized(klass:Class) {
super(klass);
this.klass = klass;
dr = new ExternalDependencyResolver( klass, this );
dr.resolveDependencies();
}
private function buildErrorRunner( message:String ):Array {
return [new ErrorReportingRunner( klass, new Error("There was an error retrieving the parameters for the testcase: cause " + message ) ) ];
}
private function buildRunners():Array {
var runners:Array = new Array();
try {
var parametersList:Array = getParametersList(klass);
if ( parametersList.length == 0 ) {
runners.push(new TestClassRunnerForParameters(klass));
} else {
for (var i:int= 0; i < parametersList.length; i++) {
runners.push(new TestClassRunnerForParameters(klass,parametersList, i));
}
}
}
catch ( error:Error ) {
runners = buildErrorRunner( error.message );
}
return runners;
}
private function getParametersList(klass:Class):Array {
var allParams:Array = new Array();
var frameworkMethod:FrameworkMethod;
var field:Field;
var methods:Array = getParametersMethods(klass);
var fields:Array = getParametersFields(klass);
var data:Array;
for ( var i:int=0; i<methods.length; i++ ) {
frameworkMethod = methods[ i ];
data = frameworkMethod.invokeExplosively(klass) as Array;
allParams = allParams.concat( data );
}
for ( var j:int=0; j<fields.length; j++ ) {
field = fields[ j ];
data = field.getObj( null ) as Array;
allParams = allParams.concat( data );
}
return allParams;
}
private function getParametersMethods(klass:Class):Array {
var methods:Array = testClass.getMetaDataMethods( AnnotationConstants.PARAMETERS );
return methods;
}
private function getParametersFields(klass:Class):Array {
var fields:Array = testClass.getMetaDataFields( AnnotationConstants.PARAMETERS, true );
return fields;
}
// begin Items copied from Suite
override protected function get children():Array {
if ( !runners ) {
if ( !externalError ) {
runners = buildRunners();
} else {
runners = buildErrorRunner( _externalDependencyError );
}
}
return runners;
}
override protected function describeChild( child:* ):IDescription {
return IRunner( child ).description;
}
override public function pleaseStop():void {
super.pleaseStop();
if ( runners ) {
for ( var i:int=0; i<runners.length; i++ ) {
( runners[ i ] as IRunner ).pleaseStop();
}
}
}
override protected function runChild( child:*, notifier:IRunNotifier, childRunnerToken:AsyncTestToken ):void {
if ( stopRequested ) {
childRunnerToken.sendResult( new StoppedByUserException() );
return;
}
IRunner( child ).run( notifier, childRunnerToken );
}
// end Items copied from Suite
}
}
import flex.lang.reflect.Field;
import flex.lang.reflect.Klass;
import flex.lang.reflect.Method;
import flex.lang.reflect.metadata.MetaDataAnnotation;
import flex.lang.reflect.metadata.MetaDataArgument;
import org.flexunit.constants.AnnotationArgumentConstants;
import org.flexunit.constants.AnnotationConstants;
import org.flexunit.internals.runners.InitializationError;
import org.flexunit.internals.runners.statements.IAsyncStatement;
import org.flexunit.runner.Description;
import org.flexunit.runner.IDescription;
import org.flexunit.runner.notification.IRunNotifier;
import org.flexunit.runners.BlockFlexUnit4ClassRunner;
import org.flexunit.runners.model.FrameworkMethod;
import org.flexunit.runners.model.ParameterizedMethod;
import org.flexunit.token.AsyncTestToken;
class TestClassRunnerForParameters extends BlockFlexUnit4ClassRunner {
private var klassInfo:Klass;
private var expandedTestList:Array;
private var parameterSetNumber:int;
private var parameterList:Array;
private var constructorParameterized:Boolean = false;
private function buildExpandedTestList():Array {
var testMethods:Array = testClass.getMetaDataMethods( AnnotationConstants.TEST );
var finalArray:Array = new Array();
for ( var i:int=0; i<testMethods.length; i++ ) {
var fwMethod:FrameworkMethod = testMethods[ i ];
var argument:MetaDataArgument = fwMethod.method.getMetaData( AnnotationConstants.TEST ).getArgument( AnnotationArgumentConstants.DATAPROVIDER );
var classMethod:Method;
var field:Field;
var results:Array;
var paramMethod:ParameterizedMethod;
if ( argument ) {
classMethod = klassInfo.getMethod( argument.value );
if ( classMethod ) {
results = classMethod.invoke( testClass ) as Array;
} else {
field = klassInfo.getField( argument.value );
if ( field ) {
var ar:Array = field.getObj(null) as Array;
results = new Array();
results = results.concat( ar );
}
}
var methodXML : XML = insertOrderMetadataIfNecessary( fwMethod.method );
for ( var j:int=0; j<results.length; j++ ) {
var method:Method = applyOrderToParameterizedTestMethod( methodXML, j, results.length );
paramMethod = new ParameterizedMethod( method, results[ j ] );
finalArray.push( paramMethod );
}
} else {
finalArray.push( fwMethod );
}
}
return finalArray;
}
protected function insertOrderMetadataIfNecessary( method : Method ) : XML
{
var xmlCopy:XML = method.methodXML.copy();
var a:MetaDataAnnotation = method.getMetaData( AnnotationConstants.TEST );
var arg:MetaDataArgument;
if ( a )
arg = a.getArgument( AnnotationArgumentConstants.ORDER );
else // CJP: If the method doesn't contain a "TEST" metadata tag, we probably shouldn't be in here anyway... throw Error?
return xmlCopy;
if ( !arg )
xmlCopy.metadata.(@name=="Test").appendChild( <arg key="order" value="0"/> );
return xmlCopy;
}
protected function applyOrderToParameterizedTestMethod( methodXML : XML, dataSetIndex : int, totalMethods : int ) : Method
{
var xmlCopy:XML = methodXML.copy();
var orderValueDec : Number = (dataSetIndex + 1) / ( Math.pow( 10, totalMethods ) );
var newOrderValue : Number = xmlCopy.metadata.(@name=="Test").arg.( @key == "order" ).attribute( "value" ) + orderValueDec;
xmlCopy.metadata.(@name=="Test").arg.( @key == "order" ).( @value = newOrderValue );
var newMethod:Method = new Method( xmlCopy );
return newMethod;
}
override protected function computeTestMethods():Array {
//OPTIMIZATION POINT
if ( !expandedTestList ) {
expandedTestList = buildExpandedTestList();
}
return expandedTestList;
}
override protected function validatePublicVoidNoArgMethods( metaDataTag:String, isStatic:Boolean, errors:Array ):void {
//Only validate the ones that do not have a dataProvider attribute for these rules
var methods:Array = testClass.getMetaDataMethods( metaDataTag );
var annotation:MetaDataAnnotation;
var argument:MetaDataArgument;
var eachTestMethod:FrameworkMethod;
for ( var i:int=0; i<methods.length; i++ ) {
eachTestMethod = methods[ i ] as FrameworkMethod;
annotation = eachTestMethod.method.getMetaData( AnnotationConstants.TEST );
if ( annotation ) {
//Does it have a dataProvider?
argument = annotation.getArgument( AnnotationArgumentConstants.DATAPROVIDER );
}
//If there is an argument, we need to punt on verification of arguments until later when we know how many there actually are
if ( !argument ) {
eachTestMethod.validatePublicVoidNoArg( isStatic, errors );
}
}
}
override protected function describeChild( child:* ):IDescription {
if ( !constructorParameterized ) {
return super.describeChild( child );
}
var params:Array = computeParams();
/* if ( !params ) {
throw new InitializationError( "Parameterized runner has not been provided data" );
}*/
var paramName:String = params?params.join ( "_" ):"Missing Params";
var method:FrameworkMethod = FrameworkMethod( child );
return Description.createTestDescription( testClass.asClass, method.name + '_' + paramName, method.metadata );
}
private function computeParams():Array {
return parameterList?parameterList[parameterSetNumber]:null;
}
override protected function createTest():Object {
var args:Array = computeParams();
if ( args && args.length > 0 ) {
return testClass.klassInfo.constructor.newInstanceApply( args );
} else {
return testClass.klassInfo.constructor.newInstance();
}
}
//we don't want the BeforeClass and AfterClass on this run to execute, this will be handled by Parameterized
override protected function classBlock( notifier:IRunNotifier ):IAsyncStatement {
return childrenInvoker( notifier );
}
public function TestClassRunnerForParameters(klass:Class, parameterList:Array=null, i:int=0) {
klassInfo = new Klass( klass );
super(klass);
this.parameterList = parameterList;
this.parameterSetNumber = i;
if ( parameterList && parameterList.length > 0 ) {
constructorParameterized = true;
}
}
}
|
Refactor for performance improvement in order injection of parameterized tests.
|
Refactor for performance improvement in order injection of parameterized tests.
|
ActionScript
|
apache-2.0
|
apache/flex-flexunit,SlavaRa/flex-flexunit,apache/flex-flexunit,apache/flex-flexunit,SlavaRa/flex-flexunit,SlavaRa/flex-flexunit,apache/flex-flexunit,SlavaRa/flex-flexunit
|
a7f07875564c2a29ed9424cfd300b9ab75302f85
|
driver/src/main/flex/org/postgresql/codec/CodecFactory.as
|
driver/src/main/flex/org/postgresql/codec/CodecFactory.as
|
package org.postgresql.codec {
import org.postgresql.Oid;
import flash.utils.Dictionary;
import org.postgresql.CodecError;
/**
* The CodecFactory manages mappings between ActionScript Objects (of certain
* Classes) and PostgreSQL column values (of certain oids). A Class can be mapped
* to an oid registering an encoder, and an oid to a Class through a decoder.
* Only a single mapping can exist for a given oid (or Class) at any given time.
*
* @see org.postgresql.Oid
* @see Class
*/
public class CodecFactory {
private var _decoders:Dictionary;
private var _encoders:Dictionary;
/**
* Constructor. No encoders or decoders are registered by default.
*/
public function CodecFactory() {
_decoders = new Dictionary();
_encoders = new Dictionary();
}
/**
* Register the given encoder to map values of the inType to the inOid. If
* an encoder was previously registered for the same inType, it is silently
* replaced.
*
* @param inType
* @param inOid
* @param encoder
*/
public function registerEncoder(inType:Class, encoder:IPGTypeEncoder):void {
_encoders[inType] = encoder;
}
/**
* Register the given decoder to map values of the given outOid to the outType. If
* a decoder was previously registered for the same outOid, it is silently replaced.
*
* @param outOid
* @param outType
* @param decoder
*/
public function registerDecoder(outOid:int, decoder:IPGTypeDecoder):void {
_decoders[outOid] = decoder;
}
/**
* Return the decoder for the given oid
* @param oid oid for which to find decoder
* @return registered decoder
* @throws org.postgresql.CodecError if no decoder has been registered for the given oid
*/
public function getDecoder(oid:int):IPGTypeDecoder {
if (oid in _decoders) {
return _decoders[oid];
} else {
throw new CodecError("Could not find suitable decoder", CodecError.DECODE, null, oid);
}
}
/**
* Return the encoder for the given Class
* @param value for which to find encoder
* @return registered encoder
* @throws org.postgresql.CodecError if no encoder is registered for the given Class
*/
public function getEncoder(clazz:Class):IPGTypeEncoder {
if (clazz in _encoders) {
return _encoders[clazz];
} else {
throw new CodecError("Could not find suitable encoder", CodecError.ENCODE, null, Oid.UNSPECIFIED, clazz);
}
}
}
}
|
package org.postgresql.codec {
import org.postgresql.Oid;
import flash.utils.Dictionary;
import org.postgresql.CodecError;
/**
* The CodecFactory manages mappings between ActionScript Objects (of certain
* Classes) and PostgreSQL column values (of certain oids). A Class can be mapped
* to an oid by registering an encoder, and an oid to a Class through a decoder.
* Only a single mapping can exist for a given oid (or Class) at any given time.
* <p/>
* Default encoders and decoders can also be registered.
* <p/>
* No encoders or decoders are registered by default.
*
* @see org.postgresql.Oid
* @see Class
*/
public class CodecFactory {
private var _decoders:Dictionary;
private var _encoders:Dictionary;
private var _defaultDecoder:IPGTypeDecoder;
private var _defaultEncoder:IPGTypeEncoder;
/**
* @private
*/
public function CodecFactory() {
_decoders = new Dictionary();
_encoders = new Dictionary();
}
/**
* Register the given encoder to map values of the inType to an oid. If
* an encoder was previously registered for the same inType, it is silently
* replaced.
*
* @param inType Class for which to register mapping
* @param encoder encoder instance to use for given class
*/
public function registerEncoder(inType:Class, encoder:IPGTypeEncoder):void {
if (!encoder) {
throw new ArgumentError("Encoder must not be null");
}
if (!inType) {
throw new ArgumentError("Class to be mapped must not be null");
}
_encoders[inType] = encoder;
}
/**
* Register a encoder to map values when no other encoder is suitable. If
* a previous default encoder was specified, it is silently replaced.
*
* @param encoder encoder instance for default encoding
*/
public function registerDefaultEncoder(encoder:IPGTypeEncoder):void {
if (!encoder) {
throw new ArgumentError("Encoder must not be null");
}
_defaultEncoder = encoder;
}
/**
* Register the given decoder to map values of the given outOid to an ActionScript type. If
* a decoder was previously registered for the same outOid, it is silently replaced.
*
* @param outOid oid for which to register mapping
* @param decoder decoder instance to use for given oid
*/
public function registerDecoder(outOid:int, decoder:IPGTypeDecoder):void {
if (!decoder) {
throw new ArgumentError("Decoder must not be null");
}
_decoders[outOid] = decoder;
}
/**
* Register a decoder to map values when no other decoder is suitable. If
* a previous default decoder was specified, it is silently replaced.
*
* @param decoder decoder instance to use for default decoding
*/
public function registerDefaultDecoder(decoder:IPGTypeDecoder):void {
if (!decoder) {
throw new ArgumentError("Decoder must not be null");
}
_defaultDecoder = decoder;
}
/**
* Return the decoder for the given oid
*
* @param oid oid for which to find decoder
* @return registered decoder
* @throws org.postgresql.CodecError if no decoder has been registered for the given oid
*/
public function getDecoder(oid:int):IPGTypeDecoder {
if (oid in _decoders) {
return _decoders[oid];
} else if (_defaultDecoder) {
return _defaultDecoder;
} else {
throw new CodecError("Could not find suitable decoder", CodecError.DECODE, null, oid);
}
}
/**
* Return the encoder for the given Class
*
* @param value for which to find encoder
* @return registered encoder
* @throws org.postgresql.CodecError if no encoder is registered for the given Class
*/
public function getEncoder(clazz:Class):IPGTypeEncoder {
if (clazz in _encoders) {
return _encoders[clazz];
} else if (_defaultEncoder) {
return _defaultEncoder;
} else {
throw new CodecError("Could not find suitable encoder", CodecError.ENCODE, null, Oid.UNSPECIFIED, clazz);
}
}
}
}
|
Support for default decoders and encoders; doc cleanup.
|
Support for default decoders and encoders; doc cleanup.
|
ActionScript
|
bsd-3-clause
|
uhoh-itsmaciek/pegasus
|
83c9869038ae4fd5447c6cba25cce7233182e8b4
|
src/aerys/minko/scene/node/camera/AbstractCamera.as
|
src/aerys/minko/scene/node/camera/AbstractCamera.as
|
package aerys.minko.scene.node.camera
{
import aerys.minko.scene.controller.camera.CameraController;
import aerys.minko.scene.data.CameraDataProvider;
import aerys.minko.scene.node.AbstractSceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Ray;
public class AbstractCamera extends AbstractSceneNode
{
public static const DEFAULT_ZNEAR : Number = .1;
public static const DEFAULT_ZFAR : Number = 500.;
protected var _cameraData : CameraDataProvider = null;
protected var _enabled : Boolean = true;
protected var _activated : Signal = new Signal('Camera.activated');
protected var _deactivated : Signal = new Signal('Camera.deactivated');
public function get cameraData() : CameraDataProvider
{
return _cameraData;
}
public function get zNear() : Number
{
return _cameraData.zNear;
}
public function set zNear(value : Number) : void
{
_cameraData.zNear = value;
}
public function get zFar() : Number
{
return _cameraData.zFar;
}
public function set zFar(value : Number) : void
{
_cameraData.zFar = value;
}
public function get enabled() : Boolean
{
return _enabled;
}
public function set enabled(value : Boolean) : void
{
if (value != _enabled)
{
_enabled = value;
if (_enabled)
_activated.execute(this);
else
_deactivated.execute(this);
}
}
public function get activated() : Signal
{
return _activated;
}
public function get deactivated() : Signal
{
return _deactivated;
}
public function get worldToView() : Matrix4x4
{
return worldToLocal;
}
public function get viewToWorld() : Matrix4x4
{
return localToWorld;
}
public function get worldToScreen() : Matrix4x4
{
return _cameraData.worldToScreen;
}
public function get projection() : Matrix4x4
{
return _cameraData.projection;
}
public function AbstractCamera(zNear : Number = DEFAULT_ZNEAR,
zFar : Number = DEFAULT_ZFAR)
{
super();
_cameraData = new CameraDataProvider(worldToView, viewToWorld);
_cameraData.zNear = zNear;
_cameraData.zFar = zFar;
initialize();
}
protected function initialize() : void
{
throw new Error('Must be overriden.');
}
public function unproject(x : Number, v : Number, out : Ray = null) : Ray
{
throw new Error('Must be overriden.');
}
}
}
|
package aerys.minko.scene.node.camera
{
import aerys.minko.scene.controller.camera.CameraController;
import aerys.minko.scene.data.CameraDataProvider;
import aerys.minko.scene.node.AbstractSceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Ray;
public class AbstractCamera extends AbstractSceneNode
{
public static const DEFAULT_ZNEAR : Number = .1;
public static const DEFAULT_ZFAR : Number = 500.;
protected var _cameraData : CameraDataProvider = null;
protected var _enabled : Boolean = true;
protected var _activated : Signal = new Signal('Camera.activated');
protected var _deactivated : Signal = new Signal('Camera.deactivated');
public function get cameraData() : CameraDataProvider
{
return _cameraData;
}
public function get zNear() : Number
{
return _cameraData.zNear;
}
public function set zNear(value : Number) : void
{
_cameraData.zNear = value;
}
public function get zFar() : Number
{
return _cameraData.zFar;
}
public function set zFar(value : Number) : void
{
_cameraData.zFar = value;
}
public function get enabled() : Boolean
{
return _enabled;
}
public function set enabled(value : Boolean) : void
{
if (value != _enabled)
{
_enabled = value;
if (_enabled)
_activated.execute(this);
else
_deactivated.execute(this);
}
}
public function get activated() : Signal
{
return _activated;
}
public function get deactivated() : Signal
{
return _deactivated;
}
public function get worldToView() : Matrix4x4
{
return worldToLocal;
}
public function get viewToWorld() : Matrix4x4
{
return localToWorld;
}
public function get worldToScreen() : Matrix4x4
{
return _cameraData.worldToScreen;
}
public function get projection() : Matrix4x4
{
return _cameraData.projection;
}
public function AbstractCamera(zNear : Number = DEFAULT_ZNEAR,
zFar : Number = DEFAULT_ZFAR)
{
super();
_cameraData = new CameraDataProvider(worldToView, viewToWorld);
_cameraData.zNear = zNear;
_cameraData.zFar = zFar;
initialize();
}
protected function initialize() : void
{
throw new Error('Must be overriden.');
}
public function unproject(x : Number, y : Number, out : Ray = null) : Ray
{
throw new Error('Must be overriden.');
}
}
}
|
fix typo
|
fix typo
|
ActionScript
|
mit
|
aerys/minko-as3
|
7aa849eb3637cd9502b931dcd7816e0cef8d40e5
|
kdp3Lib/src/com/kaltura/kdpfl/ApplicationFacade.as
|
kdp3Lib/src/com/kaltura/kdpfl/ApplicationFacade.as
|
package com.kaltura.kdpfl
{
import com.kaltura.kdpfl.controller.InitMacroCommand;
import com.kaltura.kdpfl.controller.LayoutReadyCommand;
import com.kaltura.kdpfl.controller.PlaybackCompleteCommand;
import com.kaltura.kdpfl.controller.SequenceItemPlayEndCommand;
import com.kaltura.kdpfl.controller.SequenceSkipNextCommand;
import com.kaltura.kdpfl.controller.StartupCommand;
import com.kaltura.kdpfl.controller.media.InitChangeMediaMacroCommand;
import com.kaltura.kdpfl.controller.media.LiveStreamCommand;
import com.kaltura.kdpfl.controller.media.MediaReadyCommand;
import com.kaltura.kdpfl.events.DynamicEvent;
import com.kaltura.kdpfl.model.ExternalInterfaceProxy;
import com.kaltura.kdpfl.model.type.DebugLevel;
import com.kaltura.kdpfl.model.type.NotificationType;
import com.kaltura.kdpfl.view.controls.KTrace;
import com.kaltura.kdpfl.view.media.KMediaPlayerMediator;
import com.kaltura.puremvc.as3.core.KView;
import flash.display.DisplayObject;
import mx.utils.ObjectProxy;
import org.osmf.media.MediaPlayerState;
import org.puremvc.as3.interfaces.IFacade;
import org.puremvc.as3.interfaces.IMediator;
import org.puremvc.as3.interfaces.IProxy;
import org.puremvc.as3.patterns.facade.Facade;
public class ApplicationFacade extends Facade implements IFacade
{
/**
* The current version of the KDP.
*/
public var kdpVersion : String = "v3.8.1";
/**
* save any mediator name that is registered to this array in order to delete at any time
* (the pure mvc don't support it as built-in function)
*/
private var _mediatorNameArray : Array = new Array();
/**
* save any proxy name that is registered to this array in order to delete at any time
* (the pure mvc don't support it as built-in function)
*/
private var _proxyNameArray : Array = new Array();
/**
* save any notification that create a command name that is registered to this array in order to delete at any time
* (the pure mvc don't support it as built-in function)
*/
private var _commandNameArray : Array = new Array();
/**
* The bindObject create dynamicly all attributes that need to be binded on it
*/
public var bindObject:ObjectProxy = new ObjectProxy();
/**
* a reference to KDP3 main application
*/
private var _app : DisplayObject;
/**
* the url of the kdp
*/
public var appFolder : String;
public var debugMode : Boolean = false;
/**
*
* will affect the traces that will be sent. See DebugLevel enum
*/
public var debugLevel:int;
private var externalInterface : ExternalInterfaceProxy;
/**
* return the one and only instance of the ApplicationFacade,
* if not exist it will be created.
* @return
*
*/
public static function getInstance() : ApplicationFacade
{
if (instance == null) instance = new ApplicationFacade();
return instance as ApplicationFacade;
}
/**
* All this simply does is fire a notification which is routed to
* "StartupCommand" via the "registerCommand" handlers
* @param app
*
*/
public function start(app:DisplayObject):void
{
CONFIG::isSDK46 {
kdpVersion += ".sdk46";
}
_app = app;
appFolder = app.root.loaderInfo.url;
appFolder = appFolder.substr(0, appFolder.lastIndexOf('/') + 1);
sendNotification(NotificationType.STARTUP, app);
externalInterface = retrieveProxy(ExternalInterfaceProxy.NAME) as ExternalInterfaceProxy;
}
/**
* Created to trace all notifications for debug
* @param notificationName
* @param body
* @param type
*
*/
override public function sendNotification(notificationName:String, body:Object = null, type:String = null):void {
if (debugMode) {
var s:String;
if ((notificationName == NotificationType.BYTES_DOWNLOADED_CHANGE && debugLevel == DebugLevel.HIGH) ||
(notificationName == NotificationType.PLAYER_UPDATE_PLAYHEAD && (debugLevel == DebugLevel.HIGH || debugLevel == DebugLevel.MEDIUM)) ||
(notificationName != NotificationType.PLAYER_UPDATE_PLAYHEAD && notificationName != NotificationType.BYTES_DOWNLOADED_CHANGE))
{
if (notificationName == NotificationType.PLAYER_STATE_CHANGE)
s = 'Sent ' + notificationName + ' ==> ' + body.toString();
else {
s = 'Sent ' + notificationName;
if (body) {
var found:Boolean = false;
for (var o:* in body) {
s += ", " + o + ":" + body[o];
found = true;
}
if (!found) {
s += ", " + body.toString();
}
}
}
}
if (s && s != "null") {
var curTime:Number = 0;
var kmediaPlayerMediator:KMediaPlayerMediator = retrieveMediator(KMediaPlayerMediator.NAME) as KMediaPlayerMediator;
if (kmediaPlayerMediator &&
kmediaPlayerMediator.player &&
kmediaPlayerMediator.player.state!=MediaPlayerState.LOADING &&
kmediaPlayerMediator.player.state!=MediaPlayerState.UNINITIALIZED &&
kmediaPlayerMediator.player.state!=MediaPlayerState.PLAYBACK_ERROR)
{
curTime = kmediaPlayerMediator.getCurrentTime();
}
var date:Date = new Date();
KTrace.getInstance().log(date.toTimeString(), ":", s, ", playhead position:", curTime);
}
}
super.sendNotification(notificationName, body, type);
//For external Flash/Flex application application listening to the KDP events
_app.dispatchEvent(new DynamicEvent(notificationName, body));
//For external Javascript application listening to the KDP events
if (externalInterface)
externalInterface.notifyJs(notificationName, body);
}
/**
* controls the routing of notifications to our controllers,
* we all know them as commands
*
*/
override protected function initializeController():void
{
super.initializeController();
registerCommand(NotificationType.STARTUP, StartupCommand);
// we do both init start KDP life cycle, and start to load the entry simultaneously
registerCommand(NotificationType.INITIATE_APP, InitMacroCommand);
//There are several things that need to be done as soon as the layout of the kdp is ready.
registerCommand(NotificationType.LAYOUT_READY, LayoutReadyCommand );
//when one call change media we fire the load media command again
registerCommand(NotificationType.CHANGE_MEDIA, InitChangeMediaMacroCommand);
registerCommand (NotificationType.LIVE_ENTRY, LiveStreamCommand );
registerCommand (NotificationType.MEDIA_LOADED, MediaReadyCommand );
registerCommand (NotificationType.PLAYBACK_COMPLETE, PlaybackCompleteCommand);
registerCommand(NotificationType.SEQUENCE_ITEM_PLAY_END, SequenceItemPlayEndCommand);
registerCommand(NotificationType.SEQUENCE_SKIP_NEXT, SequenceSkipNextCommand);
}
override protected function initializeView():void
{
if ( view != null ) return;
view = KView.getInstance();
}
override protected function initializeFacade():void
{
initializeView();
initializeModel();
initializeController();
}
/**
* Help to remove all commands, mediator, proxies from the facade
*
*/
public function dispose() : void
{
var i:int =0;
for(i=0; i<_commandNameArray.length; i++)
this.removeCommand( _commandNameArray[i] );
for(i=0; i<_mediatorNameArray.length; i++)
this.removeMediator( _mediatorNameArray[i] );
for(i=0; i<_proxyNameArray.length; i++)
this.removeProxy( _proxyNameArray[i] );
_commandNameArray = new Array();
_mediatorNameArray = new Array();
_proxyNameArray = new Array();
}
/**
* after registartion add the notification name to a
* @param notificationName
* @param commandClassRef
*
*/
override public function registerCommand(notificationName:String, commandClassRef:Class):void
{
super.registerCommand(notificationName, commandClassRef);
//save the notification name so we can delete it later
_commandNameArray.push( notificationName );
}
override public function registerMediator(mediator:IMediator):void
{
super.registerMediator(mediator);
//save the mediator name so we can delete it later
_mediatorNameArray.push( mediator.getMediatorName() );
}
override public function registerProxy(proxy:IProxy):void
{
bindObject[proxy.getProxyName()] = proxy.getData();
super.registerProxy(proxy);
//save the proxy name so we can delete it later
_proxyNameArray.push( proxy.getProxyName() );
}
/**
* add notification observer for a given mediator
* @param notification the notification to listen for
* @param notificationHandler handler to be called
* @param mediator
*
*/
public function addNotificationInterest(notification:String, notificationHandler:Function, mediator:IMediator):void {
(view as KView).addNotificationInterest(notification, notificationHandler, mediator);
}
public function get app () : DisplayObject
{
return _app;
}
public function set app (disObj : DisplayObject) : void
{
_app = disObj;
}
}
}
|
package com.kaltura.kdpfl
{
import com.kaltura.kdpfl.controller.InitMacroCommand;
import com.kaltura.kdpfl.controller.LayoutReadyCommand;
import com.kaltura.kdpfl.controller.PlaybackCompleteCommand;
import com.kaltura.kdpfl.controller.SequenceItemPlayEndCommand;
import com.kaltura.kdpfl.controller.SequenceSkipNextCommand;
import com.kaltura.kdpfl.controller.StartupCommand;
import com.kaltura.kdpfl.controller.media.InitChangeMediaMacroCommand;
import com.kaltura.kdpfl.controller.media.LiveStreamCommand;
import com.kaltura.kdpfl.controller.media.MediaReadyCommand;
import com.kaltura.kdpfl.events.DynamicEvent;
import com.kaltura.kdpfl.model.ExternalInterfaceProxy;
import com.kaltura.kdpfl.model.type.DebugLevel;
import com.kaltura.kdpfl.model.type.NotificationType;
import com.kaltura.kdpfl.view.controls.KTrace;
import com.kaltura.kdpfl.view.media.KMediaPlayerMediator;
import com.kaltura.puremvc.as3.core.KView;
import flash.display.DisplayObject;
import mx.utils.ObjectProxy;
import org.osmf.media.MediaPlayerState;
import org.puremvc.as3.interfaces.IFacade;
import org.puremvc.as3.interfaces.IMediator;
import org.puremvc.as3.interfaces.IProxy;
import org.puremvc.as3.patterns.facade.Facade;
public class ApplicationFacade extends Facade implements IFacade
{
/**
* The current version of the KDP.
*/
public var kdpVersion : String = "v3.8.2";
/**
* save any mediator name that is registered to this array in order to delete at any time
* (the pure mvc don't support it as built-in function)
*/
private var _mediatorNameArray : Array = new Array();
/**
* save any proxy name that is registered to this array in order to delete at any time
* (the pure mvc don't support it as built-in function)
*/
private var _proxyNameArray : Array = new Array();
/**
* save any notification that create a command name that is registered to this array in order to delete at any time
* (the pure mvc don't support it as built-in function)
*/
private var _commandNameArray : Array = new Array();
/**
* The bindObject create dynamicly all attributes that need to be binded on it
*/
public var bindObject:ObjectProxy = new ObjectProxy();
/**
* a reference to KDP3 main application
*/
private var _app : DisplayObject;
/**
* the url of the kdp
*/
public var appFolder : String;
public var debugMode : Boolean = false;
/**
*
* will affect the traces that will be sent. See DebugLevel enum
*/
public var debugLevel:int;
private var externalInterface : ExternalInterfaceProxy;
/**
* return the one and only instance of the ApplicationFacade,
* if not exist it will be created.
* @return
*
*/
public static function getInstance() : ApplicationFacade
{
if (instance == null) instance = new ApplicationFacade();
return instance as ApplicationFacade;
}
/**
* All this simply does is fire a notification which is routed to
* "StartupCommand" via the "registerCommand" handlers
* @param app
*
*/
public function start(app:DisplayObject):void
{
CONFIG::isSDK46 {
kdpVersion += ".sdk46";
}
_app = app;
appFolder = app.root.loaderInfo.url;
appFolder = appFolder.substr(0, appFolder.lastIndexOf('/') + 1);
sendNotification(NotificationType.STARTUP, app);
externalInterface = retrieveProxy(ExternalInterfaceProxy.NAME) as ExternalInterfaceProxy;
}
/**
* Created to trace all notifications for debug
* @param notificationName
* @param body
* @param type
*
*/
override public function sendNotification(notificationName:String, body:Object = null, type:String = null):void {
if (debugMode) {
var s:String;
if ((notificationName == NotificationType.BYTES_DOWNLOADED_CHANGE && debugLevel == DebugLevel.HIGH) ||
(notificationName == NotificationType.PLAYER_UPDATE_PLAYHEAD && (debugLevel == DebugLevel.HIGH || debugLevel == DebugLevel.MEDIUM)) ||
(notificationName != NotificationType.PLAYER_UPDATE_PLAYHEAD && notificationName != NotificationType.BYTES_DOWNLOADED_CHANGE))
{
if (notificationName == NotificationType.PLAYER_STATE_CHANGE)
s = 'Sent ' + notificationName + ' ==> ' + body.toString();
else {
s = 'Sent ' + notificationName;
if (body) {
var found:Boolean = false;
for (var o:* in body) {
s += ", " + o + ":" + body[o];
found = true;
}
if (!found) {
s += ", " + body.toString();
}
}
}
}
if (s && s != "null") {
var curTime:Number = 0;
var kmediaPlayerMediator:KMediaPlayerMediator = retrieveMediator(KMediaPlayerMediator.NAME) as KMediaPlayerMediator;
if (kmediaPlayerMediator &&
kmediaPlayerMediator.player &&
kmediaPlayerMediator.player.state!=MediaPlayerState.LOADING &&
kmediaPlayerMediator.player.state!=MediaPlayerState.UNINITIALIZED &&
kmediaPlayerMediator.player.state!=MediaPlayerState.PLAYBACK_ERROR)
{
curTime = kmediaPlayerMediator.getCurrentTime();
}
var date:Date = new Date();
KTrace.getInstance().log(date.toTimeString(), ":", s, ", playhead position:", curTime);
}
}
super.sendNotification(notificationName, body, type);
//For external Flash/Flex application application listening to the KDP events
_app.dispatchEvent(new DynamicEvent(notificationName, body));
//For external Javascript application listening to the KDP events
if (externalInterface)
externalInterface.notifyJs(notificationName, body);
}
/**
* controls the routing of notifications to our controllers,
* we all know them as commands
*
*/
override protected function initializeController():void
{
super.initializeController();
registerCommand(NotificationType.STARTUP, StartupCommand);
// we do both init start KDP life cycle, and start to load the entry simultaneously
registerCommand(NotificationType.INITIATE_APP, InitMacroCommand);
//There are several things that need to be done as soon as the layout of the kdp is ready.
registerCommand(NotificationType.LAYOUT_READY, LayoutReadyCommand );
//when one call change media we fire the load media command again
registerCommand(NotificationType.CHANGE_MEDIA, InitChangeMediaMacroCommand);
registerCommand (NotificationType.LIVE_ENTRY, LiveStreamCommand );
registerCommand (NotificationType.MEDIA_LOADED, MediaReadyCommand );
registerCommand (NotificationType.PLAYBACK_COMPLETE, PlaybackCompleteCommand);
registerCommand(NotificationType.SEQUENCE_ITEM_PLAY_END, SequenceItemPlayEndCommand);
registerCommand(NotificationType.SEQUENCE_SKIP_NEXT, SequenceSkipNextCommand);
}
override protected function initializeView():void
{
if ( view != null ) return;
view = KView.getInstance();
}
override protected function initializeFacade():void
{
initializeView();
initializeModel();
initializeController();
}
/**
* Help to remove all commands, mediator, proxies from the facade
*
*/
public function dispose() : void
{
var i:int =0;
for(i=0; i<_commandNameArray.length; i++)
this.removeCommand( _commandNameArray[i] );
for(i=0; i<_mediatorNameArray.length; i++)
this.removeMediator( _mediatorNameArray[i] );
for(i=0; i<_proxyNameArray.length; i++)
this.removeProxy( _proxyNameArray[i] );
_commandNameArray = new Array();
_mediatorNameArray = new Array();
_proxyNameArray = new Array();
}
/**
* after registartion add the notification name to a
* @param notificationName
* @param commandClassRef
*
*/
override public function registerCommand(notificationName:String, commandClassRef:Class):void
{
super.registerCommand(notificationName, commandClassRef);
//save the notification name so we can delete it later
_commandNameArray.push( notificationName );
}
override public function registerMediator(mediator:IMediator):void
{
super.registerMediator(mediator);
//save the mediator name so we can delete it later
_mediatorNameArray.push( mediator.getMediatorName() );
}
override public function registerProxy(proxy:IProxy):void
{
bindObject[proxy.getProxyName()] = proxy.getData();
super.registerProxy(proxy);
//save the proxy name so we can delete it later
_proxyNameArray.push( proxy.getProxyName() );
}
/**
* add notification observer for a given mediator
* @param notification the notification to listen for
* @param notificationHandler handler to be called
* @param mediator
*
*/
public function addNotificationInterest(notification:String, notificationHandler:Function, mediator:IMediator):void {
(view as KView).addNotificationInterest(notification, notificationHandler, mediator);
}
public function get app () : DisplayObject
{
return _app;
}
public function set app (disObj : DisplayObject) : void
{
_app = disObj;
}
}
}
|
bump v3.8.2
|
bump v3.8.2
|
ActionScript
|
agpl-3.0
|
shvyrev/kdp,shvyrev/kdp,kaltura/kdp,shvyrev/kdp,kaltura/kdp,kaltura/kdp
|
1617436d0b3dcc04e2f3154ba0a737e435472a26
|
asunit-4.0/src/asunit/core/TextCore.as
|
asunit-4.0/src/asunit/core/TextCore.as
|
package asunit.core {
import asunit.printers.TextPrinter;
import flash.display.DisplayObjectContainer;
/**
* TextCore is just a simple helper class that
* configures the base class AsUnitCore to use the
* standard TextPrinter.
*
* The main idea is that you may want a completely
* different text output without the default TextPrinter,
* and if that's the case, you can go ahead and
* instantiate AsUnitCore and configure it however you
* wish.
*/
public class TextCore extends AsUnitCore {
public var textPrinter:TextPrinter;
override protected function initializeObservers():void {
super.initializeObservers();
textPrinter = new TextPrinter();
addListener(textPrinter);
}
override public function set visualContext(context:DisplayObjectContainer):void {
super.visualContext = context;
// Add the TextPrinter to the Display List:
visualContext.addChild(textPrinter);
}
}
}
|
package asunit.core {
import asunit.printers.ColorTracePrinter;
import asunit.printers.TextPrinter;
import flash.display.DisplayObjectContainer;
/**
* TextCore is just a simple helper class that
* configures the base class AsUnitCore to use the
* standard TextPrinter.
*
* The main idea is that you may want a completely
* different text output without the default TextPrinter,
* and if that's the case, you can go ahead and
* instantiate AsUnitCore and configure it however you
* wish.
*/
public class TextCore extends AsUnitCore {
public var textPrinter:TextPrinter;
override protected function initializeObservers():void {
super.initializeObservers();
textPrinter = new TextPrinter();
textPrinter.traceOnComplete = false;
addListener(textPrinter);
addListener(new ColorTracePrinter());
}
override public function set visualContext(context:DisplayObjectContainer):void {
super.visualContext = context;
// Add the TextPrinter to the Display List:
visualContext.addChild(textPrinter);
}
}
}
|
modify TextCore to use ColorTracePrinter
|
modify TextCore to use ColorTracePrinter
|
ActionScript
|
mit
|
patternpark/asunit
|
9699ea3155e5765eeecd54f6284f0de32a629058
|
src/battlecode/client/viewer/GameCanvas.as
|
src/battlecode/client/viewer/GameCanvas.as
|
package battlecode.client.viewer {
import battlecode.client.viewer.render.DrawDominationBar;
import battlecode.client.viewer.render.DrawHUD;
import battlecode.client.viewer.render.DrawMap;
import battlecode.client.viewer.render.RenderConfiguration;
import battlecode.common.Team;
import battlecode.events.MatchEvent;
import flash.display.InteractiveObject;
import flash.events.Event;
import flash.events.KeyboardEvent;
import mx.binding.utils.ChangeWatcher;
import mx.containers.HBox;
import mx.containers.VBox;
import mx.events.FlexEvent;
/*
* ----------------------
* | Dom Bar |
* |--------------------|
* | |
* | DrawMap |
* | |
* | |
* ----------------------
*/
public class GameCanvas extends HBox {
private var controller:MatchController;
private var watchers:Vector.<ChangeWatcher>;
private var vbox:VBox; // container for map
private var drawDominationBar:DrawDominationBar;
private var sideBoxA:VBox;
private var sideBoxB:VBox;
private var drawMap:DrawMap;
public function GameCanvas(controller:MatchController) {
super();
this.percentWidth = 100;
this.percentHeight = 100;
this.vbox = new VBox();
this.drawDominationBar = new DrawDominationBar(controller);
this.drawMap = new DrawMap(controller);
this.sideBoxA = new DrawHUD(controller, Team.A);
this.sideBoxB = new DrawHUD(controller, Team.B);
this.controller = controller;
this.controller.addEventListener(MatchEvent.ROUND_CHANGE, onRoundChange);
this.controller.addEventListener(MatchEvent.MATCH_CHANGE, onMatchChange);
this.setStyle("paddingLeft", 0);
this.setStyle("paddingTop", 0);
this.setStyle("paddingBottom", 0);
this.setStyle("paddingRight", 0);
this.setStyle("horizontalGap", 0);
this.setStyle("verticalGap", 0);
vbox.percentWidth = 100;
vbox.percentHeight = 100;
vbox.autoLayout = false;
vbox.setStyle("paddingLeft", 0);
vbox.setStyle("paddingTop", 0);
vbox.setStyle("paddingBottom", 0);
vbox.setStyle("paddingRight", 0);
this.addChild(sideBoxA);
this.addChild(vbox);
this.addChild(sideBoxB);
vbox.addChild(drawDominationBar);
vbox.addChild(drawMap);
this.addEventListener(FlexEvent.CREATION_COMPLETE, onCreationComplete);
}
private function centerMap():void {
if (width == 0 || height == 0) return;
var containerWidth:Number = vbox.width;
var containerHeight:Number = vbox.height - drawDominationBar.height;
var mapWidth:uint = drawMap.getMapWidth();
var mapHeight:uint = drawMap.getMapHeight();
var scalingFactor:Number = Math.min(containerWidth / mapWidth, containerHeight / mapHeight);
RenderConfiguration.setScalingFactor(scalingFactor);
drawMap.redrawAll();
drawMap.x = (containerWidth - (mapWidth * scalingFactor)) / 2;
drawMap.y = (containerHeight - (mapHeight * scalingFactor)) / 2 + drawDominationBar.height;
drawDominationBar.x = 0;
drawDominationBar.y = 0;
drawDominationBar.width = vbox.width;
drawDominationBar.redrawAll();
}
private function onCreationComplete(e:Event):void {
this.watchers = new Vector.<ChangeWatcher>();
this.watchers.push(ChangeWatcher.watch(this, "width", onSizeChange));
this.watchers.push(ChangeWatcher.watch(this, "height", onSizeChange));
this.watchers.push(ChangeWatcher.watch(vbox, "width", onSizeChange));
this.watchers.push(ChangeWatcher.watch(vbox, "height", onSizeChange));
this.watchers.push(ChangeWatcher.watch(drawDominationBar, "width", onSizeChange));
this.watchers.push(ChangeWatcher.watch(drawDominationBar, "height", onSizeChange));
centerMap();
// can't be added until stage object is avail on creation complete
this.stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
}
private function onRoundChange(e:MatchEvent):void {
}
private function onMatchChange(e:MatchEvent):void {
centerMap();
controller.currentRound += 1;
}
// listens for width/height changes to recenter map
private function onSizeChange(e:Event):void {
centerMap();
}
// listens for key presses to update the render configuration
private function onKeyDown(e:KeyboardEvent):void {
if (e.ctrlKey || e.altKey) return;
switch (String.fromCharCode(e.charCode)) {
case "B":
case "b":
RenderConfiguration.toggleBroadcast();
break;
case "D":
case "d":
RenderConfiguration.toggleDiscrete();
break;
case "E":
case "e":
RenderConfiguration.toggleEnergon();
break;
case "F":
case "f":
controller.fastForwarding = !controller.fastForwarding;
break;
case "G":
case "g":
RenderConfiguration.toggleGridlines();
break;
case "H":
case "h":
RenderConfiguration.toggleDrawHeight();
break;
case "K":
case "k":
controller.keyframeRate = (controller.keyframeRate) ? 0 : 50; // toggle keyframing
break;
case "M":
case "m":
RenderConfiguration.toggleOre();
break;
case "O":
case "o":
RenderConfiguration.toggleHats();
break;
case "S":
case "s":
if (!trySkip(200)) if (!trySkip(100)) trySkip(50); // skip ahead
break;
case "X":
case "x":
RenderConfiguration.toggleExplosions();
break;
case " ":
var focusObj:InteractiveObject = this.stage.focus;
this.stage.focus = null; // hack to prevent space bar from activating other buttons
this.stage.focus = focusObj;
if (controller.currentRound == controller.match.getRounds() && controller.currentMatch < controller.totalMatches) {
controller.currentMatch++;
}
controller.playing = !controller.playing; // toggle play/pause
break;
}
}
private function trySkip(rounds:uint):Boolean {
if (controller.currentRound + rounds < controller.match.getRounds()) {
controller.currentRound += rounds;
return true;
}
return false;
}
}
}
|
package battlecode.client.viewer {
import battlecode.client.viewer.render.DrawDominationBar;
import battlecode.client.viewer.render.DrawHUD;
import battlecode.client.viewer.render.DrawMap;
import battlecode.client.viewer.render.RenderConfiguration;
import battlecode.common.Team;
import battlecode.events.MatchEvent;
import flash.display.InteractiveObject;
import flash.events.Event;
import flash.events.KeyboardEvent;
import mx.binding.utils.ChangeWatcher;
import mx.containers.HBox;
import mx.containers.VBox;
import mx.events.FlexEvent;
/*
* ----------------------
* | Dom Bar |
* |--------------------|
* | |
* | DrawMap |
* | |
* | |
* ----------------------
*/
public class GameCanvas extends HBox {
private var controller:MatchController;
private var watchers:Vector.<ChangeWatcher>;
private var vbox:VBox; // container for map
private var sideBoxA:VBox;
private var sideBoxB:VBox;
private var drawMap:DrawMap;
public function GameCanvas(controller:MatchController) {
super();
this.percentWidth = 100;
this.percentHeight = 100;
this.vbox = new VBox();
this.drawMap = new DrawMap(controller);
this.sideBoxA = new DrawHUD(controller, Team.A);
this.sideBoxB = new DrawHUD(controller, Team.B);
this.controller = controller;
this.controller.addEventListener(MatchEvent.ROUND_CHANGE, onRoundChange);
this.controller.addEventListener(MatchEvent.MATCH_CHANGE, onMatchChange);
this.setStyle("paddingLeft", 0);
this.setStyle("paddingTop", 0);
this.setStyle("paddingBottom", 0);
this.setStyle("paddingRight", 0);
this.setStyle("horizontalGap", 0);
this.setStyle("verticalGap", 0);
vbox.percentWidth = 100;
vbox.percentHeight = 100;
vbox.autoLayout = false;
vbox.setStyle("paddingLeft", 0);
vbox.setStyle("paddingTop", 0);
vbox.setStyle("paddingBottom", 0);
vbox.setStyle("paddingRight", 0);
this.addChild(sideBoxA);
this.addChild(vbox);
this.addChild(sideBoxB);
vbox.addChild(drawMap);
this.addEventListener(FlexEvent.CREATION_COMPLETE, onCreationComplete);
}
private function centerMap():void {
if (width == 0 || height == 0) return;
var containerWidth:Number = vbox.width;
var containerHeight:Number = vbox.height;
var mapWidth:uint = drawMap.getMapWidth();
var mapHeight:uint = drawMap.getMapHeight();
var scalingFactor:Number = Math.min(containerWidth / mapWidth, containerHeight / mapHeight);
RenderConfiguration.setScalingFactor(scalingFactor);
drawMap.redrawAll();
drawMap.x = (containerWidth - (mapWidth * scalingFactor)) / 2;
drawMap.y = 0;
}
private function onCreationComplete(e:Event):void {
this.watchers = new Vector.<ChangeWatcher>();
this.watchers.push(ChangeWatcher.watch(this, "width", onSizeChange));
this.watchers.push(ChangeWatcher.watch(this, "height", onSizeChange));
this.watchers.push(ChangeWatcher.watch(vbox, "width", onSizeChange));
this.watchers.push(ChangeWatcher.watch(vbox, "height", onSizeChange));
centerMap();
// can't be added until stage object is avail on creation complete
this.stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
}
private function onRoundChange(e:MatchEvent):void {
}
private function onMatchChange(e:MatchEvent):void {
centerMap();
controller.currentRound += 1;
}
// listens for width/height changes to recenter map
private function onSizeChange(e:Event):void {
centerMap();
}
// listens for key presses to update the render configuration
private function onKeyDown(e:KeyboardEvent):void {
if (e.ctrlKey || e.altKey) return;
switch (String.fromCharCode(e.charCode)) {
case "B":
case "b":
RenderConfiguration.toggleBroadcast();
break;
case "D":
case "d":
RenderConfiguration.toggleDiscrete();
break;
case "E":
case "e":
RenderConfiguration.toggleEnergon();
break;
case "F":
case "f":
controller.fastForwarding = !controller.fastForwarding;
break;
case "G":
case "g":
RenderConfiguration.toggleGridlines();
break;
case "H":
case "h":
RenderConfiguration.toggleDrawHeight();
break;
case "K":
case "k":
controller.keyframeRate = (controller.keyframeRate) ? 0 : 50; // toggle keyframing
break;
case "M":
case "m":
RenderConfiguration.toggleOre();
break;
case "O":
case "o":
RenderConfiguration.toggleHats();
break;
case "S":
case "s":
if (!trySkip(200)) if (!trySkip(100)) trySkip(50); // skip ahead
break;
case "X":
case "x":
RenderConfiguration.toggleExplosions();
break;
case " ":
var focusObj:InteractiveObject = this.stage.focus;
this.stage.focus = null; // hack to prevent space bar from activating other buttons
this.stage.focus = focusObj;
if (controller.currentRound == controller.match.getRounds() && controller.currentMatch < controller.totalMatches) {
controller.currentMatch++;
}
controller.playing = !controller.playing; // toggle play/pause
break;
}
}
private function trySkip(rounds:uint):Boolean {
if (controller.currentRound + rounds < controller.match.getRounds()) {
controller.currentRound += rounds;
return true;
}
return false;
}
}
}
|
remove domination bar from layout
|
remove domination bar from layout
|
ActionScript
|
mit
|
trun/battlecode-webclient
|
bba2554ea6e459536a67bef344accf1b84619ed0
|
HLSPlugin/src/com/kaltura/hls/m2ts/FLVTranscoder.as
|
HLSPlugin/src/com/kaltura/hls/m2ts/FLVTranscoder.as
|
package com.kaltura.hls.m2ts
{
import flash.utils.ByteArray;
import flash.net.ObjectEncoding;
import flash.utils.ByteArray;
import flash.utils.Endian;
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
/**
* Responsible for emitting FLV data. Also handles AAC conversion
* config and buffering.
*/
public class FLVTranscoder
{
public const MIN_FILE_HEADER_BYTE_COUNT:int = 9;
public var callback:Function;
private var lastTagSize:uint = 0;
private var _aacConfig:ByteArray;
private var _aacRemainder:ByteArray;
private var _aacTimestamp:Number = 0;
public function clear(clearAACConfig:Boolean = false):void
{
if(clearAACConfig)
_aacConfig = null;
_aacRemainder = new ByteArray();
_aacTimestamp = 0;
}
private static var tag:ByteArray = new ByteArray();
private function sendFLVTag(flvts:uint, type:uint, codec:int, mode:int, bytes:ByteArray, offset:uint, length:uint):void
{
tag.position = 0;
var msgLength:uint = length + ((codec >= 0) ? 1 : 0) + ((mode >= 0) ? 1 : 0);
var cursor:uint = 0;
if(msgLength > 0xffffff)
return; // too big for the length field
tag.length = FLVTags.HEADER_LENGTH + msgLength;
tag[cursor++] = type;
tag[cursor++] = (msgLength >> 16) & 0xff;
tag[cursor++] = (msgLength >> 8) & 0xff;
tag[cursor++] = (msgLength ) & 0xff;
tag[cursor++] = (flvts >> 16) & 0xff;
tag[cursor++] = (flvts >> 8) & 0xff;
tag[cursor++] = (flvts ) & 0xff;
tag[cursor++] = (flvts >> 24) & 0xff;
tag[cursor++] = 0x00; // stream ID
tag[cursor++] = 0x00;
tag[cursor++] = 0x00;
if(codec >= 0)
tag[cursor++] = codec;
if(mode >= 0)
tag[cursor++] = mode;
tag.position = cursor;
tag.writeBytes(bytes, offset, length);
cursor += length;
msgLength += 11; // account for message header in back pointer
tag.writeUnsignedInt(lastTagSize);
// Dispatch tag.
if(callback != null)
callback(flvts, tag);
lastTagSize = tag.length;
}
public function convertFLVTimestamp(pts:Number):Number
{
return pts / 90.0;
}
private static var flvGenerationBuffer:ByteArray = new ByteArray();
/**
* Convert and amit AVC NALU data.
*/
public function convert(unit:NALU):void
{
// Emit an AVCC.
var avcc:ByteArray = NALUProcessor.extractAVCC(unit);
if(avcc)
sendFLVTag(convertFLVTimestamp(unit.pts), FLVTags.TYPE_VIDEO, FLVTags.VIDEO_CODEC_AVC_KEYFRAME, FLVTags.AVC_MODE_AVCC, avcc, 0, avcc.length);
// Accumulate NALUs into buffer.
flvGenerationBuffer.length = 3;
flvGenerationBuffer[0] = (tsu >> 16) & 0xff;
flvGenerationBuffer[1] = (tsu >> 8) & 0xff;
flvGenerationBuffer[2] = (tsu ) & 0xff;
flvGenerationBuffer.position = 3;
// Check keyframe status.
var keyFrame:Boolean = false;
var totalAppended:int = 0;
NALUProcessor.walkNALUs(unit.buffer, 0, function(bytes:ByteArray, cursor:uint, length:uint):void
{
// Check for a NALU that is keyframe type.
var naluType:uint = bytes[cursor] & 0x1f;
//trace(naluType + " length=" + length);
switch(naluType)
{
case 0x09: // "access unit delimiter"
switch((bytes[cursor + 1] >> 5) & 0x07) // access unit type
{
case 0:
case 3:
case 5:
keyFrame = true;
break;
default:
keyFrame = false;
break;
}
break;
default:
// Infer keyframe state.
if(naluType == 5)
keyFrame = true;
else if(naluType == 1)
keyFrame = false;
}
// Append.
flvGenerationBuffer.writeUnsignedInt(length);
flvGenerationBuffer.writeBytes(bytes, cursor, length);
totalAppended += length;
}, true );
var flvts:uint = convertFLVTimestamp(unit.pts);
var tsu:uint = convertFLVTimestamp(unit.pts - unit.dts);
var codec:uint;
if(keyFrame)
codec = FLVTags.VIDEO_CODEC_AVC_KEYFRAME;
else
codec = FLVTags.VIDEO_CODEC_AVC_PREDICTIVEFRAME;
//trace("ts=" + flvts + " tsu=" + tsu + " keyframe = " + keyFrame);
sendFLVTag(flvts, FLVTags.TYPE_VIDEO, codec, FLVTags.AVC_MODE_PICTURE, flvGenerationBuffer, 0, flvGenerationBuffer.length);
}
private function compareBytesHelper(b1:ByteArray, b2:ByteArray):Boolean
{
var curPos:uint;
if(b1.length != b2.length)
return false;
for(curPos = 0; curPos < b1.length; curPos++)
{
if(b1[curPos] != b2[curPos])
return false;
}
return true;
}
private function sendAACConfigFLVTag(flvts:uint, profile:uint, sampleRateIndex:uint, channelConfig:uint):void
{
var isNewConfig:Boolean = true;
var audioSpecificConfig:ByteArray = new ByteArray();
var audioObjectType:uint;
audioSpecificConfig.length = 2;
switch(profile)
{
case 0x00:
audioObjectType = 0x01;
break;
case 0x01:
audioObjectType = 0x02;
break;
case 0x02:
audioObjectType = 0x03;
break;
default:
return;
}
audioSpecificConfig[0] = ((audioObjectType << 3) & 0xf8) + ((sampleRateIndex >> 1) & 0x07);
audioSpecificConfig[1] = ((sampleRateIndex << 7) & 0x80) + ((channelConfig << 3) & 0x78);
if(_aacConfig && compareBytesHelper(_aacConfig, audioSpecificConfig))
isNewConfig = false;
if(!isNewConfig)
return;
_aacConfig = audioSpecificConfig;
sendFLVTag(flvts, FLVTags.TYPE_AUDIO, FLVTags.AUDIO_CODEC_AAC, FLVTags.AAC_MODE_CONFIG, _aacConfig, 0, _aacConfig.length);
}
/**
* Convert and amit AAC data.
*/
public function convertAAC(pes:PESPacket):void
{
var timeAccumulation:Number = 0.0;
var limit:uint;
var stream:ByteArray;
var hadRemainder:Boolean = false;
var cursor:int = 0;
var length:int = pes.buffer.length;
var bytes:ByteArray = pes.buffer;
var timestamp:Number = pes.pts;
if(_aacRemainder)
{
stream = _aacRemainder;
stream.writeBytes(bytes, cursor, length);
cursor = 0;
length = stream.length;
_aacRemainder = null;
hadRemainder = true;
timeAccumulation = _aacTimestamp - timestamp;
}
else
stream = bytes;
limit = cursor + length;
// an AAC PES packet can contain multiple ADTS frames
while(cursor < limit)
{
var remaining:uint = limit - cursor;
var sampleRateIndex:uint;
var sampleRate:Number = undefined;
var profile:uint;
var channelConfig:uint;
var frameLength:uint;
if(remaining < FLVTags.ADTS_FRAME_HEADER_LENGTH)
break;
// search for syncword
if(stream[cursor] != 0xff || (stream[cursor + 1] & 0xf0) != 0xf0)
{
cursor++;
continue;
}
frameLength = (stream[cursor + 3] & 0x03) << 11;
frameLength += (stream[cursor + 4]) << 3;
frameLength += (stream[cursor + 5] >> 5) & 0x07;
// Check for an invalid ADTS header; if so look for next syncword.
if(frameLength < FLVTags.ADTS_FRAME_HEADER_LENGTH)
{
cursor++;
continue;
}
// Skip it till next PES packet.
if(frameLength > remaining)
break;
profile = (stream[cursor + 2] >> 6) & 0x03;
sampleRateIndex = (stream[cursor + 2] >> 2) & 0x0f;
switch(sampleRateIndex)
{
case 0x00:
sampleRate = 96000.0;
break;
case 0x01:
sampleRate = 88200.0;
break;
case 0x02:
sampleRate = 64000.0;
break;
case 0x03:
sampleRate = 48000.0;
break;
case 0x04:
sampleRate = 44100.0;
break;
case 0x05:
sampleRate = 32000.0;
break;
case 0x06:
sampleRate = 24000.0;
break;
case 0x07:
sampleRate = 22050.0;
break;
case 0x08:
sampleRate = 16000.0;
break;
case 0x09:
sampleRate = 12000.0;
break;
case 0x0a:
sampleRate = 11025.0;
break;
case 0x0b:
sampleRate = 8000.0;
break;
case 0x0c:
sampleRate = 7350.0;
break;
}
channelConfig = ((stream[cursor + 2] & 0x01) << 2) + ((stream[cursor + 3] >> 6) & 0x03);
if(sampleRate)
{
var flvts:uint = convertFLVTimestamp(timestamp + timeAccumulation);
sendAACConfigFLVTag(flvts, profile, sampleRateIndex, channelConfig);
//trace("Sending AAC");
sendFLVTag(flvts, FLVTags.TYPE_AUDIO, FLVTags.AUDIO_CODEC_AAC, FLVTags.AAC_MODE_FRAME, stream, cursor + FLVTags.ADTS_FRAME_HEADER_LENGTH, frameLength - FLVTags.ADTS_FRAME_HEADER_LENGTH);
timeAccumulation += (1024.0 / sampleRate) * 90000.0; // account for the duration of this frame
if(hadRemainder)
{
timeAccumulation = 0.0;
hadRemainder = false;
}
}
cursor += frameLength;
}
if(cursor < limit)
{
//trace("AAC timestamp was " + _aacTimestamp);
_aacRemainder = new ByteArray();
_aacRemainder.writeBytes(stream, cursor, limit - cursor);
_aacTimestamp = timestamp + timeAccumulation;
//trace("AAC timestamp now " + _aacTimestamp);
}
}
/**
* Convert and amit MP3 data.
*/
public function convertMP3(pes:PESPacket):void
{
sendFLVTag(convertFLVTimestamp(pes.pts), FLVTags.TYPE_AUDIO, FLVTags.AUDIO_CODEC_MP3, -1, pes.buffer, 0, pes.buffer.length);
}
private function generateScriptData(values:Array):ByteArray
{
var bytes:ByteArray = new ByteArray();
bytes.objectEncoding = ObjectEncoding.AMF0;
for each (var object:Object in values)
bytes.writeObject(object);
return bytes;
}
private function sendScriptDataFLVTag(flvts:uint, values:Array):void
{
var bytes:ByteArray = generateScriptData(values);
sendFLVTag(flvts, FLVTags.TYPE_SCRIPTDATA, -1, -1, bytes, 0, bytes.length);
}
/**
* Fire off a subtitle caption.
*/
public function createAndSendCaptionMessage( timeStamp:Number, captionBuffer:String, lang:String="", textid:Number=99):void
{
var captionObject:Array = ["onCaptionInfo", { type:"WebVTT", data:captionBuffer }];
//sendScriptDataFLVTag( timeStamp * 1000, captionObject);
// We need to strip the timestamp off of the text data
captionBuffer = captionBuffer.slice(captionBuffer.indexOf('\n') + 1);
var subtitleObject:Array = ["onTextData", { text:captionBuffer, language:lang, trackid:textid }];
sendScriptDataFLVTag( timeStamp * 1000, subtitleObject);
}
}
}
|
package com.kaltura.hls.m2ts
{
import flash.utils.ByteArray;
import flash.net.ObjectEncoding;
import flash.utils.ByteArray;
import flash.utils.Endian;
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
/**
* Responsible for emitting FLV data. Also handles AAC conversion
* config and buffering.
*/
public class FLVTranscoder
{
public const MIN_FILE_HEADER_BYTE_COUNT:int = 9;
public var callback:Function;
private var lastTagSize:uint = 0;
private var _aacConfig:ByteArray;
private var _aacRemainder:ByteArray;
private var _aacTimestamp:Number = 0;
public function clear(clearAACConfig:Boolean = false):void
{
if(clearAACConfig)
_aacConfig = null;
_aacRemainder = null;
_aacTimestamp = 0;
}
private static var tag:ByteArray = new ByteArray();
private function sendFLVTag(flvts:uint, type:uint, codec:int, mode:int, bytes:ByteArray, offset:uint, length:uint):void
{
tag.position = 0;
var msgLength:uint = length + ((codec >= 0) ? 1 : 0) + ((mode >= 0) ? 1 : 0);
var cursor:uint = 0;
if(msgLength > 0xffffff)
return; // too big for the length field
tag.length = FLVTags.HEADER_LENGTH + msgLength;
tag[cursor++] = type;
tag[cursor++] = (msgLength >> 16) & 0xff;
tag[cursor++] = (msgLength >> 8) & 0xff;
tag[cursor++] = (msgLength ) & 0xff;
tag[cursor++] = (flvts >> 16) & 0xff;
tag[cursor++] = (flvts >> 8) & 0xff;
tag[cursor++] = (flvts ) & 0xff;
tag[cursor++] = (flvts >> 24) & 0xff;
tag[cursor++] = 0x00; // stream ID
tag[cursor++] = 0x00;
tag[cursor++] = 0x00;
if(codec >= 0)
tag[cursor++] = codec;
if(mode >= 0)
tag[cursor++] = mode;
tag.position = cursor;
tag.writeBytes(bytes, offset, length);
cursor += length;
msgLength += 11; // account for message header in back pointer
tag.writeUnsignedInt(lastTagSize);
// Dispatch tag.
if(callback != null)
callback(flvts, tag);
lastTagSize = tag.length;
}
public function convertFLVTimestamp(pts:Number):Number
{
return pts / 90.0;
}
private static var flvGenerationBuffer:ByteArray = new ByteArray();
/**
* Convert and amit AVC NALU data.
*/
public function convert(unit:NALU):void
{
// Emit an AVCC.
var avcc:ByteArray = NALUProcessor.extractAVCC(unit);
if(avcc)
sendFLVTag(convertFLVTimestamp(unit.pts), FLVTags.TYPE_VIDEO, FLVTags.VIDEO_CODEC_AVC_KEYFRAME, FLVTags.AVC_MODE_AVCC, avcc, 0, avcc.length);
// Accumulate NALUs into buffer.
flvGenerationBuffer.length = 3;
flvGenerationBuffer[0] = (tsu >> 16) & 0xff;
flvGenerationBuffer[1] = (tsu >> 8) & 0xff;
flvGenerationBuffer[2] = (tsu ) & 0xff;
flvGenerationBuffer.position = 3;
// Check keyframe status.
var keyFrame:Boolean = false;
var totalAppended:int = 0;
NALUProcessor.walkNALUs(unit.buffer, 0, function(bytes:ByteArray, cursor:uint, length:uint):void
{
// Check for a NALU that is keyframe type.
var naluType:uint = bytes[cursor] & 0x1f;
//trace(naluType + " length=" + length);
switch(naluType)
{
case 0x09: // "access unit delimiter"
switch((bytes[cursor + 1] >> 5) & 0x07) // access unit type
{
case 0:
case 3:
case 5:
keyFrame = true;
break;
default:
keyFrame = false;
break;
}
break;
default:
// Infer keyframe state.
if(naluType == 5)
keyFrame = true;
else if(naluType == 1)
keyFrame = false;
}
// Append.
flvGenerationBuffer.writeUnsignedInt(length);
flvGenerationBuffer.writeBytes(bytes, cursor, length);
totalAppended += length;
}, true );
var flvts:uint = convertFLVTimestamp(unit.pts);
var tsu:uint = convertFLVTimestamp(unit.pts - unit.dts);
var codec:uint;
if(keyFrame)
codec = FLVTags.VIDEO_CODEC_AVC_KEYFRAME;
else
codec = FLVTags.VIDEO_CODEC_AVC_PREDICTIVEFRAME;
//trace("ts=" + flvts + " tsu=" + tsu + " keyframe = " + keyFrame);
sendFLVTag(flvts, FLVTags.TYPE_VIDEO, codec, FLVTags.AVC_MODE_PICTURE, flvGenerationBuffer, 0, flvGenerationBuffer.length);
}
private function compareBytesHelper(b1:ByteArray, b2:ByteArray):Boolean
{
var curPos:uint;
if(b1.length != b2.length)
return false;
for(curPos = 0; curPos < b1.length; curPos++)
{
if(b1[curPos] != b2[curPos])
return false;
}
return true;
}
private function sendAACConfigFLVTag(flvts:uint, profile:uint, sampleRateIndex:uint, channelConfig:uint):void
{
var isNewConfig:Boolean = true;
var audioSpecificConfig:ByteArray = new ByteArray();
var audioObjectType:uint;
audioSpecificConfig.length = 2;
switch(profile)
{
case 0x00:
audioObjectType = 0x01;
break;
case 0x01:
audioObjectType = 0x02;
break;
case 0x02:
audioObjectType = 0x03;
break;
default:
return;
}
audioSpecificConfig[0] = ((audioObjectType << 3) & 0xf8) + ((sampleRateIndex >> 1) & 0x07);
audioSpecificConfig[1] = ((sampleRateIndex << 7) & 0x80) + ((channelConfig << 3) & 0x78);
if(_aacConfig && compareBytesHelper(_aacConfig, audioSpecificConfig))
isNewConfig = false;
if(!isNewConfig)
return;
_aacConfig = audioSpecificConfig;
sendFLVTag(flvts, FLVTags.TYPE_AUDIO, FLVTags.AUDIO_CODEC_AAC, FLVTags.AAC_MODE_CONFIG, _aacConfig, 0, _aacConfig.length);
}
/**
* Convert and amit AAC data.
*/
public function convertAAC(pes:PESPacket):void
{
var timeAccumulation:Number = 0.0;
var limit:uint;
var stream:ByteArray;
var hadRemainder:Boolean = false;
var cursor:int = 0;
var length:int = pes.buffer.length;
var bytes:ByteArray = pes.buffer;
var timestamp:Number = pes.pts;
if(_aacRemainder)
{
stream = _aacRemainder;
stream.writeBytes(bytes, cursor, length);
cursor = 0;
length = stream.length;
_aacRemainder = null;
hadRemainder = true;
timeAccumulation = _aacTimestamp - timestamp;
}
else
stream = bytes;
limit = cursor + length;
// an AAC PES packet can contain multiple ADTS frames
while(cursor < limit)
{
var remaining:uint = limit - cursor;
var sampleRateIndex:uint;
var sampleRate:Number = undefined;
var profile:uint;
var channelConfig:uint;
var frameLength:uint;
if(remaining < FLVTags.ADTS_FRAME_HEADER_LENGTH)
break;
// search for syncword
if(stream[cursor] != 0xff || (stream[cursor + 1] & 0xf0) != 0xf0)
{
cursor++;
continue;
}
frameLength = (stream[cursor + 3] & 0x03) << 11;
frameLength += (stream[cursor + 4]) << 3;
frameLength += (stream[cursor + 5] >> 5) & 0x07;
// Check for an invalid ADTS header; if so look for next syncword.
if(frameLength < FLVTags.ADTS_FRAME_HEADER_LENGTH)
{
cursor++;
continue;
}
// Skip it till next PES packet.
if(frameLength > remaining)
break;
profile = (stream[cursor + 2] >> 6) & 0x03;
sampleRateIndex = (stream[cursor + 2] >> 2) & 0x0f;
switch(sampleRateIndex)
{
case 0x00:
sampleRate = 96000.0;
break;
case 0x01:
sampleRate = 88200.0;
break;
case 0x02:
sampleRate = 64000.0;
break;
case 0x03:
sampleRate = 48000.0;
break;
case 0x04:
sampleRate = 44100.0;
break;
case 0x05:
sampleRate = 32000.0;
break;
case 0x06:
sampleRate = 24000.0;
break;
case 0x07:
sampleRate = 22050.0;
break;
case 0x08:
sampleRate = 16000.0;
break;
case 0x09:
sampleRate = 12000.0;
break;
case 0x0a:
sampleRate = 11025.0;
break;
case 0x0b:
sampleRate = 8000.0;
break;
case 0x0c:
sampleRate = 7350.0;
break;
}
channelConfig = ((stream[cursor + 2] & 0x01) << 2) + ((stream[cursor + 3] >> 6) & 0x03);
if(sampleRate)
{
var flvts:uint = convertFLVTimestamp(timestamp + timeAccumulation);
sendAACConfigFLVTag(flvts, profile, sampleRateIndex, channelConfig);
//trace("Sending AAC");
sendFLVTag(flvts, FLVTags.TYPE_AUDIO, FLVTags.AUDIO_CODEC_AAC, FLVTags.AAC_MODE_FRAME, stream, cursor + FLVTags.ADTS_FRAME_HEADER_LENGTH, frameLength - FLVTags.ADTS_FRAME_HEADER_LENGTH);
timeAccumulation += (1024.0 / sampleRate) * 90000.0; // account for the duration of this frame
if(hadRemainder)
{
timeAccumulation = 0.0;
hadRemainder = false;
}
}
cursor += frameLength;
}
if(cursor < limit)
{
//trace("AAC timestamp was " + _aacTimestamp);
_aacRemainder = new ByteArray();
_aacRemainder.writeBytes(stream, cursor, limit - cursor);
_aacTimestamp = timestamp + timeAccumulation;
//trace("AAC timestamp now " + _aacTimestamp);
}
}
/**
* Convert and amit MP3 data.
*/
public function convertMP3(pes:PESPacket):void
{
sendFLVTag(convertFLVTimestamp(pes.pts), FLVTags.TYPE_AUDIO, FLVTags.AUDIO_CODEC_MP3, -1, pes.buffer, 0, pes.buffer.length);
}
private function generateScriptData(values:Array):ByteArray
{
var bytes:ByteArray = new ByteArray();
bytes.objectEncoding = ObjectEncoding.AMF0;
for each (var object:Object in values)
bytes.writeObject(object);
return bytes;
}
private function sendScriptDataFLVTag(flvts:uint, values:Array):void
{
var bytes:ByteArray = generateScriptData(values);
sendFLVTag(flvts, FLVTags.TYPE_SCRIPTDATA, -1, -1, bytes, 0, bytes.length);
}
/**
* Fire off a subtitle caption.
*/
public function createAndSendCaptionMessage( timeStamp:Number, captionBuffer:String, lang:String="", textid:Number=99):void
{
var captionObject:Array = ["onCaptionInfo", { type:"WebVTT", data:captionBuffer }];
//sendScriptDataFLVTag( timeStamp * 1000, captionObject);
// We need to strip the timestamp off of the text data
captionBuffer = captionBuffer.slice(captionBuffer.indexOf('\n') + 1);
var subtitleObject:Array = ["onTextData", { text:captionBuffer, language:lang, trackid:textid }];
sendScriptDataFLVTag( timeStamp * 1000, subtitleObject);
}
}
}
|
Fix for AAC packets getting 0 timestamps.
|
Fix for AAC packets getting 0 timestamps.
|
ActionScript
|
agpl-3.0
|
kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF
|
dbb51ad727b088bf1f538ff662da527295f03ad6
|
src/com/merlinds/miracle_tool/controllers/PublishCommand.as
|
src/com/merlinds/miracle_tool/controllers/PublishCommand.as
|
/**
* User: MerlinDS
* Date: 18.07.2014
* Time: 15:14
*/
package com.merlinds.miracle_tool.controllers {
import com.merlinds.debug.log;
import com.merlinds.miracle.geom.Transformation;
import com.merlinds.miracle_tool.events.ActionEvent;
import com.merlinds.miracle_tool.events.DialogEvent;
import com.merlinds.miracle_tool.models.ProjectModel;
import com.merlinds.miracle_tool.models.vo.AnimationVO;
import com.merlinds.miracle_tool.models.vo.ElementVO;
import com.merlinds.miracle_tool.models.vo.FrameVO;
import com.merlinds.miracle_tool.models.vo.SourceVO;
import com.merlinds.miracle_tool.models.vo.TimelineVO;
import com.merlinds.miracle_tool.services.ActionService;
import com.merlinds.miracle_tool.services.FileSystemService;
import com.merlinds.miracle_tool.utils.MeshUtils;
import com.merlinds.unitls.Resolutions;
import flash.display.BitmapData;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.utils.ByteArray;
import org.robotlegs.mvcs.Command;
public class PublishCommand extends Command {
[Inject]
public var projectModel:ProjectModel;
[Inject]
public var fileSystemService:FileSystemService;
[Inject]
public var actionService:ActionService;
[Inject]
public var event:ActionEvent;
private var _mesh:ByteArray;
private var _png:ByteArray;
private var _animations:ByteArray;
private var _scale:Number;
private var _elements:Object;
//==============================================================================
//{region PUBLIC METHODS
public function PublishCommand() {
super();
}
override public function execute():void {
log(this, "execute");
if(event.body == null){
var data:Object = {
projectName:this.projectModel.name
};
this.actionService.addAcceptActions(new <String>[ActionEvent.PUBLISHING]);
this.dispatch(new DialogEvent(DialogEvent.PUBLISH_SETTINGS, data));
}else{
var projectName:String = event.body.projectName;
_scale = Resolutions.width(this.projectModel.targetResolution) /
Resolutions.width(this.projectModel.referenceResolution);
this.createOutput();
this.fileSystemService.writeTexture(projectName, _png, _mesh);
this.fileSystemService.writeAnimation(_animations);
}
}
//} endregion PUBLIC METHODS ===================================================
//==============================================================================
//{region PRIVATE\PROTECTED METHODS
private function createOutput():void{
var buffer:BitmapData = new BitmapData(this.projectModel.outputSize, this.projectModel.outputSize, true, 0x0);
_elements = {};
var meshes:Array = [];
var animations:Array = [];
var n:int = this.projectModel.sources.length;
for(var i:int = 0; i < n; i++){
var mesh:Array = [];
var source:SourceVO = this.projectModel.sources[i];
var m:int = source.elements.length;
for(var j:int = 0; j < m; j++){
//push element view to buffer
var element:ElementVO = source.elements[j];
var depth:Point = new Point(element.x + this.projectModel.boundsOffset,
element.y + this.projectModel.boundsOffset);
buffer.copyPixels(element.bitmapData, element.bitmapData.rect, depth);
//get mesh
mesh.push({
name:element.name,
vertexes:MeshUtils.flipToY(element.vertexes),
uv:MeshUtils.covertToRelative(element.uv, this.projectModel.outputSize),
indexes:element.indexes
});
//save mesh bounds to buffer for animation bounds calculation
_elements[element.name] = element.vertexes;
}
meshes.push({name:source.clearName, mesh:mesh});
//get animation
m = source.animations.length;
for(j = 0; j < m; j++){
var animation:Object = this.createAnimationOutput(source.animations[j], source.clearName);
animations.push(animation);
}
}
trace("mesh");
var json:String = JSON.stringify(meshes);
trace(json);
_mesh = new ByteArray();
_mesh.writeObject(meshes);
_png = PNGEncoder.encode(buffer);
_animations = new ByteArray();
_animations.writeObject(animations);
}
private function createAnimationOutput(animationVO:AnimationVO, meshPrefix:String):Object {
var data:Object = { name:meshPrefix + "." + animationVO.name,// name of the matrix
totalFrames:animationVO.totalFrames,// Total animation frames
bounds:animationVO.bounds.clone(),
layers:[]};
var n:int = animationVO.timelines.length;
//find matrix sequence for current animation
for(var i:int = 0; i < n; i++){
var timelineVO:TimelineVO = animationVO.timelines[i];
var m:int = timelineVO.frames.length;
var layer:Layer = new Layer();
for(var j:int = 0; j < m; j++){
var frameVO:FrameVO = timelineVO.frames[j];
//create matrix
var transform:Transformation = frameVO.generateTransform(_scale,
//get previous frame transformation object
layer.matrixList.length > 0 ? layer.matrixList[ layer.matrixList.length - 1] : null
);
var index:int = transform == null ? -1 : layer.matrixList.push(transform) - 1;
var framesArray:Array = this.createFramesInfo(index, frameVO.name,
frameVO.duration, frameVO.type == "motion");
layer.framesList = layer.framesList.concat(framesArray);
}
data.layers.unshift(layer);
}
trace(JSON.stringify(data));
return data;
}
[Inline]
private function createFramesInfo(index:int, polygonName:String,
duration:int, motion:Boolean):Array {
var result:Array = new Array(duration);
if(duration < 2){
motion = false;
}
if(index > -1){
var t:Number = 1 / duration;
for(var i:int = 0; i < duration; i++){
var frameInfoData:FrameInfoData = new FrameInfoData();
frameInfoData.index = index;
frameInfoData.polygonName = polygonName;
frameInfoData.motion = motion;
frameInfoData.t = motion ? t * i : 0;
result[i] = frameInfoData;
}
}
return result;
}
//} endregion PRIVATE\PROTECTED METHODS ========================================
//==============================================================================
//{region EVENTS HANDLERS
//} endregion EVENTS HANDLERS ==================================================
//==============================================================================
//{region GETTERS/SETTERS
//} endregion GETTERS/SETTERS ==================================================
}
}
class Layer{
public var matrixList:Array;
public var framesList:Array;
public function Layer() {
this.framesList = [];
this.matrixList = [];
}
}
class FrameInfoData{
public var polygonName:String;
public var motion:Boolean;
public var index:int;
public var t:Number;
}
|
/**
* User: MerlinDS
* Date: 18.07.2014
* Time: 15:14
*/
package com.merlinds.miracle_tool.controllers {
import com.merlinds.debug.log;
import com.merlinds.miracle.geom.Transformation;
import com.merlinds.miracle_tool.events.ActionEvent;
import com.merlinds.miracle_tool.events.DialogEvent;
import com.merlinds.miracle_tool.models.ProjectModel;
import com.merlinds.miracle_tool.models.vo.AnimationVO;
import com.merlinds.miracle_tool.models.vo.ElementVO;
import com.merlinds.miracle_tool.models.vo.FrameVO;
import com.merlinds.miracle_tool.models.vo.SourceVO;
import com.merlinds.miracle_tool.models.vo.TimelineVO;
import com.merlinds.miracle_tool.services.ActionService;
import com.merlinds.miracle_tool.services.FileSystemService;
import com.merlinds.miracle_tool.utils.MeshUtils;
import com.merlinds.unitls.Resolutions;
import flash.display.BitmapData;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.utils.ByteArray;
import org.robotlegs.mvcs.Command;
public class PublishCommand extends Command {
[Inject]
public var projectModel:ProjectModel;
[Inject]
public var fileSystemService:FileSystemService;
[Inject]
public var actionService:ActionService;
[Inject]
public var event:ActionEvent;
private var _mesh:ByteArray;
private var _png:ByteArray;
private var _animations:ByteArray;
private var _scale:Number;
private var _elements:Object;
//==============================================================================
//{region PUBLIC METHODS
public function PublishCommand() {
super();
}
override public function execute():void {
log(this, "execute");
if(event.body == null){
var data:Object = {
projectName:this.projectModel.name
};
this.actionService.addAcceptActions(new <String>[ActionEvent.PUBLISHING]);
this.dispatch(new DialogEvent(DialogEvent.PUBLISH_SETTINGS, data));
}else{
var projectName:String = event.body.projectName;
_scale = Resolutions.width(this.projectModel.targetResolution) /
Resolutions.width(this.projectModel.referenceResolution);
this.createOutput();
this.fileSystemService.writeTexture(projectName, _png, _mesh);
this.fileSystemService.writeAnimation(_animations);
}
}
//} endregion PUBLIC METHODS ===================================================
//==============================================================================
//{region PRIVATE\PROTECTED METHODS
private function createOutput():void{
var buffer:BitmapData = new BitmapData(this.projectModel.outputSize, this.projectModel.outputSize, true, 0x0);
_elements = {};
var meshes:Array = [];
var animations:Array = [];
var n:int = this.projectModel.sources.length;
for(var i:int = 0; i < n; i++){
var mesh:Array = [];
var source:SourceVO = this.projectModel.sources[i];
var m:int = source.elements.length;
for(var j:int = 0; j < m; j++){
//push element view to buffer
var element:ElementVO = source.elements[j];
var depth:Point = new Point(element.x + this.projectModel.boundsOffset,
element.y + this.projectModel.boundsOffset);
buffer.copyPixels(element.bitmapData, element.bitmapData.rect, depth);
//get mesh
mesh.push({
name:element.name,
vertexes:MeshUtils.flipToY(element.vertexes),
uv:MeshUtils.covertToRelative(element.uv, this.projectModel.outputSize),
indexes:element.indexes
});
//save mesh bounds to buffer for animation bounds calculation
_elements[element.name] = element.vertexes;
}
meshes.push({name:source.clearName, mesh:mesh});
//get animation
m = source.animations.length;
for(j = 0; j < m; j++){
var animation:Object = this.createAnimationOutput(source.animations[j], source.clearName);
animations.push(animation);
}
}
trace("mesh");
var json:String = JSON.stringify(meshes);
trace(json);
_mesh = new ByteArray();
_mesh.writeObject(meshes);
_png = PNGEncoder.encode(buffer);
_animations = new ByteArray();
_animations.writeObject(animations);
}
private function createAnimationOutput(animationVO:AnimationVO, meshPrefix:String):Object {
var data:Object = { name:meshPrefix + "." + animationVO.name,// name of the matrix
totalFrames:animationVO.totalFrames,// Total animation frames
layers:[]};
//scale bounds
var bounds:Rectangle = animationVO.bounds.clone();
bounds.x = bounds.x * _scale;
bounds.y = bounds.y * _scale;
bounds.width = bounds.width * _scale;
bounds.height = bounds.height * _scale;
data.bounds = bounds;
//calculate frames
var n:int = animationVO.timelines.length;
//find matrix sequence for current animation
for(var i:int = 0; i < n; i++){
var timelineVO:TimelineVO = animationVO.timelines[i];
var m:int = timelineVO.frames.length;
var layer:Layer = new Layer();
for(var j:int = 0; j < m; j++){
var frameVO:FrameVO = timelineVO.frames[j];
//create matrix
var transform:Transformation = frameVO.generateTransform(_scale,
//get previous frame transformation object
layer.matrixList.length > 0 ? layer.matrixList[ layer.matrixList.length - 1] : null
);
var index:int = transform == null ? -1 : layer.matrixList.push(transform) - 1;
var framesArray:Array = this.createFramesInfo(index, frameVO.name,
frameVO.duration, frameVO.type == "motion");
layer.framesList = layer.framesList.concat(framesArray);
}
data.layers.unshift(layer);
}
trace(JSON.stringify(data));
return data;
}
[Inline]
private function createFramesInfo(index:int, polygonName:String,
duration:int, motion:Boolean):Array {
var result:Array = new Array(duration);
if(duration < 2){
motion = false;
}
if(index > -1){
var t:Number = 1 / duration;
for(var i:int = 0; i < duration; i++){
var frameInfoData:FrameInfoData = new FrameInfoData();
frameInfoData.index = index;
frameInfoData.polygonName = polygonName;
frameInfoData.motion = motion;
frameInfoData.t = motion ? t * i : 0;
result[i] = frameInfoData;
}
}
return result;
}
//} endregion PRIVATE\PROTECTED METHODS ========================================
//==============================================================================
//{region EVENTS HANDLERS
//} endregion EVENTS HANDLERS ==================================================
//==============================================================================
//{region GETTERS/SETTERS
//} endregion GETTERS/SETTERS ==================================================
}
}
class Layer{
public var matrixList:Array;
public var framesList:Array;
public function Layer() {
this.framesList = [];
this.matrixList = [];
}
}
class FrameInfoData{
public var polygonName:String;
public var motion:Boolean;
public var index:int;
public var t:Number;
}
|
Fix bounds scaling
|
Fix bounds scaling
|
ActionScript
|
mit
|
MerlinDS/miracle_tool
|
66f76eb954dd7fb4a0d9b92c099a53aa6ef6519a
|
ImpetusSound.as
|
ImpetusSound.as
|
package
{
import flash.media.Sound;
import flash.net.URLRequest;
public class ImpetusSound
{
private var sound:Sound;
private var channels:Vector.<ImpetusChannel>;
public function ImpetusSound(url:String):void
{
this.sound = new Sound();
this.channels = new Vector.<ImpetusChannel>;
this.sound.load(new URLRequest(url));
}
public function playNew():ImpetusChannel
{
var c:ImpetusChannel = new ImpetusChannel(this.sound.play(0));
channels.push(c);
return c;
}
public function stopAll():void
{
var len:int = this.channels.length;
for(var i:int; i < len; i++)
{
this.channels[i].stop();
}
}
}
}
|
package
{
import flash.media.Sound;
import flash.net.URLRequest;
public class ImpetusSound
{
private var url:String;
private var sound:Sound;
private var channels:Vector.<ImpetusChannel>;
public function ImpetusSound(url:String):void
{
this.url = url;
this.sound = new Sound();
this.channels = new Vector.<ImpetusChannel>;
this.sound.load(new URLRequest(url));
}
public function get getUrl():String
{
return this.url
}
public function playNew():ImpetusChannel
{
var c:ImpetusChannel = new ImpetusChannel(this.sound.play(0));
channels.push(c);
return c;
}
public function stopAll():void
{
var len:int = this.channels.length;
for(var i:int; i < len; i++)
{
this.channels[i].stop();
}
}
}
}
|
Store url & add getUrl() getter
|
Store url & add getUrl() getter
|
ActionScript
|
mit
|
Julow/Impetus
|
3748776a63b9971a7c6fd53d02ef060aa3947807
|
frameworks/projects/framework/src/FrameworkClasses.as
|
frameworks/projects/framework/src/FrameworkClasses.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
{
/**
* @private
* This class is used to link additional classes into framework.swc
* beyond those that are found by dependecy analysis starting
* from the classes specified in manifest.xml.
* For example, Button does not have a reference to ButtonSkin,
* but ButtonSkin needs to be in framework.swc along with Button.
*/
internal class FrameworkClasses
{
import mx.binding.ArrayElementWatcher; ArrayElementWatcher;
import mx.binding.BindabilityInfo; BindabilityInfo;
import mx.binding.EvalBindingResponder; EvalBindingResponder;
import mx.binding.FunctionReturnWatcher; FunctionReturnWatcher;
import mx.binding.IBindingClient; IBindingClient;
import mx.binding.IWatcherSetupUtil; IWatcherSetupUtil;
import mx.binding.IWatcherSetupUtil2; IWatcherSetupUtil2;
import mx.binding.PropertyWatcher; PropertyWatcher;
import mx.binding.RepeatableBinding; RepeatableBinding;
import mx.binding.RepeaterComponentWatcher; RepeaterComponentWatcher;
import mx.binding.RepeaterItemWatcher; RepeaterItemWatcher;
import mx.binding.StaticPropertyWatcher; StaticPropertyWatcher;
import mx.binding.XMLWatcher; XMLWatcher;
import mx.binding.utils.BindingUtils; BindingUtils;
import mx.binding.utils.ChangeWatcher; ChangeWatcher;
import mx.collections.ItemWrapper; ItemWrapper;
import mx.containers.errors.ConstraintError; ConstraintError;
import mx.containers.utilityClasses.Flex; Flex;
import mx.collections.ModifiedCollectionView; ModifiedCollectionView;
import mx.containers.utilityClasses.FlexChildInfo; FlexChildInfo;
import mx.containers.utilityClasses.IConstraintLayout; IConstraintLayout;
import mx.containers.utilityClasses.PostScaleAdapter; PostScaleAdapter;
import mx.controls.ButtonLabelPlacement; ButtonLabelPlacement;
import mx.controls.MovieClipSWFLoader; MovieClipSWFLoader;
import mx.controls.ProgressBarDirection; ProgressBarDirection;
import mx.controls.ProgressBarLabelPlacement; ProgressBarLabelPlacement;
import mx.controls.ProgressBarMode; ProgressBarMode;
import mx.controls.colorPickerClasses.WebSafePalette; WebSafePalette;
import mx.controls.menuClasses.IMenuDataDescriptor; IMenuDataDescriptor;
import mx.controls.listClasses.IDropInListItemRenderer; IDropInListItemRenderer;
import mx.controls.listClasses.IListItemRenderer; IListItemRenderer;
import mx.core.BitmapAsset; BitmapAsset;
import mx.core.ButtonAsset; ButtonAsset;
import mx.core.ByteArrayAsset; ByteArrayAsset;
import mx.core.ClassFactory; ClassFactory;
import mx.core.ContainerGlobals; ContainerGlobals;
import mx.core.ContextualClassFactory; ContextualClassFactory;
import mx.core.CrossDomainRSLItem; CrossDomainRSLItem;
import mx.core.DebuggableWorker; DebuggableWorker;
import mx.core.DeferredInstanceFromClass; DeferredInstanceFromClass;
import mx.core.DeferredInstanceFromFunction; DeferredInstanceFromFunction;
import mx.core.DesignLayer; DesignLayer;
import mx.core.EmbeddedFontRegistry; EmbeddedFontRegistry;
import mx.core.FlexLoader; FlexLoader;
import mx.core.FontAsset; FontAsset;
import mx.core.IDataRenderer; IDataRenderer;
import mx.core.IDeferredInstance; IDeferredInstance;
import mx.core.INavigatorContent; INavigatorContent;
import mx.core.ISelectableList; ISelectableList;
import mx.core.ISystemCursorClient; ISystemCursorClient;
import mx.core.ITextInput; ITextInput;
import mx.core.InteractionMode; InteractionMode;
import mx.core.IUID; IUID;
import mx.core.MovieClipAsset; MovieClipAsset;
import mx.core.MovieClipLoaderAsset; MovieClipLoaderAsset;
import mx.core.MXMLObjectAdapter; MXMLObjectAdapter;
import mx.core.ScrollPolicy; ScrollPolicy;
import mx.core.SimpleApplication; SimpleApplication;
import mx.core.SoundAsset; SoundAsset;
import mx.core.TextFieldAsset; TextFieldAsset;
import mx.core.TextFieldFactory; TextFieldFactory;
import mx.effects.easing.Back; Back;
import mx.effects.easing.Bounce; Bounce;
import mx.effects.easing.Circular; Circular;
import mx.effects.easing.Elastic; Elastic;
import mx.effects.easing.Exponential; Exponential;
import mx.events.CloseEvent; CloseEvent;
import mx.events.DropdownEvent; DropdownEvent;
import mx.events.IndexChangedEvent; IndexChangedEvent;
import mx.events.ItemClickEvent; ItemClickEvent;
import mx.events.ModuleEvent; ModuleEvent;
import mx.events.TouchInteractionEvent; TouchInteractionEvent;
import mx.events.TouchInteractionReason; TouchInteractionReason;
import mx.filters.BaseFilter; BaseFilter;
import mx.filters.BaseDimensionFilter; BaseDimensionFilter;
import mx.filters.IBitmapFilter; IBitmapFilter;
import mx.formatters.IFormatter; IFormatter;
import mx.graphics.ImageSnapshot; ImageSnapshot;
import mx.graphics.codec.PNGEncoder; PNGEncoder;
import mx.graphics.codec.JPEGEncoder; JPEGEncoder;
import mx.graphics.shaderClasses.ColorBurnShader; ColorBurnShader;
import mx.graphics.shaderClasses.ColorDodgeShader; ColorDodgeShader;
import mx.graphics.shaderClasses.ColorShader; ColorShader;
import mx.graphics.shaderClasses.ExclusionShader; ExclusionShader;
import mx.graphics.shaderClasses.HueShader; HueShader;
import mx.graphics.shaderClasses.LuminosityShader; LuminosityShader;
import mx.graphics.shaderClasses.LuminosityMaskShader; LuminosityMaskShader;
import mx.graphics.shaderClasses.SaturationShader; SaturationShader;
import mx.graphics.shaderClasses.SoftLightShader; SoftLightShader;
import mx.logging.ILogger; ILogger;
import mx.logging.Log; Log;
import mx.logging.targets.TraceTarget; TraceTarget;
import mx.managers.DragManager; DragManager;
import mx.managers.HistoryManager; HistoryManager;
import mx.managers.IHistoryManagerClient; IHistoryManagerClient;
import mx.managers.marshalClasses.CursorManagerMarshalMixin; CursorManagerMarshalMixin;
import mx.managers.marshalClasses.DragManagerMarshalMixin; DragManagerMarshalMixin;
import mx.managers.marshalClasses.FocusManagerMarshalMixin; FocusManagerMarshalMixin;
import mx.managers.marshalClasses.PopUpManagerMarshalMixin; PopUpManagerMarshalMixin;
import mx.managers.marshalClasses.ToolTipManagerMarshalMixin; ToolTipManagerMarshalMixin;
import mx.managers.PopUpManager; PopUpManager;
import mx.managers.systemClasses.ActiveWindowManager; ActiveWindowManager;
import mx.managers.systemClasses.ChildManager; ChildManager;
import mx.managers.systemClasses.MarshallingSupport; MarshallingSupport;
import mx.messaging.config.LoaderConfig; LoaderConfig;
import mx.modules.IModuleInfo; IModuleInfo;
import mx.modules.ModuleBase; ModuleBase;
import mx.modules.ModuleManager; ModuleManager;
import mx.preloaders.DownloadProgressBar; DownloadProgressBar;
import mx.preloaders.SparkDownloadProgressBar; SparkDownloadProgressBar;
import mx.printing.FlexPrintJob; FlexPrintJob;
import mx.resources.Locale; Locale;
import mx.rpc.IResponder; IResponder;
import mx.skins.Border; Border;
import mx.skins.halo.BrokenImageBorderSkin; BrokenImageBorderSkin;
import mx.skins.halo.BusyCursor; BusyCursor;
import mx.skins.halo.DefaultDragImage; DefaultDragImage;
import mx.skins.halo.HaloFocusRect; HaloFocusRect;
import mx.skins.halo.ListDropIndicator; ListDropIndicator;
import mx.skins.halo.ToolTipBorder; ToolTipBorder;
import mx.skins.ProgrammaticSkin; ProgrammaticSkin;
import mx.skins.RectangularBorder; RectangularBorder;
import mx.styles.IStyleModule; IStyleModule;
import mx.styles.AdvancedStyleClient; AdvancedStyleClient;
import mx.utils.ArrayUtil; ArrayUtil;
import mx.utils.Base64Decoder; Base64Decoder;
import mx.utils.Base64Encoder; Base64Encoder;
import mx.utils.BitFlagUtil; BitFlagUtil;
import mx.utils.DescribeTypeCache; DescribeTypeCache;
import mx.utils.DescribeTypeCacheRecord; DescribeTypeCacheRecord;
import mx.utils.DisplayUtil; DisplayUtil;
import mx.utils.GetTimerUtil; GetTimerUtil;
import mx.utils.HSBColor; HSBColor;
import mx.utils.LinkedList; LinkedList;
import mx.utils.LinkedListNode; LinkedListNode;
import mx.utils.OnDemandEventDispatcher; OnDemandEventDispatcher;
import mx.utils.OrderedObject; OrderedObject;
import mx.utils.PopUpUtil; PopUpUtil;
import mx.utils.XMLUtil; XMLUtil;
import mx.validators.Validator; Validator;
// Maintain alphabetical order
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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
{
/**
* @private
* This class is used to link additional classes into framework.swc
* beyond those that are found by dependecy analysis starting
* from the classes specified in manifest.xml.
* For example, Button does not have a reference to ButtonSkin,
* but ButtonSkin needs to be in framework.swc along with Button.
*/
internal class FrameworkClasses
{
import mx.binding.ArrayElementWatcher; ArrayElementWatcher;
import mx.binding.BindabilityInfo; BindabilityInfo;
import mx.binding.EvalBindingResponder; EvalBindingResponder;
import mx.binding.FunctionReturnWatcher; FunctionReturnWatcher;
import mx.binding.IBindingClient; IBindingClient;
import mx.binding.IWatcherSetupUtil; IWatcherSetupUtil;
import mx.binding.IWatcherSetupUtil2; IWatcherSetupUtil2;
import mx.binding.PropertyWatcher; PropertyWatcher;
import mx.binding.RepeatableBinding; RepeatableBinding;
import mx.binding.RepeaterComponentWatcher; RepeaterComponentWatcher;
import mx.binding.RepeaterItemWatcher; RepeaterItemWatcher;
import mx.binding.StaticPropertyWatcher; StaticPropertyWatcher;
import mx.binding.XMLWatcher; XMLWatcher;
import mx.binding.utils.BindingUtils; BindingUtils;
import mx.binding.utils.ChangeWatcher; ChangeWatcher;
import mx.collections.ItemWrapper; ItemWrapper;
import mx.containers.errors.ConstraintError; ConstraintError;
import mx.containers.utilityClasses.Flex; Flex;
import mx.collections.ModifiedCollectionView; ModifiedCollectionView;
import mx.containers.utilityClasses.FlexChildInfo; FlexChildInfo;
import mx.containers.utilityClasses.IConstraintLayout; IConstraintLayout;
import mx.containers.utilityClasses.PostScaleAdapter; PostScaleAdapter;
import mx.controls.ButtonLabelPlacement; ButtonLabelPlacement;
import mx.controls.MovieClipSWFLoader; MovieClipSWFLoader;
import mx.controls.ProgressBarDirection; ProgressBarDirection;
import mx.controls.ProgressBarLabelPlacement; ProgressBarLabelPlacement;
import mx.controls.ProgressBarMode; ProgressBarMode;
import mx.controls.colorPickerClasses.WebSafePalette; WebSafePalette;
import mx.controls.menuClasses.IMenuDataDescriptor; IMenuDataDescriptor;
import mx.controls.listClasses.IDropInListItemRenderer; IDropInListItemRenderer;
import mx.controls.listClasses.IListItemRenderer; IListItemRenderer;
import mx.core.BitmapAsset; BitmapAsset;
import mx.core.ButtonAsset; ButtonAsset;
import mx.core.ByteArrayAsset; ByteArrayAsset;
import mx.core.ClassFactory; ClassFactory;
import mx.core.ContainerGlobals; ContainerGlobals;
import mx.core.ContextualClassFactory; ContextualClassFactory;
import mx.core.CrossDomainRSLItem; CrossDomainRSLItem;
import mx.core.DebuggableWorker; DebuggableWorker;
import mx.core.DeferredInstanceFromClass; DeferredInstanceFromClass;
import mx.core.DeferredInstanceFromFunction; DeferredInstanceFromFunction;
import mx.core.DesignLayer; DesignLayer;
import mx.core.EmbeddedFontRegistry; EmbeddedFontRegistry;
import mx.core.FlexLoader; FlexLoader;
import mx.core.FontAsset; FontAsset;
import mx.core.IDataRenderer; IDataRenderer;
import mx.core.IDeferredInstance; IDeferredInstance;
import mx.core.INavigatorContent; INavigatorContent;
import mx.core.ISelectableList; ISelectableList;
import mx.core.ISystemCursorClient; ISystemCursorClient;
import mx.core.ITextInput; ITextInput;
import mx.core.InteractionMode; InteractionMode;
import mx.core.IUID; IUID;
import mx.core.MovieClipAsset; MovieClipAsset;
import mx.core.MovieClipLoaderAsset; MovieClipLoaderAsset;
import mx.core.MXMLObjectAdapter; MXMLObjectAdapter;
import mx.core.ScrollPolicy; ScrollPolicy;
import mx.core.SimpleApplication; SimpleApplication;
import mx.core.SoundAsset; SoundAsset;
import mx.core.TextFieldAsset; TextFieldAsset;
import mx.core.TextFieldFactory; TextFieldFactory;
import mx.effects.easing.Back; Back;
import mx.effects.easing.Bounce; Bounce;
import mx.effects.easing.Circular; Circular;
import mx.effects.easing.Elastic; Elastic;
import mx.effects.easing.Exponential; Exponential;
import mx.events.CloseEvent; CloseEvent;
import mx.events.DropdownEvent; DropdownEvent;
import mx.events.IndexChangedEvent; IndexChangedEvent;
import mx.events.ItemClickEvent; ItemClickEvent;
import mx.events.ModuleEvent; ModuleEvent;
import mx.events.TouchInteractionEvent; TouchInteractionEvent;
import mx.events.TouchInteractionReason; TouchInteractionReason;
import mx.filters.BaseFilter; BaseFilter;
import mx.filters.BaseDimensionFilter; BaseDimensionFilter;
import mx.filters.IBitmapFilter; IBitmapFilter;
import mx.formatters.IFormatter; IFormatter;
import mx.graphics.ImageSnapshot; ImageSnapshot;
import mx.graphics.codec.PNGEncoder; PNGEncoder;
import mx.graphics.codec.JPEGEncoder; JPEGEncoder;
import mx.graphics.shaderClasses.ColorBurnShader; ColorBurnShader;
import mx.graphics.shaderClasses.ColorDodgeShader; ColorDodgeShader;
import mx.graphics.shaderClasses.ColorShader; ColorShader;
import mx.graphics.shaderClasses.ExclusionShader; ExclusionShader;
import mx.graphics.shaderClasses.HueShader; HueShader;
import mx.graphics.shaderClasses.LuminosityShader; LuminosityShader;
import mx.graphics.shaderClasses.LuminosityMaskShader; LuminosityMaskShader;
import mx.graphics.shaderClasses.SaturationShader; SaturationShader;
import mx.graphics.shaderClasses.SoftLightShader; SoftLightShader;
import mx.logging.ILogger; ILogger;
import mx.logging.Log; Log;
import mx.logging.targets.TraceTarget; TraceTarget;
import mx.managers.DragManager; DragManager;
import mx.managers.HistoryManager; HistoryManager;
import mx.managers.IHistoryManagerClient; IHistoryManagerClient;
import mx.managers.marshalClasses.CursorManagerMarshalMixin; CursorManagerMarshalMixin;
import mx.managers.marshalClasses.DragManagerMarshalMixin; DragManagerMarshalMixin;
import mx.managers.marshalClasses.FocusManagerMarshalMixin; FocusManagerMarshalMixin;
import mx.managers.marshalClasses.PopUpManagerMarshalMixin; PopUpManagerMarshalMixin;
import mx.managers.marshalClasses.ToolTipManagerMarshalMixin; ToolTipManagerMarshalMixin;
import mx.managers.PopUpManager; PopUpManager;
import mx.managers.systemClasses.ActiveWindowManager; ActiveWindowManager;
import mx.managers.systemClasses.ChildManager; ChildManager;
import mx.managers.systemClasses.MarshallingSupport; MarshallingSupport;
import mx.messaging.config.LoaderConfig; LoaderConfig;
import mx.modules.IModuleInfo; IModuleInfo;
import mx.modules.ModuleBase; ModuleBase;
import mx.modules.ModuleManager; ModuleManager;
import mx.preloaders.DownloadProgressBar; DownloadProgressBar;
import mx.preloaders.SparkDownloadProgressBar; SparkDownloadProgressBar;
import mx.printing.FlexPrintJob; FlexPrintJob;
import mx.resources.Locale; Locale;
import mx.rpc.IResponder; IResponder;
import mx.skins.Border; Border;
import mx.skins.halo.BrokenImageBorderSkin; BrokenImageBorderSkin;
import mx.skins.halo.BusyCursor; BusyCursor;
import mx.skins.halo.DefaultDragImage; DefaultDragImage;
import mx.skins.halo.HaloFocusRect; HaloFocusRect;
import mx.skins.halo.ListDropIndicator; ListDropIndicator;
import mx.skins.halo.ToolTipBorder; ToolTipBorder;
import mx.skins.ProgrammaticSkin; ProgrammaticSkin;
import mx.skins.RectangularBorder; RectangularBorder;
import mx.styles.IStyleModule; IStyleModule;
import mx.styles.AdvancedStyleClient; AdvancedStyleClient;
import mx.utils.ArrayUtil; ArrayUtil;
import mx.utils.AndroidPlatformVersionOverride; AndroidPlatformVersionOverride;
import mx.utils.Base64Decoder; Base64Decoder;
import mx.utils.Base64Encoder; Base64Encoder;
import mx.utils.BitFlagUtil; BitFlagUtil;
import mx.utils.DescribeTypeCache; DescribeTypeCache;
import mx.utils.DescribeTypeCacheRecord; DescribeTypeCacheRecord;
import mx.utils.DisplayUtil; DisplayUtil;
import mx.utils.GetTimerUtil; GetTimerUtil;
import mx.utils.HSBColor; HSBColor;
import mx.utils.LinkedList; LinkedList;
import mx.utils.LinkedListNode; LinkedListNode;
import mx.utils.OnDemandEventDispatcher; OnDemandEventDispatcher;
import mx.utils.OrderedObject; OrderedObject;
import mx.utils.PopUpUtil; PopUpUtil;
import mx.utils.XMLUtil; XMLUtil;
import mx.validators.Validator; Validator;
// Maintain alphabetical order
}
}
|
Add AndroidPlatformVersionOverride to FrameworkClasses
|
Add AndroidPlatformVersionOverride to FrameworkClasses
|
ActionScript
|
apache-2.0
|
apache/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,shyamalschandra/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk
|
1a83e200b33d172818bc0c3eb52da1b52ec2adf9
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/binding/SimpleBinding.as
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/binding/SimpleBinding.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.binding
{
import flash.events.IEventDispatcher;
import flash.events.Event;
import org.apache.flex.core.IBead;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IDocument;
/**
* The SimpleBinding class is lightweight data-binding class that
* is optimized for simple assignments of one object's property to
* another object's property.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class SimpleBinding implements IBead, IDocument
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function SimpleBinding()
{
}
/**
* The source object that dispatches an event
* when the property changes
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
protected var source:IEventDispatcher;
/**
* The host mxml document for the source and
* destination objects. The source object
* is either this document for simple bindings
* like {foo} where foo is a property on
* the mxml documnet, or found as document[sourceID]
* for simple bindings like {someid.someproperty}
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
protected var document:Object;
/**
* The destination object. It is always the same
* as the strand. SimpleBindings are attached to
* the strand of the destination object.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var destination:Object;
/**
* If not null, the id of the mxml tag who's property
* is being watched for changes.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var sourceID:String;
/**
* If not null, the name of a property on the
* mxml document that is being watched for changes.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var sourcePropertyName:String;
/**
* The event name that is dispatched when the source
* property changes.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var eventName:String;
/**
* The name of the property on the strand that
* is set when the source property changes.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var destinationPropertyName:String;
/**
* @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
{
if (destination == null)
destination = value;
if (sourceID != null)
source = document[sourceID] as IEventDispatcher;
else
source = document as IEventDispatcher;
source.addEventListener(eventName, changeHandler);
destination[destinationPropertyName] = source[sourcePropertyName];
}
/**
* @copy org.apache.flex.core.IDocument#setDocument()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function setDocument(document:Object, id:String = null):void
{
this.document = document;
}
private function changeHandler(event:Event):void
{
destination[destinationPropertyName] = source[sourcePropertyName];
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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.binding
{
import flash.events.IEventDispatcher;
import flash.events.Event;
import org.apache.flex.core.IBead;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IDocument;
import org.apache.flex.events.ValueChangeEvent;
/**
* The SimpleBinding class is lightweight data-binding class that
* is optimized for simple assignments of one object's property to
* another object's property.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class SimpleBinding implements IBead, IDocument
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function SimpleBinding()
{
}
/**
* The source object that dispatches an event
* when the property changes
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
protected var source:IEventDispatcher;
/**
* The host mxml document for the source and
* destination objects. The source object
* is either this document for simple bindings
* like {foo} where foo is a property on
* the mxml documnet, or found as document[sourceID]
* for simple bindings like {someid.someproperty}
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
protected var document:Object;
/**
* The destination object. It is always the same
* as the strand. SimpleBindings are attached to
* the strand of the destination object.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var destination:Object;
/**
* If not null, the id of the mxml tag who's property
* is being watched for changes.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var sourceID:String;
/**
* If not null, the name of a property on the
* mxml document that is being watched for changes.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var sourcePropertyName:String;
/**
* The event name that is dispatched when the source
* property changes.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var eventName:String;
/**
* The name of the property on the strand that
* is set when the source property changes.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var destinationPropertyName:String;
/**
* @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
{
if (destination == null)
destination = value;
if (sourceID != null)
{
source = document[sourceID] as IEventDispatcher;
if (source == null)
{
document.addEventListener("valueChange",
sourceChangeHandler);
return;
}
}
else
source = document as IEventDispatcher;
source.addEventListener(eventName, changeHandler);
destination[destinationPropertyName] = source[sourcePropertyName];
}
/**
* @copy org.apache.flex.core.IDocument#setDocument()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function setDocument(document:Object, id:String = null):void
{
this.document = document;
}
private function changeHandler(event:Event):void
{
destination[destinationPropertyName] = source[sourcePropertyName];
}
private function sourceChangeHandler(event:ValueChangeEvent):void
{
if (event.propertyName != sourceID)
return;
if (source)
source.removeEventListener(eventName, changeHandler);
source = document[sourceID] as IEventDispatcher;
if (source)
{
source.addEventListener(eventName, changeHandler);
destination[destinationPropertyName] = source[sourcePropertyName];
}
}
}
}
|
handle source changes
|
handle source changes
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
41696bbe046754faeed4851130459fb9b806574e
|
krew-framework/krewfw/core/KrewTransition.as
|
krew-framework/krewfw/core/KrewTransition.as
|
package krewfw.core {
import starling.animation.Transitions;
/**
* Expand tween transition functions of Starling.
*/
//------------------------------------------------------------
public class KrewTransition {
// Already exists in starling
public static const EASE_IN_QUAD :String = "krew.easeInQuad"; // quadratic
public static const EASE_OUT_QUAD:String = "krew.easeOutQuad";
//------------------------------------------------------------
public static function registerExtendedTransitions():void {
Transitions.register(EASE_IN_QUAD, _easeInQuad);
Transitions.register(EASE_OUT_QUAD, _easeOutQuad);
}
private static function _easeInQuad(ratio:Number):Number {
return ratio * ratio;
}
private static function _easeOutQuad(ratio:Number):Number {
var invRatio:Number = ratio - 1.0;
return (-invRatio * invRatio) + 1;
}
}
}
|
package krewfw.core {
import starling.animation.Transitions;
/**
* Expand tween transition functions of Starling.
*/
//------------------------------------------------------------
public class KrewTransition {
// Already exists in starling
public static const EASE_IN_QUAD :String = "krew.easeInQuad"; // quadratic
public static const EASE_OUT_QUAD:String = "krew.easeOutQuad";
public static const SWING :String = "krew.swing";
//------------------------------------------------------------
public static function registerExtendedTransitions():void {
Transitions.register(EASE_IN_QUAD, _easeInQuad);
Transitions.register(EASE_OUT_QUAD, _easeOutQuad);
Transitions.register(SWING, _swing);
}
private static function _easeInQuad(ratio:Number):Number {
return ratio * ratio;
}
private static function _easeOutQuad(ratio:Number):Number {
var invRatio:Number = ratio - 1.0;
return (-invRatio * invRatio) + 1;
}
private static function _swing(ratio:Number):Number {
var swing:Number = 1 + (Math.sin(ratio * 8 * Math.PI) * (1 - ratio));
if (ratio < 0.3) {
var initInvRatio:Number = (ratio / 0.3) - 1.0;
var initEaseOut:Number = (-initInvRatio * initInvRatio) + 1;
swing *= initEaseOut;
}
return swing;
}
}
}
|
Add transition
|
Add transition
|
ActionScript
|
mit
|
tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework
|
560ad62c0e09575f26cf9d534c5acd9c3d019642
|
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.type.Signal;
public final class AssetsLibrary
{
private var _numGeometries : uint = 0;
private var _numMaterials : uint = 0;
private var _numTextures : 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 _geometries : Object;
private var _textures : Object;
private var _materials : Object;
private var _layers : Vector.<String>;
private var _nameToLayer : Object;
private var _geometryAdded : Signal;
private var _textureAdded : Signal;
private var _materialAdded : Signal;
private var _layerAdded : Signal;
public function AssetsLibrary()
{
initialize();
initializeSignals();
}
public function get numTextures() : uint
{
return _numTextures;
}
public function get numGeometries() : uint
{
return _numGeometries;
}
public function get numMaterials() : uint
{
return _numMaterials;
}
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 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 = {};
_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');
}
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 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 _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;
}
}
}
|
Add symbols
|
Add symbols
|
ActionScript
|
mit
|
aerys/minko-as3
|
0c2ace6f9a84a3df75b40efd193cb2c98030b3d6
|
OSMF/org/osmf/net/httpstreaming/flv/FLVTag.as
|
OSMF/org/osmf/net/httpstreaming/flv/FLVTag.as
|
/*****************************************************
*
* Copyright 2009 Adobe Systems Incorporated. All Rights Reserved.
*
*****************************************************
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
*
* The Initial Developer of the Original Code is Adobe Systems Incorporated.
* Portions created by Adobe Systems Incorporated are Copyright (C) 2009 Adobe Systems
* Incorporated. All Rights Reserved.
*
*****************************************************/
package org.osmf.net.httpstreaming.flv
{
import flash.utils.ByteArray;
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
[ExcludeClass]
/**
* @private
*/
public class FLVTag
{
// arguably these should move to their own class...
public static const TAG_TYPE_AUDIO:int = 8;
public static const TAG_TYPE_VIDEO:int = 9;
public static const TAG_TYPE_SCRIPTDATAOBJECT:int = 18;
// TODO: Do we call this "filtered" or "encrypted" or "DRM" or "protected"?
public static const TAG_FLAG_ENCRYPTED:int = 0x20;
public static const TAG_TYPE_ENCRYPTED_AUDIO:int = TAG_TYPE_AUDIO + TAG_FLAG_ENCRYPTED;
public static const TAG_TYPE_ENCRYPTED_VIDEO:int = TAG_TYPE_VIDEO + TAG_FLAG_ENCRYPTED;
public static const TAG_TYPE_ENCRYPTED_SCRIPTDATAOBJECT:int = TAG_TYPE_SCRIPTDATAOBJECT + TAG_FLAG_ENCRYPTED;
// but these are good here...
public static const TAG_HEADER_BYTE_COUNT:int = 11;
public static const PREV_TAG_BYTE_COUNT:int = 4;
public function FLVTag(type:int)
{
super();
bytes = new ByteArray();
bytes.length = TAG_HEADER_BYTE_COUNT;
bytes[0] = type;
}
public function read(input:IDataInput):void
{
// Reads a complete Tag, overwriting type.
readType(input);
readRemainingHeader(input);
readData(input);
readPrevTag(input);
}
public function readType(input:IDataInput):void
{
if (input.bytesAvailable < 1)
{
throw new Error("FLVTag.readType() input too short");
}
input.readBytes(bytes, 0, 1); // just the type field, 1 byte
}
public function readRemaining(input:IDataInput):void
{
// Note that the TYPE must have already been read in order to
// construct us.
readRemainingHeader(input);
readData(input);
readPrevTag(input);
}
public function readRemainingHeader(input:IDataInput):void
{
if (input.bytesAvailable < 10)
{
throw new Error("FLVTag.readHeader() input too short");
}
input.readBytes(bytes, 1, TAG_HEADER_BYTE_COUNT - 1); // skipping type field at first byte
}
public function readData(input:IDataInput):void
{
if (dataSize > 0)
{
if (input.bytesAvailable < dataSize)
{
throw new Error("FLVTag().readData input shorter than dataSize");
}
input.readBytes(bytes, TAG_HEADER_BYTE_COUNT, dataSize); // starting immediately after header, for computed size
}
}
public function readPrevTag(input:IDataInput):void
{
if (input.bytesAvailable < 4)
{
throw new Error("FLVTag.readPrevTag() input too short");
}
input.readUnsignedInt(); // discard, because we can regenerate and we also don't care if value is correct
}
public function write(output:IDataOutput):void
{
output.writeBytes(bytes, 0, TAG_HEADER_BYTE_COUNT + dataSize);
output.writeUnsignedInt(TAG_HEADER_BYTE_COUNT + dataSize); // correct prevTagSize, even though many things don't care
}
public function get tagType():uint
{
return bytes[0];
}
public function set tagType(value:uint):void
{
bytes[0] = value;
}
public function get isEncrpted():Boolean
{
return((bytes[0] & TAG_FLAG_ENCRYPTED) ? true : false);
}
public function get dataSize():uint
{
return (bytes[1] << 16) | (bytes[2] << 8) | (bytes[3]);
}
public function set dataSize(value:uint):void
{
bytes[1] = (value >> 16) & 0xff;
bytes[2] = (value >> 8) & 0xff;
bytes[3] = (value) & 0xff;
bytes.length = TAG_HEADER_BYTE_COUNT + value; // truncate/grow as necessary
}
public function get timestamp():uint
{
// noting the unusual order
return (bytes[7] << 24) | (bytes[4] << 16) | (bytes[5] << 8) | (bytes[6]);
}
private var _cachedTimestamp:Number = -1;
public function get cachedTimestamp():uint
{
if(_cachedTimestamp == -1)
_cachedTimestamp = timestamp;
return _cachedTimestamp;
}
public function set timestamp(value:uint):void
{
bytes[7] = (value >> 24) & 0xff; // extended byte in unusual location
bytes[4] = (value >> 16) & 0xff;
bytes[5] = (value >> 8) & 0xff;
bytes[6] = (value) & 0xff;
_cachedTimestamp = -1;
}
public function get data():ByteArray
{
var data:ByteArray = new ByteArray();
data.writeBytes(bytes, TAG_HEADER_BYTE_COUNT, dataSize);
return data;
}
public function set data(value:ByteArray):void
{
_cachedTimestamp = -1;
bytes.length = TAG_HEADER_BYTE_COUNT + value.length; // resize first
bytes.position = TAG_HEADER_BYTE_COUNT;
bytes.writeBytes(value, 0, value.length); // copy in
dataSize = value.length; // set dataSize field to new payload length
}
protected var bytes:ByteArray = null;
}
}
|
/*****************************************************
*
* Copyright 2009 Adobe Systems Incorporated. All Rights Reserved.
*
*****************************************************
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
*
* The Initial Developer of the Original Code is Adobe Systems Incorporated.
* Portions created by Adobe Systems Incorporated are Copyright (C) 2009 Adobe Systems
* Incorporated. All Rights Reserved.
*
*****************************************************/
package org.osmf.net.httpstreaming.flv
{
import flash.utils.ByteArray;
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
[ExcludeClass]
/**
* @private
*/
public class FLVTag
{
// arguably these should move to their own class...
public static const TAG_TYPE_AUDIO:int = 8;
public static const TAG_TYPE_VIDEO:int = 9;
public static const TAG_TYPE_SCRIPTDATAOBJECT:int = 18;
// TODO: Do we call this "filtered" or "encrypted" or "DRM" or "protected"?
public static const TAG_FLAG_ENCRYPTED:int = 0x20;
public static const TAG_TYPE_ENCRYPTED_AUDIO:int = TAG_TYPE_AUDIO + TAG_FLAG_ENCRYPTED;
public static const TAG_TYPE_ENCRYPTED_VIDEO:int = TAG_TYPE_VIDEO + TAG_FLAG_ENCRYPTED;
public static const TAG_TYPE_ENCRYPTED_SCRIPTDATAOBJECT:int = TAG_TYPE_SCRIPTDATAOBJECT + TAG_FLAG_ENCRYPTED;
// but these are good here...
public static const TAG_HEADER_BYTE_COUNT:int = 11;
public static const PREV_TAG_BYTE_COUNT:int = 4;
public function FLVTag(type:int)
{
super();
bytes = new ByteArray();
bytes.length = TAG_HEADER_BYTE_COUNT;
bytes[0] = type;
}
public function read(input:IDataInput):void
{
// Reads a complete Tag, overwriting type.
readType(input);
readRemainingHeader(input);
readData(input);
readPrevTag(input);
}
public function readType(input:IDataInput):void
{
if (input.bytesAvailable < 1)
{
throw new Error("FLVTag.readType() input too short");
}
input.readBytes(bytes, 0, 1); // just the type field, 1 byte
}
public function readRemaining(input:IDataInput):void
{
// Note that the TYPE must have already been read in order to
// construct us.
readRemainingHeader(input);
readData(input);
readPrevTag(input);
}
public function readRemainingHeader(input:IDataInput):void
{
if (input.bytesAvailable < 10)
{
throw new Error("FLVTag.readHeader() input too short");
}
input.readBytes(bytes, 1, TAG_HEADER_BYTE_COUNT - 1); // skipping type field at first byte
}
public function readData(input:IDataInput):void
{
if (dataSize > 0)
{
if (input.bytesAvailable < dataSize)
{
throw new Error("FLVTag().readData input shorter than dataSize");
}
input.readBytes(bytes, TAG_HEADER_BYTE_COUNT, dataSize); // starting immediately after header, for computed size
}
}
public function readPrevTag(input:IDataInput):void
{
if (input.bytesAvailable < 4)
{
throw new Error("FLVTag.readPrevTag() input too short");
}
input.readUnsignedInt(); // discard, because we can regenerate and we also don't care if value is correct
}
public function write(output:IDataOutput):void
{
output.writeBytes(bytes, 0, TAG_HEADER_BYTE_COUNT + dataSize);
output.writeUnsignedInt(TAG_HEADER_BYTE_COUNT + dataSize); // correct prevTagSize, even though many things don't care
}
public function get tagType():uint
{
return bytes[0];
}
public function set tagType(value:uint):void
{
bytes[0] = value;
}
public function get isEncrpted():Boolean
{
return((bytes[0] & TAG_FLAG_ENCRYPTED) ? true : false);
}
public function get dataSize():uint
{
return (bytes[1] << 16) | (bytes[2] << 8) | (bytes[3]);
}
public function set dataSize(value:uint):void
{
bytes[1] = (value >> 16) & 0xff;
bytes[2] = (value >> 8) & 0xff;
bytes[3] = (value) & 0xff;
bytes.length = TAG_HEADER_BYTE_COUNT + value; // truncate/grow as necessary
}
public function get timestamp():uint
{
// noting the unusual order
return (bytes[7] << 24) | (bytes[4] << 16) | (bytes[5] << 8) | (bytes[6]);
}
public function set timestamp(value:uint):void
{
bytes[7] = (value >> 24) & 0xff; // extended byte in unusual location
bytes[4] = (value >> 16) & 0xff;
bytes[5] = (value >> 8) & 0xff;
bytes[6] = (value) & 0xff;
}
public function get data():ByteArray
{
var data:ByteArray = new ByteArray();
data.writeBytes(bytes, TAG_HEADER_BYTE_COUNT, dataSize);
return data;
}
public function set data(value:ByteArray):void
{
bytes.length = TAG_HEADER_BYTE_COUNT + value.length; // resize first
bytes.position = TAG_HEADER_BYTE_COUNT;
bytes.writeBytes(value, 0, value.length); // copy in
dataSize = value.length; // set dataSize field to new payload length
}
protected var bytes:ByteArray = null;
}
}
|
Revert changes to OSMF.
|
Revert changes to OSMF.
|
ActionScript
|
agpl-3.0
|
kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF
|
1ea6a66ecb7ad8e75a8f4af407ef290a329b0249
|
WEB-INF/lps/lfc/kernel/swf9/LFCApplication.as
|
WEB-INF/lps/lfc/kernel/swf9/LFCApplication.as
|
/**
* LFCApplication.as
*
* @copyright Copyright 2007, 2008 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic Kernel
* @subtopic swf9
* @author Henry Minsky <[email protected]>
*/
public class LFCApplication extends Sprite {
// This serves as the superclass of DefaultApplication, currently that is where
// the compiler puts top level code to run.
#passthrough (toplevel:true) {
import flash.display.*;
import flash.events.*;
import flash.utils.*;
import flash.text.*;
import flash.system.*;
import flash.net.*;
import flash.ui.*;
import flash.text.Font;
}#
// Allow anyone access to the stage object (see ctor below)
public static var stage:Stage = null;
// Allow anyone access to write to the debugger
public static var write:Function;
public function LFCApplication () {
// Allow anyone to access the stage object
LFCApplication.stage = this.stage;
LFCApplication.write = this.write;
// trace("LFCApplication.stage = " + LFCApplication.stage);
// trace(" loaderInfo.loaderURL = " + LFCApplication.stage.loaderInfo.loaderURL);
var idleTimerPeriod = 14; // msecs
//trace('idle timer period = ', idleTimerPeriod , 'msecs');
LzIdleKernel.startTimer( idleTimerPeriod );
stage.addEventListener(KeyboardEvent.KEY_DOWN,reportKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP,reportKeyUp);
// necessary for consistent behavior - in netscape browsers HTML is ignored
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
//Stage.align = ('canvassalign' in global && global.canvassalign != null) ? global.canvassalign : "LT";
//Stage.scaleMode = ('canvasscale' in global && global.canvasscale != null) ? global.canvasscale : "noScale";
stage.addEventListener(Event.RESIZE, resizeHandler);
// Register for callbacks from the kernel
LzMouseKernel.setCallback(LzModeManager, 'rawMouseEvent');
/* TODO [hqm 2008-01] Do we want to do anything with other
* events, like click, or mousewheel ?
stage.addEventListener(MouseEvent.CLICK, reportClick);
stage.addEventListener(MouseEvent.MOUSE_WHEEL, reportWheel);
*/
LzKeyboardKernel.setCallback(LzKeys, '__keyEvent');
////////////////////////////////////////////////////////////////
// cheapo debug console
lzconsole = this;
var tfield:TextField = new TextField();
tfield.background = true;
tfield.backgroundColor = 0xcccccc;
tfield.x = 0;
tfield.y = 400;
tfield.wordWrap = true;
tfield.multiline = true;
tfield.width = 800;
tfield.height = 160;
tfield.border = true;
consoletext = tfield;
var ci:TextField = new TextField();
consoleinputtext = ci;
ci.background = true;
ci.backgroundColor = 0xffcccc;
ci.x = 0;
ci.y = 560;
ci.wordWrap = false;
ci.multiline = false;
ci.width = 800;
ci.height = 20;
ci.border = true;
ci.type = TextFieldType.INPUT;
ci.addEventListener(KeyboardEvent.KEY_DOWN, consoleInputHandler);
/* var allFonts:Array = Font.enumerateFonts(true);
allFonts.sortOn("fontName", Array.CASEINSENSITIVE);
var embeddedFonts:Array = Font.enumerateFonts(false);
embeddedFonts.sortOn("fontName", Array.CASEINSENSITIVE);
*/
var newFormat:TextFormat = new TextFormat();
newFormat.size = 11;
newFormat.font = "Verdana";
ci.defaultTextFormat = newFormat;
consoletext.defaultTextFormat = newFormat;
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
// Testing runtime code loading
////////////////////////////////////////////////////////////////
}
var debugloader:Loader;
// Debugger loader completion handler
function debugEvalListener (e:Event):void {
debugloader.unload();
//DebugExec(e.target.content).doit();
}
function consoleInputHandler (event:KeyboardEvent ){
if (event.charCode == Keyboard.ENTER) {
var expr = consoleinputtext.text;
write(expr);
consoleinputtext.text = "";
debugloader = new Loader();
debugloader.contentLoaderInfo.addEventListener(Event.INIT, debugEvalListener);
// Send EVAL request to LPS server
// It doesn't matter what path/filename we use, as long as it has ".lzx" suffix, so it is
// handled by the LPS. The lzt=eval causes the request to be served by the EVAL Responder.
var url = "hello.lzx?lzr=swf9&lz_load=false&lzt=eval&lz_script=" + encodeURIComponent(expr)+"&lzbc=" +(new Date()).getTime();
debugloader.load(new URLRequest(url),
new LoaderContext(false,
new ApplicationDomain(ApplicationDomain.currentDomain)));
}
}
////////////////////////////////////////////////////////////////
// A crude debugger output window for now
public var consoletext:TextField;
public var consoleinputtext:TextField;
public function write (...args) {
consoletext.appendText( "\n" + args.join(" "));
consoletext.scrollV = consoletext.maxScrollV;
}
////////////////////////////////////////////////////////////////
function reportWheel(event:MouseEvent):void {
/*
Debug.write(event.currentTarget.toString() +
" dispatches MouseWheelEvent. delta = " + event.delta); */
LzKeys.__mousewheelEvent(event.delta);
}
function resizeHandler(event:Event):void {
//trace('LFCApplication.resizeHandler stage width/height = ', stage.stageWidth, stage.stageHeight);
LzScreenKernel.handleResizeEvent();
}
function reportKeyUp(event:KeyboardEvent):void {
/*
trace("Key Released: " + String.fromCharCode(event.charCode) +
" (key code: " + event.keyCode + " character code: " +
event.charCode + ")");
*/
LzKeyboardKernel.__keyboardEvent(event.charCode, 'onkeyup');
}
function reportKeyDown(event:KeyboardEvent):void {
/*
trace("Key Pressed: " + String.fromCharCode(event.charCode) +
" (key code: " + event.keyCode + " character code: "
+ event.charCode + ")");
*/
LzKeyboardKernel.__keyboardEvent(event.charCode, 'onkeydown');
}
}
// Resource library
// contains {ptype, class, frames, width, height}
// ptype is one of "ar" (app relative) or "sr" (system relative)
var LzResourceLibrary = {};
var lzconsole;
|
/**
* LFCApplication.as
*
* @copyright Copyright 2007, 2008 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic Kernel
* @subtopic swf9
* @author Henry Minsky <[email protected]>
*/
public class LFCApplication extends Sprite {
// This serves as the superclass of DefaultApplication, currently that is where
// the compiler puts top level code to run.
#passthrough (toplevel:true) {
import flash.display.*;
import flash.events.*;
import flash.utils.*;
import flash.text.*;
import flash.system.*;
import flash.net.*;
import flash.ui.*;
import flash.text.Font;
}#
// Allow anyone access to the stage object (see ctor below)
public static var stage:Stage = null;
// Allow anyone access to write to the debugger
public static var write:Function;
public function LFCApplication () {
// Allow anyone to access the stage object
LFCApplication.stage = this.stage;
LFCApplication.write = this.write;
// trace("LFCApplication.stage = " + LFCApplication.stage);
// trace(" loaderInfo.loaderURL = " + LFCApplication.stage.loaderInfo.loaderURL);
var idleTimerPeriod = 14; // msecs
//trace('idle timer period = ', idleTimerPeriod , 'msecs');
LzIdleKernel.startTimer( idleTimerPeriod );
stage.addEventListener(KeyboardEvent.KEY_DOWN,reportKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP,reportKeyUp);
// necessary for consistent behavior - in netscape browsers HTML is ignored
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
//Stage.align = ('canvassalign' in global && global.canvassalign != null) ? global.canvassalign : "LT";
//Stage.scaleMode = ('canvasscale' in global && global.canvasscale != null) ? global.canvasscale : "noScale";
stage.addEventListener(Event.RESIZE, resizeHandler);
// Register for callbacks from the kernel
LzMouseKernel.setCallback(LzModeManager, 'rawMouseEvent');
/* TODO [hqm 2008-01] Do we want to do anything with other
* events, like click, or mousewheel ?
stage.addEventListener(MouseEvent.CLICK, reportClick);
stage.addEventListener(MouseEvent.MOUSE_WHEEL, reportWheel);
*/
LzKeyboardKernel.setCallback(LzKeys, '__keyEvent');
////////////////////////////////////////////////////////////////
// cheapo debug console
lzconsole = this;
var tfield:TextField = new TextField();
tfield.visible = false;
tfield.background = true;
tfield.backgroundColor = 0xcccccc;
tfield.x = 0;
tfield.y = 400;
tfield.wordWrap = true;
tfield.multiline = true;
tfield.width = 800;
tfield.height = 160;
tfield.border = true;
consoletext = tfield;
var ci:TextField = new TextField();
consoleinputtext = ci;
ci.visible = false;
ci.background = true;
ci.backgroundColor = 0xffcccc;
ci.x = 0;
ci.y = 560;
ci.wordWrap = false;
ci.multiline = false;
ci.width = 800;
ci.height = 20;
ci.border = true;
ci.type = TextFieldType.INPUT;
ci.addEventListener(KeyboardEvent.KEY_DOWN, consoleInputHandler);
/* var allFonts:Array = Font.enumerateFonts(true);
allFonts.sortOn("fontName", Array.CASEINSENSITIVE);
var embeddedFonts:Array = Font.enumerateFonts(false);
embeddedFonts.sortOn("fontName", Array.CASEINSENSITIVE);
*/
var newFormat:TextFormat = new TextFormat();
newFormat.size = 11;
newFormat.font = "Verdana";
ci.defaultTextFormat = newFormat;
consoletext.defaultTextFormat = newFormat;
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
// Testing runtime code loading
////////////////////////////////////////////////////////////////
}
var debugloader:Loader;
// Debugger loader completion handler
function debugEvalListener (e:Event):void {
debugloader.unload();
//DebugExec(e.target.content).doit();
}
function consoleInputHandler (event:KeyboardEvent ){
if (event.charCode == Keyboard.ENTER) {
var expr = consoleinputtext.text;
write(expr);
consoleinputtext.text = "";
debugloader = new Loader();
debugloader.contentLoaderInfo.addEventListener(Event.INIT, debugEvalListener);
// Send EVAL request to LPS server
// It doesn't matter what path/filename we use, as long as it has ".lzx" suffix, so it is
// handled by the LPS. The lzt=eval causes the request to be served by the EVAL Responder.
var url = "hello.lzx?lzr=swf9&lz_load=false&lzt=eval&lz_script=" + encodeURIComponent(expr)+"&lzbc=" +(new Date()).getTime();
debugloader.load(new URLRequest(url),
new LoaderContext(false,
new ApplicationDomain(ApplicationDomain.currentDomain)));
}
}
////////////////////////////////////////////////////////////////
// A crude debugger output window for now
public var consoletext:TextField;
public var consoleinputtext:TextField;
public function write (...args) {
consoletext.visible = true;
consoleinputtext.visible = true;
consoletext.appendText( "\n" + args.join(" "));
consoletext.scrollV = consoletext.maxScrollV;
}
////////////////////////////////////////////////////////////////
function reportWheel(event:MouseEvent):void {
/*
Debug.write(event.currentTarget.toString() +
" dispatches MouseWheelEvent. delta = " + event.delta); */
LzKeys.__mousewheelEvent(event.delta);
}
function resizeHandler(event:Event):void {
//trace('LFCApplication.resizeHandler stage width/height = ', stage.stageWidth, stage.stageHeight);
LzScreenKernel.handleResizeEvent();
}
function reportKeyUp(event:KeyboardEvent):void {
/*
trace("Key Released: " + String.fromCharCode(event.charCode) +
" (key code: " + event.keyCode + " character code: " +
event.charCode + ")");
*/
LzKeyboardKernel.__keyboardEvent(event.charCode, 'onkeyup');
}
function reportKeyDown(event:KeyboardEvent):void {
/*
trace("Key Pressed: " + String.fromCharCode(event.charCode) +
" (key code: " + event.keyCode + " character code: "
+ event.charCode + ")");
*/
LzKeyboardKernel.__keyboardEvent(event.charCode, 'onkeydown');
}
}
// Resource library
// contains {ptype, class, frames, width, height}
// ptype is one of "ar" (app relative) or "sr" (system relative)
var LzResourceLibrary = {};
var lzconsole;
|
Change 20080429-maxcarlson-I by maxcarlson@Roboto on 2008-04-29 10:54:55 PDT in /Users/maxcarlson/openlaszlo/trunk-clean for http://svn.openlaszlo.org/openlaszlo/trunk
|
Change 20080429-maxcarlson-I by maxcarlson@Roboto on 2008-04-29 10:54:55 PDT
in /Users/maxcarlson/openlaszlo/trunk-clean
for http://svn.openlaszlo.org/openlaszlo/trunk
Summary: Hide the swf9 debugger until messages need to be shown
New Features:
Bugs Fixed:
Technical Reviewer: hminsky
QA Reviewer: promanik
Doc Reviewer: (pending)
Documentation:
Release Notes:
Details: Hide debugger text and inputtext until write() is called.
Tests: The debugger text and inputtext start hidden, until write() is called.
git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@8902 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
|
ActionScript
|
epl-1.0
|
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
|
ac9cdd066f07d83ea5eab5bec29d1d92190425a3
|
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/) の tmx ファイルから
* 出力した json をもとに各マスの Image を返すユーティリティ
*/
//------------------------------------------------------------
public class TileMapHelper {
// avoid instantiation cost
private static var _point:Point = new Point(0, 0);
/**
* Tiled Map Editor で出力した json による Object を使って、
* 指定されたマスに対応するテクスチャを持つ Image を返す。
* orientation: "orthogonal" 専用。spacing に対応.
*
* 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);
}
}
}
|
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 で出力した json による Object を使って、
* 指定されたマスに対応するテクスチャを持つ Image を返す。
* orientation: "orthogonal" 専用。spacing に対応.
*
* 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);
}
}
}
|
Resolve conflict
|
Resolve conflict
|
ActionScript
|
mit
|
tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework
|
4a10e322153eab122625830b3de976c5b64645fe
|
src/aerys/minko/scene/controller/TransformController.as
|
src/aerys/minko/scene/controller/TransformController.as
|
package aerys.minko.scene.controller
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.Viewport;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.math.Matrix4x4;
import flash.display.BitmapData;
import flash.utils.Dictionary;
use namespace minko_math;
/**
* The TransformController handles the batched update of all the local to world matrices
* of a sub-scene. As such, it will only be active on the root node of a sub-scene and will
* automatically disable itself on other nodes.
*
* @author Jean-Marc Le Roux
*
*/
public final class TransformController extends AbstractController
{
private var _target : ISceneNode;
private var _invalidList : Boolean;
private var _nodeToId : Dictionary;
private var _idToNode : Vector.<ISceneNode>
private var _transforms : Vector.<Matrix4x4>;
private var _localToWorldTransforms : Vector.<Matrix4x4>;
private var _numChildren : Vector.<uint>;
private var _firstChildId : Vector.<uint>;
private var _parentId : Vector.<int>;
public function TransformController()
{
super();
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function renderingBeginHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : Number) : void
{
if (_invalidList)
updateTransformsList();
if (_transforms.length)
{
var rootTransform : Matrix4x4 = _transforms[0];
var isDirty : Boolean = rootTransform._hasChanged;
if (isDirty)
{
_localToWorldTransforms[0].copyFrom(rootTransform);
rootTransform._hasChanged = false;
}
updateLocalToWorld();
}
}
private function updateLocalToWorld(nodeId : uint = 0) : void
{
var numNodes : uint = _transforms.length;
var childrenOffset : uint = 1;
for (; nodeId < numNodes; ++nodeId)
{
var localToWorld : Matrix4x4 = _localToWorldTransforms[nodeId];
var numChildren : uint = _numChildren[nodeId];
var isDirty : Boolean = localToWorld._hasChanged;
var firstChildId : uint = _firstChildId[nodeId];
var lastChildId : uint = firstChildId + numChildren;
localToWorld._hasChanged = false;
for (var childId : uint = firstChildId; childId < lastChildId; ++childId)
{
var childTransform : Matrix4x4 = _transforms[childId];
var childLocalToWorld : Matrix4x4 = _localToWorldTransforms[childId];
var childIsDirty : Boolean = isDirty || childTransform._hasChanged;
if (childIsDirty)
{
var child : ISceneNode = _idToNode[childId];
childLocalToWorld
.copyFrom(childTransform)
.append(localToWorld);
childTransform._hasChanged = false;
child.localToWorldTransformChanged.execute(child, childLocalToWorld);
}
}
}
}
private function updateAncestorsAndSelfLocalToWorld(nodeId : int) : void
{
var dirtyRoot : int = nodeId;
while (nodeId >= 0)
{
if ((_transforms[nodeId] as Matrix4x4)._hasChanged)
dirtyRoot = nodeId;
nodeId = _parentId[nodeId];
}
if (dirtyRoot >= 0)
updateLocalToWorld(dirtyRoot);
}
private function targetAddedHandler(ctrl : TransformController,
target : ISceneNode) : void
{
if (_target)
throw new Error('The TransformController cannot have more than one target.');
_target = target;
_invalidList = true;
if (target is Scene)
{
(target as Scene).renderingBegin.add(renderingBeginHandler);
return;
}
if (target is Group)
{
var targetGroup : Group = target as Group;
targetGroup.descendantAdded.add(descendantAddedHandler);
targetGroup.descendantRemoved.add(descendantRemovedHandler);
}
target.added.add(addedHandler);
}
private function targetRemovedHandler(ctrl : TransformController,
target : ISceneNode) : void
{
target.added.remove(addedHandler);
if (target is Group)
{
var targetGroup : Group = target as Group;
targetGroup.descendantAdded.remove(descendantAddedHandler);
targetGroup.descendantRemoved.remove(descendantRemovedHandler);
}
_invalidList = false;
_target = null;
_nodeToId = null;
_transforms = null;
_localToWorldTransforms = null;
_numChildren = null;
_idToNode = null;
_parentId = null;
}
private function addedHandler(target : ISceneNode, ancestor : Group) : void
{
// the controller will remove itself from the node when it's not its own root anymore
// but it will watch for the 'removed' signal to add itself back if the node becomes
// its own root again
_target.removed.add(removedHandler);
_target.removeController(this);
}
private function removedHandler(target : ISceneNode, ancestor : Group) : void
{
if (target.root == target)
{
target.removed.remove(removedHandler);
target.addController(this);
}
}
private function descendantAddedHandler(root : Group,
descendant : ISceneNode) : void
{
_invalidList = true;
}
private function descendantRemovedHandler(root : Group,
descendant : ISceneNode) : void
{
_invalidList = true;
}
private function updateTransformsList() : void
{
var root : ISceneNode = _target.root;
var nodes : Vector.<ISceneNode> = new <ISceneNode>[root];
var nodeId : uint = 0;
_nodeToId = new Dictionary(true);
_transforms = new <Matrix4x4>[];
_localToWorldTransforms = new <Matrix4x4>[];
_numChildren = new <uint>[];
_firstChildId = new <uint>[];
_idToNode = new <ISceneNode>[];
_parentId = new <int>[-1];
while (nodes.length)
{
var node : ISceneNode = nodes.shift();
var group : Group = node as Group;
_nodeToId[node] = nodeId;
_idToNode[nodeId] = node;
_transforms[nodeId] = node.transform;
_localToWorldTransforms[nodeId] = new Matrix4x4().lock();
if (group)
{
var numChildren : uint = group.numChildren;
var firstChildId : uint = nodeId + nodes.length + 1;
_numChildren[nodeId] = numChildren;
_firstChildId[nodeId] = firstChildId;
for (var childId : uint = 0; childId < numChildren; ++childId)
{
_parentId[uint(firstChildId + childId)] = nodeId;
nodes.push(group.getChildAt(childId));
}
}
else
{
_numChildren[nodeId] = 0;
_firstChildId[nodeId] = 0;
}
++nodeId;
}
_invalidList = false;
}
public function getLocalToWorldTransform(node : ISceneNode,
forceUpdate : Boolean = false) : Matrix4x4
{
if (_invalidList || _nodeToId[node] == undefined)
updateTransformsList();
var nodeId : uint = _nodeToId[node];
if (forceUpdate)
updateAncestorsAndSelfLocalToWorld(nodeId);
return _localToWorldTransforms[nodeId];
}
}
}
|
package aerys.minko.scene.controller
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.Viewport;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.math.Matrix4x4;
import flash.display.BitmapData;
import flash.utils.Dictionary;
use namespace minko_math;
/**
* The TransformController handles the batched update of all the local to world matrices
* of a sub-scene. As such, it will only be active on the root node of a sub-scene and will
* automatically disable itself on other nodes.
*
* @author Jean-Marc Le Roux
*
*/
public final class TransformController extends AbstractController
{
private var _target : ISceneNode;
private var _invalidList : Boolean;
private var _nodeToId : Dictionary;
private var _idToNode : Vector.<ISceneNode>
private var _transforms : Vector.<Matrix4x4>;
private var _localToWorldTransforms : Vector.<Matrix4x4>;
private var _worldToLocalTransforms : Vector.<Matrix4x4>;
private var _numChildren : Vector.<uint>;
private var _firstChildId : Vector.<uint>;
private var _parentId : Vector.<int>;
public function TransformController()
{
super();
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function renderingBeginHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : Number) : void
{
if (_invalidList)
updateTransformsList();
if (_transforms.length)
{
var rootTransform : Matrix4x4 = _transforms[0];
var isDirty : Boolean = rootTransform._hasChanged;
if (isDirty)
{
_localToWorldTransforms[0].copyFrom(rootTransform);
rootTransform._hasChanged = false;
}
updateLocalToWorld();
}
}
private function updateLocalToWorld(nodeId : uint = 0) : void
{
var numNodes : uint = _transforms.length;
var childrenOffset : uint = 1;
for (; nodeId < numNodes; ++nodeId)
{
var localToWorld : Matrix4x4 = _localToWorldTransforms[nodeId];
var numChildren : uint = _numChildren[nodeId];
var isDirty : Boolean = localToWorld._hasChanged;
var firstChildId : uint = _firstChildId[nodeId];
var lastChildId : uint = firstChildId + numChildren;
localToWorld._hasChanged = false;
for (var childId : uint = firstChildId; childId < lastChildId; ++childId)
{
var childTransform : Matrix4x4 = _transforms[childId];
var childLocalToWorld : Matrix4x4 = _localToWorldTransforms[childId];
var childIsDirty : Boolean = isDirty || childTransform._hasChanged;
if (childIsDirty)
{
var child : ISceneNode = _idToNode[childId];
childLocalToWorld
.copyFrom(childTransform)
.append(localToWorld);
childTransform._hasChanged = false;
child.localToWorldTransformChanged.execute(child, childLocalToWorld);
}
}
}
}
private function getDirtyRoot(nodeId : int) : int
{
var dirtyRoot : int = nodeId;
while (nodeId >= 0)
{
if ((_transforms[nodeId] as Matrix4x4)._hasChanged)
dirtyRoot = nodeId;
nodeId = _parentId[nodeId];
}
return dirtyRoot;
}
private function targetAddedHandler(ctrl : TransformController,
target : ISceneNode) : void
{
if (_target)
throw new Error('The TransformController cannot have more than one target.');
_target = target;
_invalidList = true;
if (target is Scene)
{
(target as Scene).renderingBegin.add(renderingBeginHandler);
return;
}
if (target is Group)
{
var targetGroup : Group = target as Group;
targetGroup.descendantAdded.add(descendantAddedHandler);
targetGroup.descendantRemoved.add(descendantRemovedHandler);
}
target.added.add(addedHandler);
}
private function targetRemovedHandler(ctrl : TransformController,
target : ISceneNode) : void
{
target.added.remove(addedHandler);
if (target is Group)
{
var targetGroup : Group = target as Group;
targetGroup.descendantAdded.remove(descendantAddedHandler);
targetGroup.descendantRemoved.remove(descendantRemovedHandler);
}
_invalidList = false;
_target = null;
_nodeToId = null;
_transforms = null;
_localToWorldTransforms = null;
_worldToLocalTransforms = null;
_numChildren = null;
_idToNode = null;
_parentId = null;
}
private function addedHandler(target : ISceneNode, ancestor : Group) : void
{
// the controller will remove itself from the node when it's not its own root anymore
// but it will watch for the 'removed' signal to add itself back if the node becomes
// its own root again
_target.removed.add(removedHandler);
_target.removeController(this);
}
private function removedHandler(target : ISceneNode, ancestor : Group) : void
{
if (target.root == target)
{
target.removed.remove(removedHandler);
target.addController(this);
}
}
private function descendantAddedHandler(root : Group,
descendant : ISceneNode) : void
{
_invalidList = true;
}
private function descendantRemovedHandler(root : Group,
descendant : ISceneNode) : void
{
_invalidList = true;
}
private function updateTransformsList() : void
{
var root : ISceneNode = _target.root;
var nodes : Vector.<ISceneNode> = new <ISceneNode>[root];
var nodeId : uint = 0;
_nodeToId = new Dictionary(true);
_transforms = new <Matrix4x4>[];
_localToWorldTransforms = new <Matrix4x4>[];
_worldToLocalTransforms = new <Matrix4x4>[];
_numChildren = new <uint>[];
_firstChildId = new <uint>[];
_idToNode = new <ISceneNode>[];
_parentId = new <int>[-1];
while (nodes.length)
{
var node : ISceneNode = nodes.shift();
var group : Group = node as Group;
_nodeToId[node] = nodeId;
_idToNode[nodeId] = node;
_transforms[nodeId] = node.transform;
_localToWorldTransforms[nodeId] = new Matrix4x4().lock();
if (group)
{
var numChildren : uint = group.numChildren;
var firstChildId : uint = nodeId + nodes.length + 1;
_numChildren[nodeId] = numChildren;
_firstChildId[nodeId] = firstChildId;
for (var childId : uint = 0; childId < numChildren; ++childId)
{
_parentId[uint(firstChildId + childId)] = nodeId;
nodes.push(group.getChildAt(childId));
}
}
else
{
_numChildren[nodeId] = 0;
_firstChildId[nodeId] = 0;
}
++nodeId;
}
_worldToLocalTransforms.length = _localToWorldTransforms.length;
_invalidList = false;
}
public function getLocalToWorldTransform(node : ISceneNode,
forceUpdate : Boolean = false) : Matrix4x4
{
if (_invalidList || _nodeToId[node] == undefined)
updateTransformsList();
var nodeId : uint = _nodeToId[node];
if (forceUpdate)
{
var dirtyRoot : int = getDirtyRoot(nodeId);
if (dirtyRoot >= 0)
updateLocalToWorld(dirtyRoot);
}
return _localToWorldTransforms[nodeId];
}
public function getWorldToLocalTransform(node : ISceneNode,
forceUpdate : Boolean = false) : Matrix4x4
{
if (_invalidList || _nodeToId[node] == undefined)
updateTransformsList();
var nodeId : uint = _nodeToId[node];
var worldToLocalTransform : Matrix4x4 = _worldToLocalTransforms[nodeId];
if (!worldToLocalTransform)
{
_worldToLocalTransforms[nodeId] = worldToLocalTransform = new Matrix4x4();
if (!forceUpdate)
worldToLocalTransform.copyFrom(_localToWorldTransforms[nodeId]).invert();
}
if (forceUpdate)
{
var dirtyRoot : int = getDirtyRoot(nodeId);
if (dirtyRoot >= 0)
{
updateLocalToWorld(dirtyRoot);
worldToLocalTransform
.copyFrom(_localToWorldTransforms[nodeId])
.invert();
}
}
return worldToLocalTransform;
}
}
}
|
add TransformController.getWorldToLocalTransform() to get cached/lazy world to local transform
|
add TransformController.getWorldToLocalTransform() to get cached/lazy world to local transform
|
ActionScript
|
mit
|
aerys/minko-as3
|
7e9cc6dbd422706c923341f437b524fd94a99445
|
demo/DynamicDestruction/DynamicDestruction.as
|
demo/DynamicDestruction/DynamicDestruction.as
|
package {
//not yet written!
}
|
package {
//Translation of Destructable class only.
//(untested)
import nape.geom.Vec2;
import nape.phys.Body;
import nape.geom.MarchingSquares;
import nape.geom.GeomPoly;
import nape.geom.GeomPolyList;
import nape.shape.Polygon;
public class Destructible {
private static const granularity = new Vec2(5,5);
static public function cut(body:Body, inside:Function):Vector.<Body> {
var iso:Function = function(x:Number,y:Number):Number {
var p:Vec2 = new Vec2(x,y);
return (body.contains(p) && !inside(x,y)) ? -1.0 : 1.0;
};
var npolys:GeomPolyList = MarchingSquares.run(iso, body.bounds, granularity, 8);
if(npolys.length==0) return new Vector.<Body>();
body.shapes.clear();
body.position.setxy(0,0);
body.rotation = 0;
if(npolys.length==1) {
var qolys:GeomPolyList = npolys.at(0).convex_decomposition();
qolys.foreach(function (q:GeomPoly):void {
body.shapes.add(new Polygon(q));
});
body.align();
return null;
}else {
var ret:Vector.<Body> = new Vector.<Body>();
npolys.foreach(function (p:GeomPoly):void {
var nbody:Body = body.copy();
var qolys:GeomPolyList = p.convex_decomposition();
qolys.foreach(function (q:GeomPoly):void {
nbody.shapes.add(new Polygon(q));
});
nbody.align();
ret.push(nbody);
});
return ret;
}
}
}
}
|
add AS3 translation of Destructible in dynamic destruction demo
|
add AS3 translation of Destructible in dynamic destruction demo
|
ActionScript
|
bsd-2-clause
|
deltaluca/nape,deltaluca/nape,deltaluca/nape
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.