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
42b81dfac4bde646aed0b1fd1475a59f38e54bbb
www/demos/welcome.as
www/demos/welcome.as
; ; P3JS ; Write some assembly code. ; Then click 'Assemble and Run' to run it on the P3 simulator. ;
; Write some assembly code here. ; Then click 'Assemble and Run' to run it on the P3 simulator. ; For more information check 'About P3JS'. ; Try the Demos -----> -----> -----> -----> -----> -----> -----> -----> ; This is a very short program that fills the memory with ac5fh! ; Click 'Assemble and Run' to test. ORIG 8000h MOV R1, M[PC] MOV M[PC], R1 ; How does it work? Why is the value at the address 8000h not ac5fh? ; HINT ; || ; || ; \/ ; HINT: Notice that ac5fh is the binary code for 'MOV M[PC], R1'.
Update welcome.as
Update welcome.as
ActionScript
mit
goncalomb/p3js,goncalomb/p3js
42f7ce23ac5bcfde3180722a5965514f69a5c269
src/as/com/threerings/util/ExpiringSet.as
src/as/com/threerings/util/ExpiringSet.as
// // $Id$ package com.threerings.util { import flash.events.EventDispatcher; import flash.events.TimerEvent; import flash.utils.getTimer; // function import import flash.utils.Timer; /** * Dispatched when a set element expires. * * @eventType com.threerings.util.ExpiringSet.ELEMENT_EXPIRED */ [Event(name="ElementExpired", type="com.threerings.util.ValueEvent")] /** * Data structure that keeps its elements for a short time, and then removes them automatically. * * All operations are O(n), including add(). */ public class ExpiringSet extends EventDispatcher implements Set { /** The even that is dispatched when a member of this set expires. */ public static const ELEMENT_EXPIRED :String = "ElementExpired"; /** * Initializes the expiring set. * * @param ttl Time to live value for set elements, in seconds. */ public function ExpiringSet (ttl :Number) { _ttl = Math.round(ttl * 1000); _timer = new Timer(_ttl, 1); _timer.addEventListener(TimerEvent.TIMER, checkTimer); } /** * Returns the time to live value for this ExpiringSet. This value cannot be changed after * set creation. */ public function get ttl () :Number { return _ttl / 1000; } /** * Calling this function will not expire the elements, it simply removes them. No * ValueEvent will be dispatched. */ public function clear () :void { // simply trunate the data array _data.length = 0; } // from Set public function forEach (fn :Function) :void { for each (var e :ExpiringElement in _data) { fn(e.element); } } // from Set public function size () :int { return _data.length; } // from Set public function isEmpty () :Boolean { return size() == 0; } // from Set public function contains (o :Object) :Boolean { return _data.some(function (e :ExpiringElement, ... ignored) :Boolean { return e.objectEquals(o); }); } /** * Note that if you add an object that the list already contains, this method will return * false, but it will also update the expire time on that object to be this sets ttl from now, * as if the item really were being added to the list now. */ public function add (o :Object) :Boolean { var added :Boolean = true; for (var ii :int = 0; ii < _data.length; ii++) { if (ExpiringElement(_data[ii]).objectEquals(o)) { // already contained, remove this one and re-add at end _data.splice(ii, 1); added = false; break; } } // push the item onto the queue. since each element has the same TTL, elements end up // being ordered by their expiration time. _data.push(new ExpiringElement(o, getTimer() + _ttl)); if (_data.length == 1) { // set up the timer to remove this one element, otherwise it was already running _timer.reset(); _timer.delay = _ttl; _timer.start(); } return added; } // from Set public function remove (o :Object) :Boolean { // pull the item from anywhere in the queue. If we remove the first element, the timer // will harmlessly NOOP when it wakes up for (var ii :int = 0; ii < _data.length; ii++) { if (ExpiringElement(_data[ii]).objectEquals(o)) { _data.splice(ii, 1); return true; } } return false; } /** * This implementation of Set returns a fresh array that it will never reference again. * Modification of this array will not change the ExpiringSet's structure. */ public function toArray () :Array { return _data.map(function (e :ExpiringElement, ... ignored) :Object { return e.element; }); } /** * Remove probably just one element from the front of the expiration queue, and * schedule a wakeup for the time to the new head's expiration time. */ protected function checkTimer (... ignored) :void { var now :int = getTimer(); while (_data.length > 0) { var e :ExpiringElement = ExpiringElement(_data[0]); var timeToExpire :int = e.expirationTime - now; if (timeToExpire <= 0) { _data.shift(); // remove it dispatchEvent(new ValueEvent(ELEMENT_EXPIRED, e.element)); // notify } else { // the head element is not yet expired _timer.reset(); _timer.delay = timeToExpire; _timer.start(); break; } } } protected static const log :Log = Log.getLog(ExpiringSet); /** The time to live for this set, not to be changed after construction. */ protected /* final */ var _ttl :int; /** Array of ExpiringElement instances, sorted by expiration time. */ protected var _data :Array = []; protected var _timer :Timer; } } import com.threerings.util.Util; class ExpiringElement { public var expirationTime :int; public var element :Object; public function ExpiringElement (element :Object, expiration :int) { this.element = element; this.expirationTime = expiration; } public function objectEquals (element :Object) :Boolean { return Util.equals(element, this.element); } }
// // $Id$ package com.threerings.util { import flash.events.EventDispatcher; import flash.events.TimerEvent; import flash.utils.getTimer; // function import import flash.utils.Timer; /** * Dispatched when a set element expires. * * @eventType com.threerings.util.ExpiringSet.ELEMENT_EXPIRED */ [Event(name="ElementExpired", type="com.threerings.util.ValueEvent")] /** * Data structure that keeps its elements for a short time, and then removes them automatically. * * All operations are O(n), including add(). */ public class ExpiringSet extends EventDispatcher implements Set { /** The even that is dispatched when a member of this set expires. */ public static const ELEMENT_EXPIRED :String = "ElementExpired"; /** * Initializes the expiring set. * * @param ttl Time to live value for set elements, in seconds. * @param expireHandler a function to be conveniently registered as an event listener. */ public function ExpiringSet (ttl :Number, expireHandler :Function = null) { _ttl = Math.round(ttl * 1000); _timer = new Timer(_ttl, 1); _timer.addEventListener(TimerEvent.TIMER, checkTimer); if (expireHandler != null) { addEventListener(ELEMENT_EXPIRED, expireHandler); } } /** * Returns the time to live value for this ExpiringSet. This value cannot be changed after * set creation. */ public function get ttl () :Number { return _ttl / 1000; } /** * Calling this function will not expire the elements, it simply removes them. No * ValueEvent will be dispatched. */ public function clear () :void { // simply trunate the data array _data.length = 0; } // from Set public function forEach (fn :Function) :void { for each (var e :ExpiringElement in _data) { fn(e.element); } } // from Set public function size () :int { return _data.length; } // from Set public function isEmpty () :Boolean { return size() == 0; } // from Set public function contains (o :Object) :Boolean { return _data.some(function (e :ExpiringElement, ... ignored) :Boolean { return e.objectEquals(o); }); } /** * Note that if you add an object that the list already contains, this method will return * false, but it will also update the expire time on that object to be this sets ttl from now, * as if the item really were being added to the list now. */ public function add (o :Object) :Boolean { var added :Boolean = true; for (var ii :int = 0; ii < _data.length; ii++) { if (ExpiringElement(_data[ii]).objectEquals(o)) { // already contained, remove this one and re-add at end _data.splice(ii, 1); added = false; break; } } // push the item onto the queue. since each element has the same TTL, elements end up // being ordered by their expiration time. _data.push(new ExpiringElement(o, getTimer() + _ttl)); if (_data.length == 1) { // set up the timer to remove this one element, otherwise it was already running _timer.reset(); _timer.delay = _ttl; _timer.start(); } return added; } // from Set public function remove (o :Object) :Boolean { // pull the item from anywhere in the queue. If we remove the first element, the timer // will harmlessly NOOP when it wakes up for (var ii :int = 0; ii < _data.length; ii++) { if (ExpiringElement(_data[ii]).objectEquals(o)) { _data.splice(ii, 1); return true; } } return false; } /** * This implementation of Set returns a fresh array that it will never reference again. * Modification of this array will not change the ExpiringSet's structure. */ public function toArray () :Array { return _data.map(function (e :ExpiringElement, ... ignored) :Object { return e.element; }); } /** * Remove probably just one element from the front of the expiration queue, and * schedule a wakeup for the time to the new head's expiration time. */ protected function checkTimer (... ignored) :void { var now :int = getTimer(); while (_data.length > 0) { var e :ExpiringElement = ExpiringElement(_data[0]); var timeToExpire :int = e.expirationTime - now; if (timeToExpire <= 0) { _data.shift(); // remove it dispatchEvent(new ValueEvent(ELEMENT_EXPIRED, e.element)); // notify } else { // the head element is not yet expired _timer.reset(); _timer.delay = timeToExpire; _timer.start(); break; } } } protected static const log :Log = Log.getLog(ExpiringSet); /** The time to live for this set, not to be changed after construction. */ protected /* final */ var _ttl :int; /** Array of ExpiringElement instances, sorted by expiration time. */ protected var _data :Array = []; protected var _timer :Timer; } } import com.threerings.util.Util; class ExpiringElement { public var expirationTime :int; public var element :Object; public function ExpiringElement (element :Object, expiration :int) { this.element = element; this.expirationTime = expiration; } public function objectEquals (element :Object) :Boolean { return Util.equals(element, this.element); } }
Allow the event handler to be specified in the constructor.
Allow the event handler to be specified in the constructor. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@5783 542714f4-19e9-0310-aa3c-eee0fc999fb1
ActionScript
lgpl-2.1
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
7e1630cf4b6775cddd4c8494e3d807e167b66170
src/aerys/minko/render/material/phong/PCFShadowMapShader.as
src/aerys/minko/render/material/phong/PCFShadowMapShader.as
package aerys.minko.render.material.phong { import aerys.minko.render.RenderTarget; import aerys.minko.render.material.basic.BasicProperties; import aerys.minko.render.shader.SFloat; import aerys.minko.render.shader.Shader; import aerys.minko.render.shader.ShaderSettings; import aerys.minko.render.shader.part.DiffuseShaderPart; import aerys.minko.render.shader.part.animation.VertexAnimationShaderPart; import aerys.minko.scene.data.LightDataProvider; import aerys.minko.scene.node.light.SpotLight; import aerys.minko.type.enum.Blending; import aerys.minko.type.enum.TriangleCulling; public class PCFShadowMapShader extends Shader { private var _vertexAnimationPart : VertexAnimationShaderPart; private var _diffusePart : DiffuseShaderPart; private var _lightId : uint; private var _clipspacePosition : SFloat; public function PCFShadowMapShader(lightId : uint, priority : Number, renderTarget : RenderTarget) { super(renderTarget, priority); _lightId = lightId; _vertexAnimationPart = new VertexAnimationShaderPart(this); _diffusePart = new DiffuseShaderPart(this); } override protected function initializeSettings(settings : ShaderSettings) : void { super.initializeSettings(settings); settings.blending = Blending.NORMAL; settings.enabled = meshBindings.getProperty(PhongProperties.CAST_SHADOWS, true); settings.triangleCulling = meshBindings.getProperty( BasicProperties.TRIANGLE_CULLING, TriangleCulling.BACK ); } override protected function getVertexPosition() : SFloat { var lightTypeName : String = LightDataProvider.getLightPropertyName( 'type', _lightId ); var worldToScreenName : String = LightDataProvider.getLightPropertyName( 'worldToScreen', _lightId ); var lightType : uint = sceneBindings.getProperty(lightTypeName); var worldToScreen : SFloat = sceneBindings.getParameter(worldToScreenName, 16); var vertexPosition : SFloat = localToWorld( _vertexAnimationPart.getAnimatedVertexPosition() ); _clipspacePosition = multiply4x4(vertexPosition, worldToScreen); if (lightType == SpotLight.LIGHT_TYPE) return float4( _clipspacePosition.xy, multiply(_clipspacePosition.z, _clipspacePosition.w), _clipspacePosition.w ); else return _clipspacePosition; } /** * @see http://www.mvps.org/directx/articles/linear_z/linearz.htm Linear Z-buffering */ override protected function getPixelColor() : SFloat { var iClipspacePosition : SFloat = interpolate(_clipspacePosition); if (meshBindings.propertyExists(BasicProperties.ALPHA_THRESHOLD)) { var diffuse : SFloat = _diffusePart.getDiffuseColor(); var alphaThreshold : SFloat = meshBindings.getParameter( BasicProperties.ALPHA_THRESHOLD, 1 ); kill(subtract(0.5, lessThan(diffuse.w, alphaThreshold))); } return pack(iClipspacePosition.z); } } }
package aerys.minko.render.material.phong { import aerys.minko.render.RenderTarget; import aerys.minko.render.material.basic.BasicProperties; import aerys.minko.render.shader.SFloat; import aerys.minko.render.shader.Shader; import aerys.minko.render.shader.ShaderSettings; import aerys.minko.render.shader.part.DiffuseShaderPart; import aerys.minko.render.shader.part.animation.VertexAnimationShaderPart; import aerys.minko.scene.data.LightDataProvider; import aerys.minko.scene.node.light.SpotLight; import aerys.minko.type.enum.Blending; import aerys.minko.type.enum.TriangleCulling; public class PCFShadowMapShader extends Shader { private var _vertexAnimationPart : VertexAnimationShaderPart; private var _diffusePart : DiffuseShaderPart; private var _lightId : uint; private var _clipspacePosition : SFloat; public function PCFShadowMapShader(lightId : uint, priority : Number, renderTarget : RenderTarget) { super(renderTarget, priority); _lightId = lightId; _vertexAnimationPart = new VertexAnimationShaderPart(this); _diffusePart = new DiffuseShaderPart(this); } override protected function initializeSettings(settings : ShaderSettings) : void { super.initializeSettings(settings); settings.blending = Blending.NORMAL; settings.triangleCulling = meshBindings.getProperty( BasicProperties.TRIANGLE_CULLING, TriangleCulling.BACK ); } override protected function getVertexPosition() : SFloat { var lightTypeName : String = LightDataProvider.getLightPropertyName( 'type', _lightId ); var worldToScreenName : String = LightDataProvider.getLightPropertyName( 'worldToScreen', _lightId ); var lightType : uint = sceneBindings.getProperty(lightTypeName); var worldToScreen : SFloat = sceneBindings.getParameter(worldToScreenName, 16); var vertexPosition : SFloat = localToWorld( _vertexAnimationPart.getAnimatedVertexPosition() ); _clipspacePosition = multiply4x4(vertexPosition, worldToScreen); if (lightType == SpotLight.LIGHT_TYPE) return float4( _clipspacePosition.xy, multiply(_clipspacePosition.z, _clipspacePosition.w), _clipspacePosition.w ); else return _clipspacePosition; } /** * @see http://www.mvps.org/directx/articles/linear_z/linearz.htm Linear Z-buffering */ override protected function getPixelColor() : SFloat { var iClipspacePosition : SFloat = interpolate(_clipspacePosition); if (meshBindings.propertyExists(BasicProperties.ALPHA_THRESHOLD)) { var diffuse : SFloat = _diffusePart.getDiffuseColor(); var alphaThreshold : SFloat = meshBindings.getParameter( BasicProperties.ALPHA_THRESHOLD, 1 ); kill(subtract(0.5, lessThan(diffuse.w, alphaThreshold))); } return pack(iClipspacePosition.z); } } }
remove usage of PhongProperties.CAST_SHADOW to set ShaderSettings.enabled in PCFShadowMapShader because the PhongEffect will fork according to this very property and this pass simply won't exist
remove usage of PhongProperties.CAST_SHADOW to set ShaderSettings.enabled in PCFShadowMapShader because the PhongEffect will fork according to this very property and this pass simply won't exist
ActionScript
mit
aerys/minko-as3
9ceaa57ca226f9d30b874c6dfd8c16f6521fa2f9
src/org/mangui/osmf/plugins/traits/HLSDynamicStreamTrait.as
src/org/mangui/osmf/plugins/traits/HLSDynamicStreamTrait.as
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mangui.osmf.plugins.traits { import org.mangui.hls.HLS; import org.mangui.hls.event.HLSEvent; import org.osmf.traits.DynamicStreamTrait; import org.osmf.utils.OSMFStrings; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } public class HLSDynamicStreamTrait extends DynamicStreamTrait { private var _hls : HLS; public function HLSDynamicStreamTrait(hls : HLS) { CONFIG::LOGGING { Log.debug("HLSDynamicStreamTrait()"); } _hls = hls; _hls.addEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler); super(true, _hls.startLevel, hls.levels.length); } override public function dispose() : void { CONFIG::LOGGING { Log.debug("HLSDynamicStreamTrait:dispose"); } _hls.removeEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler); super.dispose(); } override public function getBitrateForIndex(index : int) : Number { if (index > numDynamicStreams - 1 || index < 0) { throw new RangeError(OSMFStrings.getString(OSMFStrings.STREAMSWITCH_INVALID_INDEX)); } var bitrate : Number = _hls.levels[index].bitrate / 1000; CONFIG::LOGGING { Log.debug("HLSDynamicStreamTrait:getBitrateForIndex(" + index + ")=" + bitrate); } return bitrate; } override public function switchTo(index : int) : void { CONFIG::LOGGING { Log.debug("HLSDynamicStreamTrait:switchTo(" + index + ")/max:" + maxAllowedIndex); } if (index < 0 || index > maxAllowedIndex) { throw new RangeError(OSMFStrings.getString(OSMFStrings.STREAMSWITCH_INVALID_INDEX)); } autoSwitch = false; if (!switching) { setSwitching(true, index); } } override protected function autoSwitchChangeStart(value : Boolean) : void { CONFIG::LOGGING { Log.debug("HLSDynamicStreamTrait:autoSwitchChangeStart:" + value); } if (value == true && _hls.autoLevel == false) { _hls.level = -1; // only seek if position is set if (!isNaN(_hls.position)) { _hls.stream.seek(_hls.position); } } } override protected function switchingChangeStart(newSwitching : Boolean, index : int) : void { CONFIG::LOGGING { Log.debug("HLSDynamicStreamTrait:switchingChangeStart(newSwitching/index):" + newSwitching + "/" + index); } if (newSwitching) { _hls.level = index; } } /** Update playback position/duration **/ private function _levelSwitchHandler(event : HLSEvent) : void { var newLevel : int = event.level; CONFIG::LOGGING { Log.debug("HLSDynamicStreamTrait:_qualitySwitchHandler:" + newLevel); } setCurrentIndex(newLevel); setSwitching(false, newLevel); }; } }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mangui.osmf.plugins.traits { import org.mangui.hls.HLS; import org.mangui.hls.event.HLSEvent; import org.osmf.traits.DynamicStreamTrait; import org.osmf.utils.OSMFStrings; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } public class HLSDynamicStreamTrait extends DynamicStreamTrait { private var _hls : HLS; public function HLSDynamicStreamTrait(hls : HLS) { CONFIG::LOGGING { Log.debug("HLSDynamicStreamTrait()"); } _hls = hls; _hls.addEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler); super(true, _hls.startLevel, hls.levels.length); } override public function dispose() : void { CONFIG::LOGGING { Log.debug("HLSDynamicStreamTrait:dispose"); } _hls.removeEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler); super.dispose(); } override public function getBitrateForIndex(index : int) : Number { if (index > numDynamicStreams - 1 || index < 0) { throw new RangeError(OSMFStrings.getString(OSMFStrings.STREAMSWITCH_INVALID_INDEX)); } var bitrate : Number = _hls.levels[index].bitrate / 1000; CONFIG::LOGGING { Log.debug("HLSDynamicStreamTrait:getBitrateForIndex(" + index + ")=" + bitrate); } return bitrate; } override public function switchTo(index : int) : void { CONFIG::LOGGING { Log.debug("HLSDynamicStreamTrait:switchTo(" + index + ")/max:" + maxAllowedIndex); } if (index < 0 || index > maxAllowedIndex) { throw new RangeError(OSMFStrings.getString(OSMFStrings.STREAMSWITCH_INVALID_INDEX)); } autoSwitch = false; if (!switching) { setSwitching(true, index); } } override protected function autoSwitchChangeStart(value : Boolean) : void { CONFIG::LOGGING { Log.debug("HLSDynamicStreamTrait:autoSwitchChangeStart:" + value); } if (value == true && _hls.autoLevel == false) { _hls.loadLevel = -1; // only seek if position is set if (!isNaN(_hls.position)) { _hls.stream.seek(_hls.position); } } } override protected function switchingChangeStart(newSwitching : Boolean, index : int) : void { CONFIG::LOGGING { Log.debug("HLSDynamicStreamTrait:switchingChangeStart(newSwitching/index):" + newSwitching + "/" + index); } if (newSwitching) { _hls.loadLevel = index; } } /** Update playback position/duration **/ private function _levelSwitchHandler(event : HLSEvent) : void { var newLevel : int = event.level; CONFIG::LOGGING { Log.debug("HLSDynamicStreamTrait:_qualitySwitchHandler:" + newLevel); } setCurrentIndex(newLevel); setSwitching(false, newLevel); }; } }
fix compil error
fix compil error
ActionScript
mpl-2.0
neilrackett/flashls,tedconf/flashls,dighan/flashls,codex-corp/flashls,clappr/flashls,hola/flashls,mangui/flashls,Peer5/flashls,codex-corp/flashls,suuhas/flashls,mangui/flashls,fixedmachine/flashls,Peer5/flashls,aevange/flashls,aevange/flashls,jlacivita/flashls,suuhas/flashls,suuhas/flashls,vidible/vdb-flashls,clappr/flashls,tedconf/flashls,aevange/flashls,Boxie5/flashls,JulianPena/flashls,suuhas/flashls,thdtjsdn/flashls,Corey600/flashls,neilrackett/flashls,aevange/flashls,vidible/vdb-flashls,NicolasSiver/flashls,fixedmachine/flashls,Peer5/flashls,Peer5/flashls,Boxie5/flashls,jlacivita/flashls,hola/flashls,thdtjsdn/flashls,loungelogic/flashls,dighan/flashls,NicolasSiver/flashls,JulianPena/flashls,loungelogic/flashls,Corey600/flashls
02e340a0e67e85aa271a42beb0370a966c156cd4
src/aerys/minko/scene/controller/AbstractScriptController.as
src/aerys/minko/scene/controller/AbstractScriptController.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.KeyboardManager; import aerys.minko.type.MouseManager; import flash.display.BitmapData; import flash.utils.Dictionary; use namespace minko_scene; public class AbstractScriptController extends EnterFrameController { private var _scene : Scene; private var _started : Dictionary; private var _time : Number; private var _lastTime : Number; private var _deltaTime : Number; private var _currentTarget : ISceneNode; private var _viewport : Viewport; private var _targetsListLocked : Boolean; private var _targetsToAdd : Vector.<ISceneNode>; private var _targetsToRemove : Vector.<ISceneNode>; private var _updateRate : Number; protected function get scene() : Scene { return _scene; } protected function get time() : Number { return _time; } protected function get deltaTime() : Number { return _deltaTime; } protected function get keyboard() : KeyboardManager { return _viewport.keyboardManager; } protected function get mouse() : MouseManager { return _viewport.mouseManager; } protected function get viewport() : Viewport { return _viewport; } protected function get updateRate() : Number { return _updateRate; } protected function set updateRate(value : Number) : void { _updateRate = value; } public function AbstractScriptController(targetType : Class = null) { super(targetType); initialize(); } protected function initialize() : void { _started = new Dictionary(true); } override protected function targetAddedToScene(target : ISceneNode, scene : Scene) : void { super.targetAddedToScene(target, scene); if (_scene && scene != _scene) throw new Error( 'The same ScriptController instance can not be used in more than one scene ' + 'at a time.' ); _scene = scene; } override protected function targetRemovedFromScene(target : ISceneNode, scene : Scene) : void { super.targetAddedToScene(target, scene); if (getNumTargetsInScene(scene)) _scene = null; } override protected function sceneEnterFrameHandler(scene : Scene, viewport : Viewport, destination : BitmapData, time : Number) : void { _deltaTime = time - _lastTime; _time = time; if (_updateRate != 0. && deltaTime < 1000. / _updateRate) return; _viewport = viewport; lockTargetsList(); beforeUpdate(); var numTargets : uint = this.numTargets; for (var i : uint = 0; i < numTargets; ++i) { var target : ISceneNode = getTarget(i); if (target.scene) { if (!_started[target]) { _started[target] = true; start(target); } update(target); } else if (_started[target]) { _started[target] = false; stop(target); } } afterUpdate(); unlockTargetsList(); _lastTime = time; } /** * The 'start' method is called on a script target at the first frame occuring after it * has been added to the scene. * * @param target * */ protected function start(target : ISceneNode) : void { // nothing } /** * The 'beforeUpdate' method is called before each target is updated via the 'update' * method. * */ protected function beforeUpdate() : void { // nothing } protected function update(target : ISceneNode) : void { // nothing } /** * The 'afterUpdate' method is called after each target has been updated via the 'update' * method. * */ protected function afterUpdate() : void { // nothing } /** * The 'start' method is called on a script target at the first frame occuring after it * has been removed from the scene. * * @param target * */ protected function stop(target : ISceneNode) : void { // nothing } private function lockTargetsList() : void { _targetsListLocked = true; } private function unlockTargetsList() : void { _targetsListLocked = false; if (_targetsToAdd) { var numTargetsToAdd : uint = _targetsToAdd.length; for (var i : uint = 0; i < numTargetsToAdd; ++i) addTarget(_targetsToAdd[i]); _targetsToAdd = null; } if (_targetsToRemove) { var numTargetsToRemove : uint = _targetsToRemove.length; for (var j : uint = 0; j < numTargetsToRemove; ++j) removeTarget(_targetsToRemove[j]); _targetsToRemove = null; } } override minko_scene function addTarget(target : ISceneNode) : void { if (_targetsListLocked) { if (_targetsToAdd) _targetsToAdd.push(target); else _targetsToAdd = new <ISceneNode>[target]; } else super.addTarget(target); } override minko_scene function removeTarget(target : ISceneNode) : void { if (_targetsListLocked) { if (_targetsToRemove) _targetsToRemove.push(target); else _targetsToRemove = new <ISceneNode>[target]; } else super.removeTarget(target); } } }
package aerys.minko.scene.controller { import flash.display.BitmapData; import flash.utils.Dictionary; 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.KeyboardManager; import aerys.minko.type.MouseManager; use namespace minko_scene; public class AbstractScriptController extends EnterFrameController { private var _scene : Scene; private var _started : Dictionary; private var _time : Number; private var _lastTime : Number; private var _deltaTime : Number; private var _currentTarget : ISceneNode; private var _viewport : Viewport; private var _targetsListLocked : Boolean; private var _targetsToAdd : Vector.<ISceneNode>; private var _targetsToRemove : Vector.<ISceneNode>; private var _updateRate : Number; protected function get scene() : Scene { return _scene; } protected function get time() : Number { return _time; } protected function get deltaTime() : Number { return _deltaTime; } protected function get keyboard() : KeyboardManager { return _viewport.keyboardManager; } protected function get mouse() : MouseManager { return _viewport.mouseManager; } protected function get viewport() : Viewport { return _viewport; } protected function get updateRate() : Number { return _updateRate; } protected function set updateRate(value : Number) : void { _updateRate = value; } public function AbstractScriptController(targetType : Class = null) { super(targetType); initialize(); } protected function initialize() : void { _started = new Dictionary(true); } override protected function targetAddedToScene(target : ISceneNode, scene : Scene) : void { super.targetAddedToScene(target, scene); if (_scene && scene != _scene) throw new Error( 'The same ScriptController instance can not be used in more than one scene ' + 'at a time.' ); if (!_started[target]) { _started[target] = true; start(target); } _scene = scene; } override protected function targetRemovedFromScene(target : ISceneNode, scene : Scene) : void { super.targetRemovedFromScene(target, scene); if (getNumTargetsInScene(scene)) _scene = null; if (_started[target]) { _started[target] = false; stop(target); } } override protected function sceneEnterFrameHandler(scene : Scene, viewport : Viewport, destination : BitmapData, time : Number) : void { _deltaTime = time - _lastTime; _time = time; if (_updateRate != 0. && deltaTime < 1000. / _updateRate) return; _viewport = viewport; lockTargetsList(); beforeUpdate(); var numTargets : uint = this.numTargets; for (var i : uint = 0; i < numTargets; ++i) { var target : ISceneNode = getTarget(i); if (target.scene) update(target); } afterUpdate(); unlockTargetsList(); _lastTime = time; } /** * The 'start' method is called on a script target at the first frame occuring after it * has been added to the scene. * * @param target * */ protected function start(target : ISceneNode) : void { // nothing } /** * The 'beforeUpdate' method is called before each target is updated via the 'update' * method. * */ protected function beforeUpdate() : void { // nothing } protected function update(target : ISceneNode) : void { // nothing } /** * The 'afterUpdate' method is called after each target has been updated via the 'update' * method. * */ protected function afterUpdate() : void { // nothing } /** * The 'start' method is called on a script target at the first frame occuring after it * has been removed from the scene. * * @param target * */ protected function stop(target : ISceneNode) : void { // nothing } private function lockTargetsList() : void { _targetsListLocked = true; } private function unlockTargetsList() : void { _targetsListLocked = false; if (_targetsToAdd) { var numTargetsToAdd : uint = _targetsToAdd.length; for (var i : uint = 0; i < numTargetsToAdd; ++i) addTarget(_targetsToAdd[i]); _targetsToAdd = null; } if (_targetsToRemove) { var numTargetsToRemove : uint = _targetsToRemove.length; for (var j : uint = 0; j < numTargetsToRemove; ++j) removeTarget(_targetsToRemove[j]); _targetsToRemove = null; } } override minko_scene function addTarget(target : ISceneNode) : void { if (_targetsListLocked) { if (_targetsToAdd) _targetsToAdd.push(target); else _targetsToAdd = new <ISceneNode>[target]; } else super.addTarget(target); } override minko_scene function removeTarget(target : ISceneNode) : void { if (_targetsListLocked) { if (_targetsToRemove) _targetsToRemove.push(target); else _targetsToRemove = new <ISceneNode>[target]; } else super.removeTarget(target); } } }
Fix AbstractScriptController not calling stop() when a target is removed.
Fix AbstractScriptController not calling stop() when a target is removed.
ActionScript
mit
aerys/minko-as3
aad824440e4e9267e5d1c64761334f93104c6212
frameworks/projects/JQuery/as/src/org/apache/flex/jquery/Application.as
frameworks/projects/JQuery/as/src/org/apache/flex/jquery/Application.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.jquery { import org.apache.flex.core.Application; import org.apache.flex.core.IFlexInfo; /* FalconJX will inject html into the index.html file. Surround with "inject_html" tag as follows: <inject_html> <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" /> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script> </inject_html> */ public class Application extends org.apache.flex.core.Application implements IFlexInfo { public function Application() { super(); } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.jquery { import org.apache.flex.core.Application; import org.apache.flex.core.IFlexInfo; public class Application extends org.apache.flex.core.Application implements IFlexInfo { /** * FalconJX will inject html into the index.html file. Surround with * "inject_html" tag as follows: * * <inject_html> * <link rel="stylesheet" * href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" /> * <script src="http://code.jquery.com/jquery-1.9.1.js"></script> * <script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script> * </inject_html> */ public function Application() { super(); } } }
move inject_html
move inject_html
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
639ba6fb32df938ac4b464e3c0db6be3aa802262
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/CSSTextField.as
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/CSSTextField.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.core { import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.text.TextFormat; import org.apache.flex.core.ValuesManager; /** * The CSSTextField class implements CSS text styles in a TextField. * Not every CSS text style is currently supported. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class CSSTextField extends TextField { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function CSSTextField() { super(); } /** * @private * The styleParent property is set if the CSSTextField * is used in a SimpleButton-based instance because * the parent property is null, defeating CSS lookup. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var styleParent:Object; /** * @private */ override public function set text(value:String):void { var sp:Object = parent; if (!sp) sp = styleParent; var tf: TextFormat = new TextFormat(); tf.font = ValuesManager.valuesImpl.getValue(sp, "fontFamily") as String; tf.size = ValuesManager.valuesImpl.getValue(sp, "fontSize"); tf.bold = ValuesManager.valuesImpl.getValue(sp, "fontWeight") == "bold"; tf.color = ValuesManager.valuesImpl.getValue(sp, "color"); var padding:Object = ValuesManager.valuesImpl.getValue(sp, "padding"); if (padding == null) padding = 0; var paddingLeft:Object = ValuesManager.valuesImpl.getValue(sp,"padding-left"); if (paddingLeft == null) paddingLeft = padding; var paddingRight:Object = ValuesManager.valuesImpl.getValue(sp,"padding-right"); if (paddingRight == null) paddingRight = padding; tf.leftMargin = paddingLeft; tf.rightMargin = paddingRight; var align:Object = ValuesManager.valuesImpl.getValue(sp, "text-align"); if (align == "center") { autoSize = TextFieldAutoSize.NONE; tf.align = "center"; } else if (align == "right") { tf.align = "right"; autoSize = TextFieldAutoSize.NONE; } defaultTextFormat = tf; super.text = value; } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.core { import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.text.TextFormat; import org.apache.flex.core.ValuesManager; /** * The CSSTextField class implements CSS text styles in a TextField. * Not every CSS text style is currently supported. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class CSSTextField extends TextField { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function CSSTextField() { super(); } /** * @private * The styleParent property is set if the CSSTextField * is used in a SimpleButton-based instance because * the parent property is null, defeating CSS lookup. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var styleParent:Object; /** * @private */ override public function set text(value:String):void { var sp:Object = parent; if (!sp) sp = styleParent; var tf: TextFormat = new TextFormat(); tf.font = ValuesManager.valuesImpl.getValue(sp, "fontFamily") as String; tf.size = ValuesManager.valuesImpl.getValue(sp, "fontSize"); tf.bold = ValuesManager.valuesImpl.getValue(sp, "fontWeight") == "bold"; tf.color = ValuesManager.valuesImpl.getValue(sp, "color"); var padding:Object = ValuesManager.valuesImpl.getValue(sp, "padding"); if (padding == null) padding = 0; var paddingLeft:Object = ValuesManager.valuesImpl.getValue(sp,"padding-left"); if (paddingLeft == null) paddingLeft = padding; var paddingRight:Object = ValuesManager.valuesImpl.getValue(sp,"padding-right"); if (paddingRight == null) paddingRight = padding; tf.leftMargin = paddingLeft; tf.rightMargin = paddingRight; var align:Object = ValuesManager.valuesImpl.getValue(sp, "text-align"); if (align == "center") { autoSize = TextFieldAutoSize.NONE; tf.align = "center"; } else if (align == "right") { tf.align = "right"; autoSize = TextFieldAutoSize.NONE; } var backgroundColor:Object = ValuesManager.valuesImpl.getValue(sp, "background-color"); if (backgroundColor != null) { this.background = true; if (backgroundColor is String) { backgroundColor = backgroundColor.replace("#", "0x"); backgroundColor = uint(backgroundColor); } this.backgroundColor = backgroundColor as uint; } defaultTextFormat = tf; super.text = value; } } }
support solid backgroundcolor
support solid backgroundcolor
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
cd6df7b32c41e4d4980c9d5b27cebe90dd58f281
src/widgets/supportClasses/ResultItem.as
src/widgets/supportClasses/ResultItem.as
/////////////////////////////////////////////////////////////////////////// // Copyright (c) 2010-2011 Esri. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /////////////////////////////////////////////////////////////////////////// package widgets.supportClasses { import com.esri.ags.Graphic; import com.esri.ags.geometry.Geometry; import com.esri.ags.geometry.MapPoint; import com.esri.ags.geometry.Multipoint; import com.esri.ags.geometry.Polygon; import com.esri.ags.geometry.Polyline; import com.esri.ags.symbols.Symbol; [Bindable] public class ResultItem { public function ResultItem(graphic:Graphic, attributes:ResultAttributes) { _graphic = graphic; _attributes = attributes; _center = getGeomCenter(graphic); } private var _graphic:Graphic; public function get graphic():Graphic { return _graphic; } private var _attributes:ResultAttributes; public function get attributes():ResultAttributes { return _attributes; } private var _center:MapPoint; public function get center():MapPoint { return _center; } public function get geometry():Geometry { return _graphic.geometry; } public function get symbol():Symbol { return _graphic.symbol; } private function getGeomCenter(graphic:Graphic):MapPoint { var point:MapPoint; var geometry:Geometry = graphic.geometry; if (geometry) { switch (geometry.type) { case Geometry.MAPPOINT: { point = geometry as MapPoint; break; } case Geometry.MULTIPOINT: { const multipoint:Multipoint = geometry as Multipoint; point = multipoint.points && multipoint.points.length > 0 ? multipoint.points[0] as MapPoint : null; break; } case Geometry.POLYLINE: { var pl:Polyline = geometry as Polyline; var pathCount:Number = pl.paths.length; var pathIndex:int = int((pathCount / 2) - 1); var midPath:Array = pl.paths[pathIndex]; var ptCount:Number = midPath.length; var ptIndex:int = int((ptCount / 2) - 1); point = pl.getPoint(pathIndex, ptIndex); break; } case Geometry.POLYGON: { const poly:Polygon = geometry as Polygon; point = poly.extent.center; break; } } } return point; } } }
/////////////////////////////////////////////////////////////////////////// // Copyright (c) 2010-2011 Esri. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /////////////////////////////////////////////////////////////////////////// package widgets.supportClasses { import com.esri.ags.Graphic; import com.esri.ags.geometry.Geometry; import com.esri.ags.geometry.MapPoint; import com.esri.ags.geometry.Multipoint; import com.esri.ags.geometry.Polygon; import com.esri.ags.geometry.Polyline; import com.esri.ags.symbols.Symbol; public class ResultItem { //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- public function ResultItem(graphic:Graphic, attributes:ResultAttributes) { _graphic = graphic; _attributes = attributes; _center = getGeomCenter(graphic); } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // graphic //-------------------------------------------------------------------------- private var _graphic:Graphic; public function get graphic():Graphic { return _graphic; } //-------------------------------------------------------------------------- // attributes //-------------------------------------------------------------------------- private var _attributes:ResultAttributes; public function get attributes():ResultAttributes { return _attributes; } //-------------------------------------------------------------------------- // center //-------------------------------------------------------------------------- private var _center:MapPoint; public function get center():MapPoint { return _center; } //-------------------------------------------------------------------------- // geometry //-------------------------------------------------------------------------- public function get geometry():Geometry { return _graphic.geometry; } //-------------------------------------------------------------------------- // symbol //-------------------------------------------------------------------------- public function get symbol():Symbol { return _graphic.symbol; } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- private function getGeomCenter(graphic:Graphic):MapPoint { var point:MapPoint; var geometry:Geometry = graphic.geometry; if (geometry) { switch (geometry.type) { case Geometry.MAPPOINT: { point = geometry as MapPoint; break; } case Geometry.MULTIPOINT: { const multipoint:Multipoint = geometry as Multipoint; point = multipoint.points && multipoint.points.length > 0 ? multipoint.points[0] as MapPoint : null; break; } case Geometry.POLYLINE: { var pl:Polyline = geometry as Polyline; var pathCount:Number = pl.paths.length; var pathIndex:int = int((pathCount / 2) - 1); var midPath:Array = pl.paths[pathIndex]; var ptCount:Number = midPath.length; var ptIndex:int = int((ptCount / 2) - 1); point = pl.getPoint(pathIndex, ptIndex); break; } case Geometry.POLYGON: { const poly:Polygon = geometry as Polygon; point = poly.extent.center; break; } } } return point; } } }
Clean up ResultItem.
Clean up ResultItem.
ActionScript
apache-2.0
CanterburyRegionalCouncil/arcgis-viewer-flex,CanterburyRegionalCouncil/arcgis-viewer-flex,Esri/arcgis-viewer-flex,CanterburyRegionalCouncil/arcgis-viewer-flex,Esri/arcgis-viewer-flex
14630aae738e5ad4c3c49befed63596d93505323
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 { /** Default bufferlength in seconds. **/ private static const LENGTH:Number = 30; /** 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:Loader; /** Store that a fragment load is in progress. **/ private var _loading: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 _tag: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:Loader, 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 reachedend:Boolean = false; 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 playliststartpts:Number = _loader.getPlayListStartPTS(); var play_position:Number; if(playliststartpts < 0) { play_position = 0; } else { play_position = playback_current_time -(playliststartpts-_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(buffer < _loader.getBufferLength() && !_loading) { 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 sequence number requested is smaller than any seqnum available. it could happen on live playlist in 2 scenarios : if bandwidth available is lower than lowest quality needed bandwidth after long pause => seek(offset) to force a restart of the playback session we target second segment */ Log.txt("long pause on live stream or bad network quality"); seek(_loader.getSegmentMaxDuration()); 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 ... reachedend = true; } } } // Append tags to buffer. if((_state == HLSStates.PLAYING && _stream.bufferLength < 10) || (_state == HLSStates.BUFFERING && buffer > 10)) { //Log.txt("appending data"); while(_tag < _buffer.length && _stream.bufferLength < 20) { try { _stream.appendBytes(_buffer[_tag].data); } catch (error:Error) { _errorHandler(new Error(_buffer[_tag].type+": "+ error.message)); } // Last tag done? Then append sequence end. if (reachedend ==true && _tag == _buffer.length - 1) { _stream.appendBytesAction(NetStreamAppendBytesAction.END_SEQUENCE); _stream.appendBytes(new ByteArray()); } _tag++; } } // Set playback state and complete. if(_stream.bufferLength < 3) { if(reachedend ==true) { if(_stream.bufferLength == 0) { _complete(); } } else if(_state == HLSStates.PLAYING) { _setState(HLSStates.BUFFERING); } } else if (_state == HLSStates.BUFFERING) { _setState(HLSStates.PLAYING); } }; /** The video completed playback. **/ private function _complete():void { _setState(HLSStates.IDLE); clearInterval(_interval); // _stream.pause(); _hls.dispatchEvent(new HLSEvent(HLSEvent.COMPLETE)); }; /** 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(_tag); _tag = 0; if (_playback_start_pts == 0) { _playback_start_pts = min_pts; _playlist_start_pts = _loader.getPlayListStartPTS(); } _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; _tag = 0; PlaybackStartPosition = position; _stream.seek(0); _stream.appendBytesAction(NetStreamAppendBytesAction.RESET_SEEK); _playback_start_time = position; _playback_start_pts = 0; _buffer_next_time = _playback_start_time; _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:Loader; /** Store that a fragment load is in progress. **/ private var _loading: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 _tag: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:Loader, 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 reachedend:Boolean = false; 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 playliststartpts:Number = _loader.getPlayListStartPTS(); var play_position:Number; if(playliststartpts < 0) { play_position = 0; } else { play_position = playback_current_time -(playliststartpts-_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(buffer < _loader.getBufferLength() && !_loading) { 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 sequence number requested is smaller than any seqnum available. it could happen on live playlist in 2 scenarios : if bandwidth available is lower than lowest quality needed bandwidth after long pause => seek(offset) to force a restart of the playback session we target second segment */ Log.txt("long pause on live stream or bad network quality"); seek(_loader.getSegmentMaxDuration()); 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 ... reachedend = true; } } } // Append tags to buffer. if((_state == HLSStates.PLAYING && _stream.bufferLength < 10) || (_state == HLSStates.BUFFERING && buffer > 10)) { //Log.txt("appending data"); while(_tag < _buffer.length && _stream.bufferLength < 20) { try { _stream.appendBytes(_buffer[_tag].data); } catch (error:Error) { _errorHandler(new Error(_buffer[_tag].type+": "+ error.message)); } // Last tag done? Then append sequence end. if (reachedend ==true && _tag == _buffer.length - 1) { _stream.appendBytesAction(NetStreamAppendBytesAction.END_SEQUENCE); _stream.appendBytes(new ByteArray()); } _tag++; } } // Set playback state and complete. if(_stream.bufferLength < 3) { if(reachedend ==true) { if(_stream.bufferLength == 0) { _complete(); } } else if(_state == HLSStates.PLAYING) { _setState(HLSStates.BUFFERING); } } else if (_state == HLSStates.BUFFERING) { _setState(HLSStates.PLAYING); } }; /** The video completed playback. **/ private function _complete():void { _setState(HLSStates.IDLE); clearInterval(_interval); // _stream.pause(); _hls.dispatchEvent(new HLSEvent(HLSEvent.COMPLETE)); }; /** 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(_tag); _tag = 0; if (_playback_start_pts == 0) { _playback_start_pts = min_pts; _playlist_start_pts = _loader.getPlayListStartPTS(); } _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; _tag = 0; PlaybackStartPosition = position; _stream.seek(0); _stream.appendBytesAction(NetStreamAppendBytesAction.RESET_SEEK); _playback_start_time = position; _playback_start_pts = 0; _buffer_next_time = _playback_start_time; _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; } }; } }
remove unused variable
remove unused variable
ActionScript
mpl-2.0
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
82f31441f63995c90cfb8ddd607aa73e1e8d4468
src/flash/htmlelements/VideoElement.as
src/flash/htmlelements/VideoElement.as
package htmlelements { import flash.display.Sprite; import flash.events.*; import flash.net.NetConnection; import flash.net.NetStream; import flash.media.Video; import flash.media.SoundTransform; import flash.utils.Timer; import FlashMediaElement; import HtmlMediaEvent; public class VideoElement extends Sprite implements IMediaElement { private var _currentUrl:String = ""; private var _autoplay:Boolean = true; private var _preload:String = ""; private var _isPreloading:Boolean = false; private var _connection:NetConnection; private var _stream:NetStream; private var _video:Video; private var _element:FlashMediaElement; private var _soundTransform; private var _oldVolume:Number = 1; // event values private var _duration:Number = 0; private var _framerate:Number; private var _isPaused:Boolean = true; private var _isEnded:Boolean = false; private var _volume:Number = 1; private var _isMuted:Boolean = false; private var _bytesLoaded:Number = 0; private var _bytesTotal:Number = 0; private var _bufferedTime:Number = 0; private var _bufferEmpty:Boolean = false; private var _videoWidth:Number = -1; private var _videoHeight:Number = -1; private var _timer:Timer; private var _isRTMP:Boolean = false; private var _isConnected:Boolean = false; private var _playWhenConnected:Boolean = false; private var _hasStartedPlaying:Boolean = false; private var _parentReference:Object; public function setReference(arg:Object):void { _parentReference = arg; } public function get video():Video { return _video; } public function get videoHeight():Number { return _videoHeight; } public function get videoWidth():Number { return _videoWidth; } public function duration():Number { return _duration; } public function currentProgress():Number { if(_stream != null) { return Math.round(_stream.bytesLoaded/_stream.bytesTotal*100); } else { return 0; } } public function currentTime():Number { if (_stream != null) { return _stream.time; } else { return 0; } } // (1) load() // calls _connection.connect(); // waits for NetConnection.Connect.Success // _stream gets created public function VideoElement(element:FlashMediaElement, autoplay:Boolean, preload:String, timerRate:Number, startVolume:Number) { _element = element; _autoplay = autoplay; _volume = startVolume; _preload = preload; _video = new Video(); addChild(_video); _connection = new NetConnection(); _connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); _connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); //_connection.connect(null); _timer = new Timer(timerRate); _timer.addEventListener("timer", timerHandler); } private function timerHandler(e:TimerEvent) { _bytesLoaded = _stream.bytesLoaded; _bytesTotal = _stream.bytesTotal; if (!_isPaused) sendEvent(HtmlMediaEvent.TIMEUPDATE); //trace("bytes", _bytesLoaded, _bytesTotal); if (_bytesLoaded < _bytesTotal) sendEvent(HtmlMediaEvent.PROGRESS); } // internal events private function netStatusHandler(event:NetStatusEvent):void { trace("netStatus", event.info.code); switch (event.info.code) { case "NetStream.Buffer.Empty": _bufferEmpty = true; _isEnded ? sendEvent(HtmlMediaEvent.ENDED) : null; break; case "NetStream.Buffer.Full": _bytesLoaded = _stream.bytesLoaded; _bytesTotal = _stream.bytesTotal; _bufferEmpty = false; sendEvent(HtmlMediaEvent.PROGRESS); break; case "NetConnection.Connect.Success": connectStream(); break; case "NetStream.Play.StreamNotFound": trace("Unable to locate video"); break; // STREAM case "NetStream.Play.Start": _isPaused = false; sendEvent(HtmlMediaEvent.LOADEDDATA); sendEvent(HtmlMediaEvent.CANPLAY); if (!_isPreloading) { sendEvent(HtmlMediaEvent.PLAY); sendEvent(HtmlMediaEvent.PLAYING); } _timer.start(); break; case "NetStream.Seek.Notify": sendEvent(HtmlMediaEvent.SEEKED); break; case "NetStream.Pause.Notify": _isPaused = true; sendEvent(HtmlMediaEvent.PAUSE); break; case "NetStream.Play.Stop": _isEnded = true; _isPaused = false; _timer.stop(); _bufferEmpty ? sendEvent(HtmlMediaEvent.ENDED) : null; break; } } private function securityErrorHandler(event:SecurityErrorEvent):void { trace("securityErrorHandler: " + event); } private function asyncErrorHandler(event:AsyncErrorEvent):void { // ignore AsyncErrorEvent events. } private function onMetaDataHandler(info:Object):void { _duration = info.duration; _framerate = info.framerate; _videoWidth = info.width; _videoHeight = info.height; // set size? sendEvent(HtmlMediaEvent.LOADEDMETADATA); if (_isPreloading) { _stream.pause(); _isPaused = true; _isPreloading = false; sendEvent(HtmlMediaEvent.PROGRESS); sendEvent(HtmlMediaEvent.TIMEUPDATE); } } // interface members public function setSrc(url:String):void { if (_isConnected && _stream) { // stop and restart _stream.pause(); } _currentUrl = url; _isRTMP = !!_currentUrl.match(/^rtmp(s|t|e|te)?\:\/\//); _isConnected = false; _hasStartedPlaying = false; } public function load():void { // disconnect existing stream and connection if (_isConnected && _stream) { _stream.pause(); _stream.close(); _connection.close(); } _isConnected = false; _isPreloading = false; // start new connection if (_isRTMP) { _connection.connect(_currentUrl.replace(/\/[^\/]+$/,"/")); } else { _connection.connect(null); } // in a few moments the "NetConnection.Connect.Success" event will fire // and call createConnection which finishes the "load" sequence sendEvent(HtmlMediaEvent.LOADSTART); } private function connectStream():void { trace("connectStream"); _stream = new NetStream(_connection); // explicitly set the sound since it could have come before the connection was made _soundTransform = new SoundTransform(_volume); _stream.soundTransform = _soundTransform; _stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); // same event as connection _stream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler); var customClient:Object = new Object(); customClient.onMetaData = onMetaDataHandler; _stream.client = customClient; _video.attachNetStream(_stream); // start downloading without playing )based on preload and play() hasn't been called) // I wish flash had a load() command to make this less awkward if (_preload != "none" && !_playWhenConnected) { _isPaused = true; //stream.bufferTime = 20; _stream.play(_currentUrl, 0, 0); _stream.pause(); _isPreloading = true; //_stream.pause(); // //sendEvent(HtmlMediaEvent.PAUSE); // have to send this because the "playing" event gets sent via event handlers } _isConnected = true; if (_playWhenConnected && !_hasStartedPlaying) { play(); _playWhenConnected = false; } } public function play():void { if (!_hasStartedPlaying && !_isConnected) { _playWhenConnected = true; load(); return; } if (_hasStartedPlaying) { if (_isPaused) { _stream.resume(); _timer.start(); _isPaused = false; sendEvent(HtmlMediaEvent.PLAY); sendEvent(HtmlMediaEvent.PLAYING); } } else { if (_isRTMP) { _stream.play(_currentUrl.split("/").pop()); } else { _stream.play(_currentUrl); } _timer.start(); _isPaused = false; _hasStartedPlaying = true; // don't toss play/playing events here, because we haven't sent a // canplay / loadeddata event yet. that'll be handled in the net // event listener } } public function pause():void { if (_stream == null) return; _stream.pause(); _isPaused = true; if (_bytesLoaded == _bytesTotal) { _timer.stop(); } _isPaused = true; sendEvent(HtmlMediaEvent.PAUSE); } public function stop():void { if (_stream == null) return; _stream.close(); _isPaused = false; _timer.stop(); sendEvent(HtmlMediaEvent.STOP); } public function setCurrentTime(pos:Number):void { if (_stream == null) return; sendEvent(HtmlMediaEvent.SEEKING); _stream.seek(pos); sendEvent(HtmlMediaEvent.TIMEUPDATE); } public function setVolume(volume:Number):void { if (_stream != null) { _soundTransform = new SoundTransform(volume); _stream.soundTransform = _soundTransform; } _volume = volume; _isMuted = (_volume == 0); sendEvent(HtmlMediaEvent.VOLUMECHANGE); } public function getVolume():Number { if(_isMuted) { return 0; } else { return _volume; } } public function setMuted(muted:Boolean):void { if (_isMuted == muted) return; if (muted) { _oldVolume = (_stream == null) ? _oldVolume : _stream.soundTransform.volume; setVolume(0); } else { setVolume(_oldVolume); } _isMuted = muted; } private function sendEvent(eventName:String) { // calculate this to mimic HTML5 _bufferedTime = _bytesLoaded / _bytesTotal * _duration; // build JSON var values:String = "duration:" + _duration + ",framerate:" + _framerate + ",currentTime:" + (_stream != null ? _stream.time : 0) + ",muted:" + _isMuted + ",paused:" + _isPaused + ",ended:" + _isEnded + ",volume:" + _volume + ",src:\"" + _currentUrl + "\"" + ",bytesTotal:" + _bytesTotal + ",bufferedBytes:" + _bytesLoaded + ",bufferedTime:" + _bufferedTime + ",videoWidth:" + _videoWidth + ",videoHeight:" + _videoHeight + ""; _element.sendEvent(eventName, values); } } }
package htmlelements { import flash.display.Sprite; import flash.events.*; import flash.net.NetConnection; import flash.net.NetStream; import flash.media.Video; import flash.media.SoundTransform; import flash.utils.Timer; import FlashMediaElement; import HtmlMediaEvent; public class VideoElement extends Sprite implements IMediaElement { private var _currentUrl:String = ""; private var _autoplay:Boolean = true; private var _preload:String = ""; private var _isPreloading:Boolean = false; private var _connection:NetConnection; private var _stream:NetStream; private var _video:Video; private var _element:FlashMediaElement; private var _soundTransform; private var _oldVolume:Number = 1; // event values private var _duration:Number = 0; private var _framerate:Number; private var _isPaused:Boolean = true; private var _isEnded:Boolean = false; private var _volume:Number = 1; private var _isMuted:Boolean = false; private var _bytesLoaded:Number = 0; private var _bytesTotal:Number = 0; private var _bufferedTime:Number = 0; private var _bufferEmpty:Boolean = false; private var _videoWidth:Number = -1; private var _videoHeight:Number = -1; private var _timer:Timer; private var _isRTMP:Boolean = false; private var _isConnected:Boolean = false; private var _playWhenConnected:Boolean = false; private var _hasStartedPlaying:Boolean = false; private var _parentReference:Object; public function setReference(arg:Object):void { _parentReference = arg; } public function get video():Video { return _video; } public function get videoHeight():Number { return _videoHeight; } public function get videoWidth():Number { return _videoWidth; } public function duration():Number { return _duration; } public function currentProgress():Number { if(_stream != null) { return Math.round(_stream.bytesLoaded/_stream.bytesTotal*100); } else { return 0; } } public function currentTime():Number { if (_stream != null) { return _stream.time; } else { return 0; } } // (1) load() // calls _connection.connect(); // waits for NetConnection.Connect.Success // _stream gets created public function VideoElement(element:FlashMediaElement, autoplay:Boolean, preload:String, timerRate:Number, startVolume:Number) { _element = element; _autoplay = autoplay; _volume = startVolume; _preload = preload; _video = new Video(); addChild(_video); _connection = new NetConnection(); _connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); _connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); //_connection.connect(null); _timer = new Timer(timerRate); _timer.addEventListener("timer", timerHandler); } private function timerHandler(e:TimerEvent) { _bytesLoaded = _stream.bytesLoaded; _bytesTotal = _stream.bytesTotal; if (!_isPaused) sendEvent(HtmlMediaEvent.TIMEUPDATE); //trace("bytes", _bytesLoaded, _bytesTotal); if (_bytesLoaded < _bytesTotal) sendEvent(HtmlMediaEvent.PROGRESS); } // internal events private function netStatusHandler(event:NetStatusEvent):void { trace("netStatus", event.info.code); switch (event.info.code) { case "NetStream.Buffer.Empty": _bufferEmpty = true; _isEnded ? sendEvent(HtmlMediaEvent.ENDED) : null; break; case "NetStream.Buffer.Full": _bytesLoaded = _stream.bytesLoaded; _bytesTotal = _stream.bytesTotal; _bufferEmpty = false; sendEvent(HtmlMediaEvent.PROGRESS); break; case "NetConnection.Connect.Success": connectStream(); break; case "NetStream.Play.StreamNotFound": trace("Unable to locate video"); break; // STREAM case "NetStream.Play.Start": _isPaused = false; sendEvent(HtmlMediaEvent.LOADEDDATA); sendEvent(HtmlMediaEvent.CANPLAY); if (!_isPreloading) { sendEvent(HtmlMediaEvent.PLAY); sendEvent(HtmlMediaEvent.PLAYING); } _timer.start(); break; case "NetStream.Seek.Notify": sendEvent(HtmlMediaEvent.SEEKED); break; case "NetStream.Pause.Notify": _isPaused = true; sendEvent(HtmlMediaEvent.PAUSE); break; case "NetStream.Play.Stop": _isEnded = true; _isPaused = false; _timer.stop(); _bufferEmpty ? sendEvent(HtmlMediaEvent.ENDED) : null; break; } } private function securityErrorHandler(event:SecurityErrorEvent):void { trace("securityErrorHandler: " + event); } private function asyncErrorHandler(event:AsyncErrorEvent):void { // ignore AsyncErrorEvent events. } private function onMetaDataHandler(info:Object):void { _duration = info.duration; _framerate = info.framerate; _videoWidth = info.width; _videoHeight = info.height; // set size? sendEvent(HtmlMediaEvent.LOADEDMETADATA); if (_isPreloading) { _stream.pause(); _isPaused = true; _isPreloading = false; sendEvent(HtmlMediaEvent.PROGRESS); sendEvent(HtmlMediaEvent.TIMEUPDATE); } } // interface members public function setSrc(url:String):void { if (_isConnected && _stream) { // stop and restart _stream.pause(); } _currentUrl = url; _isRTMP = !!_currentUrl.match(/^rtmp(s|t|e|te)?\:\/\//); _isConnected = false; _hasStartedPlaying = false; } public function load():void { // disconnect existing stream and connection if (_isConnected && _stream) { _stream.pause(); _stream.close(); _connection.close(); } _isConnected = false; _isPreloading = false; _isEnded = false; _bufferEmpty = false; // start new connection if (_isRTMP) { _connection.connect(_currentUrl.replace(/\/[^\/]+$/,"/")); } else { _connection.connect(null); } // in a few moments the "NetConnection.Connect.Success" event will fire // and call createConnection which finishes the "load" sequence sendEvent(HtmlMediaEvent.LOADSTART); } private function connectStream():void { trace("connectStream"); _stream = new NetStream(_connection); // explicitly set the sound since it could have come before the connection was made _soundTransform = new SoundTransform(_volume); _stream.soundTransform = _soundTransform; _stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); // same event as connection _stream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler); var customClient:Object = new Object(); customClient.onMetaData = onMetaDataHandler; _stream.client = customClient; _video.attachNetStream(_stream); // start downloading without playing )based on preload and play() hasn't been called) // I wish flash had a load() command to make this less awkward if (_preload != "none" && !_playWhenConnected) { _isPaused = true; //stream.bufferTime = 20; _stream.play(_currentUrl, 0, 0); _stream.pause(); _isPreloading = true; //_stream.pause(); // //sendEvent(HtmlMediaEvent.PAUSE); // have to send this because the "playing" event gets sent via event handlers } _isConnected = true; if (_playWhenConnected && !_hasStartedPlaying) { play(); _playWhenConnected = false; } } public function play():void { if (!_hasStartedPlaying && !_isConnected) { _playWhenConnected = true; load(); return; } if (_hasStartedPlaying) { if (_isPaused) { _stream.resume(); _timer.start(); _isPaused = false; sendEvent(HtmlMediaEvent.PLAY); sendEvent(HtmlMediaEvent.PLAYING); } } else { if (_isRTMP) { _stream.play(_currentUrl.split("/").pop()); } else { _stream.play(_currentUrl); } _timer.start(); _isPaused = false; _hasStartedPlaying = true; // don't toss play/playing events here, because we haven't sent a // canplay / loadeddata event yet. that'll be handled in the net // event listener } } public function pause():void { if (_stream == null) return; _stream.pause(); _isPaused = true; if (_bytesLoaded == _bytesTotal) { _timer.stop(); } _isPaused = true; sendEvent(HtmlMediaEvent.PAUSE); } public function stop():void { if (_stream == null) return; _stream.close(); _isPaused = false; _timer.stop(); sendEvent(HtmlMediaEvent.STOP); } public function setCurrentTime(pos:Number):void { if (_stream == null) return; sendEvent(HtmlMediaEvent.SEEKING); _stream.seek(pos); sendEvent(HtmlMediaEvent.TIMEUPDATE); } public function setVolume(volume:Number):void { if (_stream != null) { _soundTransform = new SoundTransform(volume); _stream.soundTransform = _soundTransform; } _volume = volume; _isMuted = (_volume == 0); sendEvent(HtmlMediaEvent.VOLUMECHANGE); } public function getVolume():Number { if(_isMuted) { return 0; } else { return _volume; } } public function setMuted(muted:Boolean):void { if (_isMuted == muted) return; if (muted) { _oldVolume = (_stream == null) ? _oldVolume : _stream.soundTransform.volume; setVolume(0); } else { setVolume(_oldVolume); } _isMuted = muted; } private function sendEvent(eventName:String) { // calculate this to mimic HTML5 _bufferedTime = _bytesLoaded / _bytesTotal * _duration; // build JSON var values:String = "duration:" + _duration + ",framerate:" + _framerate + ",currentTime:" + (_stream != null ? _stream.time : 0) + ",muted:" + _isMuted + ",paused:" + _isPaused + ",ended:" + _isEnded + ",volume:" + _volume + ",src:\"" + _currentUrl + "\"" + ",bytesTotal:" + _bytesTotal + ",bufferedBytes:" + _bytesLoaded + ",bufferedTime:" + _bufferedTime + ",videoWidth:" + _videoWidth + ",videoHeight:" + _videoHeight + ""; _element.sendEvent(eventName, values); } } }
reset variables upon load
reset variables upon load
ActionScript
agpl-3.0
libeo/Vibeo,libeo/Vibeo,libeo/Vibeo,libeo/Vibeo
fef4e4c9346bf2caf5e8e6c1efdc93fd8ff9ec05
src/flash/htmlelements/VideoElement.as
src/flash/htmlelements/VideoElement.as
package htmlelements { import flash.display.Sprite; import flash.events.*; import flash.net.NetConnection; import flash.net.NetStream; import flash.media.Video; import flash.media.SoundTransform; import flash.utils.Timer; import FlashMediaElement; import HtmlMediaEvent; public class VideoElement extends Sprite implements IMediaElement { private var _currentUrl:String = ""; private var _autoplay:Boolean = true; private var _preload:String = ""; private var _isPreloading:Boolean = false; private var _connection:NetConnection; private var _stream:NetStream; private var _video:Video; private var _element:FlashMediaElement; private var _soundTransform; private var _oldVolume:Number = 1; // event values private var _duration:Number = 0; private var _framerate:Number; private var _isPaused:Boolean = true; private var _isEnded:Boolean = false; private var _volume:Number = 1; private var _isMuted:Boolean = false; private var _bytesLoaded:Number = 0; private var _bytesTotal:Number = 0; private var _bufferedTime:Number = 0; private var _bufferEmpty:Boolean = false; private var _videoWidth:Number = -1; private var _videoHeight:Number = -1; private var _timer:Timer; private var _isRTMP:Boolean = false; private var _isConnected:Boolean = false; private var _playWhenConnected:Boolean = false; private var _hasStartedPlaying:Boolean = false; private var _parentReference:Object; public function setReference(arg:Object):void { _parentReference = arg; } public function setSize(width:Number, height:Number):void { _video.width = width; _video.height = height; } public function get video():Video { return _video; } public function get videoHeight():Number { return _videoHeight; } public function get videoWidth():Number { return _videoWidth; } public function duration():Number { return _duration; } public function currentProgress():Number { if(_stream != null) { return Math.round(_stream.bytesLoaded/_stream.bytesTotal*100); } else { return 0; } } public function currentTime():Number { if (_stream != null) { return _stream.time; } else { return 0; } } // (1) load() // calls _connection.connect(); // waits for NetConnection.Connect.Success // _stream gets created public function VideoElement(element:FlashMediaElement, autoplay:Boolean, preload:String, timerRate:Number, startVolume:Number) { _element = element; _autoplay = autoplay; _volume = startVolume; _preload = preload; _video = new Video(); addChild(_video); _connection = new NetConnection(); _connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); _connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); //_connection.connect(null); _timer = new Timer(timerRate); _timer.addEventListener("timer", timerHandler); } private function timerHandler(e:TimerEvent) { _bytesLoaded = _stream.bytesLoaded; _bytesTotal = _stream.bytesTotal; if (!_isPaused) sendEvent(HtmlMediaEvent.TIMEUPDATE); //trace("bytes", _bytesLoaded, _bytesTotal); if (_bytesLoaded < _bytesTotal) sendEvent(HtmlMediaEvent.PROGRESS); } // internal events private function netStatusHandler(event:NetStatusEvent):void { trace("netStatus", event.info.code); switch (event.info.code) { case "NetStream.Buffer.Empty": _bufferEmpty = true; _isEnded ? sendEvent(HtmlMediaEvent.ENDED) : null; break; case "NetStream.Buffer.Full": _bytesLoaded = _stream.bytesLoaded; _bytesTotal = _stream.bytesTotal; _bufferEmpty = false; sendEvent(HtmlMediaEvent.PROGRESS); break; case "NetConnection.Connect.Success": connectStream(); break; case "NetStream.Play.StreamNotFound": trace("Unable to locate video"); break; // STREAM case "NetStream.Play.Start": _isPaused = false; sendEvent(HtmlMediaEvent.LOADEDDATA); sendEvent(HtmlMediaEvent.CANPLAY); if (!_isPreloading) { sendEvent(HtmlMediaEvent.PLAY); sendEvent(HtmlMediaEvent.PLAYING); } _timer.start(); break; case "NetStream.Seek.Notify": sendEvent(HtmlMediaEvent.SEEKED); break; case "NetStream.Pause.Notify": _isPaused = true; sendEvent(HtmlMediaEvent.PAUSE); break; case "NetStream.Play.Stop": _isEnded = true; _isPaused = false; _timer.stop(); _bufferEmpty ? sendEvent(HtmlMediaEvent.ENDED) : null; break; } } private function securityErrorHandler(event:SecurityErrorEvent):void { trace("securityErrorHandler: " + event); } private function asyncErrorHandler(event:AsyncErrorEvent):void { // ignore AsyncErrorEvent events. } private function onMetaDataHandler(info:Object):void { _duration = info.duration; _framerate = info.framerate; _videoWidth = info.width; _videoHeight = info.height; // set size? sendEvent(HtmlMediaEvent.LOADEDMETADATA); if (_isPreloading) { _stream.pause(); _isPaused = true; _isPreloading = false; sendEvent(HtmlMediaEvent.PROGRESS); sendEvent(HtmlMediaEvent.TIMEUPDATE); } } // interface members public function setSrc(url:String):void { if (_isConnected && _stream) { // stop and restart _stream.pause(); } _currentUrl = url; _isRTMP = !!_currentUrl.match(/^rtmp(s|t|e|te)?\:\/\//); _isConnected = false; _hasStartedPlaying = false; } public function load():void { // disconnect existing stream and connection if (_isConnected && _stream) { _stream.pause(); _stream.close(); _connection.close(); } _isConnected = false; _isPreloading = false; _isEnded = false; _bufferEmpty = false; // start new connection if (_isRTMP) { _connection.connect(_currentUrl.replace(/\/[^\/]+$/,"/")); } else { _connection.connect(null); } // in a few moments the "NetConnection.Connect.Success" event will fire // and call createConnection which finishes the "load" sequence sendEvent(HtmlMediaEvent.LOADSTART); } private function connectStream():void { trace("connectStream"); _stream = new NetStream(_connection); // explicitly set the sound since it could have come before the connection was made _soundTransform = new SoundTransform(_volume); _stream.soundTransform = _soundTransform; _stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); // same event as connection _stream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler); var customClient:Object = new Object(); customClient.onMetaData = onMetaDataHandler; _stream.client = customClient; _video.attachNetStream(_stream); // start downloading without playing )based on preload and play() hasn't been called) // I wish flash had a load() command to make this less awkward if (_preload != "none" && !_playWhenConnected) { _isPaused = true; //stream.bufferTime = 20; _stream.play(_currentUrl, 0, 0); _stream.pause(); _isPreloading = true; //_stream.pause(); // //sendEvent(HtmlMediaEvent.PAUSE); // have to send this because the "playing" event gets sent via event handlers } _isConnected = true; if (_playWhenConnected && !_hasStartedPlaying) { play(); _playWhenConnected = false; } } public function play():void { if (!_hasStartedPlaying && !_isConnected) { _playWhenConnected = true; load(); return; } if (_hasStartedPlaying) { if (_isPaused) { _stream.resume(); _timer.start(); _isPaused = false; sendEvent(HtmlMediaEvent.PLAY); sendEvent(HtmlMediaEvent.PLAYING); } } else { if (_isRTMP) { _stream.play(_currentUrl.split("/").pop()); } else { _stream.play(_currentUrl); } _timer.start(); _isPaused = false; _hasStartedPlaying = true; // don't toss play/playing events here, because we haven't sent a // canplay / loadeddata event yet. that'll be handled in the net // event listener } } public function pause():void { if (_stream == null) return; _stream.pause(); _isPaused = true; if (_bytesLoaded == _bytesTotal) { _timer.stop(); } _isPaused = true; sendEvent(HtmlMediaEvent.PAUSE); } public function stop():void { if (_stream == null) return; _stream.close(); _isPaused = false; _timer.stop(); sendEvent(HtmlMediaEvent.STOP); } public function setCurrentTime(pos:Number):void { if (_stream == null) return; sendEvent(HtmlMediaEvent.SEEKING); _stream.seek(pos); sendEvent(HtmlMediaEvent.TIMEUPDATE); } public function setVolume(volume:Number):void { if (_stream != null) { _soundTransform = new SoundTransform(volume); _stream.soundTransform = _soundTransform; } _volume = volume; _isMuted = (_volume == 0); sendEvent(HtmlMediaEvent.VOLUMECHANGE); } public function getVolume():Number { if(_isMuted) { return 0; } else { return _volume; } } public function setMuted(muted:Boolean):void { if (_isMuted == muted) return; if (muted) { _oldVolume = (_stream == null) ? _oldVolume : _stream.soundTransform.volume; setVolume(0); } else { setVolume(_oldVolume); } _isMuted = muted; } private function sendEvent(eventName:String) { // calculate this to mimic HTML5 _bufferedTime = _bytesLoaded / _bytesTotal * _duration; // build JSON var values:String = "duration:" + _duration + ",framerate:" + _framerate + ",currentTime:" + (_stream != null ? _stream.time : 0) + ",muted:" + _isMuted + ",paused:" + _isPaused + ",ended:" + _isEnded + ",volume:" + _volume + ",src:\"" + _currentUrl + "\"" + ",bytesTotal:" + _bytesTotal + ",bufferedBytes:" + _bytesLoaded + ",bufferedTime:" + _bufferedTime + ",videoWidth:" + _videoWidth + ",videoHeight:" + _videoHeight + ""; _element.sendEvent(eventName, values); } } }
package htmlelements { import flash.display.Sprite; import flash.events.*; import flash.net.NetConnection; import flash.net.NetStream; import flash.media.Video; import flash.media.SoundTransform; import flash.utils.Timer; import FlashMediaElement; import HtmlMediaEvent; public class VideoElement extends Sprite implements IMediaElement { private var _currentUrl:String = ""; private var _autoplay:Boolean = true; private var _preload:String = ""; private var _isPreloading:Boolean = false; private var _connection:NetConnection; private var _stream:NetStream; private var _video:Video; private var _element:FlashMediaElement; private var _soundTransform; private var _oldVolume:Number = 1; // event values private var _duration:Number = 0; private var _framerate:Number; private var _isPaused:Boolean = true; private var _isEnded:Boolean = false; private var _volume:Number = 1; private var _isMuted:Boolean = false; private var _bytesLoaded:Number = 0; private var _bytesTotal:Number = 0; private var _bufferedTime:Number = 0; private var _bufferEmpty:Boolean = false; private var _videoWidth:Number = -1; private var _videoHeight:Number = -1; private var _timer:Timer; private var _isRTMP:Boolean = false; private var _isConnected:Boolean = false; private var _playWhenConnected:Boolean = false; private var _hasStartedPlaying:Boolean = false; private var _parentReference:Object; public function setReference(arg:Object):void { _parentReference = arg; } public function setSize(width:Number, height:Number):void { _video.width = width; _video.height = height; } public function get video():Video { return _video; } public function get videoHeight():Number { return _videoHeight; } public function get videoWidth():Number { return _videoWidth; } public function duration():Number { return _duration; } public function currentProgress():Number { if(_stream != null) { return Math.round(_stream.bytesLoaded/_stream.bytesTotal*100); } else { return 0; } } public function currentTime():Number { if (_stream != null) { return _stream.time; } else { return 0; } } // (1) load() // calls _connection.connect(); // waits for NetConnection.Connect.Success // _stream gets created public function VideoElement(element:FlashMediaElement, autoplay:Boolean, preload:String, timerRate:Number, startVolume:Number) { _element = element; _autoplay = autoplay; _volume = startVolume; _preload = preload; _video = new Video(); addChild(_video); _connection = new NetConnection(); _connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); _connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); //_connection.connect(null); _timer = new Timer(timerRate); _timer.addEventListener("timer", timerHandler); } private function timerHandler(e:TimerEvent) { _bytesLoaded = _stream.bytesLoaded; _bytesTotal = _stream.bytesTotal; if (!_isPaused) sendEvent(HtmlMediaEvent.TIMEUPDATE); //trace("bytes", _bytesLoaded, _bytesTotal); if (_bytesLoaded < _bytesTotal) sendEvent(HtmlMediaEvent.PROGRESS); } // internal events private function netStatusHandler(event:NetStatusEvent):void { trace("netStatus", event.info.code); switch (event.info.code) { case "NetStream.Buffer.Empty": _bufferEmpty = true; _isEnded ? sendEvent(HtmlMediaEvent.ENDED) : null; break; case "NetStream.Buffer.Full": _bytesLoaded = _stream.bytesLoaded; _bytesTotal = _stream.bytesTotal; _bufferEmpty = false; sendEvent(HtmlMediaEvent.PROGRESS); break; case "NetConnection.Connect.Success": connectStream(); break; case "NetStream.Play.StreamNotFound": trace("Unable to locate video"); break; // STREAM case "NetStream.Play.Start": _isPaused = false; sendEvent(HtmlMediaEvent.LOADEDDATA); sendEvent(HtmlMediaEvent.CANPLAY); if (!_isPreloading) { sendEvent(HtmlMediaEvent.PLAY); sendEvent(HtmlMediaEvent.PLAYING); } _timer.start(); break; case "NetStream.Seek.Notify": sendEvent(HtmlMediaEvent.SEEKED); break; case "NetStream.Pause.Notify": _isPaused = true; sendEvent(HtmlMediaEvent.PAUSE); break; case "NetStream.Play.Stop": _isEnded = true; _isPaused = false; _timer.stop(); _bufferEmpty ? sendEvent(HtmlMediaEvent.ENDED) : null; break; } } private function securityErrorHandler(event:SecurityErrorEvent):void { trace("securityErrorHandler: " + event); } private function asyncErrorHandler(event:AsyncErrorEvent):void { // ignore AsyncErrorEvent events. } private function onMetaDataHandler(info:Object):void { _duration = info.duration; _framerate = info.framerate; _videoWidth = info.width; _videoHeight = info.height; // set size? sendEvent(HtmlMediaEvent.LOADEDMETADATA); if (_isPreloading) { _stream.pause(); _isPaused = true; _isPreloading = false; sendEvent(HtmlMediaEvent.PROGRESS); sendEvent(HtmlMediaEvent.TIMEUPDATE); } } // interface members public function setSrc(url:String):void { if (_isConnected && _stream) { // stop and restart _stream.pause(); } _currentUrl = url; _isRTMP = !!_currentUrl.match(/^rtmp(s|t|e|te)?\:\/\//); _isConnected = false; _hasStartedPlaying = false; } public function load():void { // disconnect existing stream and connection if (_isConnected && _stream) { _stream.pause(); _stream.close(); _connection.close(); } _isConnected = false; _isPreloading = false; _isEnded = false; _bufferEmpty = false; // start new connection if (_isRTMP) { _connection.connect(_currentUrl.replace(/\/[^\/]+$/,"/")); } else { _connection.connect(null); } // in a few moments the "NetConnection.Connect.Success" event will fire // and call createConnection which finishes the "load" sequence sendEvent(HtmlMediaEvent.LOADSTART); } private function connectStream():void { trace("connectStream"); _stream = new NetStream(_connection); // explicitly set the sound since it could have come before the connection was made _soundTransform = new SoundTransform(_volume); _stream.soundTransform = _soundTransform; _stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); // same event as connection _stream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler); var customClient:Object = new Object(); customClient.onMetaData = onMetaDataHandler; _stream.client = customClient; _video.attachNetStream(_stream); // start downloading without playing )based on preload and play() hasn't been called) // I wish flash had a load() command to make this less awkward if (_preload != "none" && !_playWhenConnected) { _isPaused = true; //stream.bufferTime = 20; _stream.play(_currentUrl, 0, 0); _stream.pause(); _isPreloading = true; //_stream.pause(); // //sendEvent(HtmlMediaEvent.PAUSE); // have to send this because the "playing" event gets sent via event handlers } _isConnected = true; if (_playWhenConnected && !_hasStartedPlaying) { play(); _playWhenConnected = false; } } public function play():void { if (!_hasStartedPlaying && !_isConnected) { _playWhenConnected = true; load(); return; } if (_hasStartedPlaying) { if (_isPaused) { _stream.resume(); _timer.start(); _isPaused = false; sendEvent(HtmlMediaEvent.PLAY); sendEvent(HtmlMediaEvent.PLAYING); } } else { if (_isRTMP) { _stream.play(_currentUrl.split("/").pop()); } else { _stream.play(_currentUrl); } _timer.start(); _isPaused = false; _hasStartedPlaying = true; // don't toss play/playing events here, because we haven't sent a // canplay / loadeddata event yet. that'll be handled in the net // event listener } } public function pause():void { if (_stream == null) return; _stream.pause(); _isPaused = true; if (_bytesLoaded == _bytesTotal) { _timer.stop(); } _isPaused = true; sendEvent(HtmlMediaEvent.PAUSE); } public function stop():void { if (_stream == null) return; _stream.close(); _isPaused = false; _timer.stop(); sendEvent(HtmlMediaEvent.STOP); } public function setCurrentTime(pos:Number):void { if (_stream == null) return; sendEvent(HtmlMediaEvent.SEEKING); _stream.seek(pos); sendEvent(HtmlMediaEvent.TIMEUPDATE); } public function setVolume(volume:Number):void { if (_stream != null) { _soundTransform = new SoundTransform(volume); _stream.soundTransform = _soundTransform; } _volume = volume; _isMuted = (_volume == 0); sendEvent(HtmlMediaEvent.VOLUMECHANGE); } public function getVolume():Number { if(_isMuted) { return 0; } else { return _volume; } } public function setMuted(muted:Boolean):void { if (_isMuted == muted) return; if (muted) { _oldVolume = (_stream == null) ? _oldVolume : _stream.soundTransform.volume; setVolume(0); } else { setVolume(_oldVolume); } _isMuted = muted; } private function sendEvent(eventName:String) { // calculate this to mimic HTML5 _bufferedTime = _bytesLoaded / _bytesTotal * _duration; // build JSON var values:String = "duration:" + _duration + ",framerate:" + _framerate + ",currentTime:" + (_stream != null ? _stream.time : 0) + ",muted:" + _isMuted + ",paused:" + _isPaused + ",ended:" + _isEnded + ",volume:" + _volume + ",src:\"" + _currentUrl + "\"" + ",bytesTotal:" + _bytesTotal + ",bufferedBytes:" + _bytesLoaded + ",bufferedTime:" + _bufferedTime + ",videoWidth:" + _videoWidth + ",videoHeight:" + _videoHeight + ""; _element.sendEvent(eventName, values); } } }
Normalize line endings
Normalize line endings
ActionScript
agpl-3.0
libeo/Vibeo,libeo/Vibeo,libeo/Vibeo,libeo/Vibeo
328c58254e6c21efec8876dd588103f66fd21bf2
src/aerys/minko/render/material/realistic/RealisticMaterial.as
src/aerys/minko/render/material/realistic/RealisticMaterial.as
package aerys.minko.render.material.realistic { import aerys.minko.render.Effect; import aerys.minko.render.material.environment.EnvironmentMappingProperties; import aerys.minko.render.material.phong.PhongEffect; import aerys.minko.render.material.phong.PhongMaterial; import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.scene.node.Scene; import aerys.minko.type.binding.IDataProvider; import flash.utils.Dictionary; public class RealisticMaterial extends PhongMaterial { private static const DEFAULT_NAME : String = 'RealisticMaterial'; private static const SCENE_TO_EFFECT : Dictionary = new Dictionary(true); public function get environmentMap() : ITextureResource { return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP) as ITextureResource; } public function set environmentMap(value : ITextureResource) : void { setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP, value); } public function get environmentMapFiltering() : uint { return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FILTERING); } public function set environmentMapFiltering(value : uint) : void { setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FILTERING, value); } public function get environmentMapMipMapping() : uint { return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_MIPMAPPING); } public function set environmentMapMipMapping(value : uint) : void { setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_MIPMAPPING, value); } public function get environmentMapWrapping() : uint { return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_WRAPPING); } public function set environmentMapWrapping(value : uint) : void { setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_WRAPPING, value); } public function get environmentMapFormat() : uint { return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FORMAT); } public function set environmentMapFormat(value : uint) : void { setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FORMAT, value); } public function get reflectivity() : Number { return getProperty(EnvironmentMappingProperties.REFLECTIVITY) as Number; } public function set reflectivity(value : Number) : void { setProperty(EnvironmentMappingProperties.REFLECTIVITY, value); } public function get environmentMappingType() : uint { return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE) as uint; } public function set environmentMappingType(value : uint) : void { setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE, value); } public function get environmentBlending() : uint { return getProperty(EnvironmentMappingProperties.ENVIRONMENT_BLENDING) as uint; } public function set environmentBlending(value : uint) : void { setProperty(EnvironmentMappingProperties.ENVIRONMENT_BLENDING, value); } public function RealisticMaterial(properties : Object = null, effect : Effect = null, name : String = DEFAULT_NAME) { super(properties, effect || new PhongEffect(new RealisticShader()), name); } override public function clone() : IDataProvider { return new RealisticMaterial(this, effect, name); } } }
package aerys.minko.render.material.realistic { import aerys.minko.render.Effect; import aerys.minko.render.material.environment.EnvironmentMappingProperties; import aerys.minko.render.material.phong.PhongEffect; import aerys.minko.render.material.phong.PhongMaterial; import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.scene.node.Scene; import aerys.minko.type.binding.IDataProvider; import flash.utils.Dictionary; public class RealisticMaterial extends PhongMaterial { private static const DEFAULT_NAME : String = 'RealisticMaterial'; private static const DEFAULT_EFFECT : Effect = new PhongEffect( new RealisticShader() ); public function get environmentMap() : ITextureResource { return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP) as ITextureResource; } public function set environmentMap(value : ITextureResource) : void { setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP, value); } public function get environmentMapFiltering() : uint { return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FILTERING); } public function set environmentMapFiltering(value : uint) : void { setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FILTERING, value); } public function get environmentMapMipMapping() : uint { return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_MIPMAPPING); } public function set environmentMapMipMapping(value : uint) : void { setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_MIPMAPPING, value); } public function get environmentMapWrapping() : uint { return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_WRAPPING); } public function set environmentMapWrapping(value : uint) : void { setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_WRAPPING, value); } public function get environmentMapFormat() : uint { return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FORMAT); } public function set environmentMapFormat(value : uint) : void { setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FORMAT, value); } public function get reflectivity() : Number { return getProperty(EnvironmentMappingProperties.REFLECTIVITY) as Number; } public function set reflectivity(value : Number) : void { setProperty(EnvironmentMappingProperties.REFLECTIVITY, value); } public function get environmentMappingType() : uint { return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE) as uint; } public function set environmentMappingType(value : uint) : void { setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE, value); } public function get environmentBlending() : uint { return getProperty(EnvironmentMappingProperties.ENVIRONMENT_BLENDING) as uint; } public function set environmentBlending(value : uint) : void { setProperty(EnvironmentMappingProperties.ENVIRONMENT_BLENDING, value); } public function RealisticMaterial(properties : Object = null, effect : Effect = null, name : String = DEFAULT_NAME) { super(properties, effect || DEFAULT_EFFECT, name); } override public function clone() : IDataProvider { return new RealisticMaterial(this, effect, name); } } }
define a static const default effect for the RealisticMaterial and use it properly in the constructor
define a static const default effect for the RealisticMaterial and use it properly in the constructor
ActionScript
mit
aerys/minko-as3
5f9b770ac4d5d2b6799009db942e4bfcd3ffb7bc
src/goplayer/FlashContentLoadAttempt.as
src/goplayer/FlashContentLoadAttempt.as
package goplayer { import flash.display.Loader import flash.events.Event import flash.events.IOErrorEvent import flash.net.URLRequest import flash.system.ApplicationDomain import flash.system.LoaderContext import flash.system.SecurityDomain public class FlashContentLoadAttempt { private const loader : Loader = new Loader private var url : String private var listener : FlashContentLoaderListener public function FlashContentLoadAttempt (url : String, listener : FlashContentLoaderListener) { this.url = url, this.listener = listener loader.contentLoaderInfo.addEventListener (Event.COMPLETE, handleContentLoaded) loader.contentLoaderInfo.addEventListener (IOErrorEvent.IO_ERROR, handleIOError) } public function execute() : void { loader.load(new URLRequest(url)) } private function get loaderContext() : LoaderContext { const result : LoaderContext = new LoaderContext(false, new ApplicationDomain(ApplicationDomain.currentDomain)) result.securityDomain = SecurityDomain.currentDomain return result } private function handleContentLoaded(event : Event) : void { listener.handleContentLoaded(loader.contentLoaderInfo) } private function handleIOError(event : IOErrorEvent) : void { debug("Failed to load <" + url + ">: " + event.text) } } }
package goplayer { import flash.display.Loader import flash.events.Event import flash.events.IOErrorEvent import flash.net.URLRequest import flash.system.ApplicationDomain import flash.system.LoaderContext import flash.system.SecurityDomain public class FlashContentLoadAttempt { private const loader : Loader = new Loader private var url : String private var listener : FlashContentLoaderListener public function FlashContentLoadAttempt (url : String, listener : FlashContentLoaderListener) { this.url = url, this.listener = listener loader.contentLoaderInfo.addEventListener (Event.COMPLETE, handleContentLoaded) loader.contentLoaderInfo.addEventListener (IOErrorEvent.IO_ERROR, handleIOError) } public function execute() : void { loader.load(new URLRequest(url)) } private function handleContentLoaded(event : Event) : void { listener.handleContentLoaded(loader.contentLoaderInfo) } private function handleIOError(event : IOErrorEvent) : void { debug("Failed to load <" + url + ">: " + event.text) } } }
Remove custom LoaderContext creation code.
Remove custom LoaderContext creation code.
ActionScript
mit
dbrock/goplayer,dbrock/goplayer
b25a52b620acae386c3db7b31a0933c917843174
LoadSwf/src/LoadSwf.as
LoadSwf/src/LoadSwf.as
package { import flash.desktop.NativeApplication; import flash.display.DisplayObject; import flash.display.Loader; import flash.display.LoaderInfo; import flash.display.MovieClip; import flash.display.Shape; import flash.display.Sprite; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.KeyboardEvent; import flash.events.SecurityErrorEvent; import flash.filesystem.File; import flash.net.URLLoader; import flash.net.URLRequest; import flashx.textLayout.events.ModelChange; public class LoadSwf extends Sprite { private var swfLoader:Loader = new Loader(); private var swfMC:MovieClip = null; private var pathXml:XML = null; public function LoadSwf() { super(); initStage(); initPath(); } //-------------------------------- private function initStage():void { // stage.color = 0x00000; stage.addEventListener(Event.ACTIVATE, onActivate); stage.addEventListener(Event.DEACTIVATE, onDeActivate); stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp); } private function onKeyUp(e:KeyboardEvent):void { trace("onKeyUp(), "+e.keyCode); swfStop(); } private function onDeActivate(e:Event):void { trace("onDeActivate()"); swfPause(); } private function onActivate(e:Event):void { trace("onActivate()"); swfResume(); } //--------------------------------- private function initLoader():void { swfLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete); swfLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, loadIOError); swfLoader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, loadSecurityError); var url:String = jointUrl(pathXml.url); trace("url: "+url); swfLoader.load(new URLRequest(url)); } private function swfResume():void { // if (swfMC != null) { // swfMC.play(); // } } private function swfPause():void { // if (swfMC != null) { // swfMC.stop(); // } swfStop(); } private function swfStop():void { swfLoader.unloadAndStop(); NativeApplication.nativeApplication.exit(); } private function loadComplete(e:Event):void { trace("loadComplete()"); centerAndFull(swfLoader, e); swfLoader.mask = getMasker(swfLoader, e); stage.addChild(swfLoader.mask); stage.addChild(swfLoader); swfMC = swfLoader as MovieClip; } private function loadIOError(e:IOErrorEvent):void { trace("swfLoader loadIOError, "+e.toString()); } private function loadSecurityError(e:SecurityErrorEvent):void { trace("swfLoader loadSecurityError, "+e.toString()); } //----------------------- private function getMasker(o:DisplayObject, e:Event):Shape { var li:LoaderInfo = LoaderInfo(e.target); var masker:Shape = new Shape(); masker.graphics.beginFill(0xff0000); masker.graphics.drawRect(o.x, o.y, li.width*o.scaleX, li.height*o.scaleY); masker.graphics.endFill(); return masker; } private function traceInfo(o:DisplayObject):void { trace("x:"+o.x+", y:"+o.y + "\nw:"+o.width +", h:" + o.height + "\nsx:" + o.scaleX +", sy:"+o.scaleY+", sz:"+o.scaleZ); } private function centerAndFull(o:DisplayObject, e:Event):void { traceInfo(o); var loadInfo:LoaderInfo = LoaderInfo(e.target); //full var scalex:Number = stage.stageWidth / loadInfo.width; var scaley:Number = stage.stageHeight / loadInfo.height; var scale:Number = scalex < scaley ? scalex : scaley; o.width *= scale; o.height *= scale; //center o.x = (stage.stageWidth - loadInfo.width*scale) / 2; o.y = (stage.stageHeight - loadInfo.height*scale) / 2; traceInfo(o); } //----------------------- private function initPath():void { var loader:URLLoader = new URLLoader(); loader.addEventListener(Event.COMPLETE, function(e:Event):void { trace("xml load complete, \n"+e.target.data); pathXml = XML(e.target.data); initLoader(); }); loader.addEventListener(IOErrorEvent.IO_ERROR, function(e:IOErrorEvent):void { trace("io error, "+e.toString()); }); loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function(e:SecurityErrorEvent):void { trace("security error, "+e.toString()); }); loader.load(new URLRequest(jointUrl("data/path.xml"))); } private function getRootUrl():String { return File.documentsDirectory.url+File.separator; } private function jointUrl(name:String):String { return getRootUrl()+name; } //-- for test -- private function readDir():void { var file:File = File.documentsDirectory; var fileObj:File; var docsDirectory:Array = file.getDirectoryListing(); trace(file.url+"\n"+file.nativePath); for (var i:int = 0; i < docsDirectory.length; i++) { fileObj = docsDirectory[i]; trace(fileObj.name); } } } }
package { import flash.desktop.NativeApplication; import flash.display.AVM1Movie; import flash.display.DisplayObject; import flash.display.Loader; import flash.display.LoaderInfo; import flash.display.MovieClip; import flash.display.Shape; import flash.display.Sprite; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.KeyboardEvent; import flash.events.SecurityErrorEvent; import flash.filesystem.File; import flash.net.URLLoader; import flash.net.URLRequest; import flash.net.drm.AuthenticationMethod; import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.text.TextFormat; import flashx.textLayout.events.ModelChange; public class LoadSwf extends Sprite { private var swfLoader:Loader = new Loader(); private var swfMC:MovieClip = null; private var pathXml:XML = null; public function LoadSwf() { super(); initStage(); initPath(); } //-------------------------------- private function initStage():void { // stage.color = 0x00000; stage.addEventListener(Event.ACTIVATE, onActivate); stage.addEventListener(Event.DEACTIVATE, onDeActivate); stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp); } private function onKeyUp(e:KeyboardEvent):void { trace("onKeyUp(), "+e.keyCode); swfStop(); } private function onDeActivate(e:Event):void { trace("onDeActivate()"); swfPause(); } private function onActivate(e:Event):void { trace("onActivate()"); swfResume(); } //--------------------------------- private function initLoader():void { swfLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete); swfLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, loadIOError); swfLoader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, loadSecurityError); var url:String = jointUrl(pathXml.url); trace("url: "+url); swfLoader.load(new URLRequest(url)); } private function swfResume():void { // if (swfMC != null) { // swfMC.play(); // } } private function swfPause():void { // if (swfMC != null) { // swfMC.stop(); // } swfStop(); } private function swfStop():void { swfLoader.unloadAndStop(); NativeApplication.nativeApplication.exit(); } private function loadComplete(e:Event):void { trace("loadComplete()"); if (swfLoader.content is AVM1Movie) { var loaderInfo:LoaderInfo = LoaderInfo(e.target); var msg:String = loaderInfo.url + " is AVM1Movie.\n" + "Only support ActionScript 3.0 swf!"; swfLoader.unloadAndStop(); trace(msg); showError(msg); return ; } centerAndFull(swfLoader, e); swfLoader.mask = getMasker(swfLoader, e); stage.addChild(swfLoader.mask); stage.addChild(swfLoader); swfMC = swfLoader as MovieClip; } private function loadIOError(e:IOErrorEvent):void { trace("swfLoader loadIOError, "+e.toString()); showError(e.toString()); } private function loadSecurityError(e:SecurityErrorEvent):void { trace("swfLoader loadSecurityError, "+e.toString()); showError(e.toString()); } //----------------------- private function getMasker(o:DisplayObject, e:Event):Shape { var li:LoaderInfo = LoaderInfo(e.target); var masker:Shape = new Shape(); masker.graphics.beginFill(0xff0000); masker.graphics.drawRect(o.x, o.y, li.width*o.scaleX, li.height*o.scaleY); masker.graphics.endFill(); return masker; } private function traceInfo(o:DisplayObject):void { trace("x:"+o.x+", y:"+o.y + "\nw:"+o.width +", h:" + o.height + "\nsx:" + o.scaleX +", sy:"+o.scaleY+", sz:"+o.scaleZ); } private function centerAndFull(o:DisplayObject, e:Event):void { traceInfo(o); var loadInfo:LoaderInfo = LoaderInfo(e.target); //full var scalex:Number = stage.stageWidth / loadInfo.width; var scaley:Number = stage.stageHeight / loadInfo.height; var scale:Number = scalex < scaley ? scalex : scaley; o.width *= scale; o.height *= scale; //center o.x = (stage.stageWidth - loadInfo.width*scale) / 2; o.y = (stage.stageHeight - loadInfo.height*scale) / 2; traceInfo(o); } //----------------------- private function showError(msg:String):void { var tfor:TextFormat = new TextFormat(); tfor.size = 15; tfor.color = 0xff0000; tfor.align = "center"; var tf:TextField = new TextField(); tf.wordWrap = true; tf.multiline = true; tf.selectable = false; tf.border = false; tf.defaultTextFormat = tfor; tf.text = "播放失败!\n请确认文件是否存在,或者重新打开一次!" + "\n" + msg; tf.setTextFormat(tfor); tf.width = stage.stageWidth/3*2; tf.height = stage.stageHeight/2; stage.addChild(tf); trace("stage: " + stage.stageWidth+","+stage.stageHeight +"\ntf: "+tf.x + "," + tf.y + ", "+tf.width + ","+tf.height); tf.x = (stage.stageWidth - tf.width)/2; tf.y = (stage.stageHeight - tf.height)/2; } //----------------------- private function initPath():void { var loader:URLLoader = new URLLoader(); loader.addEventListener(Event.COMPLETE, function(e:Event):void { trace("xml load complete, \n"+e.target.data); pathXml = XML(e.target.data); initLoader(); }); loader.addEventListener(IOErrorEvent.IO_ERROR, function(e:IOErrorEvent):void { trace("io error, "+e.toString()); showError(e.toString()); }); loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function(e:SecurityErrorEvent):void { trace("security error, "+e.toString()); showError(e.toString()); }); loader.load(new URLRequest(jointUrl("data/path.xml"))); } private function getRootUrl():String { return File.documentsDirectory.url+File.separator; } private function jointUrl(name:String):String { return getRootUrl()+name; } //-- for test -- private function readDir():void { var file:File = File.documentsDirectory; var fileObj:File; var docsDirectory:Array = file.getDirectoryListing(); trace(file.url+"\n"+file.nativePath); for (var i:int = 0; i < docsDirectory.length; i++) { fileObj = docsDirectory[i]; trace(fileObj.name); } } } }
add showError() # modified: LoadSwf/src/LoadSwf.as
add showError() # modified: LoadSwf/src/LoadSwf.as
ActionScript
mit
victoryckl/flex-demos,victoryckl/flex-demos,victoryckl/flex-demos
34748301601e5a3239e641643fdbc8c0e1235b53
frameworks/as/projects/FlexJSJX/src/org/apache/flex/html/beads/layouts/FlexibleFirstChildHorizontalLayout.as
frameworks/as/projects/FlexJSJX/src/org/apache/flex/html/beads/layouts/FlexibleFirstChildHorizontalLayout.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.html.beads.layouts { import org.apache.flex.core.IBeadLayout; import org.apache.flex.core.ILayoutParent; import org.apache.flex.core.IStrand; import org.apache.flex.core.IParent; import org.apache.flex.core.IUIBase; import org.apache.flex.core.UIBase; import org.apache.flex.core.ValuesManager; import org.apache.flex.events.Event; import org.apache.flex.events.IEventDispatcher; /** * The FlexibleFirstChildHorizontalLayout class is a simple layout * bead. It takes the set of children and lays them out * horizontally in one row, separating them according to * CSS layout rules for margin and padding styles. But it * will size the first child to take up as much or little * room as possible. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class FlexibleFirstChildHorizontalLayout implements IBeadLayout { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function FlexibleFirstChildHorizontalLayout() { } private var _strand:IStrand; /** * @copy org.apache.flex.core.IBead#strand * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function set strand(value:IStrand):void { _strand = value; IEventDispatcher(value).addEventListener("layoutNeeded", changeHandler); IEventDispatcher(value).addEventListener("widthChanged", changeHandler); IEventDispatcher(value).addEventListener("childrenAdded", changeHandler); IEventDispatcher(value).addEventListener("itemsCreated", changeHandler); } private function changeHandler(event:Event):void { var layoutParent:ILayoutParent = _strand.getBeadByType(ILayoutParent) as ILayoutParent; var contentView:IParent = layoutParent.contentView; var n:int = contentView.numElements; var marginLeft:Object; var marginRight:Object; var marginTop:Object; var marginBottom:Object; var margin:Object; var maxHeight:Number = 0; var verticalMargins:Array = []; var xx:Number = layoutParent.resizableView.width; var padding:Object = determinePadding(); xx -= padding.paddingLeft + padding.paddingRight; for (var i:int = n - 1; i >= 0; i--) { var child:IUIBase = contentView.getElementAt(i) as IUIBase; margin = ValuesManager.valuesImpl.getValue(child, "margin"); if (margin is Array) { if (margin.length == 1) marginLeft = marginTop = marginRight = marginBottom = margin[0]; else if (margin.length <= 3) { marginLeft = marginRight = margin[1]; marginTop = marginBottom = margin[0]; } else if (margin.length == 4) { marginLeft = margin[3]; marginBottom = margin[2]; marginRight = margin[1]; marginTop = margin[0]; } } else if (margin == null) { marginLeft = ValuesManager.valuesImpl.getValue(child, "margin-left"); marginTop = ValuesManager.valuesImpl.getValue(child, "margin-top"); marginRight = ValuesManager.valuesImpl.getValue(child, "margin-right"); marginBottom = ValuesManager.valuesImpl.getValue(child, "margin-bottom"); } else { marginLeft = marginTop = marginBottom = marginRight = margin; } var ml:Number; var mr:Number; var mt:Number; var mb:Number; var lastmr:Number; mt = Number(marginTop); if (isNaN(mt)) mt = 0; mb = Number(marginBottom); if (isNaN(mb)) mb = 0; if (marginLeft == "auto") ml = 0; else { ml = Number(marginLeft); if (isNaN(ml)) ml = 0; } if (marginRight == "auto") mr = 0; else { mr = Number(marginRight); if (isNaN(mr)) mr = 0; } child.y = mt; maxHeight = Math.max(maxHeight, mt + child.height + mb); if (i == 0) { child.x = ml; child.width = xx - mr; } else child.x = xx - child.width - mr; xx -= child.width + mr + ml; lastmr = mr; var valign:Object = ValuesManager.valuesImpl.getValue(child, "vertical-align"); verticalMargins.push({ marginTop: mt, marginBottom: mb, valign: valign }); } for (i = 0; i < n; i++) { var obj:Object = verticalMargins[0] child = contentView.getElementAt(i) as IUIBase; if (obj.valign == "middle") child.y = (maxHeight - child.height) / 2; else if (valign == "bottom") child.y = maxHeight - child.height - obj.marginBottom; else child.y = obj.marginTop; } layoutParent.resizableView.height = maxHeight; } // TODO (aharui): utility class or base class /** * Determines the top and left padding values, if any, as set by * padding style values. This includes "padding" for all padding values * as well as "padding-left" and "padding-top". * * Returns an object with paddingLeft and paddingTop properties. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected function determinePadding():Object { var paddingLeft:Object; var paddingTop:Object; var paddingRight:Object; var padding:Object = ValuesManager.valuesImpl.getValue(_strand, "padding"); if (typeof(padding) == "Array") { if (padding.length == 1) paddingLeft = paddingTop = paddingRight = padding[0]; else if (padding.length <= 3) { paddingLeft = padding[1]; paddingTop = padding[0]; paddingRight = padding[1]; } else if (padding.length == 4) { paddingLeft = padding[3]; paddingTop = padding[0]; paddingRight = padding[1]; } } else if (padding == null) { paddingLeft = ValuesManager.valuesImpl.getValue(_strand, "padding-left"); paddingTop = ValuesManager.valuesImpl.getValue(_strand, "padding-top"); paddingRight = ValuesManager.valuesImpl.getValue(_strand, "padding-right"); } else { paddingLeft = paddingTop = paddingRight = padding; } var pl:Number = Number(paddingLeft); var pt:Number = Number(paddingTop); var pr:Number = Number(paddingRight); return {paddingLeft:pl, paddingTop:pt, paddingRight:pr}; } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.html.beads.layouts { import org.apache.flex.core.IBeadLayout; import org.apache.flex.core.ILayoutParent; import org.apache.flex.core.IStrand; import org.apache.flex.core.IParent; import org.apache.flex.core.IUIBase; import org.apache.flex.core.UIBase; import org.apache.flex.core.ValuesManager; import org.apache.flex.events.Event; import org.apache.flex.events.IEventDispatcher; /** * The FlexibleFirstChildHorizontalLayout class is a simple layout * bead. It takes the set of children and lays them out * horizontally in one row, separating them according to * CSS layout rules for margin and padding styles. But it * will size the first child to take up as much or little * room as possible. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class FlexibleFirstChildHorizontalLayout implements IBeadLayout { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function FlexibleFirstChildHorizontalLayout() { } private var _strand:IStrand; /** * @copy org.apache.flex.core.IBead#strand * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function set strand(value:IStrand):void { _strand = value; IEventDispatcher(value).addEventListener("layoutNeeded", changeHandler); IEventDispatcher(value).addEventListener("widthChanged", changeHandler); IEventDispatcher(value).addEventListener("childrenAdded", changeHandler); IEventDispatcher(value).addEventListener("itemsCreated", changeHandler); } private function changeHandler(event:Event):void { var layoutParent:ILayoutParent = _strand.getBeadByType(ILayoutParent) as ILayoutParent; var contentView:IParent = layoutParent.contentView; var n:int = contentView.numElements; var marginLeft:Object; var marginRight:Object; var marginTop:Object; var marginBottom:Object; var margin:Object; var maxHeight:Number = 0; var verticalMargins:Array = []; var xx:Number = layoutParent.resizableView.width; if (isNaN(xx)) return; var padding:Object = determinePadding(); xx -= padding.paddingLeft + padding.paddingRight; for (var i:int = n - 1; i >= 0; i--) { var child:IUIBase = contentView.getElementAt(i) as IUIBase; margin = ValuesManager.valuesImpl.getValue(child, "margin"); if (margin is Array) { if (margin.length == 1) marginLeft = marginTop = marginRight = marginBottom = margin[0]; else if (margin.length <= 3) { marginLeft = marginRight = margin[1]; marginTop = marginBottom = margin[0]; } else if (margin.length == 4) { marginLeft = margin[3]; marginBottom = margin[2]; marginRight = margin[1]; marginTop = margin[0]; } } else if (margin == null) { marginLeft = ValuesManager.valuesImpl.getValue(child, "margin-left"); marginTop = ValuesManager.valuesImpl.getValue(child, "margin-top"); marginRight = ValuesManager.valuesImpl.getValue(child, "margin-right"); marginBottom = ValuesManager.valuesImpl.getValue(child, "margin-bottom"); } else { marginLeft = marginTop = marginBottom = marginRight = margin; } var ml:Number; var mr:Number; var mt:Number; var mb:Number; var lastmr:Number; mt = Number(marginTop); if (isNaN(mt)) mt = 0; mb = Number(marginBottom); if (isNaN(mb)) mb = 0; if (marginLeft == "auto") ml = 0; else { ml = Number(marginLeft); if (isNaN(ml)) ml = 0; } if (marginRight == "auto") mr = 0; else { mr = Number(marginRight); if (isNaN(mr)) mr = 0; } child.y = mt; maxHeight = Math.max(maxHeight, mt + child.height + mb); if (i == 0) { child.x = ml; child.width = xx - mr; } else child.x = xx - child.width - mr; xx -= child.width + mr + ml; lastmr = mr; var valign:Object = ValuesManager.valuesImpl.getValue(child, "vertical-align"); verticalMargins.push({ marginTop: mt, marginBottom: mb, valign: valign }); } for (i = 0; i < n; i++) { var obj:Object = verticalMargins[0] child = contentView.getElementAt(i) as IUIBase; if (obj.valign == "middle") child.y = (maxHeight - child.height) / 2; else if (valign == "bottom") child.y = maxHeight - child.height - obj.marginBottom; else child.y = obj.marginTop; } layoutParent.resizableView.height = maxHeight; } // TODO (aharui): utility class or base class /** * Determines the top and left padding values, if any, as set by * padding style values. This includes "padding" for all padding values * as well as "padding-left" and "padding-top". * * Returns an object with paddingLeft and paddingTop properties. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected function determinePadding():Object { var paddingLeft:Object; var paddingTop:Object; var paddingRight:Object; var padding:Object = ValuesManager.valuesImpl.getValue(_strand, "padding"); if (typeof(padding) == "Array") { if (padding.length == 1) paddingLeft = paddingTop = paddingRight = padding[0]; else if (padding.length <= 3) { paddingLeft = padding[1]; paddingTop = padding[0]; paddingRight = padding[1]; } else if (padding.length == 4) { paddingLeft = padding[3]; paddingTop = padding[0]; paddingRight = padding[1]; } } else if (padding == null) { paddingLeft = ValuesManager.valuesImpl.getValue(_strand, "padding-left"); paddingTop = ValuesManager.valuesImpl.getValue(_strand, "padding-top"); paddingRight = ValuesManager.valuesImpl.getValue(_strand, "padding-right"); } else { paddingLeft = paddingTop = paddingRight = padding; } var pl:Number = Number(paddingLeft); var pt:Number = Number(paddingTop); var pr:Number = Number(paddingRight); if (isNaN(pl)) pl = 0; if (isNaN(pt)) pt = 0; if (isNaN(pr)) pr = 0; return {paddingLeft:pl, paddingTop:pt, paddingRight:pr}; } } }
handle NaN
handle NaN
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
fd5b8f5a81a2bbfb23fe4e0d69eeb34a4d7fc31f
src/aerys/minko/render/shader/Signature.as
src/aerys/minko/render/shader/Signature.as
package aerys.minko.render.shader { import aerys.minko.type.Signal; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; /** * ShaderSignature objects describe the "signature" of ActionScript shaders and make * it posible to know whether a compatible program already exists or if the shader * must be forked. * * @author Jean-Marc Le Roux */ public final class Signature { public static const OPERATION_EXISTS : uint = 1; public static const OPERATION_GET : uint = 2; public static const SOURCE_MESH : uint = 4; public static const SOURCE_SCENE : uint = 8; private var _keys : Vector.<String> = new <String>[]; private var _values : Vector.<Object> = new <Object>[]; private var _flags : Vector.<uint> = new <uint>[]; public function get numKeys() : uint { return _keys.length; } public function Signature(shaderName : String) { } public function getKey(index : uint) : String { return _keys[index]; } public function getFlags(index : uint) : uint { return _flags[index]; } public function update(key : String, value : Object, flags : uint) : void { // quit if we already have this entry var numKeys : uint = _keys.length; for (var keyId : uint = 0; keyId < numKeys; ++keyId) if (_keys[keyId] == key && _flags[keyId] == flags) return; // add the test to the list _keys.push(key); _values.push(value); _flags.push(flags); } public function isValid(meshBindings : DataBindings, sceneBindings : DataBindings) : Boolean { var numKeys : uint = _keys.length; for (var i : uint = 0; i < numKeys; ++i) { var key : String = _keys[i]; var flags : uint = _flags[i]; var value : Object = _values[i]; var source : DataBindings = flags & SOURCE_SCENE ? sceneBindings : meshBindings; if (flags & OPERATION_GET) { if (!source.propertyExists(key)) return false; if (!compare(source.getProperty(key), value)) return false; } else if (flags & OPERATION_EXISTS) { if (source.propertyExists(key) != value) return false; } } return true; } public function mergeWith(otherSignature : Signature) : void { var otherLength : uint = otherSignature._keys.length; for (var i : uint = 0; i < otherLength; ++i) update( otherSignature._keys[i], otherSignature._values[i], otherSignature._flags[i] ); } public function clone() : Signature { var clone : Signature = new Signature(null); clone._flags = _flags.slice(); clone._keys = _keys.slice(); clone._values = _values.slice(); return clone; } /** * @fixme This is n^2!!!!! * @fixme optimize me with a dictionary!!! */ public function useProperties(properties : Vector.<String>, fromScene : Boolean) : Boolean { var numProperties : uint = properties.length; var numKeys : uint = _keys.length; var flag : uint = fromScene ? SOURCE_SCENE : SOURCE_MESH; for (var j : uint = 0; j < numProperties; ++j) for (var i : uint = 0; i < numKeys; ++i) if (_keys[i] == properties[j] && (flag & _flags[i]) != 0) return true; return false; } private function compare(value1 : Object, value2 : Object) : Boolean { if ((value1 == null && value2 != null) || (value1 != null && value2 == null)) return false; var constructor : Object = value1.constructor; var count : int = 0; if (constructor != value2.constructor) return false; if (constructor == Vector4) return (value1 as Vector4).equals(value2 as Vector4, true); if (constructor == Matrix4x4) return (value1 as Matrix4x4).compareTo(value2 as Matrix4x4); if (value1 is Vector.<Number>) { var numbers1 : Vector.<Number> = value1 as Vector.<Number>; var numbers2 : Vector.<Number> = value2 as Vector.<Number>; count = numbers1.length; if (count != numbers2.length) return false; while (count >= 0) { if (numbers1[count] != numbers2[count]) return false; --count; } } else if (value1 is Vector.<Vector4>) { var vectors1 : Vector.<Vector4> = value1 as Vector.<Vector4>; var vectors2 : Vector.<Vector4> = value2 as Vector.<Vector4>; count = vectors1.length; if (count != vectors2.length) return false; while (count >= 0) { if (!(vectors1[count] as Vector4).equals(vectors2[count])) return false; --count; } } else if (value1 is Vector.<Matrix4x4>) { var matrices1 : Vector.<Matrix4x4> = value1 as Vector.<Matrix4x4>; var matrices2 : Vector.<Matrix4x4> = value2 as Vector.<Matrix4x4>; count = matrices1.length; if (count != matrices2.length) return false; while (count >= 0) { if (!(matrices1[count] as Matrix4x4).compareTo(matrices2[count])) return false; --count; } } return value1 === value2; } } }
package aerys.minko.render.shader { import aerys.minko.type.Signal; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; /** * ShaderSignature objects describe the "signature" of ActionScript shaders and make * it posible to know whether a compatible program already exists or if the shader * must be forked. * * @author Jean-Marc Le Roux */ public final class Signature { public static const OPERATION_EXISTS : uint = 1; public static const OPERATION_GET : uint = 2; public static const SOURCE_MESH : uint = 4; public static const SOURCE_SCENE : uint = 8; private var _keys : Vector.<String> = new <String>[]; private var _values : Vector.<Object> = new <Object>[]; private var _flags : Vector.<uint> = new <uint>[]; public function get numKeys() : uint { return _keys.length; } public function Signature(shaderName : String) { } public function getKey(index : uint) : String { return _keys[index]; } public function getFlags(index : uint) : uint { return _flags[index]; } public function update(key : String, value : Object, flags : uint) : void { // quit if we already have this entry var numKeys : uint = _keys.length; for (var keyId : uint = 0; keyId < numKeys; ++keyId) if (_keys[keyId] == key && _flags[keyId] == flags) return; // add the test to the list _keys.push(key); _values.push(value); _flags.push(flags); } public function isValid(meshBindings : DataBindings, sceneBindings : DataBindings) : Boolean { var numKeys : uint = _keys.length; for (var i : uint = 0; i < numKeys; ++i) { var key : String = _keys[i]; var flags : uint = _flags[i]; var value : Object = _values[i]; var source : DataBindings = flags & SOURCE_SCENE ? sceneBindings : meshBindings; if (flags & OPERATION_GET) { if (!source.propertyExists(key)) return false; if (!compare(source.getProperty(key), value)) return false; } else if (flags & OPERATION_EXISTS) { if (source.propertyExists(key) != value) return false; } } return true; } public function mergeWith(otherSignature : Signature) : void { var otherLength : uint = otherSignature._keys.length; for (var i : uint = 0; i < otherLength; ++i) update( otherSignature._keys[i], otherSignature._values[i], otherSignature._flags[i] ); } public function clone() : Signature { var clone : Signature = new Signature(null); clone._flags = _flags.slice(); clone._keys = _keys.slice(); clone._values = _values.slice(); return clone; } /** * @fixme This is n^2!!!!! * @fixme optimize me with a dictionary!!! */ public function useProperties(properties : Vector.<String>, fromScene : Boolean) : Boolean { var numProperties : uint = properties.length; var numKeys : uint = _keys.length; var flag : uint = fromScene ? SOURCE_SCENE : SOURCE_MESH; for (var j : uint = 0; j < numProperties; ++j) for (var i : uint = 0; i < numKeys; ++i) if (_keys[i] == properties[j] && (flag & _flags[i]) != 0) return true; return false; } private function compare(value1 : Object, value2 : Object) : Boolean { if ((value1 == null && value2 != null) || (value1 != null && value2 == null)) return false; var constructor : Object = value1.constructor; var count : int = 0; if (constructor != value2.constructor) return false; if (constructor == Vector4) return (value1 as Vector4).equals(value2 as Vector4, true); if (constructor == Matrix4x4) return (value1 as Matrix4x4).compareTo(value2 as Matrix4x4); if (value1 is Vector.<Number>) { var numbers1 : Vector.<Number> = value1 as Vector.<Number>; var numbers2 : Vector.<Number> = value2 as Vector.<Number>; count = numbers1.length; if (count != numbers2.length) return false; while (count >= 0) { if (numbers1[count] != numbers2[count]) return false; --count; } } else if (value1 is Vector.<Vector4>) { var vectors1 : Vector.<Vector4> = value1 as Vector.<Vector4>; var vectors2 : Vector.<Vector4> = value2 as Vector.<Vector4>; count = vectors1.length; if (count != vectors2.length) return false; while (count >= 0) { if (!(vectors1[count] as Vector4).equals(vectors2[count])) return false; --count; } } else if (value1 is Vector.<Matrix4x4>) { var matrices1 : Vector.<Matrix4x4> = value1 as Vector.<Matrix4x4>; var matrices2 : Vector.<Matrix4x4> = value2 as Vector.<Matrix4x4>; count = matrices1.length; if (count != matrices2.length) return false; while (count >= 0) { if (!(matrices1[count] as Matrix4x4).compareTo(matrices2[count])) return false; --count; } } return value1 === value2; } } }
fix coding style
fix coding style
ActionScript
mit
aerys/minko-as3
0024caa3719fe9aa146450022f12b2d2f2bab65a
src/com/axis/rtspclient/RTPTiming.as
src/com/axis/rtspclient/RTPTiming.as
package com.axis.rtspclient { import flash.utils.ByteArray; public class RTPTiming { public var rtpTime:Object; public var range:Object; public var live:Boolean; public function RTPTiming(rtpTime:Object, range:Object, live:Boolean) { this.rtpTime = rtpTime; this.range = range; this.live = live; } public function rtpTimeForControl(control:String):Number { /* control parameter and url in rtp-info may not equal but control * parameter is always part of the url */ for (var c:String in this.rtpTime) { if (c.indexOf(control) >= 0) { return this.rtpTime[c]; } } return 0; } public function toString():String { var res:String = 'rtpTime:'; for (var control:String in rtpTime) { res += '\n ' + control + ': ' + rtpTime[control]; } if (range) { res += '\nrange: ' + range.from + ' - ' + range.to; } res += '\nlive: ' + live; return res; } public static function parse(rtpInfo:String, range:String):RTPTiming { var rtpTime:Object = {}; for each (var track:String in rtpInfo.split(',')) { var rtpTimeMatch:Object = /^.*url=([^;]*);.*rtptime=(\d+).*$/.exec(track); rtpTime[rtpTimeMatch[1]] = parseInt(rtpTimeMatch[2]); } var rangeMatch:Object = /^npt=(.*)-(.*)$/.exec(range); var rangeFrom:String = rangeMatch[1]; var rangeTo:String = rangeMatch[2]; var from:Number = 0; var to:Number = rangeTo.length > 0 ? Math.round(parseFloat(rangeTo) * 1000) : -1; var live:Boolean = rangeFrom == 'now' || to == -1; if (rangeFrom != 'now') { from = Math.round(parseFloat(rangeFrom) * 1000); /* Some idiot RTSP servers writes Range: npt=0.000-0.000 in the header... */ to = to <= from ? -1 : to; } return new RTPTiming(rtpTime, { from: from, to: to }, live); } } }
package com.axis.rtspclient { import flash.utils.ByteArray; public class RTPTiming { public var rtpTime:Object; public var range:Object; public var live:Boolean; public function RTPTiming(rtpTime:Object, range:Object, live:Boolean) { this.rtpTime = rtpTime; this.range = range; this.live = live; } public function rtpTimeForControl(control:String):Number { /* control parameter and url in rtp-info may not equal but control * parameter is always part of the url */ for (var c:String in this.rtpTime) { if (c.indexOf(control) >= 0) { return this.rtpTime[c]; } } return 0; } public function toString():String { var res:String = 'rtpTime:'; for (var control:String in rtpTime) { res += '\n ' + control + ': ' + rtpTime[control]; } if (range) { res += '\nrange: ' + range.from + ' - ' + range.to; } res += '\nlive: ' + live; return res; } public static function parse(rtpInfo:String, range:String):RTPTiming { var rtpTime:Object = {}; for each (var track:String in rtpInfo.split(',')) { var rtpTimeMatch:Object = /^.*url=([^;]*);.*rtptime=(\d+).*$/.exec(track); rtpTime[rtpTimeMatch[1]] = parseInt(rtpTimeMatch[2]); } var rangeMatch:Object = /^npt=(.*)-(.*)$/.exec(range); var rangeFrom:String = rangeMatch[1]; var rangeTo:String = rangeMatch[2]; var from:Number = 0; var to:Number = rangeTo.length > 0 ? Math.round(parseFloat(rangeTo) * 1000) : -1; var live:Boolean = rangeFrom == 'now'; if (rangeFrom != 'now') { from = Math.round(parseFloat(rangeFrom) * 1000); /* Some idiot RTSP servers writes Range: npt=0.000-0.000 in the header... */ to = to <= from ? -1 : to; } return new RTPTiming(rtpTime, { from: from, to: to }, live); } } }
Fix incorrect assumption about live streaming
RTSP: Fix incorrect assumption about live streaming Do not assume live stream if to-value in range header is empty.
ActionScript
bsd-3-clause
gaetancollaud/locomote-video-player,AxisCommunications/locomote-video-player
484c2bf799fcfd423bf287bcb1180dc326531ba4
src/org/mangui/hls/HLS.as
src/org/mangui/hls/HLS.as
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mangui.hls { import flash.display.Stage; import flash.net.NetConnection; import flash.net.NetStream; import flash.net.URLStream; import flash.events.EventDispatcher; import flash.events.Event; import org.mangui.hls.controller.LevelController; import org.mangui.hls.controller.AudioTrackController; import org.mangui.hls.event.HLSEvent; import org.mangui.hls.loader.LevelLoader; import org.mangui.hls.loader.AltAudioLevelLoader; import org.mangui.hls.model.Level; import org.mangui.hls.model.AudioTrack; import org.mangui.hls.playlist.AltAudioTrack; import org.mangui.hls.stream.HLSNetStream; import org.mangui.hls.stream.StreamBuffer; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } /** Class that manages the streaming process. **/ public class HLS extends EventDispatcher { private var _levelLoader : LevelLoader; private var _altAudioLevelLoader : AltAudioLevelLoader; private var _audioTrackController : AudioTrackController; private var _levelController : LevelController; private var _streamBuffer : StreamBuffer; /** HLS NetStream **/ private var _hlsNetStream : HLSNetStream; /** HLS URLStream **/ private var _hlsURLStream : Class; private var _client : Object = {}; private var _stage : Stage; /* level handling */ private var _level : int; /* overrided quality_manual_level level */ private var _manual_level : int = -1; /** Create and connect all components. **/ public function HLS() { var connection : NetConnection = new NetConnection(); connection.connect(null); _levelLoader = new LevelLoader(this); _altAudioLevelLoader = new AltAudioLevelLoader(this); _audioTrackController = new AudioTrackController(this); _levelController = new LevelController(this); _streamBuffer = new StreamBuffer(this, _audioTrackController, _levelController); _hlsURLStream = URLStream as Class; // default loader _hlsNetStream = new HLSNetStream(connection, this, _streamBuffer); this.addEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler); }; /** Forward internal errors. **/ override public function dispatchEvent(event : Event) : Boolean { if (event.type == HLSEvent.ERROR) { CONFIG::LOGGING { Log.error((event as HLSEvent).error); } _hlsNetStream.close(); } return super.dispatchEvent(event); }; private function _levelSwitchHandler(event : HLSEvent) : void { _level = event.level; }; public function dispose() : void { this.removeEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler); _levelLoader.dispose(); _altAudioLevelLoader.dispose(); _audioTrackController.dispose(); _levelController.dispose(); _streamBuffer.dispose(); _hlsNetStream.dispose_(); _levelLoader = null; _altAudioLevelLoader = null; _audioTrackController = null; _levelController = null; _hlsNetStream = null; _client = null; _stage = null; _hlsNetStream = null; } /** Return the quality level used when starting a fresh playback **/ public function get startlevel() : int { return _levelController.startlevel; }; /** Return the quality level used after a seek operation **/ public function get seeklevel() : int { return _levelController.seeklevel; }; /** Return the quality level of the currently played fragment **/ public function get playbacklevel() : int { return _hlsNetStream.playbackLevel; }; /** Return the quality level of last loaded fragment **/ public function get level() : int { return _level; }; /* set quality level for next loaded fragment (-1 for automatic level selection) */ public function set level(level : int) : void { _manual_level = level; }; /* check if we are in automatic level selection mode */ public function get autolevel() : Boolean { return (_manual_level == -1); }; /* return manual level */ public function get manuallevel() : int { return _manual_level; }; /** Return a Vector of quality level **/ public function get levels() : Vector.<Level> { return _levelLoader.levels; }; /** Return the current playback position. **/ public function get position() : Number { return _streamBuffer.position; }; /** Return the current playback state. **/ public function get playbackState() : String { return _hlsNetStream.playbackState; }; /** Return the current seek state. **/ public function get seekState() : String { return _hlsNetStream.seekState; }; /** Return the type of stream (VOD/LIVE). **/ public function get type() : String { return _levelLoader.type; }; /** Load and parse a new HLS URL **/ public function load(url : String) : void { _hlsNetStream.close(); _levelLoader.load(url); }; /** return HLS NetStream **/ public function get stream() : NetStream { return _hlsNetStream; } public function get client() : Object { return _client; } public function set client(value : Object) : void { _client = value; } /** get current Buffer Length **/ public function get bufferLength() : Number { return _hlsNetStream.bufferLength; }; /** get audio tracks list**/ public function get audioTracks() : Vector.<AudioTrack> { return _audioTrackController.audioTracks; }; /** get alternate audio tracks list from playlist **/ public function get altAudioTracks() : Vector.<AltAudioTrack> { return _levelLoader.altAudioTracks; }; /** get index of the selected audio track (index in audio track lists) **/ public function get audioTrack() : int { return _audioTrackController.audioTrack; }; /** select an audio track, based on its index in audio track lists**/ public function set audioTrack(val : int) : void { _audioTrackController.audioTrack = val; } /* set stage */ public function set stage(stage : Stage) : void { _stage = stage; } /* get stage */ public function get stage() : Stage { return _stage; } /* set URL stream loader */ public function set URLstream(urlstream : Class) : void { _hlsURLStream = urlstream; } /* retrieve URL stream loader */ public function get URLstream() : Class { return _hlsURLStream; } } ; }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mangui.hls { import flash.display.Stage; import flash.net.NetConnection; import flash.net.NetStream; import flash.net.URLStream; import flash.events.EventDispatcher; import flash.events.Event; import org.mangui.hls.controller.LevelController; import org.mangui.hls.controller.AudioTrackController; import org.mangui.hls.event.HLSEvent; import org.mangui.hls.loader.LevelLoader; import org.mangui.hls.loader.AltAudioLevelLoader; import org.mangui.hls.model.Level; import org.mangui.hls.model.AudioTrack; import org.mangui.hls.playlist.AltAudioTrack; import org.mangui.hls.stream.HLSNetStream; import org.mangui.hls.stream.StreamBuffer; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } /** Class that manages the streaming process. **/ public class HLS extends EventDispatcher { private var _levelLoader : LevelLoader; private var _altAudioLevelLoader : AltAudioLevelLoader; private var _audioTrackController : AudioTrackController; private var _levelController : LevelController; private var _streamBuffer : StreamBuffer; /** HLS NetStream **/ private var _hlsNetStream : HLSNetStream; /** HLS URLStream **/ private var _hlsURLStream : Class; private var _client : Object = {}; private var _stage : Stage; /* level handling */ private var _level : int; /* overrided quality_manual_level level */ private var _manual_level : int = -1; /** Create and connect all components. **/ public function HLS() { var connection : NetConnection = new NetConnection(); connection.connect(null); _levelLoader = new LevelLoader(this); _altAudioLevelLoader = new AltAudioLevelLoader(this); _audioTrackController = new AudioTrackController(this); _levelController = new LevelController(this); _streamBuffer = new StreamBuffer(this, _audioTrackController, _levelController); _hlsURLStream = URLStream as Class; // default loader _hlsNetStream = new HLSNetStream(connection, this, _streamBuffer); this.addEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler); }; /** Forward internal errors. **/ override public function dispatchEvent(event : Event) : Boolean { if (event.type == HLSEvent.ERROR) { CONFIG::LOGGING { Log.error((event as HLSEvent).error); } _hlsNetStream.close(); } return super.dispatchEvent(event); }; private function _levelSwitchHandler(event : HLSEvent) : void { _level = event.level; }; public function dispose() : void { this.removeEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler); _levelLoader.dispose(); _altAudioLevelLoader.dispose(); _audioTrackController.dispose(); _levelController.dispose(); _hlsNetStream.dispose_(); _streamBuffer.dispose(); _levelLoader = null; _altAudioLevelLoader = null; _audioTrackController = null; _levelController = null; _hlsNetStream = null; _client = null; _stage = null; _hlsNetStream = null; } /** Return the quality level used when starting a fresh playback **/ public function get startlevel() : int { return _levelController.startlevel; }; /** Return the quality level used after a seek operation **/ public function get seeklevel() : int { return _levelController.seeklevel; }; /** Return the quality level of the currently played fragment **/ public function get playbacklevel() : int { return _hlsNetStream.playbackLevel; }; /** Return the quality level of last loaded fragment **/ public function get level() : int { return _level; }; /* set quality level for next loaded fragment (-1 for automatic level selection) */ public function set level(level : int) : void { _manual_level = level; }; /* check if we are in automatic level selection mode */ public function get autolevel() : Boolean { return (_manual_level == -1); }; /* return manual level */ public function get manuallevel() : int { return _manual_level; }; /** Return a Vector of quality level **/ public function get levels() : Vector.<Level> { return _levelLoader.levels; }; /** Return the current playback position. **/ public function get position() : Number { return _streamBuffer.position; }; /** Return the current playback state. **/ public function get playbackState() : String { return _hlsNetStream.playbackState; }; /** Return the current seek state. **/ public function get seekState() : String { return _hlsNetStream.seekState; }; /** Return the type of stream (VOD/LIVE). **/ public function get type() : String { return _levelLoader.type; }; /** Load and parse a new HLS URL **/ public function load(url : String) : void { _hlsNetStream.close(); _levelLoader.load(url); }; /** return HLS NetStream **/ public function get stream() : NetStream { return _hlsNetStream; } public function get client() : Object { return _client; } public function set client(value : Object) : void { _client = value; } /** get current Buffer Length **/ public function get bufferLength() : Number { return _hlsNetStream.bufferLength; }; /** get audio tracks list**/ public function get audioTracks() : Vector.<AudioTrack> { return _audioTrackController.audioTracks; }; /** get alternate audio tracks list from playlist **/ public function get altAudioTracks() : Vector.<AltAudioTrack> { return _levelLoader.altAudioTracks; }; /** get index of the selected audio track (index in audio track lists) **/ public function get audioTrack() : int { return _audioTrackController.audioTrack; }; /** select an audio track, based on its index in audio track lists**/ public function set audioTrack(val : int) : void { _audioTrackController.audioTrack = val; } /* set stage */ public function set stage(stage : Stage) : void { _stage = stage; } /* get stage */ public function get stage() : Stage { return _stage; } /* set URL stream loader */ public function set URLstream(urlstream : Class) : void { _hlsURLStream = urlstream; } /* retrieve URL stream loader */ public function get URLstream() : Class { return _hlsURLStream; } } ; }
Fix for dispose function in HLS.as
Fix for dispose function in HLS.as while disposing HLS stream it throws a NPE, TypeError: Error #1009: Cannot access a property or method of a null object reference. at org.mangui.hls.stream::StreamBuffer/stop()[flashls/src/org/mangui/hls/stream/StreamBuffer.as:87] at org.mangui.hls.stream::HLSNetStream/close()[flashls/src/org/mangui/hls/stream/HLSNetStream.as:346] at org.mangui.hls.stream::HLSNetStream/dispose_()[flashls/src/org/mangui/hls/stream/HLSNetStream.as:353] at org.mangui.hls::HLS/dispose()[flashls/src/org/mangui/hls/HLS.as:81] Fixed it by disposing _hlsNetStream first and then disposing _streamBuffer in HLS.as
ActionScript
mpl-2.0
Boxie5/flashls,aevange/flashls,suuhas/flashls,thdtjsdn/flashls,mangui/flashls,Boxie5/flashls,NicolasSiver/flashls,neilrackett/flashls,Peer5/flashls,dighan/flashls,Corey600/flashls,tedconf/flashls,codex-corp/flashls,clappr/flashls,Peer5/flashls,loungelogic/flashls,thdtjsdn/flashls,tedconf/flashls,vidible/vdb-flashls,aevange/flashls,neilrackett/flashls,fixedmachine/flashls,jlacivita/flashls,suuhas/flashls,aevange/flashls,Peer5/flashls,JulianPena/flashls,suuhas/flashls,codex-corp/flashls,hola/flashls,fixedmachine/flashls,JulianPena/flashls,hola/flashls,suuhas/flashls,Corey600/flashls,dighan/flashls,vidible/vdb-flashls,jlacivita/flashls,clappr/flashls,loungelogic/flashls,NicolasSiver/flashls,Peer5/flashls,aevange/flashls,mangui/flashls
ab87a5f9bb63c443213b61ff729969d3fdec1a68
frameworks/projects/mobiletheme/src/spark/skins/ios7/ButtonSkin.as
frameworks/projects/mobiletheme/src/spark/skins/ios7/ButtonSkin.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package spark.skins.ios7 { import flash.display.DisplayObject; import mx.core.DPIClassification; import mx.core.mx_internal; import mx.events.FlexEvent; import spark.components.supportClasses.StyleableTextField; import spark.skins.ios7.assets.Button_up; import spark.skins.mobile.supportClasses.ButtonSkinBase; use namespace mx_internal; /** * ActionScript-based skin for Button controls in mobile applications. The skin supports * iconClass and labelPlacement. It uses FXG classes to * implement the vector drawing. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public class ButtonSkin extends ButtonSkinBase { //-------------------------------------------------------------------------- // // Class constants // //-------------------------------------------------------------------------- /** * An array of color distribution ratios. * This is used in the chrome color fill. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ mx_internal static const CHROME_COLOR_RATIOS:Array = [0, 127.5]; /** * An array of alpha values for the corresponding colors in the colors array. * This is used in the chrome color fill. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ mx_internal static const CHROME_COLOR_ALPHAS:Array = [1, 1]; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function ButtonSkin() { super(); //In iOS7, buttons look like simple links, without any shape containing the text //We still need to assign an asset to determine the size of the button //Button_up is a simple transparent graphic object upBorderSkin = spark.skins.ios7.assets.Button_up; downBorderSkin = spark.skins.ios7.assets.Button_up; layoutCornerEllipseSize = 0; switch (applicationDPI) { case DPIClassification.DPI_640: { layoutGap = 20; layoutPaddingLeft = 40; layoutPaddingRight = 40; layoutPaddingTop = 40; layoutPaddingBottom = 40; layoutBorderSize = 2; measuredDefaultWidth = 128; measuredDefaultHeight = 172; break; } case DPIClassification.DPI_480: { layoutGap = 14; layoutPaddingLeft = 30; layoutPaddingRight = 30; layoutPaddingTop = 30; layoutPaddingBottom = 30; layoutBorderSize = 2; measuredDefaultWidth = 96; measuredDefaultHeight = 130; break; } case DPIClassification.DPI_320: { layoutGap = 10; layoutPaddingLeft = 20; layoutPaddingRight = 20; layoutPaddingTop = 20; layoutPaddingBottom = 20; layoutBorderSize = 2; measuredDefaultWidth = 64; measuredDefaultHeight = 86; break; } case DPIClassification.DPI_240: { layoutGap = 7; layoutPaddingLeft = 15; layoutPaddingRight = 15; layoutPaddingTop = 15; layoutPaddingBottom = 15; layoutBorderSize = 1; measuredDefaultWidth = 48; measuredDefaultHeight = 65; break; } case DPIClassification.DPI_120: { layoutGap = 4; layoutPaddingLeft = 8; layoutPaddingRight = 8; layoutPaddingTop = 8; layoutPaddingBottom = 8; layoutBorderSize = 1; measuredDefaultWidth = 24; measuredDefaultHeight = 33; break; } default: { layoutGap = 5; layoutPaddingLeft = 10; layoutPaddingRight = 10; layoutPaddingTop = 10; layoutPaddingBottom = 10; layoutBorderSize = 1; measuredDefaultWidth = 32; measuredDefaultHeight = 43; break; } } } //-------------------------------------------------------------------------- // // Layout variables // //-------------------------------------------------------------------------- /** * Defines the corner radius. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ protected var layoutCornerEllipseSize:uint; //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- private var _border:DisplayObject; private var changeFXGSkin:Boolean = false; private var borderClass:Class; mx_internal var fillColorStyleName:String = "chromeColor"; /** * Defines the shadow for the Button control's label. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public var labelDisplayShadow:StyleableTextField; /** * Read-only button border graphic. Use getBorderClassForCurrentState() * to specify a graphic per-state. * * @see #getBorderClassForCurrentState() */ protected function get border():DisplayObject { return _border; } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- /** * Class to use for the border in the up state. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 * * @default Button_up */ protected var upBorderSkin:Class; /** * Class to use for the border in the down state. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 * * @default Button_down */ protected var downBorderSkin:Class; //-------------------------------------------------------------------------- // // Overridden methods // //-------------------------------------------------------------------------- /** * @private */ override protected function createChildren():void { super.createChildren(); setStyle("textAlign", "center"); } /** * @private */ override protected function commitCurrentState():void { super.commitCurrentState(); borderClass = getBorderClassForCurrentState(); if (!(_border is borderClass)) changeFXGSkin = true; // update borderClass and background invalidateDisplayList(); } /** * @private */ override protected function layoutContents(unscaledWidth:Number, unscaledHeight:Number):void { super.layoutContents(unscaledWidth, unscaledHeight); // size the FXG background if (changeFXGSkin) { changeFXGSkin = false; if (_border) { removeChild(_border); _border = null; } if (borderClass) { _border = new borderClass(); addChildAt(_border, 0); } } layoutBorder(unscaledWidth, unscaledHeight); } /** * Position the background of the skin. Override this function to re-position the background. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ mx_internal function layoutBorder(unscaledWidth:Number, unscaledHeight:Number):void { setElementSize(border, unscaledWidth, unscaledHeight); setElementPosition(border, 0, 0); } /** * Returns the borderClass to use based on the currentState. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ protected function getBorderClassForCurrentState():Class { if (currentState == "down") return downBorderSkin; else return upBorderSkin; } //-------------------------------------------------------------------------- // // Event Handlers // //-------------------------------------------------------------------------- /** * @private */ override protected function labelDisplay_valueCommitHandler(event:FlexEvent):void { super.labelDisplay_valueCommitHandler(event); } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package spark.skins.ios7 { import flash.display.DisplayObject; import mx.core.DPIClassification; import mx.core.mx_internal; import mx.events.FlexEvent; import spark.components.supportClasses.StyleableTextField; import spark.skins.ios7.assets.Button_up; import spark.skins.mobile.supportClasses.ButtonSkinBase; use namespace mx_internal; /** * ActionScript-based skin for Button controls in mobile applications. The skin supports * iconClass and labelPlacement. It uses FXG classes to * implement the vector drawing. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public class ButtonSkin extends ButtonSkinBase { //-------------------------------------------------------------------------- // // Class constants // //-------------------------------------------------------------------------- /** * An array of color distribution ratios. * This is used in the chrome color fill. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ mx_internal static const CHROME_COLOR_RATIOS:Array = [0, 127.5]; /** * An array of alpha values for the corresponding colors in the colors array. * This is used in the chrome color fill. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ mx_internal static const CHROME_COLOR_ALPHAS:Array = [1, 1]; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public function ButtonSkin() { super(); //In iOS7, buttons look like simple links, without any shape containing the text //We still need to assign an asset to determine the size of the button //Button_up is a simple transparent graphic object upBorderSkin = spark.skins.ios7.assets.Button_up; downBorderSkin = spark.skins.ios7.assets.Button_up; layoutCornerEllipseSize = 0; switch (applicationDPI) { case DPIClassification.DPI_640: { layoutGap = 20; layoutPaddingLeft = 40; layoutPaddingRight = 40; layoutPaddingTop = 40; layoutPaddingBottom = 40; layoutBorderSize = 2; measuredDefaultWidth = 128; measuredDefaultHeight = 172; break; } case DPIClassification.DPI_480: { layoutGap = 14; layoutPaddingLeft = 30; layoutPaddingRight = 30; layoutPaddingTop = 30; layoutPaddingBottom = 30; layoutBorderSize = 2; measuredDefaultWidth = 96; measuredDefaultHeight = 130; break; } case DPIClassification.DPI_320: { layoutGap = 10; layoutPaddingLeft = 20; layoutPaddingRight = 20; layoutPaddingTop = 20; layoutPaddingBottom = 20; layoutBorderSize = 2; measuredDefaultWidth = 64; measuredDefaultHeight = 86; break; } case DPIClassification.DPI_240: { layoutGap = 7; layoutPaddingLeft = 15; layoutPaddingRight = 15; layoutPaddingTop = 15; layoutPaddingBottom = 15; layoutBorderSize = 1; measuredDefaultWidth = 48; measuredDefaultHeight = 65; break; } case DPIClassification.DPI_120: { layoutGap = 4; layoutPaddingLeft = 8; layoutPaddingRight = 8; layoutPaddingTop = 8; layoutPaddingBottom = 8; layoutBorderSize = 1; measuredDefaultWidth = 24; measuredDefaultHeight = 33; break; } default: { layoutGap = 5; layoutPaddingLeft = 10; layoutPaddingRight = 10; layoutPaddingTop = 10; layoutPaddingBottom = 10; layoutBorderSize = 1; measuredDefaultWidth = 32; measuredDefaultHeight = 43; break; } } } //-------------------------------------------------------------------------- // // Layout variables // //-------------------------------------------------------------------------- /** * Defines the corner radius. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ protected var layoutCornerEllipseSize:uint; //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- private var _border:DisplayObject; private var changeFXGSkin:Boolean = false; private var borderClass:Class; mx_internal var fillColorStyleName:String = "chromeColor"; /** * Defines the shadow for the Button control's label. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ public var labelDisplayShadow:StyleableTextField; /** * Read-only button border graphic. Use getBorderClassForCurrentState() * to specify a graphic per-state. * * @see #getBorderClassForCurrentState() */ protected function get border():DisplayObject { return _border; } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- /** * Class to use for the border in the up state. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 * * @default Button_up */ protected var upBorderSkin:Class; /** * Class to use for the border in the down state. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 * * @default Button_down */ protected var downBorderSkin:Class; //-------------------------------------------------------------------------- // // Overridden methods // //-------------------------------------------------------------------------- /** * @private */ override protected function createChildren():void { super.createChildren(); setStyle("textAlign", "center"); } override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void { super.updateDisplayList(unscaledWidth,unscaledHeight); if(currentState == "down") { this.alpha = 0.5; } else { this.alpha = 1.0; } } /** * @private */ override protected function commitCurrentState():void { super.commitCurrentState(); borderClass = getBorderClassForCurrentState(); if (!(_border is borderClass)) changeFXGSkin = true; // update borderClass and background invalidateDisplayList(); } /** * @private */ override protected function layoutContents(unscaledWidth:Number, unscaledHeight:Number):void { super.layoutContents(unscaledWidth, unscaledHeight); // size the FXG background if (changeFXGSkin) { changeFXGSkin = false; if (_border) { removeChild(_border); _border = null; } if (borderClass) { _border = new borderClass(); addChildAt(_border, 0); } } layoutBorder(unscaledWidth, unscaledHeight); } /** * Position the background of the skin. Override this function to re-position the background. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ mx_internal function layoutBorder(unscaledWidth:Number, unscaledHeight:Number):void { setElementSize(border, unscaledWidth, unscaledHeight); setElementPosition(border, 0, 0); } /** * Returns the borderClass to use based on the currentState. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 2.5 * @productversion Flex 4.5 */ protected function getBorderClassForCurrentState():Class { if (currentState == "down") return downBorderSkin; else return upBorderSkin; } //-------------------------------------------------------------------------- // // Event Handlers // //-------------------------------------------------------------------------- /** * @private */ override protected function labelDisplay_valueCommitHandler(event:FlexEvent):void { super.labelDisplay_valueCommitHandler(event); } } }
Fix Button's downstate
Fix Button's downstate
ActionScript
apache-2.0
SlavaRa/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk
a2e875a4a9b5115eb441f171294f20cac1b0340a
swfcat.as
swfcat.as
package { import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; 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 }; private const DEFAULT_FACILITATOR_ADDR:Object = { host: "173.255.221.44", port: 9002 }; // 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; [Embed(source="badge.png")] private var BadgeImage:Class; public function puts(s:String):void { output_text.appendText(s + "\n"); output_text.scrollV = output_text.maxScrollV; } public function swfcat() { // Absolute positioning. stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; output_text = new TextField(); output_text.width = stage.stageWidth; output_text.height = stage.stageHeight; output_text.background = true; output_text.backgroundColor = 0x001f0f; output_text.textColor = 0x44cc44; puts("Starting."); // Wait until the query string parameters are loaded. this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete); } private function loaderinfo_complete(e:Event):void { var fac_spec:String; puts("Parameters loaded."); if (this.loaderInfo.parameters["debug"]) addChild(output_text); else addChild(new BadgeImage()); fac_spec = this.loaderInfo.parameters["facilitator"]; if (fac_spec) { 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; } } else { fac_addr = DEFAULT_FACILITATOR_ADDR; } 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.display.StageAlign; import flash.display.StageScaleMode; 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 }; private const DEFAULT_FACILITATOR_ADDR:Object = { host: "173.255.221.44", port: 9002 }; // 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; [Embed(source="badge.png")] private var BadgeImage:Class; public function puts(s:String):void { output_text.appendText(s + "\n"); output_text.scrollV = output_text.maxScrollV; } public function swfcat() { // Absolute positioning. stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; output_text = new TextField(); output_text.width = stage.stageWidth; output_text.height = stage.stageHeight; output_text.background = true; output_text.backgroundColor = 0x001f0f; output_text.textColor = 0x44cc44; puts("Starting."); // Wait until the query string parameters are loaded. this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete); } private function loaderinfo_complete(e:Event):void { var fac_spec:String; puts("Parameters loaded."); if (this.loaderInfo.parameters["debug"]) addChild(output_text); else addChild(new BadgeImage()); fac_spec = this.loaderInfo.parameters["facilitator"]; if (fac_spec) { 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; } } else { fac_addr = DEFAULT_FACILITATOR_ADDR; } 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.addEventListener(Event.COMPLETE, function():void { proxy_pair.log("Complete."); }) 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.EventDispatcher; 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 extends EventDispatcher { // 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(); dispatchEvent(new Event(Event.COMPLETE)); }); s_r.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { log("Tor: I/O error: " + e.text + "."); if (s_c.connected) s_c.close(); dispatchEvent(new Event(Event.COMPLETE)); }); s_r.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { log("Tor: security error: " + e.text + "."); if (s_c.connected) s_c.close(); dispatchEvent(new Event(Event.COMPLETE)); }); 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(); dispatchEvent(new Event(Event.COMPLETE)); }); s_c.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { log("Client: I/O error: " + e.text + "."); if (s_r.connected) s_r.close(); dispatchEvent(new Event(Event.COMPLETE)); }); s_c.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { log("Client: security error: " + e.text + "."); if (s_r.connected) s_r.close(); dispatchEvent(new Event(Event.COMPLETE)); }); 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); }); } }
Add an Event.COMPLETE message when a ProxyPair finishes.
Add an Event.COMPLETE message when a ProxyPair finishes.
ActionScript
mit
arlolra/flashproxy,arlolra/flashproxy,glamrock/flashproxy,glamrock/flashproxy,infinity0/flashproxy,arlolra/flashproxy,glamrock/flashproxy,arlolra/flashproxy,glamrock/flashproxy,arlolra/flashproxy,infinity0/flashproxy,glamrock/flashproxy,infinity0/flashproxy,glamrock/flashproxy,infinity0/flashproxy,infinity0/flashproxy,arlolra/flashproxy,arlolra/flashproxy,infinity0/flashproxy
c7a9d76ff775335ea1d02306143958950a5b5cf5
src/aerys/minko/render/shader/part/phong/contribution/AbstractContributionShaderPart.as
src/aerys/minko/render/shader/part/phong/contribution/AbstractContributionShaderPart.as
package aerys.minko.render.shader.part.phong.contribution { import aerys.minko.render.material.basic.BasicProperties; import aerys.minko.render.material.phong.PhongProperties; import aerys.minko.render.shader.SFloat; import aerys.minko.render.shader.Shader; import aerys.minko.render.shader.part.phong.LightAwareShaderPart; import aerys.minko.type.enum.SamplerFiltering; import aerys.minko.type.enum.SamplerFormat; /** * Methods in this class allow to compute light contributions. * It is extended by InfiniteShaderPart for directional lights, and LocalizedShaderPart for point and spot lights. * * All methods are available in tangent, local and world space. * * - Computing in tangent space is computationally more expensive, both in CPU and GPU, because we need to feed * more data to the shaders than the other methods but it allows to do both bump and parallax mapping. * * - Doing it in local space is computationally more expensive on the CPU, because the light * position will need to be converted in the CPU for each mesh and at each frame will produce the lighter shaders. * * Doing as much work on the CPU as possible, and have as short a possible shader would be the way to go * if adobe's compiler was better than it is. Therefor, minko defaults to computing everything in world space * which is faster in practical tests. * * The cost of each light will be in O(number of drawcalls) on the CPU. * However, this is the way that will lead to the smaller shaders, and is therefor recomended when used * in small scenes with many lights. * * - Computing lights in world space is cheaper on the CPU, because no extra computation is * needed for each mesh, but will cost one extra matrix multiplication on the GPU (we need the world position * or every fragment). * * @author Romain Gilliotte * */ public class AbstractContributionShaderPart extends LightAwareShaderPart { public function AbstractContributionShaderPart(main : Shader) { super(main); } /** * Creates the shader subgraph to compute the diffuse value of a given light. * Computations will be done in tangent space. * * @param lightId The id of the localized light (PointLight or SpotLight) * @return Shader subgraph representing the diffuse value of this light. */ public function computeDiffuseInTangentSpace(lightId : uint) : SFloat { throw new Error('Must be overriden'); } /** * Creates the shader subgraph to compute the diffuse value of a given light. * Computation will be done in local space. * * @param lightId The id of the localized light (PointLight or SpotLight) * @return Shader subgraph representing the diffuse value of this light. */ public function computeDiffuseInLocalSpace(lightId : uint) : SFloat { throw new Error('Must be overriden'); } /** * Creates the shader subgraph to compute the diffuse value of a given light. * Computation will be done in world space. * * @param lightId The id of the light * @return Shader subgraph representing the diffuse value of this light. */ public function computeDiffuseInWorldSpace(lightId : uint) : SFloat { throw new Error('Must be overriden'); } /** * Creates the shader subgraph to compute the specular value of a given light. * Computation will be done in tangent space. * * @param lightId * @return */ public function computeSpecularInTangentSpace(lightId : uint) : SFloat { throw new Error('Must be overriden'); } /** * Creates the shader subgraph to compute the specular value of a given light. * Computation will be done in local space. * * @param lightId * @return */ public function computeSpecularInLocalSpace(lightId : uint) : SFloat { throw new Error('Must be overriden'); } /** * Creates the shader subgraph to compute the specular value of a given light. * Computation will be done in world space. * * @param lightId * @return */ public function computeSpecularInWorldSpace(lightId : uint) : SFloat { throw new Error('Must be overriden'); } /** * Compute final diffuse value from light direction and normal. * Both requested vector can be in any space (tangent, local, light, view or whatever) but must be in the same space. * Also they must be recheable in the fragment shader (they must be constant, or already interpolated) * * @param lightId * @param fsLightDirection * @param fsNormal * @return */ protected function diffuseFromVectors(lightId : uint, fsLightDirection : SFloat, fsNormal : SFloat) : SFloat { var fsLambertProduct : SFloat = saturate(negate(dotProduct3(fsLightDirection, fsNormal))); var cDiffuse : SFloat = getLightParameter(lightId, 'diffuse', 1); if (meshBindings.propertyExists(PhongProperties.DIFFUSE_MULTIPLIER)) cDiffuse.scaleBy(meshBindings.getParameter(PhongProperties.DIFFUSE_MULTIPLIER, 1)); return multiply(cDiffuse, fsLambertProduct); } /** * Compute final specular value from light direction, normal, and camera direction. * All three requested vector can be in any space (tangent, local, light, view or whatever) but must all be in the same sapce. * Also they must be recheable in the fragment shader (they must be constant, or already interpolated) * * @param lightId * @param fsLightDirection * @param fsNormal * @param fsCameraDirection * @return */ protected function specularFromVectors(lightId : uint, fsLightDirection : SFloat, fsNormal : SFloat, fsCameraDirection : SFloat) : SFloat { var fsLightReflectedDirection : SFloat = reflect(fsLightDirection, fsNormal); var fsLambertProduct : SFloat = saturate(negate(dotProduct3(fsLightReflectedDirection, fsCameraDirection))); var cLightSpecular : SFloat = getLightParameter(lightId, 'specular', 1); var cLightShininess : SFloat = getLightParameter(lightId, 'shininess', 1); if (meshBindings.propertyExists(PhongProperties.SPECULAR)) { var specular : SFloat = meshBindings.getParameter(PhongProperties.SPECULAR, 3); cLightSpecular = multiply(cLightSpecular, specular); } if (meshBindings.propertyExists(PhongProperties.SPECULAR_MAP)) { var fsSpecularSample : SFloat = sampleTexture( meshBindings.getTextureParameter( PhongProperties.SPECULAR_MAP, 1, 0, 1, 0, meshBindings.getProperty(PhongProperties.SPECULAR_MAP_FORMAT, SamplerFormat.RGBA) ), fsUV ); cLightSpecular.scaleBy(fsSpecularSample.x); } if (meshBindings.propertyExists(PhongProperties.SHININESS)) cLightShininess.scaleBy(meshBindings.getParameter(PhongProperties.SHININESS, 1)); return multiply(cLightSpecular, power(fsLambertProduct, cLightShininess)); } } }
package aerys.minko.render.shader.part.phong.contribution { import aerys.minko.render.material.basic.BasicProperties; import aerys.minko.render.material.phong.PhongProperties; import aerys.minko.render.shader.SFloat; import aerys.minko.render.shader.Shader; import aerys.minko.render.shader.part.phong.LightAwareShaderPart; import aerys.minko.type.enum.SamplerFiltering; import aerys.minko.type.enum.SamplerFormat; /** * Methods in this class allow to compute light contributions. * It is extended by InfiniteShaderPart for directional lights, and LocalizedShaderPart for point and spot lights. * * All methods are available in tangent, local and world space. * * - Computing in tangent space is computationally more expensive, both in CPU and GPU, because we need to feed * more data to the shaders than the other methods but it allows to do both bump and parallax mapping. * * - Doing it in local space is computationally more expensive on the CPU, because the light * position will need to be converted in the CPU for each mesh and at each frame will produce the lighter shaders. * * Doing as much work on the CPU as possible, and have as short a possible shader would be the way to go * if adobe's compiler was better than it is. Therefor, minko defaults to computing everything in world space * which is faster in practical tests. * * The cost of each light will be in O(number of drawcalls) on the CPU. * However, this is the way that will lead to the smaller shaders, and is therefor recomended when used * in small scenes with many lights. * * - Computing lights in world space is cheaper on the CPU, because no extra computation is * needed for each mesh, but will cost one extra matrix multiplication on the GPU (we need the world position * or every fragment). * * @author Romain Gilliotte * */ public class AbstractContributionShaderPart extends LightAwareShaderPart { public function AbstractContributionShaderPart(main : Shader) { super(main); } /** * Creates the shader subgraph to compute the diffuse value of a given light. * Computations will be done in tangent space. * * @param lightId The id of the localized light (PointLight or SpotLight) * @return Shader subgraph representing the diffuse value of this light. */ public function computeDiffuseInTangentSpace(lightId : uint) : SFloat { throw new Error('Must be overriden'); } /** * Creates the shader subgraph to compute the diffuse value of a given light. * Computation will be done in local space. * * @param lightId The id of the localized light (PointLight or SpotLight) * @return Shader subgraph representing the diffuse value of this light. */ public function computeDiffuseInLocalSpace(lightId : uint) : SFloat { throw new Error('Must be overriden'); } /** * Creates the shader subgraph to compute the diffuse value of a given light. * Computation will be done in world space. * * @param lightId The id of the light * @return Shader subgraph representing the diffuse value of this light. */ public function computeDiffuseInWorldSpace(lightId : uint) : SFloat { throw new Error('Must be overriden'); } /** * Creates the shader subgraph to compute the specular value of a given light. * Computation will be done in tangent space. * * @param lightId * @return */ public function computeSpecularInTangentSpace(lightId : uint) : SFloat { throw new Error('Must be overriden'); } /** * Creates the shader subgraph to compute the specular value of a given light. * Computation will be done in local space. * * @param lightId * @return */ public function computeSpecularInLocalSpace(lightId : uint) : SFloat { throw new Error('Must be overriden'); } /** * Creates the shader subgraph to compute the specular value of a given light. * Computation will be done in world space. * * @param lightId * @return */ public function computeSpecularInWorldSpace(lightId : uint) : SFloat { throw new Error('Must be overriden'); } /** * Compute final diffuse value from light direction and normal. * Both requested vector can be in any space (tangent, local, light, view or whatever) but must be in the same space. * Also they must be recheable in the fragment shader (they must be constant, or already interpolated) * * @param lightId * @param fsLightDirection * @param fsNormal * @return */ protected function diffuseFromVectors(lightId : uint, fsLightDirection : SFloat, fsNormal : SFloat) : SFloat { var fsLambertProduct : SFloat = saturate(negate(dotProduct3(fsLightDirection, fsNormal))); var cDiffuse : SFloat = getLightParameter(lightId, 'diffuse', 1); if (meshBindings.propertyExists(PhongProperties.DIFFUSE_MULTIPLIER)) cDiffuse.scaleBy(meshBindings.getParameter(PhongProperties.DIFFUSE_MULTIPLIER, 1)); return multiply(cDiffuse, fsLambertProduct); } /** * Compute final specular value from light direction, normal, and camera direction. * All three requested vector can be in any space (tangent, local, light, view or whatever) but must all be in the same sapce. * Also they must be recheable in the fragment shader (they must be constant, or already interpolated) * * @param lightId * @param fsLightDirection * @param fsNormal * @param fsCameraDirection * @return */ protected function specularFromVectors(lightId : uint, fsLightDirection : SFloat, fsNormal : SFloat, fsCameraDirection : SFloat) : SFloat { var fsLightReflectedDirection : SFloat = reflect(fsLightDirection, fsNormal); var fsLambertProduct : SFloat = saturate(negate(dotProduct3(fsLightReflectedDirection, fsCameraDirection))); var cLightSpecular : SFloat = getLightParameter(lightId, 'specular', 1); var cLightShininess : SFloat = getLightParameter(lightId, 'shininess', 1); if (meshBindings.propertyExists(PhongProperties.SPECULAR)) { var specular : SFloat = meshBindings.getParameter(PhongProperties.SPECULAR, 4); cLightSpecular = multiply(cLightSpecular, specular.xyz); } if (meshBindings.propertyExists(PhongProperties.SPECULAR_MAP)) { var fsSpecularSample : SFloat = sampleTexture( meshBindings.getTextureParameter( PhongProperties.SPECULAR_MAP, 1, 0, 1, 0, meshBindings.getProperty(PhongProperties.SPECULAR_MAP_FORMAT, SamplerFormat.RGBA) ), fsUV ); cLightSpecular.scaleBy(fsSpecularSample.x); } if (meshBindings.propertyExists(PhongProperties.SHININESS)) cLightShininess.scaleBy(meshBindings.getParameter(PhongProperties.SHININESS, 1)); return multiply(cLightSpecular, power(fsLambertProduct, cLightShininess)); } } }
Fix specular color value
Fix specular color value
ActionScript
mit
aerys/minko-as3
cfc892b0fff59ab9beacf929cf48055c0518aa01
src/com/esri/builder/components/serviceBrowser/supportClasses/ServiceDirectoryBuilder.as
src/com/esri/builder/components/serviceBrowser/supportClasses/ServiceDirectoryBuilder.as
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008-2013 Esri. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //////////////////////////////////////////////////////////////////////////////// package com.esri.builder.components.serviceBrowser.supportClasses { import com.esri.ags.components.IdentityManager; import com.esri.ags.components.supportClasses.Credential; import com.esri.ags.tasks.JSONTask; import com.esri.builder.components.serviceBrowser.filters.GPTaskFilter; import com.esri.builder.components.serviceBrowser.filters.GeocoderFilter; import com.esri.builder.components.serviceBrowser.filters.INodeFilter; import com.esri.builder.components.serviceBrowser.filters.MapLayerFilter; import com.esri.builder.components.serviceBrowser.filters.MapServerFilter; import com.esri.builder.components.serviceBrowser.filters.QueryableLayerFilter; import com.esri.builder.components.serviceBrowser.filters.RouteLayerFilter; import com.esri.builder.components.serviceBrowser.nodes.ServiceDirectoryRootNode; import com.esri.builder.model.Model; import com.esri.builder.model.PortalModel; import com.esri.builder.supportClasses.LogUtil; import flash.events.EventDispatcher; import flash.net.URLVariables; import mx.logging.ILogger; import mx.logging.Log; import mx.resources.ResourceManager; import mx.rpc.Fault; import mx.rpc.Responder; import mx.rpc.events.FaultEvent; import mx.rpc.events.ResultEvent; import mx.rpc.http.HTTPService; public final class ServiceDirectoryBuilder extends EventDispatcher { private static const LOG:ILogger = LogUtil.createLogger(ServiceDirectoryBuilder); private static const DEFAULT_REQUEST_TIMEOUT_IN_SECONDS:Number = 10; private var serviceDirectoryBuildRequest:ServiceDirectoryBuildRequest; private var hasCrossDomain:Boolean; private var crossDomainRequest:HTTPService; private var credential:Credential; private var rootNode:ServiceDirectoryRootNode; private var currentNodeFilter:INodeFilter; private var isServiceSecured:Boolean; private var securityWarning:String; private var owningSystemURL:String; public function buildServiceDirectory(serviceDirectoryBuildRequest:ServiceDirectoryBuildRequest):void { if (Log.isInfo()) { LOG.info("Building service directory"); } this.serviceDirectoryBuildRequest = serviceDirectoryBuildRequest; try { checkCrossDomainBeforeBuildingDirectory(); } catch (error:Error) { //TODO: handle error } } private function checkCrossDomainBeforeBuildingDirectory():void { if (Log.isDebug()) { LOG.debug("Checking service URL crossdomain.xml"); } crossDomainRequest = new HTTPService(); crossDomainRequest.url = extractCrossDomainPolicyFileURL(serviceDirectoryBuildRequest.url); crossDomainRequest.addEventListener(ResultEvent.RESULT, crossDomainRequest_resultHandler); crossDomainRequest.addEventListener(FaultEvent.FAULT, crossDomainRequest_faultHandler); crossDomainRequest.requestTimeout = DEFAULT_REQUEST_TIMEOUT_IN_SECONDS; crossDomainRequest.send(); function crossDomainRequest_resultHandler(event:ResultEvent):void { if (Log.isDebug()) { LOG.debug("Found service crossdomain.xml"); } crossDomainRequest.removeEventListener(ResultEvent.RESULT, crossDomainRequest_resultHandler); crossDomainRequest.removeEventListener(FaultEvent.FAULT, crossDomainRequest_faultHandler); crossDomainRequest = null; hasCrossDomain = true; getServiceInfo(); } function crossDomainRequest_faultHandler(event:FaultEvent):void { if (Log.isDebug()) { LOG.debug("Could not find service crossdomain.xml"); } crossDomainRequest.removeEventListener(ResultEvent.RESULT, crossDomainRequest_resultHandler); crossDomainRequest.removeEventListener(FaultEvent.FAULT, crossDomainRequest_faultHandler); crossDomainRequest = null; hasCrossDomain = false; getServiceInfo(); } } private function extractCrossDomainPolicyFileURL(url:String):String { var baseURL:RegExp = /(https?:\/\/)([^\/]+\/)/ var baseURLMatch:Array = url.match(baseURL); return baseURLMatch[0] + 'crossdomain.xml'; } private function getServiceInfo():void { var serviceInfoRequest:JSONTask = new JSONTask(); serviceInfoRequest.url = extractServiceInfoURL(serviceDirectoryBuildRequest.url); const param:URLVariables = new URLVariables(); param.f = 'json'; serviceInfoRequest.execute(param, new Responder(serviceInfoRequest_resultHandler, serviceInfoRequest_faultHandler)); function serviceInfoRequest_resultHandler(serverInfo:Object):void { owningSystemURL = serverInfo.owningSystemUrl; if (PortalModel.getInstance().hasSameOrigin(owningSystemURL)) { if (PortalModel.getInstance().portal.signedIn) { IdentityManager.instance.getCredential( serviceDirectoryBuildRequest.url, false, new Responder(getCredential_successHandler, getCredential_faultHandler)); function getCredential_successHandler(credential:Credential):void { checkIfServiceIsSecure(serverInfo); } function getCredential_faultHandler(fault:Fault):void { checkIfServiceIsSecure(serverInfo); } } else { var credential:Credential = IdentityManager.instance.findCredential(serviceDirectoryBuildRequest.url); if (credential) { credential.destroy(); } checkIfServiceIsSecure(serverInfo); } } else { checkIfServiceIsSecure(serverInfo); } } function serviceInfoRequest_faultHandler(fault:Fault):void { checkIfServiceIsSecure(null); } } private function checkIfServiceIsSecure(serverInfo:Object):void { if (Log.isInfo()) { LOG.info("Checking if service is secure"); } if (serverInfo) { isServiceSecured = (serverInfo.currentVersion >= 10.01 && serverInfo.authInfo && serverInfo.authInfo.isTokenBasedSecurity); if (isServiceSecured) { if (Log.isDebug()) { LOG.debug("Service is secure"); } if (Log.isDebug()) { LOG.debug("Checking token service crossdomain.xml"); } const tokenServiceCrossDomainRequest:HTTPService = new HTTPService(); tokenServiceCrossDomainRequest.url = extractCrossDomainPolicyFileURL(serverInfo.authInfo.tokenServicesUrl); tokenServiceCrossDomainRequest.resultFormat = HTTPService.RESULT_FORMAT_E4X; tokenServiceCrossDomainRequest.addEventListener(ResultEvent.RESULT, tokenServiceSecurityRequest_resultHandler); tokenServiceCrossDomainRequest.addEventListener(FaultEvent.FAULT, tokenServiceSecurityRequest_faultHandler); tokenServiceCrossDomainRequest.send(); function tokenServiceSecurityRequest_resultHandler(event:ResultEvent):void { if (Log.isDebug()) { LOG.debug("Found token service crossdomain.xml"); } tokenServiceCrossDomainRequest.removeEventListener(ResultEvent.RESULT, tokenServiceSecurityRequest_resultHandler); tokenServiceCrossDomainRequest.removeEventListener(FaultEvent.FAULT, tokenServiceSecurityRequest_faultHandler); const startsWithHTTPS:RegExp = /^https/; if (startsWithHTTPS.test(tokenServiceCrossDomainRequest.url)) { const tokenServiceCrossDomainXML:XML = event.result as XML; const hasSecurityEnabled:Boolean = tokenServiceCrossDomainXML.child("allow-access-from").(attribute("secure") == "false").length() == 0 || tokenServiceCrossDomainXML.child("allow-http-request-headers-from").(attribute("secure") == "false").length() == 0; if (hasSecurityEnabled && !startsWithHTTPS.test(Model.instance.appDir.url)) { securityWarning = ResourceManager.getInstance().getString('BuilderStrings', 'serviceBrowser.secureTokenServiceWithSecureCrossDomain'); } } } function tokenServiceSecurityRequest_faultHandler(event:FaultEvent):void { if (Log.isDebug()) { LOG.debug("Could not find token service crossdomain.xml"); } tokenServiceCrossDomainRequest.removeEventListener(ResultEvent.RESULT, tokenServiceSecurityRequest_resultHandler); tokenServiceCrossDomainRequest.removeEventListener(FaultEvent.FAULT, tokenServiceSecurityRequest_faultHandler); securityWarning = ResourceManager.getInstance().getString('BuilderStrings', 'serviceBrowser.secureTokenServiceMissingCrossDomain'); } } //continue with building service directory startBuildingDirectory(); } else { //continue with building service directory startBuildingDirectory(); } } private function extractServiceInfoURL(url:String):String { return url.replace('/rest/services', '/rest/info'); } private function startBuildingDirectory():void { if (Log.isInfo()) { LOG.info('Building serviced directory {0}', serviceDirectoryBuildRequest.url); } const servicesDirectoryURL:RegExp = /.+\/rest\/services\/?/; const serviceURLRootMatch:Array = servicesDirectoryURL.exec(serviceDirectoryBuildRequest.url); if (!serviceURLRootMatch) { return; } currentNodeFilter = filterFromSearchType(serviceDirectoryBuildRequest.searchType); rootNode = new ServiceDirectoryRootNode(serviceDirectoryBuildRequest.url, currentNodeFilter); rootNode.addEventListener(URLNodeTraversalEvent.END_REACHED, rootNode_completeHandler); rootNode.addEventListener(FaultEvent.FAULT, rootNode_faultHandler); credential = IdentityManager.instance.findCredential(serviceURLRootMatch[0]); if (credential) { rootNode.token = credential.token; } rootNode.loadChildren(); } private function filterFromSearchType(searchType:String):INodeFilter { if (searchType == ServiceDirectoryBuildRequest.QUERYABLE_LAYER_SEARCH) { return new QueryableLayerFilter(); } else if (searchType == ServiceDirectoryBuildRequest.GEOPROCESSING_TASK_SEARCH) { return new GPTaskFilter(); } else if (searchType == ServiceDirectoryBuildRequest.GEOCODER_SEARCH) { return new GeocoderFilter(); } else if (searchType == ServiceDirectoryBuildRequest.ROUTE_LAYER_SEARCH) { return new RouteLayerFilter(); } else if (searchType == ServiceDirectoryBuildRequest.MAP_SERVER_SEARCH) { return new MapServerFilter(); } else //MAP LAYER SEARCH { return new MapLayerFilter(); } } private function rootNode_completeHandler(event:URLNodeTraversalEvent):void { if (Log.isInfo()) { LOG.info("Finished building service directory"); } dispatchEvent( new ServiceDirectoryBuilderEvent(ServiceDirectoryBuilderEvent.COMPLETE, new ServiceDirectoryInfo(rootNode, event.urlNodes, currentNodeFilter, hasCrossDomain, isServiceSecured, securityWarning, owningSystemURL))); } protected function rootNode_faultHandler(event:FaultEvent):void { if (Log.isInfo()) { LOG.info("Could not build service directory"); } dispatchEvent(event); } } }
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008-2013 Esri. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //////////////////////////////////////////////////////////////////////////////// package com.esri.builder.components.serviceBrowser.supportClasses { import com.esri.ags.components.IdentityManager; import com.esri.ags.components.supportClasses.Credential; import com.esri.ags.tasks.JSONTask; import com.esri.builder.components.serviceBrowser.filters.GPTaskFilter; import com.esri.builder.components.serviceBrowser.filters.GeocoderFilter; import com.esri.builder.components.serviceBrowser.filters.INodeFilter; import com.esri.builder.components.serviceBrowser.filters.MapLayerFilter; import com.esri.builder.components.serviceBrowser.filters.MapServerFilter; import com.esri.builder.components.serviceBrowser.filters.QueryableLayerFilter; import com.esri.builder.components.serviceBrowser.filters.RouteLayerFilter; import com.esri.builder.components.serviceBrowser.nodes.ServiceDirectoryRootNode; import com.esri.builder.model.Model; import com.esri.builder.model.PortalModel; import com.esri.builder.supportClasses.LogUtil; import flash.events.EventDispatcher; import flash.net.URLVariables; import mx.logging.ILogger; import mx.logging.Log; import mx.resources.ResourceManager; import mx.rpc.Fault; import mx.rpc.Responder; import mx.rpc.events.FaultEvent; import mx.rpc.events.ResultEvent; import mx.rpc.http.HTTPService; public final class ServiceDirectoryBuilder extends EventDispatcher { private static const LOG:ILogger = LogUtil.createLogger(ServiceDirectoryBuilder); private static const DEFAULT_REQUEST_TIMEOUT_IN_SECONDS:Number = 10; private var serviceDirectoryBuildRequest:ServiceDirectoryBuildRequest; private var hasCrossDomain:Boolean; private var crossDomainRequest:HTTPService; private var credential:Credential; private var rootNode:ServiceDirectoryRootNode; private var currentNodeFilter:INodeFilter; private var isServiceSecured:Boolean; private var securityWarning:String; private var owningSystemURL:String; public function buildServiceDirectory(serviceDirectoryBuildRequest:ServiceDirectoryBuildRequest):void { if (Log.isInfo()) { LOG.info("Building service directory"); } this.serviceDirectoryBuildRequest = serviceDirectoryBuildRequest; try { checkCrossDomainBeforeBuildingDirectory(); } catch (error:Error) { //TODO: handle error } } private function checkCrossDomainBeforeBuildingDirectory():void { if (Log.isDebug()) { LOG.debug("Checking service URL crossdomain.xml"); } crossDomainRequest = new HTTPService(); crossDomainRequest.url = extractCrossDomainPolicyFileURL(serviceDirectoryBuildRequest.url); crossDomainRequest.addEventListener(ResultEvent.RESULT, crossDomainRequest_resultHandler); crossDomainRequest.addEventListener(FaultEvent.FAULT, crossDomainRequest_faultHandler); crossDomainRequest.requestTimeout = DEFAULT_REQUEST_TIMEOUT_IN_SECONDS; crossDomainRequest.send(); function crossDomainRequest_resultHandler(event:ResultEvent):void { if (Log.isDebug()) { LOG.debug("Found service crossdomain.xml"); } crossDomainRequest.removeEventListener(ResultEvent.RESULT, crossDomainRequest_resultHandler); crossDomainRequest.removeEventListener(FaultEvent.FAULT, crossDomainRequest_faultHandler); crossDomainRequest = null; hasCrossDomain = true; getServiceInfo(); } function crossDomainRequest_faultHandler(event:FaultEvent):void { if (Log.isDebug()) { LOG.debug("Could not find service crossdomain.xml"); } crossDomainRequest.removeEventListener(ResultEvent.RESULT, crossDomainRequest_resultHandler); crossDomainRequest.removeEventListener(FaultEvent.FAULT, crossDomainRequest_faultHandler); crossDomainRequest = null; hasCrossDomain = false; getServiceInfo(); } } private function extractCrossDomainPolicyFileURL(url:String):String { var baseURL:RegExp = /(https?:\/\/)([^\/]+\/)/ var baseURLMatch:Array = url.match(baseURL); return baseURLMatch[0] + 'crossdomain.xml'; } private function getServiceInfo():void { var serviceInfoRequest:JSONTask = new JSONTask(); serviceInfoRequest.url = extractServiceInfoURL(serviceDirectoryBuildRequest.url); const param:URLVariables = new URLVariables(); param.f = 'json'; serviceInfoRequest.execute(param, new Responder(serviceInfoRequest_resultHandler, serviceInfoRequest_faultHandler)); function serviceInfoRequest_resultHandler(serverInfo:Object):void { owningSystemURL = serverInfo.owningSystemUrl; if (PortalModel.getInstance().hasSameOrigin(owningSystemURL)) { if (PortalModel.getInstance().portal.signedIn) { IdentityManager.instance.getCredential( serviceDirectoryBuildRequest.url, false, new Responder(getCredential_successHandler, getCredential_faultHandler)); function getCredential_successHandler(credential:Credential):void { checkIfServiceIsSecure(serverInfo); } function getCredential_faultHandler(fault:Fault):void { checkIfServiceIsSecure(serverInfo); } } else { var credential:Credential = IdentityManager.instance.findCredential(serviceDirectoryBuildRequest.url); if (credential) { credential.destroy(); } checkIfServiceIsSecure(serverInfo); } } else { checkIfServiceIsSecure(serverInfo); } } function serviceInfoRequest_faultHandler(fault:Fault):void { checkIfServiceIsSecure(null); } } private function checkIfServiceIsSecure(serverInfo:Object):void { if (Log.isInfo()) { LOG.info("Checking if service is secure"); } if (serverInfo) { isServiceSecured = (serverInfo.currentVersion >= 10.01 && serverInfo.authInfo && serverInfo.authInfo.isTokenBasedSecurity && (serverInfo.authInfo.tokenServicesUrl || serverInfo.authInfo.tokenServiceUrl)); if (isServiceSecured) { if (Log.isDebug()) { LOG.debug("Service is secure"); } if (Log.isDebug()) { LOG.debug("Checking token service crossdomain.xml"); } const tokenServiceCrossDomainRequest:HTTPService = new HTTPService(); const tokenServiceURL:String = serverInfo.authInfo.tokenServicesUrl || serverInfo.authInfo.tokenServiceUrl; tokenServiceCrossDomainRequest.url = extractCrossDomainPolicyFileURL(tokenServiceURL); tokenServiceCrossDomainRequest.resultFormat = HTTPService.RESULT_FORMAT_E4X; tokenServiceCrossDomainRequest.addEventListener(ResultEvent.RESULT, tokenServiceSecurityRequest_resultHandler); tokenServiceCrossDomainRequest.addEventListener(FaultEvent.FAULT, tokenServiceSecurityRequest_faultHandler); tokenServiceCrossDomainRequest.send(); function tokenServiceSecurityRequest_resultHandler(event:ResultEvent):void { if (Log.isDebug()) { LOG.debug("Found token service crossdomain.xml"); } tokenServiceCrossDomainRequest.removeEventListener(ResultEvent.RESULT, tokenServiceSecurityRequest_resultHandler); tokenServiceCrossDomainRequest.removeEventListener(FaultEvent.FAULT, tokenServiceSecurityRequest_faultHandler); const startsWithHTTPS:RegExp = /^https/; if (startsWithHTTPS.test(tokenServiceCrossDomainRequest.url)) { const tokenServiceCrossDomainXML:XML = event.result as XML; const hasSecurityEnabled:Boolean = tokenServiceCrossDomainXML.child("allow-access-from").(attribute("secure") == "false").length() == 0 || tokenServiceCrossDomainXML.child("allow-http-request-headers-from").(attribute("secure") == "false").length() == 0; if (hasSecurityEnabled && !startsWithHTTPS.test(Model.instance.appDir.url)) { securityWarning = ResourceManager.getInstance().getString('BuilderStrings', 'serviceBrowser.secureTokenServiceWithSecureCrossDomain'); } } } function tokenServiceSecurityRequest_faultHandler(event:FaultEvent):void { if (Log.isDebug()) { LOG.debug("Could not find token service crossdomain.xml"); } tokenServiceCrossDomainRequest.removeEventListener(ResultEvent.RESULT, tokenServiceSecurityRequest_resultHandler); tokenServiceCrossDomainRequest.removeEventListener(FaultEvent.FAULT, tokenServiceSecurityRequest_faultHandler); securityWarning = ResourceManager.getInstance().getString('BuilderStrings', 'serviceBrowser.secureTokenServiceMissingCrossDomain'); } } //continue with building service directory startBuildingDirectory(); } else { //continue with building service directory startBuildingDirectory(); } } private function extractServiceInfoURL(url:String):String { return url.replace('/rest/services', '/rest/info'); } private function startBuildingDirectory():void { if (Log.isInfo()) { LOG.info('Building serviced directory {0}', serviceDirectoryBuildRequest.url); } const servicesDirectoryURL:RegExp = /.+\/rest\/services\/?/; const serviceURLRootMatch:Array = servicesDirectoryURL.exec(serviceDirectoryBuildRequest.url); if (!serviceURLRootMatch) { return; } currentNodeFilter = filterFromSearchType(serviceDirectoryBuildRequest.searchType); rootNode = new ServiceDirectoryRootNode(serviceDirectoryBuildRequest.url, currentNodeFilter); rootNode.addEventListener(URLNodeTraversalEvent.END_REACHED, rootNode_completeHandler); rootNode.addEventListener(FaultEvent.FAULT, rootNode_faultHandler); credential = IdentityManager.instance.findCredential(serviceURLRootMatch[0]); if (credential) { rootNode.token = credential.token; } rootNode.loadChildren(); } private function filterFromSearchType(searchType:String):INodeFilter { if (searchType == ServiceDirectoryBuildRequest.QUERYABLE_LAYER_SEARCH) { return new QueryableLayerFilter(); } else if (searchType == ServiceDirectoryBuildRequest.GEOPROCESSING_TASK_SEARCH) { return new GPTaskFilter(); } else if (searchType == ServiceDirectoryBuildRequest.GEOCODER_SEARCH) { return new GeocoderFilter(); } else if (searchType == ServiceDirectoryBuildRequest.ROUTE_LAYER_SEARCH) { return new RouteLayerFilter(); } else if (searchType == ServiceDirectoryBuildRequest.MAP_SERVER_SEARCH) { return new MapServerFilter(); } else //MAP LAYER SEARCH { return new MapLayerFilter(); } } private function rootNode_completeHandler(event:URLNodeTraversalEvent):void { if (Log.isInfo()) { LOG.info("Finished building service directory"); } dispatchEvent( new ServiceDirectoryBuilderEvent(ServiceDirectoryBuilderEvent.COMPLETE, new ServiceDirectoryInfo(rootNode, event.urlNodes, currentNodeFilter, hasCrossDomain, isServiceSecured, securityWarning, owningSystemURL))); } protected function rootNode_faultHandler(event:FaultEvent):void { if (Log.isInfo()) { LOG.info("Could not build service directory"); } dispatchEvent(event); } } }
Use either tokenServicesUrl or tokenServiceUrl when building the token service cross-domain policy file URL.
Use either tokenServicesUrl or tokenServiceUrl when building the token service cross-domain policy file URL.
ActionScript
apache-2.0
Esri/arcgis-viewer-builder-flex
6bdc75b2d7fea5c4750612fd0c9541e7bff3c0b3
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; [SWF(width="640", height="480")] 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 = 640; output_text.height = 480; 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.display.StageAlign; import flash.display.StageScaleMode; 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() { // Absolute positioning. stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; output_text = new TextField(); output_text.width = stage.stageWidth; output_text.height = stage.stageHeight; output_text.background = true; output_text.backgroundColor = 0x001f0f; output_text.textColor = 0x44CC44; 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); }); } }
Remove hardcoded width and height from SWF source.
Remove hardcoded width and height from SWF source. Let it be completely controlled by containing HTML.
ActionScript
mit
infinity0/flashproxy,arlolra/flashproxy,glamrock/flashproxy,glamrock/flashproxy,glamrock/flashproxy,infinity0/flashproxy,infinity0/flashproxy,arlolra/flashproxy,arlolra/flashproxy,glamrock/flashproxy,infinity0/flashproxy,arlolra/flashproxy,glamrock/flashproxy,arlolra/flashproxy,glamrock/flashproxy,infinity0/flashproxy,arlolra/flashproxy,arlolra/flashproxy,infinity0/flashproxy
1c954cc3cf06bab67ae4b05fbd6a694744aebe3d
src/com/esri/builder/controllers/supportClasses/WidgetTypeLoader.as
src/com/esri/builder/controllers/supportClasses/WidgetTypeLoader.as
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008-2013 Esri. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //////////////////////////////////////////////////////////////////////////////// package com.esri.builder.controllers.supportClasses { import com.esri.builder.model.CustomWidgetType; import com.esri.builder.model.Model; import com.esri.builder.model.WidgetType; import com.esri.builder.model.WidgetTypeRegistryModel; import com.esri.builder.supportClasses.LogUtil; import com.esri.builder.views.BuilderAlert; import flash.events.EventDispatcher; import flash.filesystem.File; import flash.filesystem.FileMode; import flash.filesystem.FileStream; import flash.system.ApplicationDomain; 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; import mx.resources.ResourceManager; public class WidgetTypeLoader extends EventDispatcher { private static const LOG:ILogger = LogUtil.createLogger(WidgetTypeLoader); private var widgetTypeArr:Array = []; private var pendingModuleInfos:Array = []; private var modulesToLoad:uint; public function loadWidgetTypes():void { if (Log.isInfo()) { LOG.info('Loading modules...'); } var moduleFiles:Array = getModuleFiles(WellKnownDirectories.getInstance().bundledModules) .concat(getModuleFiles(WellKnownDirectories.getInstance().customModules)); //TODO: remove XML files from found SWF files modulesToLoad = moduleFiles.length; // Load the found modules. for each (var moduleFile:File in moduleFiles) { if (Log.isDebug()) { LOG.debug('loading module {0}', moduleFile.url); } //we assume XML module files are custom if (moduleFile.extension == "xml") { loadCustomWidgetTypeConfig(moduleFile); } else if (moduleFile.extension == "swf") { loadModule(moduleFile); } } checkIfNoMoreModuleInfosLeft(); } private function loadModule(moduleFile:File):void { var fileBytes:ByteArray = new ByteArray(); var fileStream:FileStream = new FileStream(); fileStream.open(moduleFile, FileMode.READ); fileStream.readBytes(fileBytes); fileStream.close(); const moduleInfo:IModuleInfo = ModuleManager.getModule(moduleFile.url); pendingModuleInfos.push(moduleInfo); moduleInfo.addEventListener(ModuleEvent.READY, moduleInfo_readyHandler); moduleInfo.addEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler); moduleInfo.load(ApplicationDomain.currentDomain, null, fileBytes, FlexGlobals.topLevelApplication.moduleFactory); } public function loadCustomWidgetTypeConfig(configFile:File):void { var customWidgetType:CustomWidgetType = createCustomWidgetTypeFromConfig(configFile); if (customWidgetType) { WidgetTypeRegistryModel.getInstance().widgetTypeRegistry.addWidgetType(customWidgetType); } markModuleAsLoaded(); } private function createCustomWidgetTypeFromConfig(configFile:File):CustomWidgetType { var fileStream:FileStream = new FileStream(); var customWidgetType:CustomWidgetType; try { fileStream.open(configFile, FileMode.READ); const configXML:XML = XML(fileStream.readUTFBytes(fileStream.bytesAvailable)); customWidgetType = parseCustomWidgetType(configXML); } catch (e:Error) { if (Log.isWarn()) { LOG.warn('Error creating custom module {0}', configFile.nativePath); } } finally { fileStream.close(); } return customWidgetType; } private function parseCustomWidgetType(configXML:XML):CustomWidgetType { 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; } /* Finds module files at the parent-directory level */ private function getModuleFiles(directory:File):Array { var moduleFiles:Array = []; if (directory.isDirectory) { const files:Array = directory.getDirectoryListing(); for each (var file:File in files) { if (isModuleFile(file)) { moduleFiles.push(file); } } } return moduleFiles; } private function isModuleFile(file:File):Boolean { const moduleFileName:RegExp = /^.*Module\.(swf|xml)$/; return !file.isDirectory && (moduleFileName.test(file.name)); } private function moduleInfo_readyHandler(event:ModuleEvent):void { var moduleInfo:IModuleInfo = event.currentTarget as IModuleInfo; moduleInfo.removeEventListener(ModuleEvent.READY, moduleInfo_readyHandler); moduleInfo.removeEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler); const builderModule:IBuilderModule = event.module.factory.create() as IBuilderModule; if (builderModule) { var customModulesDirectoryURL:String = WellKnownDirectories.getInstance().customModules.url; var isCustomModule:Boolean = (moduleInfo.url.indexOf(customModulesDirectoryURL) > -1); const widgetType:WidgetType = isCustomModule ? new CustomWidgetType(builderModule) : new WidgetType(builderModule); widgetTypeArr.push(widgetType); if (Log.isDebug()) { LOG.debug('Module {0} is resolved', widgetType.name); } } markModuleAsLoaded(); removeModuleInfo(moduleInfo); checkIfNoMoreModuleInfosLeft(); } private function removeModuleInfo(moduleInfo:IModuleInfo):void { const index:int = pendingModuleInfos.indexOf(moduleInfo); if (index > -1) { pendingModuleInfos.splice(index, 1); } } private function checkIfNoMoreModuleInfosLeft():void { if (modulesToLoad === 0) { sortAndAssignWidgetTypes(); } } private function markModuleAsLoaded():void { modulesToLoad--; } private function sortAndAssignWidgetTypes():void { if (Log.isInfo()) { LOG.info('All modules resolved'); } widgetTypeArr.sort(compareWidgetTypes); var widgetTypes:Array = widgetTypeArr.filter(widgetTypeFilter); for each (var widgetType:WidgetType in widgetTypes) { WidgetTypeRegistryModel.getInstance().widgetTypeRegistry.addWidgetType(widgetType); } var layoutWidgetTypes:Array = widgetTypeArr.filter(layoutWidgetTypeFilter); for each (var layoutWidgetType:WidgetType in layoutWidgetTypes) { WidgetTypeRegistryModel.getInstance().layoutWidgetTypeRegistry.addWidgetType(layoutWidgetType); } function widgetTypeFilter(item:WidgetType, index:int, source:Array):Boolean { return item.isManaged; } function layoutWidgetTypeFilter(item:WidgetType, index:int, source:Array):Boolean { return !item.isManaged; } dispatchEvent(new WidgetTypeLoaderEvent(WidgetTypeLoaderEvent.LOAD_TYPES_COMPLETE)); } private function compareWidgetTypes(lhs:WidgetType, rhs:WidgetType):int { const lhsLabel:String = lhs.label.toLowerCase(); const rhsLabel:String = rhs.label.toLowerCase(); if (lhsLabel < rhsLabel) { return -1; } if (lhsLabel > rhsLabel) { return 1; } return 0; } private function moduleInfo_errorHandler(event:ModuleEvent):void { if (Log.isWarn()) { LOG.warn('Module error: {0}', event.errorText); } var moduleInfo:IModuleInfo = event.currentTarget as IModuleInfo; moduleInfo.removeEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler); moduleInfo.removeEventListener(ModuleEvent.READY, moduleInfo_readyHandler); Model.instance.status = event.errorText; BuilderAlert.show(event.errorText, ResourceManager.getInstance().getString('BuilderStrings', 'error')); markModuleAsLoaded(); removeModuleInfo(moduleInfo); checkIfNoMoreModuleInfosLeft(); } } }
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008-2013 Esri. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //////////////////////////////////////////////////////////////////////////////// package com.esri.builder.controllers.supportClasses { import com.esri.builder.model.CustomWidgetType; import com.esri.builder.model.Model; import com.esri.builder.model.WidgetType; import com.esri.builder.model.WidgetTypeRegistryModel; import com.esri.builder.supportClasses.LogUtil; import com.esri.builder.views.BuilderAlert; import flash.events.EventDispatcher; import flash.filesystem.File; import flash.filesystem.FileMode; import flash.filesystem.FileStream; import flash.system.ApplicationDomain; 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; import mx.resources.ResourceManager; public class WidgetTypeLoader extends EventDispatcher { private static const LOG:ILogger = LogUtil.createLogger(WidgetTypeLoader); private var widgetTypeArr:Array = []; private var pendingModuleInfos:Array = []; private var modulesToLoad:uint; public function loadWidgetTypes():void { if (Log.isInfo()) { LOG.info('Loading modules...'); } var moduleFiles:Array = getModuleFiles(WellKnownDirectories.getInstance().bundledModules) .concat(getModuleFiles(WellKnownDirectories.getInstance().customModules)); //TODO: remove XML files from found SWF files modulesToLoad = moduleFiles.length; // Load the found modules. for each (var moduleFile:File in moduleFiles) { if (Log.isDebug()) { LOG.debug('loading module {0}', moduleFile.url); } //we assume XML module files are custom if (moduleFile.extension == "xml") { loadCustomWidgetTypeConfig(moduleFile); } else if (moduleFile.extension == "swf") { loadModule(moduleFile); } } checkIfNoMoreModuleInfosLeft(); } private function loadModule(moduleFile:File):void { var fileBytes:ByteArray = new ByteArray(); var fileStream:FileStream = new FileStream(); fileStream.open(moduleFile, FileMode.READ); fileStream.readBytes(fileBytes); fileStream.close(); const moduleInfo:IModuleInfo = ModuleManager.getModule(moduleFile.url); pendingModuleInfos.push(moduleInfo); moduleInfo.addEventListener(ModuleEvent.READY, moduleInfo_readyHandler); moduleInfo.addEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler); moduleInfo.load(ApplicationDomain.currentDomain, null, fileBytes, FlexGlobals.topLevelApplication.moduleFactory); } public function loadCustomWidgetTypeConfig(configFile:File):void { var customWidgetType:CustomWidgetType = createCustomWidgetTypeFromConfig(configFile); if (customWidgetType) { WidgetTypeRegistryModel.getInstance().widgetTypeRegistry.addWidgetType(customWidgetType); } markModuleAsLoaded(); } private function createCustomWidgetTypeFromConfig(configFile:File):CustomWidgetType { var fileStream:FileStream = new FileStream(); var customWidgetType:CustomWidgetType; try { fileStream.open(configFile, FileMode.READ); const configXML:XML = XML(fileStream.readUTFBytes(fileStream.bytesAvailable)); customWidgetType = parseCustomWidgetType(configXML); } catch (e:Error) { if (Log.isWarn()) { LOG.warn('Error creating custom module {0}', configFile.nativePath); } } finally { fileStream.close(); } return customWidgetType; } private function parseCustomWidgetType(configXML:XML):CustomWidgetType { 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; } private function getModuleFiles(directory:File):Array { var moduleFiles:Array = []; if (directory.isDirectory) { const files:Array = directory.getDirectoryListing(); for each (var file:File in files) { if(file.isDirectory) { moduleFiles = moduleFiles.concat(getModuleFiles(file)); } else if (isModuleFile(file)) { moduleFiles.push(file); } } } return moduleFiles; } private function isModuleFile(file:File):Boolean { const moduleFileName:RegExp = /^.*Module\.(swf|xml)$/; return !file.isDirectory && (moduleFileName.test(file.name)); } private function moduleInfo_readyHandler(event:ModuleEvent):void { var moduleInfo:IModuleInfo = event.currentTarget as IModuleInfo; moduleInfo.removeEventListener(ModuleEvent.READY, moduleInfo_readyHandler); moduleInfo.removeEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler); const builderModule:IBuilderModule = event.module.factory.create() as IBuilderModule; if (builderModule) { var customModulesDirectoryURL:String = WellKnownDirectories.getInstance().customModules.url; var isCustomModule:Boolean = (moduleInfo.url.indexOf(customModulesDirectoryURL) > -1); const widgetType:WidgetType = isCustomModule ? new CustomWidgetType(builderModule) : new WidgetType(builderModule); widgetTypeArr.push(widgetType); if (Log.isDebug()) { LOG.debug('Module {0} is resolved', widgetType.name); } } markModuleAsLoaded(); removeModuleInfo(moduleInfo); checkIfNoMoreModuleInfosLeft(); } private function removeModuleInfo(moduleInfo:IModuleInfo):void { const index:int = pendingModuleInfos.indexOf(moduleInfo); if (index > -1) { pendingModuleInfos.splice(index, 1); } } private function checkIfNoMoreModuleInfosLeft():void { if (modulesToLoad === 0) { sortAndAssignWidgetTypes(); } } private function markModuleAsLoaded():void { modulesToLoad--; } private function sortAndAssignWidgetTypes():void { if (Log.isInfo()) { LOG.info('All modules resolved'); } widgetTypeArr.sort(compareWidgetTypes); var widgetTypes:Array = widgetTypeArr.filter(widgetTypeFilter); for each (var widgetType:WidgetType in widgetTypes) { WidgetTypeRegistryModel.getInstance().widgetTypeRegistry.addWidgetType(widgetType); } var layoutWidgetTypes:Array = widgetTypeArr.filter(layoutWidgetTypeFilter); for each (var layoutWidgetType:WidgetType in layoutWidgetTypes) { WidgetTypeRegistryModel.getInstance().layoutWidgetTypeRegistry.addWidgetType(layoutWidgetType); } function widgetTypeFilter(item:WidgetType, index:int, source:Array):Boolean { return item.isManaged; } function layoutWidgetTypeFilter(item:WidgetType, index:int, source:Array):Boolean { return !item.isManaged; } dispatchEvent(new WidgetTypeLoaderEvent(WidgetTypeLoaderEvent.LOAD_TYPES_COMPLETE)); } private function compareWidgetTypes(lhs:WidgetType, rhs:WidgetType):int { const lhsLabel:String = lhs.label.toLowerCase(); const rhsLabel:String = rhs.label.toLowerCase(); if (lhsLabel < rhsLabel) { return -1; } if (lhsLabel > rhsLabel) { return 1; } return 0; } private function moduleInfo_errorHandler(event:ModuleEvent):void { if (Log.isWarn()) { LOG.warn('Module error: {0}', event.errorText); } var moduleInfo:IModuleInfo = event.currentTarget as IModuleInfo; moduleInfo.removeEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler); moduleInfo.removeEventListener(ModuleEvent.READY, moduleInfo_readyHandler); Model.instance.status = event.errorText; BuilderAlert.show(event.errorText, ResourceManager.getInstance().getString('BuilderStrings', 'error')); markModuleAsLoaded(); removeModuleInfo(moduleInfo); checkIfNoMoreModuleInfosLeft(); } } }
Update WidgetTypeLoader#getModuleFiles() to return nested module files.
Update WidgetTypeLoader#getModuleFiles() to return nested module files.
ActionScript
apache-2.0
Esri/arcgis-viewer-builder-flex
c7265a6c04144e36e814c7ce7da1c10cfac9bd06
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 # 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. 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
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
Use the local urbi-console.
Use the local urbi-console. Alternatively, I could change PATH and let find_urbi_server do the job. Not sure what's the easiest. This way we can have a specific failure when urbi-console is not there but it should. * src/tests/liburbi-check.as ($URBI_SERVER): Find the shipped urbi-console if there is one.
ActionScript
bsd-3-clause
urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi
d691a1fe60a793051f18c4a396ce0d126feaddf6
src/aerys/minko/scene/controller/light/DirectionalLightController.as
src/aerys/minko/scene/controller/light/DirectionalLightController.as
package aerys.minko.scene.controller.light { import aerys.minko.scene.data.LightDataProvider; import aerys.minko.scene.node.Scene; import aerys.minko.scene.node.light.AbstractLight; import aerys.minko.scene.node.light.DirectionalLight; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; /** * * @author Jean-Marc Le Roux * */ public final class DirectionalLightController extends LightController { private static const SCREEN_TO_UV : Matrix4x4 = new Matrix4x4( .5, .0, .0, .0, .0, -.5, .0, .0, .0, .0, 1., .0, .5, .5, .0, 1. ); private var _worldPosition : Vector4; private var _worldDirection : Vector4; private var _worldToScreen : Matrix4x4; private var _worldToUV : Matrix4x4; private var _projection : Matrix4x4; public function DirectionalLightController() { super(DirectionalLight); initialize(); } private function initialize() : void { _worldPosition = new Vector4(); _worldDirection = new Vector4(); _worldToScreen = new Matrix4x4(); _worldToUV = new Matrix4x4(); _projection = new Matrix4x4(); } override protected function lightAddedHandler(ctrl : LightController, target : AbstractLight) : void { super.lightAddedHandler(ctrl, target); lightData.setLightProperty('worldPosition', _worldPosition); lightData.setLightProperty('worldDirection', _worldDirection); lightData.setLightProperty('worldToScreen', _worldToScreen); lightData.setLightProperty('worldToUV', _worldToUV); lightData.setLightProperty('projection', _projection); } override protected function lightAddedToSceneHandler(light : AbstractLight, scene : Scene) : void { super.lightAddedToSceneHandler(light, scene); updateProjectionMatrix(); lightLocalToWorldChangedHandler(light.localToWorld); light.localToWorld.changed.add(lightLocalToWorldChangedHandler); } override protected function lightRemovedFromSceneHandler(light : AbstractLight, scene : Scene) : void { super.lightRemovedFromSceneHandler(light, scene); light.localToWorld.changed.remove(lightLocalToWorldChangedHandler); } override protected function lightDataChangedHandler(lightData : LightDataProvider, propertyName : String) : void { super.lightDataChangedHandler(lightData, propertyName); propertyName = LightDataProvider.getPropertyName(propertyName); if (propertyName == 'shadowWidth' || propertyName == 'shadowMaxZ') updateProjectionMatrix(); } private function lightLocalToWorldChangedHandler(localToWorld : Matrix4x4) : void { // compute position localToWorld.getTranslation(_worldPosition); // compute direction _worldDirection = localToWorld.deltaTransformVector(Vector4.Z_AXIS, _worldDirection); _worldDirection.normalize(); // update world to screen/uv _worldToScreen.lock().copyFrom(light.worldToLocal).append(_projection).unlock(); _worldToUV.lock().copyFrom(_worldToScreen).append(SCREEN_TO_UV).unlock(); } private function updateProjectionMatrix() : void { var zFar : Number = lightData.getLightProperty('shadowMaxZ'); var width : Number = lightData.getLightProperty('shadowWidth'); _projection.initialize( 2. / width, 0., 0., 0., 0., 2. / width, 0., 0., 0., 0., 2. / zFar, 0., 0., 0., 0., 1. ); _worldToScreen.lock().copyFrom(light.worldToLocal).append(_projection).unlock(); _worldToUV.lock().copyFrom(_worldToScreen).append(SCREEN_TO_UV).unlock(); } } }
package aerys.minko.scene.controller.light { import aerys.minko.scene.data.LightDataProvider; import aerys.minko.scene.node.Scene; import aerys.minko.scene.node.light.AbstractLight; import aerys.minko.scene.node.light.DirectionalLight; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; /** * * @author Jean-Marc Le Roux * */ public final class DirectionalLightController extends LightController { private static const SCREEN_TO_UV : Matrix4x4 = new Matrix4x4( .5, .0, .0, .0, .0, -.5, .0, .0, .0, .0, 1., .0, .5, .5, .0, 1. ); private var _worldPosition : Vector4; private var _worldDirection : Vector4; private var _worldToScreen : Matrix4x4; private var _worldToUV : Matrix4x4; private var _projection : Matrix4x4; public function DirectionalLightController() { super(DirectionalLight); initialize(); } private function initialize() : void { _worldPosition = new Vector4(); _worldDirection = new Vector4(); _worldToScreen = new Matrix4x4(); _worldToUV = new Matrix4x4(); _projection = new Matrix4x4(); } override protected function lightAddedHandler(ctrl : LightController, target : AbstractLight) : void { super.lightAddedHandler(ctrl, target); lightData.setLightProperty('worldPosition', _worldPosition); lightData.setLightProperty('worldDirection', _worldDirection); lightData.setLightProperty('worldToScreen', _worldToScreen); lightData.setLightProperty('worldToUV', _worldToUV); lightData.setLightProperty('projection', _projection); } override protected function lightAddedToSceneHandler(light : AbstractLight, scene : Scene) : void { super.lightAddedToSceneHandler(light, scene); updateProjectionMatrix(); lightLocalToWorldChangedHandler(light.localToWorld); light.localToWorld.changed.add(lightLocalToWorldChangedHandler); } override protected function lightRemovedFromSceneHandler(light : AbstractLight, scene : Scene) : void { super.lightRemovedFromSceneHandler(light, scene); light.localToWorld.changed.remove(lightLocalToWorldChangedHandler); } override protected function lightDataChangedHandler(lightData : LightDataProvider, propertyName : String) : void { super.lightDataChangedHandler(lightData, propertyName); propertyName = LightDataProvider.getPropertyName(propertyName); if (propertyName == 'shadowWidth' || propertyName == 'shadowZFar') updateProjectionMatrix(); } private function lightLocalToWorldChangedHandler(localToWorld : Matrix4x4) : void { // compute position localToWorld.getTranslation(_worldPosition); // compute direction _worldDirection = localToWorld.deltaTransformVector(Vector4.Z_AXIS, _worldDirection); _worldDirection.normalize(); // update world to screen/uv _worldToScreen.lock().copyFrom(light.worldToLocal).append(_projection).unlock(); _worldToUV.lock().copyFrom(_worldToScreen).append(SCREEN_TO_UV).unlock(); } private function updateProjectionMatrix() : void { var zFar : Number = lightData.getLightProperty('shadowZFar'); var width : Number = lightData.getLightProperty('shadowWidth'); _projection.initialize( 2. / width, 0., 0., 0., 0., 2. / width, 0., 0., 0., 0., 2. / zFar, 0., 0., 0., 0., 1. ); _worldToScreen.lock().copyFrom(light.worldToLocal).append(_projection).unlock(); _worldToUV.lock().copyFrom(_worldToScreen).append(SCREEN_TO_UV).unlock(); } } }
fix wrong reference to the 'shadowMaxZ' property
fix wrong reference to the 'shadowMaxZ' property
ActionScript
mit
aerys/minko-as3
3d45d55a7cd30d0af511a90b17bff0c489585a2f
frameworks/as/projects/FlexJSJX/src/org/apache/flex/core/StatesWithTransitionsImpl.as
frameworks/as/projects/FlexJSJX/src/org/apache/flex/core/StatesWithTransitionsImpl.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.core { import mx.states.AddItems; import mx.states.SetEventHandler; import mx.states.SetProperty; import mx.states.State; import org.apache.flex.core.IParent; import org.apache.flex.core.IStatesObject; import org.apache.flex.effects.Effect; import org.apache.flex.events.Event; import org.apache.flex.events.EventDispatcher; import org.apache.flex.events.IEventDispatcher; import org.apache.flex.events.ValueChangeEvent; import org.apache.flex.states.Transition; import org.apache.flex.utils.MXMLDataInterpreter; /** * The StatesWithTransitionsImpl class implements a set of * view state functionality that includes transitions between states. * It only supports AddItems and SetProperty and SetEventHandler * changes at this time. * * @flexjsignoreimport org.apache.flex.core.IStatesObject * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class StatesWithTransitionsImpl extends EventDispatcher implements IStatesImpl, IBead { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function StatesWithTransitionsImpl() { super(); } private var _strand:IStrand; private var sawInitComplete:Boolean; /** * @copy org.apache.flex.core.IBead#strand * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function set strand(value:IStrand):void { _strand = value; IEventDispatcher(_strand).addEventListener("currentStateChange", stateChangeHandler); IEventDispatcher(_strand).addEventListener("initComplete", initialStateHandler); } /** * @private * @flexjsignorecoercion org.apache.flex.core.IStatesObject */ private function initialStateHandler(event:org.apache.flex.events.Event):void { sawInitComplete = true; stateChangeHandler(new ValueChangeEvent("currentStateChange", false, false, null, IStatesObject(_strand).currentState)); } /** * @private * @flexjsignorecoercion org.apache.flex.core.IStatesObject */ private function stateChangeHandler(event:ValueChangeEvent):void { if (!sawInitComplete) return; var doc:IStatesObject = _strand as IStatesObject; var transitions:Array = doc.transitions; if (transitions && transitions.length > 0) { for each (var t:Transition in transitions) { if (t.fromState == "*" || t.fromState == event.oldValue) { if (t.toState == "*" || t.toState == event.newValue) { transitionEffects = t.effects.slice(); for each (var e:Effect in transitionEffects) { e.captureStartValues(); } break; } } } } var arr:Array = doc.states; for each (var s:State in arr) { if (s.name == event.oldValue) { revert(s); break; } } for each (s in arr) { if (s.name == event.newValue) { apply(s); break; } } if (transitionEffects && transitionEffects.length > 0) { for each (e in transitionEffects) { e.captureEndValues(); } } var playingTransition:Boolean; if (transitionEffects && transitionEffects.length > 0) { playingTransition = true; for each (e in transitionEffects) { e.addEventListener(Effect.EFFECT_END, effectEndHandler); e.play(); } } if (!playingTransition) doc.dispatchEvent(new Event("stateChangeComplete")); } private var transitionEffects:Array; /** * @private * @flexjsignorecoercion org.apache.flex.core.IStatesObject */ private function effectEndHandler(event:Event):void { // in case of extraneous calls to effectEndHandler if (transitionEffects == null) return; var n:int = transitionEffects.length; for (var i:int = 0; i < n; i++) { event.target.removeEventListener(Effect.EFFECT_END, effectEndHandler); if (transitionEffects[i] == event.target) transitionEffects.splice(i, 1); } if (transitionEffects.length == 0) { transitionEffects = null; var doc:IStatesObject = _strand as IStatesObject; doc.dispatchEvent(new Event("stateChangeComplete")); } } private function revert(s:State):void { var arr:Array = s.overrides; for each (var o:Object in arr) { if (o is AddItems) { var ai:AddItems = AddItems(o); for each (var item:IChild in ai.items) { var parent:IParent = item.parent as IParent; parent.removeElement(item); } if (parent is IContainer) IContainer(parent).childrenAdded(); } else if (o is SetProperty) { var sp:SetProperty = SetProperty(o); if (sp.target != null) setProperty(getProperty(sp.document, sp.target), sp.name, sp.previousValue); else setProperty(sp.document, sp.name, sp.previousValue); } else if (o is SetEventHandler) { var seh:SetEventHandler = SetEventHandler(o); if (seh.target != null) { getProperty(seh.document, seh.target).removeEventListener(seh.name, seh.handlerFunction); } else { seh.document.removeEventListener(seh.name, seh.handlerFunction); } } } } private function apply(s:State):void { var arr:Array = s.overrides; for each (var o:Object in arr) { if (o is AddItems) { var ai:AddItems = AddItems(o); if (ai.items == null) { ai.items = ai.itemsDescriptor.items as Array; if (ai.items == null) { ai.items = MXMLDataInterpreter.generateMXMLArray(ai.document, null, ai.itemsDescriptor.descriptor); ai.itemsDescriptor.items = ai.items; } } for each (var item:Object in ai.items) { var parent:IParent = ai.document as IParent; if (ai.destination != null) parent = parent[ai.destination] as IParent; if (ai.relativeTo != null) { var child:Object = ai.document[ai.relativeTo]; if (ai.destination == null) parent = child.parent as IParent; var index:int = parent.getElementIndex(child); if (ai.position == "after") index++; parent.addElementAt(item, index); } else { parent.addElement(item); } } if (parent is IContainer) IContainer(parent).childrenAdded(); } else if (o is SetProperty) { var sp:SetProperty = SetProperty(o); if (sp.target != null) { sp.previousValue = getProperty(getProperty(sp.document, sp.target), sp.name); setProperty(getProperty(sp.document, sp.target), sp.name, sp.value); } else { sp.previousValue = getProperty(sp.document, sp.name); setProperty(sp.document, sp.name, sp.value); } } else if (o is SetEventHandler) { var seh:SetEventHandler = SetEventHandler(o); if (seh.target != null) { getProperty(seh.document, seh.target).addEventListener(seh.name, seh.handlerFunction); } else { seh.document.addEventListener(seh.name, seh.handlerFunction); } } } } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.core { import mx.states.AddItems; import mx.states.SetEventHandler; import mx.states.SetProperty; import mx.states.State; import org.apache.flex.core.IParent; import org.apache.flex.core.IStatesObject; import org.apache.flex.effects.Effect; import org.apache.flex.events.Event; import org.apache.flex.events.EventDispatcher; import org.apache.flex.events.IEventDispatcher; import org.apache.flex.events.ValueChangeEvent; import org.apache.flex.states.Transition; import org.apache.flex.utils.MXMLDataInterpreter; /** * The StatesWithTransitionsImpl class implements a set of * view state functionality that includes transitions between states. * It only supports AddItems and SetProperty and SetEventHandler * changes at this time. * * @flexjsignoreimport org.apache.flex.core.IStatesObject * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class StatesWithTransitionsImpl extends EventDispatcher implements IStatesImpl, IBead { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function StatesWithTransitionsImpl() { super(); } private var _strand:IStrand; private var sawInitComplete:Boolean; /** * @copy org.apache.flex.core.IBead#strand * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function set strand(value:IStrand):void { _strand = value; IEventDispatcher(_strand).addEventListener("currentStateChange", stateChangeHandler); IEventDispatcher(_strand).addEventListener("initComplete", initialStateHandler); } /** * @private * @flexjsignorecoercion org.apache.flex.core.IStatesObject */ private function initialStateHandler(event:org.apache.flex.events.Event):void { sawInitComplete = true; stateChangeHandler(new ValueChangeEvent("currentStateChange", false, false, null, IStatesObject(_strand).currentState)); } /** * @private * @flexjsignorecoercion org.apache.flex.core.IStatesObject */ private function stateChangeHandler(event:ValueChangeEvent):void { if (!sawInitComplete) return; var doc:IStatesObject = _strand as IStatesObject; var transitions:Array = doc.transitions; if (transitions && transitions.length > 0) { for each (var t:Transition in transitions) { if (t.fromState == "*" || t.fromState == event.oldValue) { if (t.toState == "*" || t.toState == event.newValue) { transitionEffects = t.effects.slice(); for each (var e:Effect in transitionEffects) { e.captureStartValues(); } break; } } } } var arr:Array = doc.states; for each (var s:State in arr) { if (s.name == event.oldValue) { revert(s); break; } } for each (s in arr) { if (s.name == event.newValue) { apply(s); break; } } if (transitionEffects && transitionEffects.length > 0) { for each (e in transitionEffects) { e.captureEndValues(); } } var playingTransition:Boolean; if (transitionEffects && transitionEffects.length > 0) { playingTransition = true; for each (e in transitionEffects) { e.addEventListener(Effect.EFFECT_END, effectEndHandler); e.play(); } } if (!playingTransition) doc.dispatchEvent(new Event("stateChangeComplete")); } private var transitionEffects:Array; /** * @private * @flexjsignorecoercion org.apache.flex.core.IStatesObject */ private function effectEndHandler(event:Event):void { // in case of extraneous calls to effectEndHandler if (transitionEffects == null) return; var n:int = transitionEffects.length; for (var i:int = 0; i < n; i++) { event.target.removeEventListener(Effect.EFFECT_END, effectEndHandler); if (transitionEffects[i] == event.target) transitionEffects.splice(i, 1); } if (transitionEffects.length == 0) { transitionEffects = null; var doc:IStatesObject = _strand as IStatesObject; doc.dispatchEvent(new Event("stateChangeComplete")); } } private function revert(s:State):void { var arr:Array = s.overrides; for each (var o:Object in arr) { if (o is AddItems) { var ai:AddItems = AddItems(o); for each (var item:IChild in ai.items) { var parent:IParent = item.parent as IParent; parent.removeElement(item); } if (parent is IContainer) IContainer(parent).childrenAdded(); } else if (o is SetProperty) { var sp:SetProperty = SetProperty(o); if (sp.target != null) setProperty(getProperty(sp.document, sp.target), sp.name, sp.previousValue); else setProperty(sp.document, sp.name, sp.previousValue); } else if (o is SetEventHandler) { var seh:SetEventHandler = SetEventHandler(o); if (seh.target != null) { getProperty(seh.document, seh.target).removeEventListener(seh.name, seh.handlerFunction); } else { seh.document.removeEventListener(seh.name, seh.handlerFunction); } } } } private function apply(s:State):void { var arr:Array = s.overrides; for each (var o:Object in arr) { if (o is AddItems) { var ai:AddItems = AddItems(o); if (ai.items == null) { ai.items = ai.itemsDescriptor.items as Array; if (ai.items == null) { ai.items = MXMLDataInterpreter.generateMXMLArray(ai.document, null, ai.itemsDescriptor.descriptor); ai.itemsDescriptor.items = ai.items; } } for each (var item:Object in ai.items) { var parent:IParent = ai.document as IParent; if (ai.destination) parent = getProperty(parent, ai.destination) as IParent; if (ai.relativeTo != null) { var child:Object = getProperty(ai.document, ai.relativeTo); if (ai.destination) parent = IChild(child).parent as IParent; var index:int = parent.getElementIndex(child); if (ai.position == "after") index++; parent.addElementAt(item, index); } else { parent.addElement(item); } } if (parent is IContainer) IContainer(parent).childrenAdded(); } else if (o is SetProperty) { var sp:SetProperty = SetProperty(o); if (sp.target != null) { sp.previousValue = getProperty(getProperty(sp.document, sp.target), sp.name); setProperty(getProperty(sp.document, sp.target), sp.name, sp.value); } else { sp.previousValue = getProperty(sp.document, sp.name); setProperty(sp.document, sp.name, sp.value); } } else if (o is SetEventHandler) { var seh:SetEventHandler = SetEventHandler(o); if (seh.target != null) { getProperty(seh.document, seh.target).addEventListener(seh.name, seh.handlerFunction); } else { seh.document.addEventListener(seh.name, seh.handlerFunction); } } } } } }
handle property fetches
handle property fetches
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
4219b7b1570fe3747137117d79f02746d839ff52
bin/Data/Scripts/20_HugeObjectCount.as
bin/Data/Scripts/20_HugeObjectCount.as
// Huge object count example. // This sample demonstrates: // - Creating a scene with 250 x 250 simple objects // - Competing with http://yosoygames.com.ar/wp/2013/07/ogre-2-0-is-up-to-3x-faster/ :) // - Allowing examination of performance hotspots in the rendering code // - Optionally speeding up rendering by grouping objects with the StaticModelGroup component #include "Scripts/Utilities/Sample.as" Array<Node@> boxNodes; bool animate = false; bool useGroups = false; 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() { if (scene_ is null) scene_ = Scene(); else { scene_.Clear(); boxNodes.Clear(); } // Create the Octree component to the scene so that drawable objects can be rendered. Use default volume // (-1000, -1000, -1000) to (1000, 1000, 1000) scene_.CreateComponent("Octree"); // Create a Zone for ambient light & fog control Node@ zoneNode = scene_.CreateChild("Zone"); Zone@ zone = zoneNode.CreateComponent("Zone"); zone.boundingBox = BoundingBox(-1000.0f, 1000.0f); zone.fogColor = Color(0.2f, 0.2f, 0.2f); zone.fogStart = 200.0f; zone.fogEnd = 300.0f; // Create a directional light Node@ lightNode = scene_.CreateChild("DirectionalLight"); lightNode.direction = Vector3(-0.6f, -1.0f, -0.8f); // The direction vector does not need to be normalized Light@ light = lightNode.CreateComponent("Light"); light.lightType = LIGHT_DIRECTIONAL; light.castShadows = true; { // Create a floor object, 1000 x 1000 world units. Adjust position so that the ground is at zero Y Node@ floorNode = scene_.CreateChild("Floor"); floorNode.position = Vector3(0.0f, -2.0f, 0.0f); floorNode.scale = Vector3(100.0f, 1.0f, 100.0f); StaticModel@ floorObject = floorNode.CreateComponent("StaticModel"); floorObject.model = cache.GetResource("Model", "Models/Box.mdl"); // Make the floor physical by adding RigidBody and CollisionShape components. The RigidBody's default // parameters make the object static (zero mass.) Note that a CollisionShape by itself will not participate // in the physics simulation RigidBody@ body = floorNode.CreateComponent("RigidBody"); CollisionShape@ shape = floorNode.CreateComponent("CollisionShape"); // Set a box shape of size 1 x 1 x 1 for collision. The shape will be scaled with the scene node scale, so the // rendering and physics representation sizes should match (the box model is also 1 x 1 x 1.) shape.SetBox(Vector3(1.0f, 1.0f, 1.0f)); } if (!useGroups) { light.color = Color(0.7f, 0.35f, 0.0f); // Create individual box StaticModels in the scene for (int y = -125; y < 125; ++y) { for (int x = -125; x < 125; ++x) { Node@ boxNode = scene_.CreateChild("Box"); boxNode.position = Vector3(x * 0.3f, 0.0f, y * 0.3f); boxNode.SetScale(0.25f); StaticModel@ boxObject = boxNode.CreateComponent("StaticModel"); boxObject.castShadows = true; boxObject.model = cache.GetResource("Model", "Models/Plane.mdl"); boxObject.material = cache.GetResource("Material", "Materials/List.xml"); boxNodes.Push(boxNode); } } } else { light.color = Color(0.6f, 0.6f, 0.6f); light.specularIntensity = 1.5f; // Create StaticModelGroups in the scene StaticModelGroup@ lastGroup; for (int y = -125; y < 125; ++y) { for (int x = -125; x < 125; ++x) { // Create new group if no group yet, or the group has already "enough" objects. The tradeoff is between culling // accuracy and the amount of CPU processing needed for all the objects. Note that the group's own transform // does not matter, and it does not render anything if instance nodes are not added to it if (lastGroup is null || lastGroup.numInstanceNodes >= 25 * 25) { Node@ boxGroupNode = scene_.CreateChild("BoxGroup"); lastGroup = boxGroupNode.CreateComponent("StaticModelGroup"); lastGroup.model = cache.GetResource("Model", "Models/Plane.mdl"); lastGroup.material = cache.GetResource("Material", "Materials/List.xml"); lastGroup.castShadows = true; } Node@ boxNode = scene_.CreateChild("Box"); boxNode.position = Vector3(x * 0.3f, 0.0f, y * 0.3f); boxNode.SetScale(0.25f); boxNodes.Push(boxNode); lastGroup.AddInstanceNode(boxNode); } } } // Create the camera. Create it outside the scene so that we can clear the whole scene without affecting it if (cameraNode is null) { cameraNode = Node("Camera"); cameraNode.position = Vector3(0.0f, 10.0f, -100.0f); Camera@ camera = cameraNode.CreateComponent("Camera"); camera.farClip = 300.0f; } } void CreateInstructions() { // Construct new Text object, set string to display and font to use Text@ instructionText = ui.root.CreateChild("Text"); instructionText.text = "Use WASD keys and mouse to move\n" "Space to toggle animation\n" "G to toggle object group optimization"; instructionText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15); // The text has multiple rows. Center them in relation to each other instructionText.textAlignment = HA_CENTER; // Position the text relative to the screen center instructionText.horizontalAlignment = HA_CENTER; instructionText.verticalAlignment = VA_CENTER; instructionText.SetPosition(0, ui.root.height / 4); } void SetupViewport() { // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen Viewport@ viewport = Viewport(scene_, cameraNode.GetComponent("Camera")); renderer.viewports[0] = viewport; } void SubscribeToEvents() { // Subscribe HandleUpdate() function for processing update events SubscribeToEvent("Update", "HandleUpdate"); } 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 = 20.0f; // Mouse sensitivity as degrees per pixel const float MOUSE_SENSITIVITY = 0.1f; // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees IntVector2 mouseMove = input.mouseMove; yaw += MOUSE_SENSITIVITY * mouseMove.x; pitch += MOUSE_SENSITIVITY * mouseMove.y; pitch = Clamp(pitch, -90.0f, 90.0f); // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero cameraNode.rotation = Quaternion(pitch, yaw, 0.0f); // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed if (input.keyDown['W']) cameraNode.Translate(Vector3(0.0f, 0.0f, 1.0f) * MOVE_SPEED * timeStep); if (input.keyDown['S']) cameraNode.Translate(Vector3(0.0f, 0.0f, -1.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); } void AnimateObjects(float timeStep) { const float ROTATE_SPEED = 15.0f; // Rotate about the Z axis (roll) Quaternion rotateQuat(ROTATE_SPEED * timeStep, Vector3(0.0f, 0.0f, 1.0f)); for (uint i = 0; i < boxNodes.length; ++i) boxNodes[i].Rotate(rotateQuat); } void HandleUpdate(StringHash eventType, VariantMap& eventData) { // Take the frame time step, which is stored as a float float timeStep = eventData["TimeStep"].GetFloat(); // Toggle animation with space if (input.keyPress[KEY_SPACE]) animate = !animate; // Toggle grouped / ungrouped mode if (input.keyPress['G']) { useGroups = !useGroups; CreateScene(); } // Move the camera, scale movement with time step MoveCamera(timeStep); // Animate scene if enabled if (animate) AnimateObjects(timeStep); } // 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\">Group</replace>" + " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" + " <element type=\"Text\">" + " <attribute name=\"Name\" value=\"KeyBinding\" />" + " <attribute name=\"Text\" value=\"G\" />" + " </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\">Animation</replace>" + " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" + " <element type=\"Text\">" + " <attribute name=\"Name\" value=\"KeyBinding\" />" + " <attribute name=\"Text\" value=\"SPACE\" />" + " </element>" + " </add>" + "</patch>";
// Huge object count example. // This sample demonstrates: // - Creating a scene with 250 x 250 simple objects // - Competing with http://yosoygames.com.ar/wp/2013/07/ogre-2-0-is-up-to-3x-faster/ :) // - Allowing examination of performance hotspots in the rendering code // - Optionally speeding up rendering by grouping objects with the StaticModelGroup component #include "Scripts/Utilities/Sample.as" Array<Node@> boxNodes; bool animate = false; bool useGroups = false; 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() { if (scene_ is null) scene_ = Scene(); else { scene_.Clear(); boxNodes.Clear(); } // Create the Octree component to the scene so that drawable objects can be rendered. Use default volume // (-1000, -1000, -1000) to (1000, 1000, 1000) scene_.CreateComponent("Octree"); // Create a Zone for ambient light & fog control Node@ zoneNode = scene_.CreateChild("Zone"); Zone@ zone = zoneNode.CreateComponent("Zone"); zone.boundingBox = BoundingBox(-1000.0f, 1000.0f); zone.fogColor = Color(0.2f, 0.2f, 0.2f); zone.fogStart = 200.0f; zone.fogEnd = 300.0f; // Create a directional light Node@ lightNode = scene_.CreateChild("DirectionalLight"); lightNode.direction = Vector3(-0.6f, -1.0f, -0.8f); // The direction vector does not need to be normalized Light@ light = lightNode.CreateComponent("Light"); light.lightType = LIGHT_DIRECTIONAL; if (!useGroups) { light.color = Color(0.7f, 0.35f, 0.0f); // Create individual box StaticModels in the scene for (int y = -125; y < 125; ++y) { for (int x = -125; x < 125; ++x) { Node@ boxNode = scene_.CreateChild("Box"); boxNode.position = Vector3(x * 0.3f, 0.0f, y * 0.3f); boxNode.SetScale(0.25f); StaticModel@ boxObject = boxNode.CreateComponent("StaticModel"); boxObject.model = cache.GetResource("Model", "Models/Box.mdl"); boxNodes.Push(boxNode); } } } else { light.color = Color(0.6f, 0.6f, 0.6f); light.specularIntensity = 1.5f; // Create StaticModelGroups in the scene StaticModelGroup@ lastGroup; for (int y = -125; y < 125; ++y) { for (int x = -125; x < 125; ++x) { // Create new group if no group yet, or the group has already "enough" objects. The tradeoff is between culling // accuracy and the amount of CPU processing needed for all the objects. Note that the group's own transform // does not matter, and it does not render anything if instance nodes are not added to it if (lastGroup is null || lastGroup.numInstanceNodes >= 25 * 25) { Node@ boxGroupNode = scene_.CreateChild("BoxGroup"); lastGroup = boxGroupNode.CreateComponent("StaticModelGroup"); lastGroup.model = cache.GetResource("Model", "Models/Box.mdl"); } Node@ boxNode = scene_.CreateChild("Box"); boxNode.position = Vector3(x * 0.3f, 0.0f, y * 0.3f); boxNode.SetScale(0.25f); boxNodes.Push(boxNode); lastGroup.AddInstanceNode(boxNode); } } } // Create the camera. Create it outside the scene so that we can clear the whole scene without affecting it if (cameraNode is null) { cameraNode = Node("Camera"); cameraNode.position = Vector3(0.0f, 10.0f, -100.0f); Camera@ camera = cameraNode.CreateComponent("Camera"); camera.farClip = 300.0f; } } void CreateInstructions() { // Construct new Text object, set string to display and font to use Text@ instructionText = ui.root.CreateChild("Text"); instructionText.text = "Use WASD keys and mouse to move\n" "Space to toggle animation\n" "G to toggle object group optimization"; instructionText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15); // The text has multiple rows. Center them in relation to each other instructionText.textAlignment = HA_CENTER; // Position the text relative to the screen center instructionText.horizontalAlignment = HA_CENTER; instructionText.verticalAlignment = VA_CENTER; instructionText.SetPosition(0, ui.root.height / 4); } void SetupViewport() { // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen Viewport@ viewport = Viewport(scene_, cameraNode.GetComponent("Camera")); renderer.viewports[0] = viewport; } void SubscribeToEvents() { // Subscribe HandleUpdate() function for processing update events SubscribeToEvent("Update", "HandleUpdate"); } 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 = 20.0f; // Mouse sensitivity as degrees per pixel const float MOUSE_SENSITIVITY = 0.1f; // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees IntVector2 mouseMove = input.mouseMove; yaw += MOUSE_SENSITIVITY * mouseMove.x; pitch += MOUSE_SENSITIVITY * mouseMove.y; pitch = Clamp(pitch, -90.0f, 90.0f); // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero cameraNode.rotation = Quaternion(pitch, yaw, 0.0f); // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed if (input.keyDown['W']) cameraNode.Translate(Vector3(0.0f, 0.0f, 1.0f) * MOVE_SPEED * timeStep); if (input.keyDown['S']) cameraNode.Translate(Vector3(0.0f, 0.0f, -1.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); } void AnimateObjects(float timeStep) { const float ROTATE_SPEED = 15.0f; // Rotate about the Z axis (roll) Quaternion rotateQuat(ROTATE_SPEED * timeStep, Vector3(0.0f, 0.0f, 1.0f)); for (uint i = 0; i < boxNodes.length; ++i) boxNodes[i].Rotate(rotateQuat); } void HandleUpdate(StringHash eventType, VariantMap& eventData) { // Take the frame time step, which is stored as a float float timeStep = eventData["TimeStep"].GetFloat(); // Toggle animation with space if (input.keyPress[KEY_SPACE]) animate = !animate; // Toggle grouped / ungrouped mode if (input.keyPress['G']) { useGroups = !useGroups; CreateScene(); } // Move the camera, scale movement with time step MoveCamera(timeStep); // Animate scene if enabled if (animate) AnimateObjects(timeStep); } // 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\">Group</replace>" + " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" + " <element type=\"Text\">" + " <attribute name=\"Name\" value=\"KeyBinding\" />" + " <attribute name=\"Text\" value=\"G\" />" + " </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\">Animation</replace>" + " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" + " <element type=\"Text\">" + " <attribute name=\"Name\" value=\"KeyBinding\" />" + " <attribute name=\"Text\" value=\"SPACE\" />" + " </element>" + " </add>" + "</patch>";
Revert mistaken change to 20_HugeObjectCount.as.
Revert mistaken change to 20_HugeObjectCount.as.
ActionScript
mit
SuperWangKai/Urho3D,c4augustus/Urho3D,SuperWangKai/Urho3D,abdllhbyrktr/Urho3D,SirNate0/Urho3D,henu/Urho3D,MonkeyFirst/Urho3D,fire/Urho3D-1,tommy3/Urho3D,eugeneko/Urho3D,MeshGeometry/Urho3D,codemon66/Urho3D,carnalis/Urho3D,tommy3/Urho3D,carnalis/Urho3D,orefkov/Urho3D,bacsmar/Urho3D,weitjong/Urho3D,tommy3/Urho3D,codedash64/Urho3D,victorholt/Urho3D,weitjong/Urho3D,SirNate0/Urho3D,codedash64/Urho3D,xiliu98/Urho3D,helingping/Urho3D,fire/Urho3D-1,victorholt/Urho3D,PredatorMF/Urho3D,abdllhbyrktr/Urho3D,c4augustus/Urho3D,urho3d/Urho3D,299299/Urho3D,bacsmar/Urho3D,helingping/Urho3D,fire/Urho3D-1,SuperWangKai/Urho3D,PredatorMF/Urho3D,MeshGeometry/Urho3D,MeshGeometry/Urho3D,299299/Urho3D,urho3d/Urho3D,helingping/Urho3D,c4augustus/Urho3D,abdllhbyrktr/Urho3D,weitjong/Urho3D,carnalis/Urho3D,xiliu98/Urho3D,c4augustus/Urho3D,PredatorMF/Urho3D,abdllhbyrktr/Urho3D,luveti/Urho3D,c4augustus/Urho3D,luveti/Urho3D,rokups/Urho3D,eugeneko/Urho3D,codedash64/Urho3D,rokups/Urho3D,henu/Urho3D,SirNate0/Urho3D,codemon66/Urho3D,codemon66/Urho3D,henu/Urho3D,kostik1337/Urho3D,kostik1337/Urho3D,SirNate0/Urho3D,MonkeyFirst/Urho3D,SuperWangKai/Urho3D,tommy3/Urho3D,rokups/Urho3D,cosmy1/Urho3D,helingping/Urho3D,iainmerrick/Urho3D,victorholt/Urho3D,fire/Urho3D-1,iainmerrick/Urho3D,kostik1337/Urho3D,luveti/Urho3D,MeshGeometry/Urho3D,tommy3/Urho3D,rokups/Urho3D,orefkov/Urho3D,iainmerrick/Urho3D,codedash64/Urho3D,iainmerrick/Urho3D,xiliu98/Urho3D,MeshGeometry/Urho3D,kostik1337/Urho3D,299299/Urho3D,cosmy1/Urho3D,cosmy1/Urho3D,bacsmar/Urho3D,carnalis/Urho3D,weitjong/Urho3D,weitjong/Urho3D,helingping/Urho3D,299299/Urho3D,cosmy1/Urho3D,MonkeyFirst/Urho3D,henu/Urho3D,urho3d/Urho3D,luveti/Urho3D,SuperWangKai/Urho3D,kostik1337/Urho3D,299299/Urho3D,MonkeyFirst/Urho3D,orefkov/Urho3D,PredatorMF/Urho3D,orefkov/Urho3D,bacsmar/Urho3D,victorholt/Urho3D,299299/Urho3D,henu/Urho3D,victorholt/Urho3D,codemon66/Urho3D,codedash64/Urho3D,rokups/Urho3D,urho3d/Urho3D,xiliu98/Urho3D,rokups/Urho3D,eugeneko/Urho3D,carnalis/Urho3D,luveti/Urho3D,MonkeyFirst/Urho3D,eugeneko/Urho3D,cosmy1/Urho3D,xiliu98/Urho3D,iainmerrick/Urho3D,SirNate0/Urho3D,abdllhbyrktr/Urho3D,fire/Urho3D-1,codemon66/Urho3D
84913f7992511028e0080e6873c1eaeb72f3c844
src/Level.as
src/Level.as
package { import Modules.*; import Testing.*; import Values.OpcodeValue; /** * ... * @author Nicholas "PleasingFungus" Feinberg */ public class Level { public var name:String; public var goal:LevelGoal; public var modules:Vector.<Module>; public var expectedOps:Vector.<OpcodeValue> public var allowedModules:Vector.<Class> public var predecessors:Vector.<Level>; public var delay:Boolean; public function Level(Name:String, Goal:LevelGoal, delay:Boolean = false, AllowedModules:Array = null, ExpectedOps:Array = null, Modules:Array = null) { name = Name; this.goal = Goal; modules = new Vector.<Module>; if (Modules) for each (var module:Module in Modules) modules.push(module); expectedOps = new Vector.<OpcodeValue>; if (ExpectedOps) for each (var op:OpcodeValue in ExpectedOps) expectedOps.push(op); allowedModules = new Vector.<Class>; if (AllowedModules) for each (var allowedModule:Class in AllowedModules) allowedModules.push(allowedModule); else allowedModules = Module.ALL_MODULES; this.delay = delay; predecessors = new Vector.<Level>; } public static function list():Vector.<Level> { var levels:Vector.<Level> = new Vector.<Level>; levels.push(new Level("Tutorial 1: Wires", new WireTutorialGoal, false, [], [], [new ConstIn(12, 16, 1), new Adder(20, 16), new DataWriter(28, 16)]), new Level("Tutorial 2: Acc.", new AccumulatorTutorialGoal, false, [ConstIn, Adder, Latch, DataWriter], [])); var addCPU:Level = new Level("Add-CPU", new GeneratedGoal("Set-Add-Save!", Test), false, [ConstIn, And, Adder, Clock, Latch, InstructionMemory, DataMemory, Regfile, InstructionMux, InstructionDemux], [OpcodeValue.OP_SET, OpcodeValue.OP_ADD, OpcodeValue.OP_SAV]); var addCPU_D:Level = new Level("Add-CPU Delay", new GeneratedGoal("Set-Add-Save!", Test, 12, 10000), true, null, [OpcodeValue.OP_SET, OpcodeValue.OP_ADD, OpcodeValue.OP_SAV]); var cpuJMP:Level = new Level("Jump! Jump!", new GeneratedGoal("Jump!", JumpTest), false, [ConstIn, And, Adder, Clock, Latch, InstructionMemory, DataMemory, Regfile, InstructionMux, InstructionDemux], [OpcodeValue.OP_SET, OpcodeValue.OP_ADD, OpcodeValue.OP_SAV, OpcodeValue.OP_JMP]); addCPU_D.predecessors.push(addCPU); cpuJMP.predecessors.push(addCPU); levels.push(addCPU, addCPU_D, cpuJMP); return levels; } } }
package { import Modules.*; import Testing.*; import Values.OpcodeValue; /** * ... * @author Nicholas "PleasingFungus" Feinberg */ public class Level { public var name:String; public var goal:LevelGoal; public var modules:Vector.<Module>; public var expectedOps:Vector.<OpcodeValue> public var allowedModules:Vector.<Class> public var predecessors:Vector.<Level>; public var delay:Boolean; public function Level(Name:String, Goal:LevelGoal, delay:Boolean = false, AllowedModules:Array = null, ExpectedOps:Array = null, Modules:Array = null) { name = Name; this.goal = Goal; modules = new Vector.<Module>; if (Modules) for each (var module:Module in Modules) modules.push(module); expectedOps = new Vector.<OpcodeValue>; if (ExpectedOps) for each (var op:OpcodeValue in ExpectedOps) expectedOps.push(op); allowedModules = new Vector.<Class>; if (AllowedModules) for each (var allowedModule:Class in AllowedModules) allowedModules.push(allowedModule); else allowedModules = Module.ALL_MODULES; this.delay = delay; predecessors = new Vector.<Level>; } public static function list():Vector.<Level> { var levels:Vector.<Level> = new Vector.<Level>; levels.push(new Level("Tutorial 1A: Wires", new WireTutorialGoal, false, [], [], [new ConstIn(12, 12, 1), new ConstIn(12, 20, 2), new DataWriter(22, 16)]), new Level("Tutorial 1B: Modules", new WireTutorialGoal, false, [Adder, DataWriter], [], [new ConstIn(12, 16, 1)]), new Level("Tutorial 2: Acc.", new AccumulatorTutorialGoal, false, [ConstIn, Adder, Latch, DataWriter], [])); var addCPU:Level = new Level("Add-CPU", new GeneratedGoal("Set-Add-Save!", Test), false, [ConstIn, And, Adder, Clock, Latch, InstructionMemory, DataMemory, Regfile, InstructionMux, InstructionDemux], [OpcodeValue.OP_SET, OpcodeValue.OP_ADD, OpcodeValue.OP_SAV]); var addCPU_D:Level = new Level("Add-CPU Delay", new GeneratedGoal("Set-Add-Save!", Test, 12, 10000), true, null, [OpcodeValue.OP_SET, OpcodeValue.OP_ADD, OpcodeValue.OP_SAV]); var cpuJMP:Level = new Level("Jump! Jump!", new GeneratedGoal("Jump!", JumpTest), false, [ConstIn, And, Adder, Clock, Latch, InstructionMemory, DataMemory, Regfile, InstructionMux, InstructionDemux], [OpcodeValue.OP_SET, OpcodeValue.OP_ADD, OpcodeValue.OP_SAV, OpcodeValue.OP_JMP]); addCPU_D.predecessors.push(addCPU); cpuJMP.predecessors.push(addCPU); levels.push(addCPU, addCPU_D, cpuJMP); return levels; } } }
Split first tutorial in 1/2
Split first tutorial in 1/2
ActionScript
mit
PleasingFungus/mde2,PleasingFungus/mde2
d07491c4b7f0410db401b48f02bae21154451806
runtime/src/main/as/flump/display/LibraryLoader.as
runtime/src/main/as/flump/display/LibraryLoader.as
// // Flump - Copyright 2012 Three Rings Design package flump.display { import flash.utils.ByteArray; import flump.executor.Executor; import flump.executor.Future; import starling.core.Starling; /** * Loads zip files created by the flump exporter and parses them into Library instances. */ public class LibraryLoader { /** * Loads a Library from the zip in the given bytes. * * @param bytes The bytes containing the zip * * @param executor The executor on which the loading should run. If not specified, it'll run on * a new single-use executor. * * @param scaleFactor the desired scale factor of the textures to load. If the Library contains * textures with multiple scale factors, loader will load the textures with the scale factor * closest to this value. If scaleFactor <= 0 (the default), Starling.contentScaleFactor will be * used. * * @return a Future to use to track the success or failure of loading the resources out of the * bytes. If the loading succeeds, the Future's onSuccess will fire with an instance of * Library. If it fails, the Future's onFail will fire with the Error that caused the * loading failure. */ public static function loadBytes (bytes :ByteArray, executor :Executor=null, scaleFactor :Number=-1) :Future { return (executor || new Executor(1)).submit(new Loader(bytes, scaleFactor).load); } /** * Loads a Library from the zip at the given url. * * @param bytes The url where the zip can be found * * @param executor The executor on which the loading should run. If not specified, it'll run on * a new single-use executor. * * @param scaleFactor the desired scale factor of the textures to load. If the Library contains * textures with multiple scale factors, loader will load the textures with the scale factor * closest to this value. If scaleFactor <= 0 (the default), Starling.contentScaleFactor will be * used. * * @return a Future to use to track the success or failure of loading the resources from the * url. If the loading succeeds, the Future's onSuccess will fire with an instance of * Library. If it fails, the Future's onFail will fire with the Error that caused the * loading failure. */ public static function loadURL (url :String, executor :Executor=null, scaleFactor :Number=-1) :Future { return (executor || new Executor(1)).submit(new Loader(url, scaleFactor).load); } /** @private */ public static const LIBRARY_LOCATION :String = "library.json"; /** @private */ public static const MD5_LOCATION :String = "md5"; /** @private */ public static const VERSION_LOCATION :String = "version"; /** * @private * The version produced and parsable by this version of the code. The version in a resources * zip must equal the version compiled into the parsing code for parsing to succeed. */ public static const VERSION :String = "1"; } } import flash.events.Event; import flash.geom.Point; import flash.net.URLRequest; import flash.utils.ByteArray; import flash.utils.Dictionary; import deng.fzip.FZip; import deng.fzip.FZipErrorEvent; import deng.fzip.FZipEvent; import deng.fzip.FZipFile; import flump.display.Library; import flump.display.LibraryLoader; import flump.display.Movie; import flump.executor.Executor; import flump.executor.Future; import flump.executor.FutureTask; import flump.executor.load.ImageLoader; import flump.executor.load.LoadedImage; import flump.mold.AtlasMold; import flump.mold.AtlasTextureMold; import flump.mold.LibraryMold; import flump.mold.MovieMold; import flump.mold.TextureGroupMold; import starling.core.Starling; import starling.display.DisplayObject; import starling.display.Image; import starling.display.Sprite; import starling.textures.Texture; interface SymbolCreator { function create (library :Library) :DisplayObject; } class LibraryImpl implements Library { public function LibraryImpl (creators :Dictionary) { _creators = creators; } public function createMovie (symbol :String) :Movie { return Movie(createDisplayObject(symbol)); } public function createImage (symbol :String) :DisplayObject { const disp :DisplayObject = createDisplayObject(symbol); if (disp is Movie) throw new Error(symbol + " is a movie, not a texture"); return disp; } public function get movieSymbols () :Vector.<String> { const names :Vector.<String> = new Vector.<String>(); for (var creatorName :String in _creators) { if (_creators[creatorName] is MovieCreator) names.push(creatorName); } return names; } public function get imageSymbols () :Vector.<String> { const names :Vector.<String> = new Vector.<String>(); for (var creatorName :String in _creators) { if (_creators[creatorName] is ImageCreator) names.push(creatorName); } return names; } public function createDisplayObject (name :String) :DisplayObject { var creator :SymbolCreator = _creators[name]; if (creator == null) throw new Error("No such id '" + name + "'"); return creator.create(this); } protected var _creators :Dictionary; } class Loader { public function Loader (toLoad :Object, scaleFactor :Number) { _scaleFactor = (scaleFactor > 0 ? scaleFactor : Starling.contentScaleFactor); _toLoad = toLoad; } public function load (future :FutureTask) :void { _future = future; _zip.addEventListener(Event.COMPLETE, _future.monitoredCallback(onZipLoadingComplete)); _zip.addEventListener(FZipErrorEvent.PARSE_ERROR, _future.fail); _zip.addEventListener(FZipEvent.FILE_LOADED, _future.monitoredCallback(onFileLoaded)); if (_toLoad is String) _zip.load(new URLRequest(String(_toLoad))); else _zip.loadBytes(ByteArray(_toLoad)); } protected function onFileLoaded (e :FZipEvent) :void { const loaded :FZipFile = _zip.removeFileAt(_zip.getFileCount() - 1); const name :String = loaded.filename; if (name == LibraryLoader.LIBRARY_LOCATION) { const jsonString :String = loaded.content.readUTFBytes(loaded.content.length); _lib = LibraryMold.fromJSON(JSON.parse(jsonString)); } else if (name.indexOf(PNG, name.length - PNG.length) != -1) { _pngBytes[name] = loaded.content; } else if (name == LibraryLoader.VERSION_LOCATION) { const zipVersion :String = loaded.content.readUTFBytes(loaded.content.length) if (zipVersion != LibraryLoader.VERSION) { throw new Error("Zip is version " + zipVersion + " but the code needs " + LibraryLoader.VERSION); } _versionChecked = true; } else if (name == LibraryLoader.MD5_LOCATION ) { // Nothing to verify } else {} // ignore unknown files } protected function onZipLoadingComplete (..._) :void { _zip = null; if (_lib == null) throw new Error(LibraryLoader.LIBRARY_LOCATION + " missing from zip"); if (!_versionChecked) throw new Error(LibraryLoader.VERSION_LOCATION + " missing from zip"); const loader :ImageLoader = new ImageLoader(); _pngLoaders.terminated.add(_future.monitoredCallback(onPngLoadingComplete)); // Determine the scale factor we want to use var textureGroup :TextureGroupMold = _lib.bestTextureGroupForScaleFactor(_scaleFactor); if (textureGroup != null) { for each (var atlas :AtlasMold in textureGroup.atlases) { loadAtlas(loader, atlas); } } _pngLoaders.shutdown(); } protected function loadAtlas (loader :ImageLoader, atlas :AtlasMold) :void { const pngBytes :* = _pngBytes[atlas.file]; if (pngBytes === undefined) { throw new Error("Expected an atlas '" + atlas.file + "', but it wasn't in the zip"); } const atlasFuture :Future = loader.loadFromBytes(pngBytes, _pngLoaders); atlasFuture.failed.add(onPngLoadingFailed); atlasFuture.succeeded.add(function (img :LoadedImage) :void { const baseTexture :Texture = Texture.fromBitmapData( img.bitmapData, true, // generateMipMaps - do we want this? false, // optimizeForRenderToTexture atlas.scaleFactor); for each (var atlasTexture :AtlasTextureMold in atlas.textures) { _creators[atlasTexture.symbol] = new ImageCreator( Texture.fromTexture(baseTexture, atlasTexture.bounds), atlasTexture.offset, atlasTexture.symbol); } }); } protected function onPngLoadingComplete (..._) :void { for each (var movie :MovieMold in _lib.movies) { movie.fillLabels(); _creators[movie.id] = new MovieCreator(movie, _lib.frameRate); } _future.succeed(new LibraryImpl(_creators)); } protected function onPngLoadingFailed (e :*) :void { if (_future.isComplete) return; _future.fail(e); _pngLoaders.shutdownNow(); } protected var _toLoad :Object; protected var _scaleFactor :Number; protected var _future :FutureTask; protected var _versionChecked :Boolean; protected var _zip :FZip = new FZip(); protected var _lib :LibraryMold; protected const _creators :Dictionary = new Dictionary();//<name, ImageCreator/MovieCreator> protected const _pngBytes :Dictionary = new Dictionary();//<String name, ByteArray> protected const _pngLoaders :Executor = new Executor(1); protected static const PNG :String = ".png"; } class ImageCreator implements SymbolCreator { public var texture :Texture; public var offset :Point; public var symbol :String; public function ImageCreator (texture :Texture, offset :Point, symbol :String) { this.texture = texture; this.offset = offset; this.symbol = symbol; } public function create (library :Library) :DisplayObject { const image :Image = new Image(texture); image.x = offset.x; image.y = offset.y; const holder :Sprite = new Sprite(); holder.addChild(image); holder.name = symbol; return holder; } } class MovieCreator implements SymbolCreator { public var mold :MovieMold; public var frameRate :Number; public function MovieCreator (mold :MovieMold, frameRate :Number) { this.mold = mold; this.frameRate = frameRate; } public function create (library :Library) :DisplayObject { return new Movie(mold, frameRate, library); } }
// // Flump - Copyright 2012 Three Rings Design package flump.display { import flash.utils.ByteArray; import flump.executor.Executor; import flump.executor.Future; import starling.core.Starling; /** * Loads zip files created by the flump exporter and parses them into Library instances. */ public class LibraryLoader { /** * Loads a Library from the zip in the given bytes. * * @param bytes The bytes containing the zip * * @param executor The executor on which the loading should run. If not specified, it'll run on * a new single-use executor. * * @param scaleFactor the desired scale factor of the textures to load. If the Library contains * textures with multiple scale factors, loader will load the textures with the scale factor * closest to this value. If scaleFactor <= 0 (the default), Starling.contentScaleFactor will be * used. * * @return a Future to use to track the success or failure of loading the resources out of the * bytes. If the loading succeeds, the Future's onSuccess will fire with an instance of * Library. If it fails, the Future's onFail will fire with the Error that caused the * loading failure. */ public static function loadBytes (bytes :ByteArray, executor :Executor=null, scaleFactor :Number=-1) :Future { return (executor || new Executor(1)).submit(new Loader(bytes, scaleFactor).load); } /** * Loads a Library from the zip at the given url. * * @param bytes The url where the zip can be found * * @param executor The executor on which the loading should run. If not specified, it'll run on * a new single-use executor. * * @param scaleFactor the desired scale factor of the textures to load. If the Library contains * textures with multiple scale factors, loader will load the textures with the scale factor * closest to this value. If scaleFactor <= 0 (the default), Starling.contentScaleFactor will be * used. * * @return a Future to use to track the success or failure of loading the resources from the * url. If the loading succeeds, the Future's onSuccess will fire with an instance of * Library. If it fails, the Future's onFail will fire with the Error that caused the * loading failure. */ public static function loadURL (url :String, executor :Executor=null, scaleFactor :Number=-1) :Future { return (executor || new Executor(1)).submit(new Loader(url, scaleFactor).load); } /** @private */ public static const LIBRARY_LOCATION :String = "library.json"; /** @private */ public static const MD5_LOCATION :String = "md5"; /** @private */ public static const VERSION_LOCATION :String = "version"; /** * @private * The version produced and parsable by this version of the code. The version in a resources * zip must equal the version compiled into the parsing code for parsing to succeed. */ public static const VERSION :String = "1"; } } import flash.events.Event; import flash.geom.Point; import flash.geom.Rectangle; import flash.net.URLRequest; import flash.utils.ByteArray; import flash.utils.Dictionary; import deng.fzip.FZip; import deng.fzip.FZipErrorEvent; import deng.fzip.FZipEvent; import deng.fzip.FZipFile; import flump.display.Library; import flump.display.LibraryLoader; import flump.display.Movie; import flump.executor.Executor; import flump.executor.Future; import flump.executor.FutureTask; import flump.executor.load.ImageLoader; import flump.executor.load.LoadedImage; import flump.mold.AtlasMold; import flump.mold.AtlasTextureMold; import flump.mold.LibraryMold; import flump.mold.MovieMold; import flump.mold.TextureGroupMold; import starling.core.Starling; import starling.display.DisplayObject; import starling.display.Image; import starling.display.Sprite; import starling.textures.Texture; interface SymbolCreator { function create (library :Library) :DisplayObject; } class LibraryImpl implements Library { public function LibraryImpl (creators :Dictionary) { _creators = creators; } public function createMovie (symbol :String) :Movie { return Movie(createDisplayObject(symbol)); } public function createImage (symbol :String) :DisplayObject { const disp :DisplayObject = createDisplayObject(symbol); if (disp is Movie) throw new Error(symbol + " is a movie, not a texture"); return disp; } public function get movieSymbols () :Vector.<String> { const names :Vector.<String> = new Vector.<String>(); for (var creatorName :String in _creators) { if (_creators[creatorName] is MovieCreator) names.push(creatorName); } return names; } public function get imageSymbols () :Vector.<String> { const names :Vector.<String> = new Vector.<String>(); for (var creatorName :String in _creators) { if (_creators[creatorName] is ImageCreator) names.push(creatorName); } return names; } public function createDisplayObject (name :String) :DisplayObject { var creator :SymbolCreator = _creators[name]; if (creator == null) throw new Error("No such id '" + name + "'"); return creator.create(this); } protected var _creators :Dictionary; } class Loader { public function Loader (toLoad :Object, scaleFactor :Number) { _scaleFactor = (scaleFactor > 0 ? scaleFactor : Starling.contentScaleFactor); _toLoad = toLoad; } public function load (future :FutureTask) :void { _future = future; _zip.addEventListener(Event.COMPLETE, _future.monitoredCallback(onZipLoadingComplete)); _zip.addEventListener(FZipErrorEvent.PARSE_ERROR, _future.fail); _zip.addEventListener(FZipEvent.FILE_LOADED, _future.monitoredCallback(onFileLoaded)); if (_toLoad is String) _zip.load(new URLRequest(String(_toLoad))); else _zip.loadBytes(ByteArray(_toLoad)); } protected function onFileLoaded (e :FZipEvent) :void { const loaded :FZipFile = _zip.removeFileAt(_zip.getFileCount() - 1); const name :String = loaded.filename; if (name == LibraryLoader.LIBRARY_LOCATION) { const jsonString :String = loaded.content.readUTFBytes(loaded.content.length); _lib = LibraryMold.fromJSON(JSON.parse(jsonString)); } else if (name.indexOf(PNG, name.length - PNG.length) != -1) { _pngBytes[name] = loaded.content; } else if (name == LibraryLoader.VERSION_LOCATION) { const zipVersion :String = loaded.content.readUTFBytes(loaded.content.length) if (zipVersion != LibraryLoader.VERSION) { throw new Error("Zip is version " + zipVersion + " but the code needs " + LibraryLoader.VERSION); } _versionChecked = true; } else if (name == LibraryLoader.MD5_LOCATION ) { // Nothing to verify } else {} // ignore unknown files } protected function onZipLoadingComplete (..._) :void { _zip = null; if (_lib == null) throw new Error(LibraryLoader.LIBRARY_LOCATION + " missing from zip"); if (!_versionChecked) throw new Error(LibraryLoader.VERSION_LOCATION + " missing from zip"); const loader :ImageLoader = new ImageLoader(); _pngLoaders.terminated.add(_future.monitoredCallback(onPngLoadingComplete)); // Determine the scale factor we want to use var textureGroup :TextureGroupMold = _lib.bestTextureGroupForScaleFactor(_scaleFactor); if (textureGroup != null) { for each (var atlas :AtlasMold in textureGroup.atlases) { loadAtlas(loader, atlas); } } _pngLoaders.shutdown(); } protected function loadAtlas (loader :ImageLoader, atlas :AtlasMold) :void { const pngBytes :* = _pngBytes[atlas.file]; if (pngBytes === undefined) { throw new Error("Expected an atlas '" + atlas.file + "', but it wasn't in the zip"); } const atlasFuture :Future = loader.loadFromBytes(pngBytes, _pngLoaders); atlasFuture.failed.add(onPngLoadingFailed); atlasFuture.succeeded.add(function (img :LoadedImage) :void { var scale :Number = atlas.scaleFactor; const baseTexture :Texture = Texture.fromBitmapData( img.bitmapData, false, // generateMipMaps false, // optimizeForRenderToTexture scale); for each (var atlasTexture :AtlasTextureMold in atlas.textures) { var bounds :Rectangle = atlasTexture.bounds; var offset :Point = atlasTexture.offset; // Starling expects subtexture bounds to be unscaled if (scale != 1) { bounds = bounds.clone(); bounds.x /= scale; bounds.y /= scale; bounds.width /= scale; bounds.height /= scale; offset = offset.clone(); offset.x /= scale; offset.y /= scale; } _creators[atlasTexture.symbol] = new ImageCreator( Texture.fromTexture(baseTexture, bounds), offset, atlasTexture.symbol); } }); } protected function onPngLoadingComplete (..._) :void { for each (var movie :MovieMold in _lib.movies) { movie.fillLabels(); _creators[movie.id] = new MovieCreator(movie, _lib.frameRate); } _future.succeed(new LibraryImpl(_creators)); } protected function onPngLoadingFailed (e :*) :void { if (_future.isComplete) return; _future.fail(e); _pngLoaders.shutdownNow(); } protected var _toLoad :Object; protected var _scaleFactor :Number; protected var _future :FutureTask; protected var _versionChecked :Boolean; protected var _zip :FZip = new FZip(); protected var _lib :LibraryMold; protected const _creators :Dictionary = new Dictionary();//<name, ImageCreator/MovieCreator> protected const _pngBytes :Dictionary = new Dictionary();//<String name, ByteArray> protected const _pngLoaders :Executor = new Executor(1); protected static const PNG :String = ".png"; } class ImageCreator implements SymbolCreator { public var texture :Texture; public var offset :Point; public var symbol :String; public function ImageCreator (texture :Texture, offset :Point, symbol :String) { this.texture = texture; this.offset = offset; this.symbol = symbol; } public function create (library :Library) :DisplayObject { const image :Image = new Image(texture); image.x = offset.x; image.y = offset.y; const holder :Sprite = new Sprite(); holder.addChild(image); holder.name = symbol; return holder; } } class MovieCreator implements SymbolCreator { public var mold :MovieMold; public var frameRate :Number; public function MovieCreator (mold :MovieMold, frameRate :Number) { this.mold = mold; this.frameRate = frameRate; } public function create (library :Library) :DisplayObject { return new Movie(mold, frameRate, library); } }
Fix atlas subtexture creation
Fix atlas subtexture creation We were doing the wrong thing when scaleFactor != 1
ActionScript
mit
mathieuanthoine/flump,funkypandagame/flump,mathieuanthoine/flump,funkypandagame/flump,tconkling/flump,mathieuanthoine/flump,tconkling/flump
281602aeaa02f4a066e7f136c345843fb6b4fe9f
src/avm1lib/AS2Utils.as
src/avm1lib/AS2Utils.as
/** * Copyright 2014 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package avm1lib { import flash.display.MovieClip; import flash.display.Stage; [native(cls="AS2Utils")] public class AS2Utils { public static native function getAS2Object(nativeObject: Object) : Object; public static native function addProperty(obj: Object, name: String, getter: Function, setter: Function, enumerable: Boolean = true); public static native function resolveTarget(target_mc:* = undefined) : MovieClip; public static native function resolveLevel(level: Number) : MovieClip; public static native function get currentStage() : Stage; public static function getTarget(mc: Object) { var nativeObject = mc._as3Object; if (nativeObject === nativeObject.root) { return '/'; } var path = ''; do { path = '/' + nativeObject.name + path; nativeObject = nativeObject.parent; } while (nativeObject !== nativeObject.root); return path; } public static function addEventHandlerProxy(obj: Object, propertyName: String, eventName: String, argsConverter: Function = null) { _addEventHandlerProxy(obj, propertyName, eventName, argsConverter); } private static native function _installObjectMethods(); { _installObjectMethods(); } } } import avm1lib.AS2Utils; AS2Utils; function _addEventHandlerProxy(obj: Object, propertyName: String, eventName: String, argsConverter: Function) { var currentHandler: Function = null; var handlerRunner: Function = null; AS2Utils.addProperty(obj, propertyName, function(): Function { return currentHandler; }, function setter(newHandler: Function) { if (!this._as3Object) { // prototype/class ? var defaultListeners = this._as2DefaultListeners || (this._as2DefaultListeners = []); defaultListeners.push({setter: setter, value: newHandler}); // see also initDefaultListeners() return; } if (propertyName === 'onRelease' || propertyName === 'onReleaseOutside' || propertyName === 'onRollOut' || propertyName === 'onRollOver') { this._as3Object.mouseEnabled = true; this._as3Object.buttonMode = true; } if (currentHandler === newHandler) { return; } if (currentHandler != null) { this._as3Object.removeEventListener(eventName, handlerRunner); } currentHandler = newHandler; if (currentHandler != null) { handlerRunner = (function (obj: Object, handler: Function) { return function handlerRunner() { var args = argsConverter != null ? argsConverter(arguments) : null; return handler.apply(obj, args); }; })(this, currentHandler); this._as3Object.addEventListener(eventName, handlerRunner); } else { handlerRunner = null; } }, false); }
/** * Copyright 2014 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package avm1lib { import flash.display.MovieClip; import flash.display.Stage; [native(cls="AS2Utils")] public class AS2Utils { public static native function getAS2Object(nativeObject: Object) : Object; public static native function addProperty(obj: Object, name: String, getter: Function, setter: Function, enumerable: Boolean = true); public static native function resolveTarget(target_mc:* = undefined) : MovieClip; public static native function resolveLevel(level: Number) : MovieClip; public static native function get currentStage() : Stage; public static function getTarget(mc: Object) { var nativeObject = mc._as3Object; if (nativeObject === nativeObject.root) { return '/'; } var path = ''; do { path = '/' + nativeObject.name + path; nativeObject = nativeObject.parent; } while (nativeObject !== nativeObject.root); return path; } public static function addEventHandlerProxy(obj: Object, propertyName: String, eventName: String, argsConverter: Function = null) { _addEventHandlerProxy(obj, propertyName, eventName, argsConverter); } private static native function _installObjectMethods(); { _installObjectMethods(); } } } import avm1lib.AS2Utils; AS2Utils; function _addEventHandlerProxy(obj: Object, propertyName: String, eventName: String, argsConverter: Function) { var currentHandler: Function = null; var handlerRunner: Function = null; AS2Utils.addProperty(obj, propertyName, function(): Function { return currentHandler; }, function setter(newHandler: Function) { if (!this._as3Object) { // prototype/class ? var defaultListeners = this._as2DefaultListeners || (this._as2DefaultListeners = []); defaultListeners.push({setter: setter, value: newHandler}); // see also initDefaultListeners() return; } // AS2 MovieClips don't receive roll/release events by default until they set one of the following properties. // This behaviour gets triggered whenever those properties are set, despite of the actual value they are set to. if (propertyName === 'onRelease' || propertyName === 'onReleaseOutside' || propertyName === 'onRollOut' || propertyName === 'onRollOver') { this._as3Object.mouseEnabled = true; this._as3Object.buttonMode = true; } if (currentHandler === newHandler) { return; } if (currentHandler != null) { this._as3Object.removeEventListener(eventName, handlerRunner); } currentHandler = newHandler; if (currentHandler != null) { handlerRunner = (function (obj: Object, handler: Function) { return function handlerRunner() { var args = argsConverter != null ? argsConverter(arguments) : null; return handler.apply(obj, args); }; })(this, currentHandler); this._as3Object.addEventListener(eventName, handlerRunner); } else { handlerRunner = null; } }, false); }
Add comment to _addEventHandlerProxy
Add comment to _addEventHandlerProxy
ActionScript
apache-2.0
tschneidereit/shumway,tschneidereit/shumway,mbebenita/shumway,tschneidereit/shumway,mozilla/shumway,tschneidereit/shumway,tschneidereit/shumway,mozilla/shumway,yurydelendik/shumway,mozilla/shumway,yurydelendik/shumway,mbebenita/shumway,mbebenita/shumway,mbebenita/shumway,yurydelendik/shumway,mbebenita/shumway,yurydelendik/shumway,mbebenita/shumway,mozilla/shumway,mozilla/shumway,mbebenita/shumway,yurydelendik/shumway,mozilla/shumway,mozilla/shumway,mbebenita/shumway,tschneidereit/shumway,mozilla/shumway,tschneidereit/shumway,yurydelendik/shumway,yurydelendik/shumway,tschneidereit/shumway,yurydelendik/shumway
a17cf4d2725783b8e88a307b61094d9ae19dc654
build-aux/urbi.as
build-aux/urbi.as
## -*- shell-script -*- ## urbi.as: This file is part of build-aux. ## Copyright (C) Gostai S.A.S., 2006-2008. ## ## This software is provided "as is" without warranty of any kind, ## either expressed or implied, including but not limited to the ## implied warranties of fitness for a particular purpose. ## ## See the LICENSE file for more information. ## For comments, bug reports and feedback: http://www.urbiforge.com ## m4_pattern_allow([^URBI_SERVER$]) m4_divert_text([URBI-INIT], [ # check_dir VARIABLE WITNESS # -------------------------- # Check that VARIABLE contains a directory name that contains WITNESS. check_dir () { local var=$[1] local witness=$[2] local dir eval "dir=\$$[1]" test x"$dir" != x || fatal "undefined variable: $var" shift test -e "$dir" || fatal "$var does not exist: $dir" "(pwd = $(pwd))" test -d "$dir" || fatal "$var is not a directory: $dir" "(pwd = $(pwd))" if test x"$witness" != x; then test -f "$dir/$witness" || fatal "$var does not contain $witness: $dir" "(pwd = $(pwd))" fi } # check_and_abs_dir VAR WITNESS # ----------------------------- # Check that $VAR/WITNESS exists, and set VAR to $(absolute $VAR). check_and_abs_dir () { local var=$[1] local witness=$[2] check_dir "$[@]" # Normalize the directory name, and as safety belts, run the same # tests on it. But save time if possible. So put in "$@" the dirs # to check, the last one being the actual result. AS_IF([! is_absolute "$val"], [local dir eval "dir=\$$[1]" dir=$(absolute "$val") check_dir "$dir" "$witness" eval "$var='$dir'" ]) } # find_srcdir WITNESS # ------------------- # Find the location of the src directory of the tests suite. # Make sure the value is correct by checking for the presence of WITNESS. find_srcdir () { # Guess srcdir if not defined. if test -z "$srcdir"; then # Try to compute it from $[0]. srcdir=$(dirname "$[0]") fi check_dir srcdir "$[1]" } # find_top_builddir [POSSIBILITIES] # --------------------------------- # Set/check top_builddir. # - $top_builddir if the user wants to define it, # - (dirname $0)/.. since that's where we are supposed to be # - ../.. for the common case where we're in tests/my-test.dir # - .. if we're in tests/ # - . if we're in top-builddir. find_top_builddir () { if test x"$top_builddir" = x; then if test $[#] = 0; then set $(dirname "$0")/.. ../.. .. . fi for d do if test -f "$d/config.status"; then top_builddir=$d break fi done fi check_dir top_builddir "config.status" } # find_urbi_server # ---------------- # Set URBI_SERVER to the location of urbi-server. find_urbi_server () { case $URBI_SERVER in ('') # If URBI_SERVER is not defined, try to find one. If we are in # $top_builddir/tests/TEST.dir, then look in $top_builddir/src. URBI_SERVER=$(find_prog "urbi-server" \ "$top_builddir/src${PATH_SEPARATOR}.") ;; (*[[\\/]]*) # A path, relative or absolute. Make it absolute. URBI_SERVER=$(absolute "$URBI_SERVER") ;; (*) # A simple name, most certainly urbi-server. # Find it in the PATH. local res res=$(find_prog "$URBI_SERVER") # If we can't find it, then ucore-pc was probably not installed. # Skip. test x"$res" != x || error SKIP "cannot find $URBI_SERVER in $PATH" URBI_SERVER=$res ;; esac if test -z "$URBI_SERVER"; then fatal "cannot find urbi-server, please define URBI_SERVER" fi if test ! -f "$URBI_SERVER"; then fatal "cannot find urbi-server, please check \$URBI_SERVER: $URBI_SERVER" fi # Check its version. if ! run "Server version" "$URBI_SERVER" --version >&3; then fatal "cannot run $URBI_SERVER --version" fi } # spawn_urbi_server FLAGS # ----------------------- # Spawn an $URBI_SERVER in back-ground, registering it as the child "server". # Wait until the server.port file is created. Make it fatal if this does # not happen with 10s. # # Dies if the server does not create server.port for whatever reason. spawn_urbi_server () { rm -f server.port local flags="--port 0 --port-file server.port $*" local cmd="$(instrument "server.val") $URBI_SERVER $flags" echo "$cmd" >server.cmd $cmd </dev/null >server.out 2>server.err & children_register server # Wait for the port file to be completed: it must have one full line # (with \n to be sure it is complete). local t=0 local tmax=8 local dt=.5 # 0 if we stop, 1 to continue sleeping. local cont while children_alive server && { test ! -f server.port || test $(wc -l <server.port) = 0; }; do # test/expr don't like floating points. cont=$(echo "$t <= $tmax" | bc) case $cont in (1) sleep $dt t=$(echo "$t + $dt" | bc);; (0) fatal "$URBI_SERVER did not issue port in server.port in ${tmax}s";; esac done test -f server.port || fatal "$URBI_SERVER failed before creating server.por" } ])
## -*- shell-script -*- ## urbi.as: This file is part of build-aux. ## Copyright (C) Gostai S.A.S., 2006-2008. ## ## This software is provided "as is" without warranty of any kind, ## either expressed or implied, including but not limited to the ## implied warranties of fitness for a particular purpose. ## ## See the LICENSE file for more information. ## For comments, bug reports and feedback: http://www.urbiforge.com ## m4_pattern_allow([^URBI_SERVER$]) m4_divert_text([URBI-INIT], [ # check_dir VARIABLE WITNESS # -------------------------- # Check that VARIABLE contains a directory name that contains WITNESS. check_dir () { local var=$[1] local witness=$[2] local dir eval "dir=\$$[1]" test x"$dir" != x || fatal "undefined variable: $var" shift test -e "$dir" || fatal "$var does not exist: $dir" "(pwd = $(pwd))" test -d "$dir" || fatal "$var is not a directory: $dir" "(pwd = $(pwd))" if test x"$witness" != x; then test -f "$dir/$witness" || fatal "$var does not contain $witness: $dir" "(pwd = $(pwd))" fi } # check_and_abs_dir VAR WITNESS # ----------------------------- # Check that $VAR/WITNESS exists, and set VAR to $(absolute $VAR). check_and_abs_dir () { local var=$[1] local witness=$[2] check_dir "$[@]" # Normalize the directory name, and as safety belts, run the same # tests on it. But save time if possible. So put in "$@" the dirs # to check, the last one being the actual result. AS_IF([! is_absolute "$val"], [local dir eval "dir=\$$[1]" dir=$(absolute "$val") check_dir "$dir" "$witness" eval "$var='$dir'" ]) } # find_srcdir WITNESS # ------------------- # Find the location of the src directory of the tests suite. # Make sure the value is correct by checking for the presence of WITNESS. find_srcdir () { # Guess srcdir if not defined. if test -z "$srcdir"; then # Try to compute it from $[0]. srcdir=$(dirname "$[0]") fi check_dir srcdir "$[1]" } # find_top_builddir [POSSIBILITIES] # --------------------------------- # Set/check top_builddir. # - $top_builddir if the user wants to define it, # - (dirname $0)/.. since that's where we are supposed to be # - ../.. for the common case where we're in tests/my-test.dir # - .. if we're in tests/ # - . if we're in top-builddir. find_top_builddir () { if test x"$top_builddir" = x; then if test $[#] = 0; then set $(dirname "$0")/.. ../.. .. . fi for d do if test -f "$d/config.status"; then top_builddir=$d break fi done fi check_dir top_builddir "config.status" } # find_urbi_server # ---------------- # Set URBI_SERVER to the location of urbi-server. find_urbi_server () { case $URBI_SERVER in ('') # If URBI_SERVER is not defined, try to find one. If we are in # $top_builddir/tests/TEST.dir, then look in $top_builddir/src. URBI_SERVER=$(find_prog "urbi-server" \ "$top_builddir/src${PATH_SEPARATOR}.") ;; (*[[\\/]]*) # A path, relative or absolute. Make it absolute. URBI_SERVER=$(absolute "$URBI_SERVER") ;; (*) # A simple name, most certainly urbi-server. # Find it in the PATH. local res res=$(find_prog "$URBI_SERVER") # If we can't find it, then ucore-pc was probably not installed. # Skip. test x"$res" != x || error SKIP "cannot find $URBI_SERVER in $PATH" URBI_SERVER=$res ;; esac if test -z "$URBI_SERVER"; then fatal "cannot find urbi-server, please define URBI_SERVER" fi if test ! -f "$URBI_SERVER"; then fatal "cannot find urbi-server, please check \$URBI_SERVER: $URBI_SERVER" fi # Check its version. if ! run "Server version" "$URBI_SERVER" --version >&3; then fatal "cannot run $URBI_SERVER --version" fi } # spawn_urbi_server FLAGS # ----------------------- # Spawn an $URBI_SERVER in back-ground, registering it as the child "server". # Wait until the server.port file is created. Make it fatal if this does # not happen with 10s. # # Dies if the server does not create server.port for whatever reason. spawn_urbi_server () { rm -f server.port local flags="--port 0 --port-file server.port $*" local cmd="$(instrument "server.val") $URBI_SERVER $flags" echo "$cmd" >server.cmd $cmd </dev/null >server.out 2>server.err & children_register server # Wait for the port file to be completed: it must have one full line # (with \n to be sure it is complete). local t=0 local tmax=20 local dt=.5 # 0 if we stop, 1 to continue sleeping. local cont while children_alive server && { test ! -f server.port || test $(wc -l <server.port) = 0; }; do # test/expr don't like floating points. cont=$(echo "$t <= $tmax" | bc) case $cont in (1) sleep $dt t=$(echo "$t + $dt" | bc);; (0) fatal "$URBI_SERVER did not issue port in server.port in ${tmax}s";; esac done test -f server.port || fatal "$URBI_SERVER failed before creating server.por" } ])
Increase wait time to help tests requiring qemu.
Increase wait time to help tests requiring qemu. Pretty much harmless in other cases, as this timeout is only reached in rare conditions. * build-aux/urbi.as: Wait for server.port for 20s.
ActionScript
bsd-3-clause
aldebaran/libport,aldebaran/libport,aldebaran/libport,aldebaran/libport,aldebaran/libport
607033421656cde9fa3aef0efcda8e47175e22f9
src/org/mangui/HLS/muxing/PES.as
src/org/mangui/HLS/muxing/PES.as
package org.mangui.HLS.muxing { import flash.utils.ByteArray; /** Representation of a Packetized Elementary Stream. **/ public class PES { /** Is it AAC audio or AVC video. **/ public var audio : Boolean; /** The PES data (including headers). **/ public var data : ByteArray; /** Start of the payload. **/ public var payload : Number; /** Timestamp from the PTS header. **/ public var pts : Number; /** Timestamp from the DTS header. **/ public var dts : Number; /** PES packet len **/ public var len : Number; /** PES packet len **/ public var payload_len : Number; /** Save the first chunk of PES data. **/ public function PES(dat : ByteArray, aud : Boolean) { data = dat; audio = aud; parse(); }; /** When all data is appended, parse the PES headers. **/ private function parse() : void { data.position = 0; // Start code prefix and packet ID. var prefix : Number = data.readUnsignedInt(); /*Audio streams (0x1C0-0x1DF) Video streams (0x1E0-0x1EF) 0x1BD is special case, could be audio or video (ffmpeg\libavformat\mpeg.c) */ if ((audio && (prefix > 0x1df || prefix < 0x1c0 && prefix != 0x1bd)) || (!audio && prefix != 0x1e0 && prefix != 0x1ea && prefix != 0x1bd)) { throw new Error("PES start code not found or not AAC/AVC: " + prefix); } // read len len = data.readUnsignedShort(); // Ignore marker bits. data.position += 1; // Check for PTS var flags : uint = (data.readUnsignedByte() & 192) >> 6; // Check PES header length var length : uint = data.readUnsignedByte(); if (flags == 2 || flags == 3) { // Grab the timestamp from PTS data (spread out over 5 bytes): // XXXX---X -------- -------X -------- -------X var _pts : Number = Number((data.readUnsignedByte() & 0x0e)) * Number(1 << 29) + Number((data.readUnsignedShort() >> 1) << 15) + Number((data.readUnsignedShort() >> 1)); // check if greater than 2^32 -1 if (_pts > 4294967295) { // if greater, it is a negative timestamp, compute 2 complement (XOR with 2^32 - 1), then add 1 _pts ^= 4294967295; _pts = -(_pts+1); } length -= 5; var _dts : Number = _pts; if (flags == 3) { // Grab the DTS (like PTS) _dts = Number((data.readUnsignedByte() & 0x0e)) * Number(1 << 29) + Number((data.readUnsignedShort() >> 1) << 15) + Number((data.readUnsignedShort() >> 1)); // check if greater than 2^32 -1 if (_dts > 4294967295) { // if greater, it is a negative timestamp, compute 2 complement (XOR with 2^32 - 1), then add 1 _dts ^= 4294967295; _dts = -(_dts+1); } length -= 5; } pts = Math.round(_pts / 90); dts = Math.round(_dts / 90); // Log.info("pts/dts: " + pts + "/"+ dts); } // Skip other header data and parse payload. data.position += length; payload = data.position; if(len) { payload_len = len - data.position + 6; } else { payload_len = 0; } }; } }
package org.mangui.HLS.muxing { import flash.utils.ByteArray; /** Representation of a Packetized Elementary Stream. **/ public class PES { /** Is it AAC audio or AVC video. **/ public var audio : Boolean; /** The PES data (including headers). **/ public var data : ByteArray; /** Start of the payload. **/ public var payload : Number; /** Timestamp from the PTS header. **/ public var pts : Number; /** Timestamp from the DTS header. **/ public var dts : Number; /** PES packet len **/ public var len : Number; /** PES packet len **/ public var payload_len : Number; /** Save the first chunk of PES data. **/ public function PES(dat : ByteArray, aud : Boolean) { data = dat; audio = aud; parse(); }; /** When all data is appended, parse the PES headers. **/ private function parse() : void { data.position = 0; // Start code prefix and packet ID. var prefix : Number = data.readUnsignedInt(); /*Audio streams (0x1C0-0x1DF) Video streams (0x1E0-0x1EF) 0x1BD is special case, could be audio or video (ffmpeg\libavformat\mpeg.c) */ if ((audio && (prefix > 0x1df || prefix < 0x1c0 && prefix != 0x1bd)) || (!audio && prefix != 0x1e0 && prefix != 0x1ea && prefix != 0x1bd)) { throw new Error("PES start code not found or not AAC/AVC: " + prefix); } // read len len = data.readUnsignedShort(); // Ignore marker bits. data.position += 1; // Check for PTS var flags : uint = (data.readUnsignedByte() & 192) >> 6; // Check PES header length var length : uint = data.readUnsignedByte(); if (flags == 2 || flags == 3) { // Grab the timestamp from PTS data (spread out over 5 bytes): // XXXX---X -------- -------X -------- -------X var _pts : Number = Number((data.readUnsignedByte() & 0x0e)) * Number(1 << 29) + Number((data.readUnsignedShort() >> 1) << 15) + Number((data.readUnsignedShort() >> 1)); // check if greater than 2^32 -1 if (_pts > 4294967295) { // decrement 2^33 _pts -= 8589934592; } length -= 5; var _dts : Number = _pts; if (flags == 3) { // Grab the DTS (like PTS) _dts = Number((data.readUnsignedByte() & 0x0e)) * Number(1 << 29) + Number((data.readUnsignedShort() >> 1) << 15) + Number((data.readUnsignedShort() >> 1)); // check if greater than 2^32 -1 if (_dts > 4294967295) { // decrement 2^33 _dts -= 8589934592; } length -= 5; } pts = Math.round(_pts / 90); dts = Math.round(_dts / 90); // Log.info("pts/dts: " + pts + "/"+ dts); } // Skip other header data and parse payload. data.position += length; payload = data.position; if(len) { payload_len = len - data.position + 6; } else { payload_len = 0; } }; } }
fix computation of negative PTS/DTS value
fix computation of negative PTS/DTS value
ActionScript
mpl-2.0
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
ece2ee33a1f6c43f8c46992cb692c69564d9f711
frameworks/projects/Core/src/main/flex/org/apache/flex/core/TransformCompoundModel.as
frameworks/projects/Core/src/main/flex/org/apache/flex/core/TransformCompoundModel.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.core { import org.apache.flex.geom.Matrix; [DefaultProperty("transformModels")] public class TransformCompoundModel extends TransformModel { public function set transformModels(value:Array):void { if (value && value.length > 0) { var length:int = value.length; var product:Matrix = (value[0] as ITransformModel).matrix.clone(); for (var i:int = 1; i < length; i++) { var current:Matrix = (value[i] as ITransformModel).matrix; concat(product, current); } matrix = product; } else { matrix = null; } } private function concat(product:Matrix, factor:Matrix):void { var result_a:Number = product.a * factor.a; var result_b:Number = 0.0; var result_c:Number = 0.0; var result_d:Number = product.d * factor.d; var result_tx:Number = product.tx * factor.a + factor.tx; var result_ty:Number = product.ty * factor.d + factor.ty; if (product.b != 0.0 || product.c != 0.0 || factor.b != 0.0 || factor.c != 0.0) { result_a = result_a + product.b * factor.c; result_d = result_d + product.c * factor.b; result_b = result_b + (product.a * factor.b + product.b * factor.d); result_c = result_c + (product.c * factor.a + product.d * factor.c); result_tx = result_tx + product.ty * factor.c; result_ty = result_ty + product.tx * factor.b; } product.a = result_a; product.b = result_b; product.c = result_c; product.d = result_d; product.tx = result_tx; product.ty = result_ty; } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.core { import org.apache.flex.geom.Matrix; [DefaultProperty("transformModels")] public class TransformCompoundModel extends TransformModel { public function set transformModels(value:Array):void { if (value && value.length > 0) { var length:int = value.length; var product:Matrix = (value[0] as ITransformModel).matrix.clone(); for (var i:int = 1; i < length; i++) { var current:Matrix = (value[i] as ITransformModel).matrix; product.concat(current); } matrix = product; } else { matrix = null; } } } }
Use Matrix concat
Use Matrix concat
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
af37c501e573afab88f7aefe44dcbc3094a8be9e
src/aerys/minko/render/material/phong/PhongEffect.as
src/aerys/minko/render/material/phong/PhongEffect.as
package aerys.minko.render.material.phong { import aerys.minko.render.DataBindingsProxy; import aerys.minko.render.Effect; import aerys.minko.render.RenderTarget; import aerys.minko.render.material.phong.multipass.PhongAdditionalShader; import aerys.minko.render.material.phong.multipass.PhongAmbientShader; import aerys.minko.render.material.phong.multipass.PhongEmissiveShader; import aerys.minko.render.material.phong.multipass.ZPrepassShader; import aerys.minko.render.material.phong.shadow.ExponentialShadowMapShader; import aerys.minko.render.material.phong.shadow.PCFShadowMapShader; import aerys.minko.render.material.phong.shadow.ParaboloidShadowMapShader; import aerys.minko.render.material.phong.shadow.VarianceShadowMapShader; import aerys.minko.render.resource.texture.CubeTextureResource; import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.render.resource.texture.TextureResource; import aerys.minko.render.shader.Shader; import aerys.minko.scene.data.LightDataProvider; import aerys.minko.scene.node.light.AmbientLight; import aerys.minko.scene.node.light.PointLight; import aerys.minko.type.enum.ShadowMappingQuality; import aerys.minko.type.enum.ShadowMappingType; /** * <p>The PhongEffect using the Phong lighting model to render the geometry according to * the lighting setup of the scene. It supports an infinite number of lights/projected * shadows and will automatically switch between singlepass and multipass rendering * in order to give the best performances whenever possible.</p> * * </p>Because of the Stage3D restrictions regarding the number of shader operations or * the number of available registers, the number of lights might be to big to allow them * to be rendered in a single pass. In this situation, the PhongEffect will automatically * fallback and use multipass rendering.</p> * * <p>Multipass rendering is done as follow:</p> * <ul> * <li>The "base" pass renders objects with one per-pixel directional lights with shadows, * the lightmap and the ambient/emissive lighting.</li> * <li>Each "additional" pass (one per light) will render a single light with shadows and * blend it using additive blending.</li> * </ul> * * The singlepass rendering will mimic this behavior in order to get preserve consistency. * * @author Jean-Marc Le Roux * */ public class PhongEffect extends Effect { private var _useRenderToTexture : Boolean; private var _singlePassShader : Shader; private var _emissiveShader : Shader; private var _targets : Array; public function PhongEffect(useRenderToTexture : Boolean = false, singlePassShader : Shader = null, emissiveShader : Shader = null) { super(); _useRenderToTexture = useRenderToTexture; _singlePassShader = singlePassShader || new PhongSinglePassShader(null, 0); _emissiveShader = emissiveShader || new PhongEmissiveShader(null, null, .25); _targets = []; } override protected function initializePasses(sceneBindings : DataBindingsProxy, meshBindings : DataBindingsProxy) : Vector.<Shader> { var passes : Vector.<Shader> = super.initializePasses(sceneBindings, meshBindings); for (var lightId : uint = 0; lightPropertyExists(sceneBindings, lightId, 'enabled'); ++lightId) { if (lightPropertyExists(sceneBindings, lightId, 'shadowCastingType')) { var lightType : uint = getLightProperty(sceneBindings, lightId, 'type'); var shadowMappingType : uint = getLightProperty( sceneBindings, lightId, 'shadowCastingType' ); switch (shadowMappingType) { case ShadowMappingType.PCF: if (lightType == PointLight.LIGHT_TYPE) pushCubeShadowMappingPass(sceneBindings, lightId, passes); else pushPCFShadowMappingPass(sceneBindings, lightId, passes); break ; case ShadowMappingType.DUAL_PARABOLOID: pushDualParaboloidShadowMappingPass(sceneBindings, lightId, passes); break ; case ShadowMappingType.VARIANCE: pushVarianceShadowMappingPass(sceneBindings, lightId, passes); break ; case ShadowMappingType.EXPONENTIAL: pushExponentialShadowMappingPass(sceneBindings, lightId, passes); break ; } } } passes.push(_singlePassShader); return passes; } override protected function initializeFallbackPasses(sceneBindings : DataBindingsProxy, meshBindings : DataBindingsProxy) : Vector.<Shader> { var passes : Vector.<Shader> = new <Shader>[]; var discardDirectional : Boolean = true; var ambientEnabled : Boolean = meshBindings.propertyExists('lightmap'); var renderTarget : RenderTarget = null; if (_useRenderToTexture) { var accumulatorSize : uint = sceneBindings.getProperty('viewportWidth'); accumulatorSize = 1 << Math.ceil(Math.log(accumulatorSize) * Math.LOG2E); renderTarget = _targets[accumulatorSize] = new RenderTarget( accumulatorSize, accumulatorSize, new TextureResource(accumulatorSize, accumulatorSize) ); } for (var lightId : uint = 0; lightPropertyExists(sceneBindings, lightId, 'enabled'); ++lightId) { var lightType : uint = getLightProperty(sceneBindings, lightId, 'type'); if (lightType == AmbientLight.LIGHT_TYPE) { ambientEnabled = true; continue; } if (getLightProperty(sceneBindings, lightId, 'diffuseEnabled')) passes.push( new PhongAdditionalShader(lightId, true, false, renderTarget, .5) ); if (getLightProperty(sceneBindings, lightId, 'specularEnabled')) passes.push( new PhongAdditionalShader(lightId, false, true, null, 0.) ); if (lightPropertyExists(sceneBindings, lightId, 'shadowCastingType')) { var shadowMappingType : uint = getLightProperty( sceneBindings, lightId, 'shadowCastingType' ); switch (shadowMappingType) { case ShadowMappingType.PCF: if (lightType == PointLight.LIGHT_TYPE) pushCubeShadowMappingPass(sceneBindings, lightId, passes); else pushPCFShadowMappingPass(sceneBindings, lightId, passes); break ; case ShadowMappingType.DUAL_PARABOLOID: pushDualParaboloidShadowMappingPass(sceneBindings, lightId, passes); break ; case ShadowMappingType.VARIANCE: pushVarianceShadowMappingPass(sceneBindings, lightId, passes); break ; case ShadowMappingType.EXPONENTIAL: pushExponentialShadowMappingPass(sceneBindings, lightId, passes); break ; } } } if (ambientEnabled) passes.push(new PhongAmbientShader(renderTarget, .75)); passes.push(new ZPrepassShader(renderTarget, 1)); passes.push(new PhongEmissiveShader( renderTarget ? renderTarget.textureResource : null, null, .25 )); return passes; } private function pushPCFShadowMappingPass(sceneBindings : DataBindingsProxy, lightId : uint, passes : Vector.<Shader>) : void { var textureResource : TextureResource = getLightProperty( sceneBindings, lightId, 'shadowMap' ); var renderTarget : RenderTarget = new RenderTarget( textureResource.width, textureResource.height, textureResource, 0, 0xffffffff ); passes.push(new PCFShadowMapShader(lightId, lightId + 1, renderTarget)); } private function pushDualParaboloidShadowMappingPass(sceneBindings : DataBindingsProxy, lightId : uint, passes : Vector.<Shader>) : void { var frontTextureResource : TextureResource = getLightProperty( sceneBindings, lightId, 'shadowMapFront' ); var backTextureResource : TextureResource = getLightProperty( sceneBindings, lightId, 'shadowMapBack' ); var size : uint = frontTextureResource.width; var frontRenderTarget : RenderTarget = new RenderTarget( size, size, frontTextureResource, 0, 0xffffffff ); var backRenderTarget : RenderTarget = new RenderTarget( size, size, backTextureResource, 0, 0xffffffff ); passes.push( new ParaboloidShadowMapShader(lightId, true, lightId + 0.5, frontRenderTarget), new ParaboloidShadowMapShader(lightId, false, lightId + 1, backRenderTarget) ); } private function pushCubeShadowMappingPass(sceneBindings : DataBindingsProxy, lightId : uint, passes : Vector.<Shader>) : void { var cubeTexture : CubeTextureResource = getLightProperty( sceneBindings, lightId, 'shadowMap' ); var textureSize : uint = cubeTexture.size; for (var i : uint = 0; i < 6; ++i) passes.push(new PCFShadowMapShader( lightId, lightId + .1 * i, new RenderTarget(textureSize, textureSize, cubeTexture, i, 0xffffffff), i )); } private function pushVarianceShadowMappingPass(sceneBindings : DataBindingsProxy, lightId : uint, passes : Vector.<Shader>) : void { var lightType : uint = getLightProperty( sceneBindings, lightId, 'type' ); if (lightType != PointLight.LIGHT_TYPE) { var textureResource : ITextureResource = null; var renderTarget : RenderTarget = null; if (hasShadowBlurPass(sceneBindings, lightId)) textureResource = getLightProperty(sceneBindings, lightId, 'rawShadowMap'); else textureResource = getLightProperty(sceneBindings, lightId, 'shadowMap'); renderTarget = new RenderTarget( textureResource.width, textureResource.height, textureResource, 0, 0xffffffff ); passes.push(new VarianceShadowMapShader(lightId, 4, lightId + 1, renderTarget)); } else { var cubeTexture : CubeTextureResource = getLightProperty( sceneBindings, lightId, 'shadowMap' ); var textureSize : uint = cubeTexture.size; for (var i : uint = 0; i < 6; ++i) passes.push(new VarianceShadowMapShader( lightId, i, lightId + .1 * i, new RenderTarget(textureSize, textureSize, cubeTexture, i, 0xffffffff) )); } } private function pushExponentialShadowMappingPass(sceneBindings : DataBindingsProxy, lightId : uint, passes : Vector.<Shader>):void { var lightType : uint = getLightProperty( sceneBindings, lightId, 'type' ); if (lightType != PointLight.LIGHT_TYPE) { var textureResource : ITextureResource = null; var renderTarget : RenderTarget = null; if (hasShadowBlurPass(sceneBindings, lightId)) textureResource = getLightProperty(sceneBindings, lightId, 'rawShadowMap'); else textureResource = getLightProperty(sceneBindings, lightId, 'shadowMap'); renderTarget = new RenderTarget( textureResource.width, textureResource.height, textureResource, 0, 0xffffffff ); passes.push(new ExponentialShadowMapShader(lightId, 4, lightId + 1, renderTarget)); } else { var cubeTexture : CubeTextureResource = getLightProperty( sceneBindings, lightId, 'shadowMap' ); var textureSize : uint = cubeTexture.size; for (var i : uint = 0; i < 6; ++i) passes.push(new ExponentialShadowMapShader( lightId, i, lightId + .1 * i, new RenderTarget(textureSize, textureSize, cubeTexture, i, 0xffffffff) )); } } private function hasShadowBlurPass(sceneBindings : DataBindingsProxy, lightId : uint) : Boolean { var quality : uint = getLightProperty(sceneBindings, lightId, 'shadowQuality'); return quality > ShadowMappingQuality.HARD; } private function lightPropertyExists(sceneBindings : DataBindingsProxy, lightId : uint, propertyName : String) : Boolean { return sceneBindings.propertyExists( LightDataProvider.getLightPropertyName(propertyName, lightId) ); } private function getLightProperty(sceneBindings : DataBindingsProxy, lightId : uint, propertyName : String) : * { return sceneBindings.getProperty( LightDataProvider.getLightPropertyName(propertyName, lightId) ); } } }
package aerys.minko.render.material.phong { import aerys.minko.render.DataBindingsProxy; import aerys.minko.render.Effect; import aerys.minko.render.RenderTarget; import aerys.minko.render.material.phong.multipass.PhongAdditionalShader; import aerys.minko.render.material.phong.multipass.PhongAmbientShader; import aerys.minko.render.material.phong.multipass.PhongEmissiveShader; import aerys.minko.render.material.phong.multipass.ZPrepassShader; import aerys.minko.render.material.phong.shadow.ExponentialShadowMapShader; import aerys.minko.render.material.phong.shadow.PCFShadowMapShader; import aerys.minko.render.material.phong.shadow.ParaboloidShadowMapShader; import aerys.minko.render.material.phong.shadow.VarianceShadowMapShader; import aerys.minko.render.resource.texture.CubeTextureResource; import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.render.resource.texture.TextureResource; import aerys.minko.render.shader.Shader; import aerys.minko.scene.data.LightDataProvider; import aerys.minko.scene.node.light.AmbientLight; import aerys.minko.scene.node.light.PointLight; import aerys.minko.type.enum.ShadowMappingQuality; import aerys.minko.type.enum.ShadowMappingType; /** * <p>The PhongEffect using the Phong lighting model to render the geometry according to * the lighting setup of the scene. It supports an infinite number of lights/projected * shadows and will automatically switch between singlepass and multipass rendering * in order to give the best performances whenever possible.</p> * * </p>Because of the Stage3D restrictions regarding the number of shader operations or * the number of available registers, the number of lights might be to big to allow them * to be rendered in a single pass. In this situation, the PhongEffect will automatically * fallback and use multipass rendering.</p> * * <p>Multipass rendering is done as follow:</p> * <ul> * <li>The "base" pass renders objects with one per-pixel directional lights with shadows, * the lightmap and the ambient/emissive lighting.</li> * <li>Each "additional" pass (one per light) will render a single light with shadows and * blend it using additive blending.</li> * </ul> * * The singlepass rendering will mimic this behavior in order to get preserve consistency. * * @author Jean-Marc Le Roux * */ public class PhongEffect extends Effect { private var _useRenderToTexture : Boolean; private var _singlePassShader : Shader; private var _emissiveShader : Shader; private var _targets : Array; public function PhongEffect(useRenderToTexture : Boolean = false, singlePassShader : Shader = null, emissiveShader : Shader = null) { super(); _useRenderToTexture = useRenderToTexture; _singlePassShader = singlePassShader || new PhongSinglePassShader(null, 0); _emissiveShader = emissiveShader || new PhongEmissiveShader(null, null, .25); _targets = []; } override protected function initializePasses(sceneBindings : DataBindingsProxy, meshBindings : DataBindingsProxy) : Vector.<Shader> { var passes : Vector.<Shader> = super.initializePasses(sceneBindings, meshBindings); for (var lightId : uint = 0; lightPropertyExists(sceneBindings, lightId, 'enabled') && getLightProperty(sceneBindings, lightId, 'enabled'); ++lightId) { if (lightPropertyExists(sceneBindings, lightId, 'shadowCastingType')) { var lightType : uint = getLightProperty(sceneBindings, lightId, 'type'); var shadowMappingType : uint = getLightProperty( sceneBindings, lightId, 'shadowCastingType' ); switch (shadowMappingType) { case ShadowMappingType.PCF: if (lightType == PointLight.LIGHT_TYPE) pushCubeShadowMappingPass(sceneBindings, lightId, passes); else pushPCFShadowMappingPass(sceneBindings, lightId, passes); break ; case ShadowMappingType.DUAL_PARABOLOID: pushDualParaboloidShadowMappingPass(sceneBindings, lightId, passes); break ; case ShadowMappingType.VARIANCE: pushVarianceShadowMappingPass(sceneBindings, lightId, passes); break ; case ShadowMappingType.EXPONENTIAL: pushExponentialShadowMappingPass(sceneBindings, lightId, passes); break ; } } } passes.push(_singlePassShader); return passes; } override protected function initializeFallbackPasses(sceneBindings : DataBindingsProxy, meshBindings : DataBindingsProxy) : Vector.<Shader> { var passes : Vector.<Shader> = new <Shader>[]; var discardDirectional : Boolean = true; var ambientEnabled : Boolean = meshBindings.propertyExists('lightmap'); var renderTarget : RenderTarget = null; if (_useRenderToTexture) { var accumulatorSize : uint = sceneBindings.getProperty('viewportWidth'); accumulatorSize = 1 << Math.ceil(Math.log(accumulatorSize) * Math.LOG2E); renderTarget = _targets[accumulatorSize] = new RenderTarget( accumulatorSize, accumulatorSize, new TextureResource(accumulatorSize, accumulatorSize) ); } for (var lightId : uint = 0; lightPropertyExists(sceneBindings, lightId, 'enabled') && getLightProperty(sceneBindings, lightId, 'enabled'); ++lightId) { var lightType : uint = getLightProperty(sceneBindings, lightId, 'type'); if (lightType == AmbientLight.LIGHT_TYPE) { ambientEnabled = true; continue; } if (getLightProperty(sceneBindings, lightId, 'diffuseEnabled')) passes.push( new PhongAdditionalShader(lightId, true, false, renderTarget, .5) ); if (getLightProperty(sceneBindings, lightId, 'specularEnabled')) passes.push( new PhongAdditionalShader(lightId, false, true, null, 0.) ); if (lightPropertyExists(sceneBindings, lightId, 'shadowCastingType')) { var shadowMappingType : uint = getLightProperty( sceneBindings, lightId, 'shadowCastingType' ); switch (shadowMappingType) { case ShadowMappingType.PCF: if (lightType == PointLight.LIGHT_TYPE) pushCubeShadowMappingPass(sceneBindings, lightId, passes); else pushPCFShadowMappingPass(sceneBindings, lightId, passes); break ; case ShadowMappingType.DUAL_PARABOLOID: pushDualParaboloidShadowMappingPass(sceneBindings, lightId, passes); break ; case ShadowMappingType.VARIANCE: pushVarianceShadowMappingPass(sceneBindings, lightId, passes); break ; case ShadowMappingType.EXPONENTIAL: pushExponentialShadowMappingPass(sceneBindings, lightId, passes); break ; } } } // if (ambientEnabled) // passes.push(new PhongAmbientShader(renderTarget, .75)); passes.push(new ZPrepassShader(renderTarget, 1)); passes.push(new PhongEmissiveShader( renderTarget ? renderTarget.textureResource : null, null, .25 )); return passes; } private function pushPCFShadowMappingPass(sceneBindings : DataBindingsProxy, lightId : uint, passes : Vector.<Shader>) : void { var textureResource : TextureResource = getLightProperty( sceneBindings, lightId, 'shadowMap' ); var renderTarget : RenderTarget = new RenderTarget( textureResource.width, textureResource.height, textureResource, 0, 0xffffffff ); passes.push(new PCFShadowMapShader(lightId, lightId + 1, renderTarget)); } private function pushDualParaboloidShadowMappingPass(sceneBindings : DataBindingsProxy, lightId : uint, passes : Vector.<Shader>) : void { var frontTextureResource : TextureResource = getLightProperty( sceneBindings, lightId, 'shadowMapFront' ); var backTextureResource : TextureResource = getLightProperty( sceneBindings, lightId, 'shadowMapBack' ); var size : uint = frontTextureResource.width; var frontRenderTarget : RenderTarget = new RenderTarget( size, size, frontTextureResource, 0, 0xffffffff ); var backRenderTarget : RenderTarget = new RenderTarget( size, size, backTextureResource, 0, 0xffffffff ); passes.push( new ParaboloidShadowMapShader(lightId, true, lightId + 0.5, frontRenderTarget), new ParaboloidShadowMapShader(lightId, false, lightId + 1, backRenderTarget) ); } private function pushCubeShadowMappingPass(sceneBindings : DataBindingsProxy, lightId : uint, passes : Vector.<Shader>) : void { var cubeTexture : CubeTextureResource = getLightProperty( sceneBindings, lightId, 'shadowMap' ); var textureSize : uint = cubeTexture.size; for (var i : uint = 0; i < 6; ++i) passes.push(new PCFShadowMapShader( lightId, lightId + .1 * i, new RenderTarget(textureSize, textureSize, cubeTexture, i, 0xffffffff), i )); } private function pushVarianceShadowMappingPass(sceneBindings : DataBindingsProxy, lightId : uint, passes : Vector.<Shader>) : void { var lightType : uint = getLightProperty( sceneBindings, lightId, 'type' ); if (lightType != PointLight.LIGHT_TYPE) { var textureResource : ITextureResource = null; var renderTarget : RenderTarget = null; if (hasShadowBlurPass(sceneBindings, lightId)) textureResource = getLightProperty(sceneBindings, lightId, 'rawShadowMap'); else textureResource = getLightProperty(sceneBindings, lightId, 'shadowMap'); renderTarget = new RenderTarget( textureResource.width, textureResource.height, textureResource, 0, 0xffffffff ); passes.push(new VarianceShadowMapShader(lightId, 4, lightId + 1, renderTarget)); } else { var cubeTexture : CubeTextureResource = getLightProperty( sceneBindings, lightId, 'shadowMap' ); var textureSize : uint = cubeTexture.size; for (var i : uint = 0; i < 6; ++i) passes.push(new VarianceShadowMapShader( lightId, i, lightId + .1 * i, new RenderTarget(textureSize, textureSize, cubeTexture, i, 0xffffffff) )); } } private function pushExponentialShadowMappingPass(sceneBindings : DataBindingsProxy, lightId : uint, passes : Vector.<Shader>):void { var lightType : uint = getLightProperty( sceneBindings, lightId, 'type' ); if (lightType != PointLight.LIGHT_TYPE) { var textureResource : ITextureResource = null; var renderTarget : RenderTarget = null; if (hasShadowBlurPass(sceneBindings, lightId)) textureResource = getLightProperty(sceneBindings, lightId, 'rawShadowMap'); else textureResource = getLightProperty(sceneBindings, lightId, 'shadowMap'); renderTarget = new RenderTarget( textureResource.width, textureResource.height, textureResource, 0, 0xffffffff ); passes.push(new ExponentialShadowMapShader(lightId, 4, lightId + 1, renderTarget)); } else { var cubeTexture : CubeTextureResource = getLightProperty( sceneBindings, lightId, 'shadowMap' ); var textureSize : uint = cubeTexture.size; for (var i : uint = 0; i < 6; ++i) passes.push(new ExponentialShadowMapShader( lightId, i, lightId + .1 * i, new RenderTarget(textureSize, textureSize, cubeTexture, i, 0xffffffff) )); } } private function hasShadowBlurPass(sceneBindings : DataBindingsProxy, lightId : uint) : Boolean { var quality : uint = getLightProperty(sceneBindings, lightId, 'shadowQuality'); return quality > ShadowMappingQuality.HARD; } private function lightPropertyExists(sceneBindings : DataBindingsProxy, lightId : uint, propertyName : String) : Boolean { return sceneBindings.propertyExists( LightDataProvider.getLightPropertyName(propertyName, lightId) ); } private function getLightProperty(sceneBindings : DataBindingsProxy, lightId : uint, propertyName : String) : * { return sceneBindings.getProperty( LightDataProvider.getLightPropertyName(propertyName, lightId) ); } } }
fix PhongEffect passes init. to avoid pushing passes for lights when light.enabled != true
fix PhongEffect passes init. to avoid pushing passes for lights when light.enabled != true
ActionScript
mit
aerys/minko-as3
9f3c0a53927fd89c8df57167a11e998520b1bde4
HLSPlugin/src/com/kaltura/hls/m2ts/M2TSFileHandler.as
HLSPlugin/src/com/kaltura/hls/m2ts/M2TSFileHandler.as
package com.kaltura.hls.m2ts { import com.kaltura.hls.HLSStreamingResource; import com.kaltura.hls.SubtitleTrait; import com.kaltura.hls.manifest.HLSManifestEncryptionKey; import com.kaltura.hls.muxing.AACParser; import com.kaltura.hls.subtitles.SubTitleParser; import com.kaltura.hls.subtitles.TextTrackCue; import com.kaltura.hls.HLSIndexHandler; import flash.utils.ByteArray; import flash.utils.IDataInput; import flash.utils.getTimer; import flash.external.ExternalInterface; import org.osmf.events.HTTPStreamingEvent; import org.osmf.net.httpstreaming.HTTPStreamingFileHandlerBase; import org.osmf.net.httpstreaming.flv.FLVTagAudio; /** * Process M2TS data into FLV data and return it for rendering via OSMF video system. */ public class M2TSFileHandler extends HTTPStreamingFileHandlerBase { public var subtitleTrait:SubtitleTrait; public var key:HLSManifestEncryptionKey; public var segmentId:uint = 0; public var resource:HLSStreamingResource; public var segmentUri:String; public var isBestEffort:Boolean = false; private var _parser:TSPacketParser; private var _curTimeOffset:uint; private var _buffer:ByteArray; private var _fragReadBuffer:ByteArray; private var _encryptedDataBuffer:ByteArray; private var _timeOrigin:uint; private var _timeOriginNeeded:Boolean; private var _segmentBeginSeconds:Number; private var _segmentLastSeconds:Number; private var _firstSeekTime:Number; private var _lastContinuityToken:String; private var _extendedIndexHandler:IExtraIndexHandlerState; private var _lastFLVMessageTime:Number; private var _injectingSubtitles:Boolean = false; private var _lastInjectedSubtitleTime:Number = 0; private var _decryptionIV:ByteArray; public function M2TSFileHandler() { super(); _encryptedDataBuffer = new ByteArray(); _parser = new TSPacketParser(); _parser.callback = handleFLVMessage; _timeOrigin = 0; _timeOriginNeeded = true; _segmentBeginSeconds = -1; _segmentLastSeconds = -1; _firstSeekTime = 0; _extendedIndexHandler = null; _lastContinuityToken = null; } public function get duration():Number { if(_segmentLastSeconds > _segmentBeginSeconds) return _segmentLastSeconds - _segmentBeginSeconds; return -1; } public function set extendedIndexHandler(handler:IExtraIndexHandlerState):void { _extendedIndexHandler = handler; } public function get extendedIndexHandler():IExtraIndexHandlerState { return _extendedIndexHandler; } public override function beginProcessFile(seek:Boolean, seekTime:Number):void { if( key && !key.isLoading && !key.isLoaded) throw new Error("Tried to process segment with key not set to load or loaded."); if(isBestEffort) { trace("Doing extra flush for best effort file handler"); _parser.flush(); _parser.clear(); } // Decryption reset if ( key ) { trace("Resetting _decryptionIV"); if ( key.iv ) _decryptionIV = key.retrieveStoredIV(); else _decryptionIV = HLSManifestEncryptionKey.createIVFromID( segmentId ); } var discontinuity:Boolean = false; if(_extendedIndexHandler) { var currentContinuityToken:String = _extendedIndexHandler.getCurrentContinuityToken(); if(_lastContinuityToken != currentContinuityToken) discontinuity = true; _lastContinuityToken = currentContinuityToken; } if(seek) { _parser.clear(); _timeOriginNeeded = true; if(_extendedIndexHandler) _firstSeekTime = _extendedIndexHandler.calculateFileOffsetForTime(seekTime) * 1000.0; } else if(discontinuity) { // Kick the converter state, but try to avoid upsetting the audio stream. _parser.clear(false); if(_segmentLastSeconds >= 0.0) { _timeOriginNeeded = true; if(_extendedIndexHandler) _firstSeekTime = _extendedIndexHandler.getCurrentSegmentOffset() * 1000.0; else _firstSeekTime = _segmentLastSeconds * 1000.0 + 30; } } else if(_extendedIndexHandler && _segmentLastSeconds >= 0.0) { var currentFileOffset:Number = _extendedIndexHandler.getCurrentSegmentOffset(); var delta:Number = currentFileOffset - _segmentLastSeconds; // If it's a big jump, handle it. if(delta > 5.0) { _timeOriginNeeded = true; _firstSeekTime = currentFileOffset * 1000.0; } } _segmentBeginSeconds = -1; _segmentLastSeconds = -1; _lastInjectedSubtitleTime = -1; _encryptedDataBuffer.length = 0; // Note the start as a debug event. _parser.sendDebugEvent( {type:"segmentStart", uri:segmentUri}); } public override function get inputBytesNeeded():Number { return 0; } public static var tmpBuffer:ByteArray = new ByteArray(); private function basicProcessFileSegment(input:IDataInput, _flush:Boolean):ByteArray { if ( key && !key.isLoaded ) { trace("basicProcessFileSegment - Waiting on key to download."); if(input) input.readBytes( _encryptedDataBuffer, _encryptedDataBuffer.length ); return null; } tmpBuffer.position = 0; tmpBuffer.length = 0; if ( _encryptedDataBuffer.length > 0 ) { // Restore any pending encrypted data. trace("Restoring " + _encryptedDataBuffer.length + " bytes of encrypted data."); _encryptedDataBuffer.position = 0; _encryptedDataBuffer.readBytes( tmpBuffer ); _encryptedDataBuffer.clear(); } if(!input) input = new ByteArray(); var amountToRead:int = input.bytesAvailable; if(amountToRead > 1024*128) amountToRead = 1024*128; trace("READING " + amountToRead + " OF " + input.bytesAvailable); if(amountToRead > 0) input.readBytes( tmpBuffer, tmpBuffer.length, amountToRead); if ( key ) { // We need to decrypt available data. var bytesToRead:uint = tmpBuffer.length; var leftoverBytes:uint = bytesToRead % 16; bytesToRead -= leftoverBytes; trace("Decrypting " + tmpBuffer.length + " bytes of encrypted data."); key.usePadding = false; if ( leftoverBytes > 0 ) { // Place any bytes left over (not divisible by 16) into our encrypted buffer // to decrypt later, when we have more bytes tmpBuffer.position = bytesToRead; tmpBuffer.readBytes( _encryptedDataBuffer ); tmpBuffer.length = bytesToRead; trace("Storing " + _encryptedDataBuffer.length + " bytes of encrypted data."); } else { // Attempt to unpad if our buffer is equally divisible by 16. // It could mean that we've reached the end of the file segment. key.usePadding = true; } // Store our current IV so we can use it do decrypt var currentIV:ByteArray = _decryptionIV; // Stash the IV for our next set of bytes - last block of the ciphertext. _decryptionIV = new ByteArray(); tmpBuffer.position = bytesToRead - 16; tmpBuffer.readBytes( _decryptionIV ); // Aaaaand... decrypt! tmpBuffer = key.decrypt( tmpBuffer, currentIV ); } // If it's AAC, process it. if(AACParser.probe(tmpBuffer)) { //trace("GOT AAC " + tmpBuffer.bytesAvailable); var aac:AACParser = new AACParser(); aac.parse(tmpBuffer, _fragReadHandler); //trace(" - returned " + _fragReadBuffer.length + " bytes!"); _fragReadBuffer.position = 0; if(isBestEffort && _fragReadBuffer.length > 0) { trace("Discarding AAC data from best effort."); _fragReadBuffer.length = 0; } return _fragReadBuffer; } // Parse it as MPEG TS data. var buffer:ByteArray = new ByteArray(); _buffer = buffer; _parser.appendBytes(tmpBuffer); if ( _flush ) { trace("flushing parser"); _parser.flush(); } _buffer = null; buffer.position = 0; // Throw it out if it's a best effort fetch. if(isBestEffort && buffer.length > 0) { trace("Discarding normal data from best effort."); buffer.length = 0; } if(buffer.length == 0) return null; return buffer; } private function _fragReadHandler(audioTags:Vector.<FLVTagAudio>, adif:ByteArray):void { _fragReadBuffer = new ByteArray(); var audioTag:FLVTagAudio = new FLVTagAudio(); audioTag.soundFormat = FLVTagAudio.SOUND_FORMAT_AAC; audioTag.data = adif; audioTag.isAACSequenceHeader = true; audioTag.write(_fragReadBuffer); for(var i:int=0; i<audioTags.length; i++) audioTags[i].write(_fragReadBuffer); } public override function processFileSegment(input:IDataInput):ByteArray { return basicProcessFileSegment(input, false); } public override function endProcessFile(input:IDataInput):ByteArray { if ( key && !key.isLoaded ) trace("HIT END OF FILE WITH NO KEY!"); if ( key ) key.usePadding = true; // Note the start as a debug event. _parser.sendDebugEvent( {type:"segmentEnd", uri:segmentUri}); var rv:ByteArray = basicProcessFileSegment(input, true); var elapsed:Number = _segmentLastSeconds - _segmentBeginSeconds; // Also update end time - don't trace it as we'll increase it incrementally. if(HLSIndexHandler.endTimeWitnesses[segmentUri] == null) { trace("Noting segment end time for " + segmentUri + " of " + _segmentLastSeconds); if(_segmentLastSeconds != _segmentLastSeconds) throw new Error("Got a NaN _segmentLastSeconds for " + segmentUri + "!"); HLSIndexHandler.endTimeWitnesses[segmentUri] = _segmentLastSeconds; } if(elapsed <= 0.0 && _extendedIndexHandler) { elapsed = _extendedIndexHandler.getTargetSegmentDuration(); // XXX fudge hack! } dispatchEvent(new HTTPStreamingEvent(HTTPStreamingEvent.FRAGMENT_DURATION, false, false, elapsed)); return rv; } public override function flushFileSegment(input:IDataInput):ByteArray { return basicProcessFileSegment(input || new ByteArray(), true); } private function handleFLVMessage(timestamp:uint, message:ByteArray):void { var timestampSeconds:Number = timestamp / 1000.0; if(_segmentBeginSeconds < 0) { _segmentBeginSeconds = timestampSeconds; trace("Noting segment start time for " + segmentUri + " of " + timestampSeconds); HLSIndexHandler.startTimeWitnesses[segmentUri] = timestampSeconds; } if(timestampSeconds > _segmentLastSeconds) _segmentLastSeconds = timestampSeconds; if(isBestEffort) return; var type:int = message[0]; ExternalInterface.call("onTag(" + timestampSeconds + ", " + type + ")"); //trace("Got " + message.length + " bytes at " + timestampSeconds + " seconds"); if(_timeOriginNeeded) { _timeOrigin = timestamp; _timeOriginNeeded = false; } if(timestamp < _timeOrigin) _timeOrigin = timestamp; // Encode the timestamp. message[6] = (timestamp ) & 0xff; message[5] = (timestamp >> 8) & 0xff; message[4] = (timestamp >> 16) & 0xff; message[7] = (timestamp >> 24) & 0xff; var lastMsgTime:Number = _lastFLVMessageTime; _lastFLVMessageTime = timestampSeconds; // If timer was reset due to seek, reset last subtitle time if(timestampSeconds < _lastInjectedSubtitleTime) { trace("Bumping back on subtitle threshold.") _lastInjectedSubtitleTime = timestampSeconds; } // Inject any subtitle tags between messages injectSubtitles( _lastInjectedSubtitleTime + 0.001, timestampSeconds ); //trace( "MESSAGE RECEIVED " + timestampSeconds ); _buffer.writeBytes(message); } protected var _lastCue:TextTrackCue = null; private function injectSubtitles( startTime:Number, endTime:Number ):void { //if(startTime > endTime) trace("***** BAD BEHAVIOR " + startTime + " " + endTime); //trace("Inject subtitles " + startTime + " " + endTime); // Early out if no subtitles, no time has elapsed or we are already injecting subtitles if ( !subtitleTrait || endTime - startTime <= 0 || _injectingSubtitles ) return; var subtitles:Vector.<SubTitleParser> = subtitleTrait.activeSubtitles; if ( !subtitles ) return; _injectingSubtitles = true; var subtitleCount:int = subtitles.length; for ( var i:int = 0; i < subtitleCount; i++ ) { var subtitle:SubTitleParser = subtitles[ i ]; if ( subtitle.startTime > endTime ) break; 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) { _parser.createAndSendCaptionMessage( cue.startTime, cue.text, subtitleTrait.language ); _lastInjectedSubtitleTime = cue.startTime; _lastCue = cue; } } } _injectingSubtitles = false; } } }
package com.kaltura.hls.m2ts { import com.kaltura.hls.HLSStreamingResource; import com.kaltura.hls.SubtitleTrait; import com.kaltura.hls.manifest.HLSManifestEncryptionKey; import com.kaltura.hls.muxing.AACParser; import com.kaltura.hls.subtitles.SubTitleParser; import com.kaltura.hls.subtitles.TextTrackCue; import com.kaltura.hls.HLSIndexHandler; import flash.utils.ByteArray; import flash.utils.IDataInput; import flash.utils.getTimer; import flash.external.ExternalInterface; import org.osmf.events.HTTPStreamingEvent; import org.osmf.net.httpstreaming.HTTPStreamingFileHandlerBase; import org.osmf.net.httpstreaming.flv.FLVTagAudio; /** * Process M2TS data into FLV data and return it for rendering via OSMF video system. */ public class M2TSFileHandler extends HTTPStreamingFileHandlerBase { public var subtitleTrait:SubtitleTrait; public var key:HLSManifestEncryptionKey; public var segmentId:uint = 0; public var resource:HLSStreamingResource; public var segmentUri:String; public var isBestEffort:Boolean = false; private var _parser:TSPacketParser; private var _curTimeOffset:uint; private var _buffer:ByteArray; private var _fragReadBuffer:ByteArray; private var _encryptedDataBuffer:ByteArray; private var _timeOrigin:uint; private var _timeOriginNeeded:Boolean; private var _segmentBeginSeconds:Number; private var _segmentLastSeconds:Number; private var _firstSeekTime:Number; private var _lastContinuityToken:String; private var _extendedIndexHandler:IExtraIndexHandlerState; private var _lastFLVMessageTime:Number; private var _injectingSubtitles:Boolean = false; private var _lastInjectedSubtitleTime:Number = 0; private var _decryptionIV:ByteArray; public function M2TSFileHandler() { super(); _encryptedDataBuffer = new ByteArray(); _parser = new TSPacketParser(); _parser.callback = handleFLVMessage; _timeOrigin = 0; _timeOriginNeeded = true; _segmentBeginSeconds = -1; _segmentLastSeconds = -1; _firstSeekTime = 0; _extendedIndexHandler = null; _lastContinuityToken = null; } public function get duration():Number { if(_segmentLastSeconds > _segmentBeginSeconds) return _segmentLastSeconds - _segmentBeginSeconds; return -1; } public function set extendedIndexHandler(handler:IExtraIndexHandlerState):void { _extendedIndexHandler = handler; } public function get extendedIndexHandler():IExtraIndexHandlerState { return _extendedIndexHandler; } public override function beginProcessFile(seek:Boolean, seekTime:Number):void { if( key && !key.isLoading && !key.isLoaded) throw new Error("Tried to process segment with key not set to load or loaded."); if(isBestEffort) { trace("Doing extra flush for best effort file handler"); _parser.flush(); _parser.clear(); } // Decryption reset if ( key ) { trace("Resetting _decryptionIV"); if ( key.iv ) _decryptionIV = key.retrieveStoredIV(); else _decryptionIV = HLSManifestEncryptionKey.createIVFromID( segmentId ); } var discontinuity:Boolean = false; if(_extendedIndexHandler) { var currentContinuityToken:String = _extendedIndexHandler.getCurrentContinuityToken(); if(_lastContinuityToken != currentContinuityToken) discontinuity = true; _lastContinuityToken = currentContinuityToken; } if(seek) { _parser.clear(); _timeOriginNeeded = true; if(_extendedIndexHandler) _firstSeekTime = _extendedIndexHandler.calculateFileOffsetForTime(seekTime) * 1000.0; } else if(discontinuity) { // Kick the converter state, but try to avoid upsetting the audio stream. _parser.clear(false); if(_segmentLastSeconds >= 0.0) { _timeOriginNeeded = true; if(_extendedIndexHandler) _firstSeekTime = _extendedIndexHandler.getCurrentSegmentOffset() * 1000.0; else _firstSeekTime = _segmentLastSeconds * 1000.0 + 30; } } else if(_extendedIndexHandler && _segmentLastSeconds >= 0.0) { var currentFileOffset:Number = _extendedIndexHandler.getCurrentSegmentOffset(); var delta:Number = currentFileOffset - _segmentLastSeconds; // If it's a big jump, handle it. if(delta > 5.0) { _timeOriginNeeded = true; _firstSeekTime = currentFileOffset * 1000.0; } } _segmentBeginSeconds = -1; _segmentLastSeconds = -1; _lastInjectedSubtitleTime = -1; _encryptedDataBuffer.length = 0; // Note the start as a debug event. _parser.sendDebugEvent( {type:"segmentStart", uri:segmentUri}); } public override function get inputBytesNeeded():Number { return 0; } public static var tmpBuffer:ByteArray = new ByteArray(); private function basicProcessFileSegment(input:IDataInput, _flush:Boolean):ByteArray { if ( key && !key.isLoaded ) { trace("basicProcessFileSegment - Waiting on key to download."); if(input) input.readBytes( _encryptedDataBuffer, _encryptedDataBuffer.length ); return null; } tmpBuffer.position = 0; tmpBuffer.length = 0; if ( _encryptedDataBuffer.length > 0 ) { // Restore any pending encrypted data. trace("Restoring " + _encryptedDataBuffer.length + " bytes of encrypted data."); _encryptedDataBuffer.position = 0; _encryptedDataBuffer.readBytes( tmpBuffer ); _encryptedDataBuffer.clear(); } if(!input) input = new ByteArray(); var amountToRead:int = input.bytesAvailable; if(amountToRead > 1024*128) amountToRead = 1024*128; trace("READING " + amountToRead + " OF " + input.bytesAvailable); if(amountToRead > 0) input.readBytes( tmpBuffer, tmpBuffer.length, amountToRead); if ( key ) { // We need to decrypt available data. var bytesToRead:uint = tmpBuffer.length; var leftoverBytes:uint = bytesToRead % 16; bytesToRead -= leftoverBytes; trace("Decrypting " + tmpBuffer.length + " bytes of encrypted data."); key.usePadding = false; if ( leftoverBytes > 0 ) { // Place any bytes left over (not divisible by 16) into our encrypted buffer // to decrypt later, when we have more bytes tmpBuffer.position = bytesToRead; tmpBuffer.readBytes( _encryptedDataBuffer ); tmpBuffer.length = bytesToRead; trace("Storing " + _encryptedDataBuffer.length + " bytes of encrypted data."); } else { // Attempt to unpad if our buffer is equally divisible by 16. // It could mean that we've reached the end of the file segment. key.usePadding = true; } // Store our current IV so we can use it do decrypt var currentIV:ByteArray = _decryptionIV; // Stash the IV for our next set of bytes - last block of the ciphertext. _decryptionIV = new ByteArray(); tmpBuffer.position = bytesToRead - 16; tmpBuffer.readBytes( _decryptionIV ); // Aaaaand... decrypt! tmpBuffer = key.decrypt( tmpBuffer, currentIV ); } // If it's AAC, process it. if(AACParser.probe(tmpBuffer)) { //trace("GOT AAC " + tmpBuffer.bytesAvailable); var aac:AACParser = new AACParser(); aac.parse(tmpBuffer, _fragReadHandler); //trace(" - returned " + _fragReadBuffer.length + " bytes!"); _fragReadBuffer.position = 0; if(isBestEffort && _fragReadBuffer.length > 0) { trace("Discarding AAC data from best effort."); _fragReadBuffer.length = 0; } return _fragReadBuffer; } // Parse it as MPEG TS data. var buffer:ByteArray = new ByteArray(); _buffer = buffer; _parser.appendBytes(tmpBuffer); if ( _flush ) { trace("flushing parser"); _parser.flush(); } _buffer = null; buffer.position = 0; // Throw it out if it's a best effort fetch. if(isBestEffort && buffer.length > 0) { trace("Discarding normal data from best effort."); buffer.length = 0; } if(buffer.length == 0) return null; return buffer; } private function _fragReadHandler(audioTags:Vector.<FLVTagAudio>, adif:ByteArray):void { _fragReadBuffer = new ByteArray(); var audioTag:FLVTagAudio = new FLVTagAudio(); audioTag.soundFormat = FLVTagAudio.SOUND_FORMAT_AAC; audioTag.data = adif; audioTag.isAACSequenceHeader = true; audioTag.write(_fragReadBuffer); for(var i:int=0; i<audioTags.length; i++) audioTags[i].write(_fragReadBuffer); } public override function processFileSegment(input:IDataInput):ByteArray { return basicProcessFileSegment(input, false); } public override function endProcessFile(input:IDataInput):ByteArray { if ( key && !key.isLoaded ) trace("HIT END OF FILE WITH NO KEY!"); if ( key ) key.usePadding = true; // Note the start as a debug event. _parser.sendDebugEvent( {type:"segmentEnd", uri:segmentUri}); var rv:ByteArray = basicProcessFileSegment(input, true); var elapsed:Number = _segmentLastSeconds - _segmentBeginSeconds; // Also update end time - don't trace it as we'll increase it incrementally. if(HLSIndexHandler.endTimeWitnesses[segmentUri] == null && !isBestEffort) { trace("Noting segment end time for " + segmentUri + " of " + _segmentLastSeconds); if(_segmentLastSeconds != _segmentLastSeconds) throw new Error("Got a NaN _segmentLastSeconds for " + segmentUri + "!"); HLSIndexHandler.endTimeWitnesses[segmentUri] = _segmentLastSeconds; } if(elapsed <= 0.0 && _extendedIndexHandler) { elapsed = _extendedIndexHandler.getTargetSegmentDuration(); // XXX fudge hack! } dispatchEvent(new HTTPStreamingEvent(HTTPStreamingEvent.FRAGMENT_DURATION, false, false, elapsed)); return rv; } public override function flushFileSegment(input:IDataInput):ByteArray { return basicProcessFileSegment(input || new ByteArray(), true); } private function handleFLVMessage(timestamp:uint, message:ByteArray):void { var timestampSeconds:Number = timestamp / 1000.0; if(_segmentBeginSeconds < 0) { _segmentBeginSeconds = timestampSeconds; trace("Noting segment start time for " + segmentUri + " of " + timestampSeconds); HLSIndexHandler.startTimeWitnesses[segmentUri] = timestampSeconds; } if(timestampSeconds > _segmentLastSeconds) _segmentLastSeconds = timestampSeconds; if(isBestEffort) return; var type:int = message[0]; ExternalInterface.call("onTag(" + timestampSeconds + ", " + type + ")"); //trace("Got " + message.length + " bytes at " + timestampSeconds + " seconds"); if(_timeOriginNeeded) { _timeOrigin = timestamp; _timeOriginNeeded = false; } if(timestamp < _timeOrigin) _timeOrigin = timestamp; // Encode the timestamp. message[6] = (timestamp ) & 0xff; message[5] = (timestamp >> 8) & 0xff; message[4] = (timestamp >> 16) & 0xff; message[7] = (timestamp >> 24) & 0xff; var lastMsgTime:Number = _lastFLVMessageTime; _lastFLVMessageTime = timestampSeconds; // If timer was reset due to seek, reset last subtitle time if(timestampSeconds < _lastInjectedSubtitleTime) { trace("Bumping back on subtitle threshold.") _lastInjectedSubtitleTime = timestampSeconds; } // Inject any subtitle tags between messages injectSubtitles( _lastInjectedSubtitleTime + 0.001, timestampSeconds ); //trace( "MESSAGE RECEIVED " + timestampSeconds ); _buffer.writeBytes(message); } protected var _lastCue:TextTrackCue = null; private function injectSubtitles( startTime:Number, endTime:Number ):void { //if(startTime > endTime) trace("***** BAD BEHAVIOR " + startTime + " " + endTime); //trace("Inject subtitles " + startTime + " " + endTime); // Early out if no subtitles, no time has elapsed or we are already injecting subtitles if ( !subtitleTrait || endTime - startTime <= 0 || _injectingSubtitles ) return; var subtitles:Vector.<SubTitleParser> = subtitleTrait.activeSubtitles; if ( !subtitles ) return; _injectingSubtitles = true; var subtitleCount:int = subtitles.length; for ( var i:int = 0; i < subtitleCount; i++ ) { var subtitle:SubTitleParser = subtitles[ i ]; if ( subtitle.startTime > endTime ) break; 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) { _parser.createAndSendCaptionMessage( cue.startTime, cue.text, subtitleTrait.language ); _lastInjectedSubtitleTime = cue.startTime; _lastCue = cue; } } } _injectingSubtitles = false; } } }
Fix bad segment end estimation.
Fix bad segment end estimation.
ActionScript
agpl-3.0
kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF
db4cc87c69b8b39da8876107ce846060a168343c
src/org/mangui/hls/stream/HLSNetStream.as
src/org/mangui/hls/stream/HLSNetStream.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.stream { import org.mangui.hls.controller.BufferThresholdController; import org.mangui.hls.event.HLSPlayMetrics; import org.mangui.hls.event.HLSError; import org.mangui.hls.event.HLSEvent; import org.mangui.hls.constant.HLSSeekStates; import org.mangui.hls.constant.HLSPlayStates; import org.mangui.hls.flv.FLVTag; import org.mangui.hls.HLS; import org.mangui.hls.HLSSettings; import org.mangui.hls.utils.Hex; import flash.events.Event; import flash.events.NetStatusEvent; import flash.events.TimerEvent; import flash.net.*; import flash.utils.*; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } /** Class that overrides standard flash.net.NetStream class, keeps the buffer filled, handles seek and play state * * play state transition : * FROM TO condition * HLSPlayStates.IDLE HLSPlayStates.PLAYING_BUFFERING play()/play2()/seek() called * HLSPlayStates.PLAYING_BUFFERING HLSPlayStates.PLAYING buflen > minBufferLength * HLSPlayStates.PAUSED_BUFFERING HLSPlayStates.PAUSED buflen > minBufferLength * HLSPlayStates.PLAYING HLSPlayStates.PLAYING_BUFFERING buflen < lowBufferLength * HLSPlayStates.PAUSED HLSPlayStates.PAUSED_BUFFERING buflen < lowBufferLength */ public class HLSNetStream extends NetStream { /** Reference to the framework controller. **/ private var _hls : HLS; /** reference to buffer threshold controller */ private var _bufferThresholdController : BufferThresholdController; /** FLV Tag Buffer . **/ private var _streamBuffer : StreamBuffer; /** Timer used to check buffer and position. **/ private var _timer : Timer; /** Current playback state. **/ private var _playbackState : String; /** Current seek state. **/ private var _seekState : String; /** current playback level **/ private var _playbackLevel : int; /** Netstream client proxy */ private var _client : HLSNetStreamClient; /** Create the buffer. **/ public function HLSNetStream(connection : NetConnection, hls : HLS, streamBuffer : StreamBuffer) : void { super(connection); super.bufferTime = 0.1; _hls = hls; _bufferThresholdController = new BufferThresholdController(hls); _streamBuffer = streamBuffer; _playbackState = HLSPlayStates.IDLE; _seekState = HLSSeekStates.IDLE; _timer = new Timer(100, 0); _timer.addEventListener(TimerEvent.TIMER, _checkBuffer); _client = new HLSNetStreamClient(); _client.registerCallback("onHLSFragmentChange", onHLSFragmentChange); _client.registerCallback("onID3Data", onID3Data); super.client = _client; }; public function onHLSFragmentChange(level : int, seqnum : int, cc : int, audio_only : Boolean, program_date : Number, width : int, height : int, ... tags) : void { CONFIG::LOGGING { Log.debug("playing fragment(level/sn/cc):" + level + "/" + seqnum + "/" + cc); } _playbackLevel = level; var tag_list : Array = new Array(); for (var i : uint = 0; i < tags.length; i++) { tag_list.push(tags[i]); CONFIG::LOGGING { Log.debug("custom tag:" + tags[i]); } } _hls.dispatchEvent(new HLSEvent(HLSEvent.FRAGMENT_PLAYING, new HLSPlayMetrics(level, seqnum, cc, audio_only, program_date, width, height, tag_list))); } // function is called by SCRIPT in FLV public function onID3Data(data : ByteArray) : void { var dump : String = "unset"; // we dump the content as hex to get it to the Javascript in the browser. // from lots of searching, we could use base64, but even then, the decode would // not be native, so hex actually seems more efficient dump = Hex.fromArray(data); CONFIG::LOGGING { Log.debug("id3:" + dump); } _hls.dispatchEvent(new HLSEvent(HLSEvent.ID3_UPDATED, dump)); } /** timer function, check/update NetStream state, and append tags if needed **/ private function _checkBuffer(e : Event) : void { var buffer : Number = this.bufferLength; // Log.info("netstream/total:" + super.bufferLength + "/" + this.bufferLength); // Set playback state. no need to check buffer status if seeking if (_seekState != HLSSeekStates.SEEKING) { // check low buffer condition if (buffer <= 0.1) { if (_streamBuffer.reachedEnd) { // Last tag done? Then append sequence end. super.appendBytesAction(NetStreamAppendBytesAction.END_SEQUENCE); super.appendBytes(new ByteArray()); // reach end of playlist + playback complete (as buffer is empty). // stop timer, report event and switch to IDLE mode. _timer.stop(); CONFIG::LOGGING { Log.debug("reached end of VOD playlist, notify playback complete"); } _hls.dispatchEvent(new HLSEvent(HLSEvent.PLAYBACK_COMPLETE)); _setPlaybackState(HLSPlayStates.IDLE); _setSeekState(HLSSeekStates.IDLE); return; } else { // buffer <= 0.1 and not EOS, pause playback super.pause(); } } // if buffer len is below lowBufferLength, get into buffering state if (!_streamBuffer.reachedEnd && buffer < _bufferThresholdController.lowBufferLength) { if (_playbackState == HLSPlayStates.PLAYING) { // low buffer condition and play state. switch to play buffering state _setPlaybackState(HLSPlayStates.PLAYING_BUFFERING); } else if (_playbackState == HLSPlayStates.PAUSED) { // low buffer condition and pause state. switch to paused buffering state _setPlaybackState(HLSPlayStates.PAUSED_BUFFERING); } } // if buffer len is above minBufferLength, get out of buffering state if (buffer >= _bufferThresholdController.minBufferLength || _streamBuffer.reachedEnd) { if (_playbackState == HLSPlayStates.PLAYING_BUFFERING) { CONFIG::LOGGING { Log.debug("resume playback"); } // resume playback in case it was paused, this can happen if buffer was in really low condition (less than 0.1s) super.resume(); _setPlaybackState(HLSPlayStates.PLAYING); } else if (_playbackState == HLSPlayStates.PAUSED_BUFFERING) { _setPlaybackState(HLSPlayStates.PAUSED); } } } }; /** Return the current playback state. **/ public function get playbackState() : String { return _playbackState; }; /** Return the current seek state. **/ public function get seekState() : String { return _seekState; }; /** Return the current playback quality level **/ public function get playbackLevel() : int { return _playbackLevel; }; /** append tags to NetStream **/ public function appendTags(tags : Vector.<FLVTag>) : void { if (_seekState == HLSSeekStates.SEEKING) { /* this is our first injection after seek(), let's flush netstream now this is to avoid black screen during seek command */ super.close(); CONFIG::FLASH_11_1 { try { super.useHardwareDecoder = HLSSettings.useHardwareVideoDecoder; } catch(e : Error) { } } super.play(null); super.appendBytesAction(NetStreamAppendBytesAction.RESET_SEEK); // immediatly pause NetStream, it will be resumed when enough data will be buffered in the NetStream super.pause(); } // append all tags for each (var tagBuffer : FLVTag in tags) { try { if (tagBuffer.type == FLVTag.DISCONTINUITY) { super.appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN); super.appendBytes(FLVTag.getHeader()); } super.appendBytes(tagBuffer.data); } catch (error : Error) { var hlsError : HLSError = new HLSError(HLSError.TAG_APPENDING_ERROR, null, tagBuffer.type + ": " + error.message); _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, hlsError)); } } if (_seekState == HLSSeekStates.SEEKING) { // dispatch event to mimic NetStream behaviour dispatchEvent(new NetStatusEvent(NetStatusEvent.NET_STATUS, false, false, {code:"NetStream.Seek.Notify", level:"status"})); _setSeekState(HLSSeekStates.SEEKED); } }; /** Change playback state. **/ private function _setPlaybackState(state : String) : void { if (state != _playbackState) { CONFIG::LOGGING { Log.debug('[PLAYBACK_STATE] from ' + _playbackState + ' to ' + state); } _playbackState = state; _hls.dispatchEvent(new HLSEvent(HLSEvent.PLAYBACK_STATE, _playbackState)); } }; /** Change seeking state. **/ private function _setSeekState(state : String) : void { if (state != _seekState) { CONFIG::LOGGING { Log.debug('[SEEK_STATE] from ' + _seekState + ' to ' + state); } _seekState = state; _hls.dispatchEvent(new HLSEvent(HLSEvent.SEEK_STATE, _seekState)); } }; override public function play(...args) : void { var _playStart : Number; if (args.length >= 2) { _playStart = Number(args[1]); } else { _playStart = -1; } CONFIG::LOGGING { Log.info("HLSNetStream:play(" + _playStart + ")"); } seek(_playStart); _setPlaybackState(HLSPlayStates.PLAYING_BUFFERING); } override public function play2(param : NetStreamPlayOptions) : void { CONFIG::LOGGING { Log.info("HLSNetStream:play2(" + param.start + ")"); } seek(param.start); _setPlaybackState(HLSPlayStates.PLAYING_BUFFERING); } /** Pause playback. **/ override public function pause() : void { CONFIG::LOGGING { Log.info("HLSNetStream:pause"); } if (_playbackState == HLSPlayStates.PLAYING) { super.pause(); _setPlaybackState(HLSPlayStates.PAUSED); } else if (_playbackState == HLSPlayStates.PLAYING_BUFFERING) { super.pause(); _setPlaybackState(HLSPlayStates.PAUSED_BUFFERING); } }; /** Resume playback. **/ override public function resume() : void { CONFIG::LOGGING { Log.info("HLSNetStream:resume"); } if (_playbackState == HLSPlayStates.PAUSED) { super.resume(); _setPlaybackState(HLSPlayStates.PLAYING); } else if (_playbackState == HLSPlayStates.PAUSED_BUFFERING) { // dont resume NetStream here, it will be resumed by Timer. this avoids resuming playback while seeking is in progress _setPlaybackState(HLSPlayStates.PLAYING_BUFFERING); } }; /** get Buffer Length **/ override public function get bufferLength() : Number { return netStreamBufferLength + _streamBuffer.bufferLength; }; /** get Back Buffer Length **/ override public function get backBufferLength() : Number { return _streamBuffer.backBufferLength; }; public function get netStreamBufferLength() : Number { if (_seekState == HLSSeekStates.SEEKING) { return 0; } else { return super.bufferLength; } }; /** Start playing data in the buffer. **/ override public function seek(position : Number) : void { CONFIG::LOGGING { Log.info("HLSNetStream:seek(" + position + ")"); } _streamBuffer.seek(position); _setSeekState(HLSSeekStates.SEEKING); /* if HLS was in paused state before seeking, * switch to paused buffering state * otherwise, switch to playing buffering state */ switch(_playbackState) { case HLSPlayStates.PAUSED: case HLSPlayStates.PAUSED_BUFFERING: _setPlaybackState(HLSPlayStates.PAUSED_BUFFERING); break; case HLSPlayStates.PLAYING: case HLSPlayStates.PLAYING_BUFFERING: _setPlaybackState(HLSPlayStates.PLAYING_BUFFERING); break; default: break; } /* always pause NetStream while seeking, even if we are in play state * in that case, NetStream will be resumed during next call to appendTags() */ super.pause(); _timer.start(); }; public override function set client(client : Object) : void { _client.delegate = client; }; public override function get client() : Object { return _client.delegate; } /** Stop playback. **/ override public function close() : void { CONFIG::LOGGING { Log.info("HLSNetStream:close"); } super.close(); _streamBuffer.stop(); _timer.stop(); _setPlaybackState(HLSPlayStates.IDLE); _setSeekState(HLSSeekStates.IDLE); }; public function dispose_() : void { close(); _bufferThresholdController.dispose(); } } }
/* 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.stream { import org.mangui.hls.controller.BufferThresholdController; import org.mangui.hls.event.HLSPlayMetrics; import org.mangui.hls.event.HLSError; import org.mangui.hls.event.HLSEvent; import org.mangui.hls.constant.HLSSeekStates; import org.mangui.hls.constant.HLSPlayStates; import org.mangui.hls.flv.FLVTag; import org.mangui.hls.HLS; import org.mangui.hls.HLSSettings; import org.mangui.hls.utils.Hex; import flash.events.Event; import flash.events.NetStatusEvent; import flash.events.TimerEvent; import flash.net.*; import flash.utils.*; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } /** Class that overrides standard flash.net.NetStream class, keeps the buffer filled, handles seek and play state * * play state transition : * FROM TO condition * HLSPlayStates.IDLE HLSPlayStates.PLAYING_BUFFERING play()/play2()/seek() called * HLSPlayStates.PLAYING_BUFFERING HLSPlayStates.PLAYING buflen > minBufferLength * HLSPlayStates.PAUSED_BUFFERING HLSPlayStates.PAUSED buflen > minBufferLength * HLSPlayStates.PLAYING HLSPlayStates.PLAYING_BUFFERING buflen < lowBufferLength * HLSPlayStates.PAUSED HLSPlayStates.PAUSED_BUFFERING buflen < lowBufferLength */ public class HLSNetStream extends NetStream { /** Reference to the framework controller. **/ private var _hls : HLS; /** reference to buffer threshold controller */ private var _bufferThresholdController : BufferThresholdController; /** FLV Tag Buffer . **/ private var _streamBuffer : StreamBuffer; /** Timer used to check buffer and position. **/ private var _timer : Timer; /** Current playback state. **/ private var _playbackState : String; /** Current seek state. **/ private var _seekState : String; /** current playback level **/ private var _playbackLevel : int; /** Netstream client proxy */ private var _client : HLSNetStreamClient; /** Create the buffer. **/ public function HLSNetStream(connection : NetConnection, hls : HLS, streamBuffer : StreamBuffer) : void { super(connection); super.bufferTime = 0.1; _hls = hls; _bufferThresholdController = new BufferThresholdController(hls); _streamBuffer = streamBuffer; _playbackState = HLSPlayStates.IDLE; _seekState = HLSSeekStates.IDLE; _timer = new Timer(100, 0); _timer.addEventListener(TimerEvent.TIMER, _checkBuffer); _client = new HLSNetStreamClient(); _client.registerCallback("onHLSFragmentChange", onHLSFragmentChange); _client.registerCallback("onID3Data", onID3Data); super.client = _client; }; public function onHLSFragmentChange(level : int, seqnum : int, cc : int, audio_only : Boolean, program_date : Number, width : int, height : int, ... tags) : void { CONFIG::LOGGING { Log.debug("playing fragment(level/sn/cc):" + level + "/" + seqnum + "/" + cc); } _playbackLevel = level; var tag_list : Array = new Array(); for (var i : uint = 0; i < tags.length; i++) { tag_list.push(tags[i]); CONFIG::LOGGING { Log.debug("custom tag:" + tags[i]); } } _hls.dispatchEvent(new HLSEvent(HLSEvent.FRAGMENT_PLAYING, new HLSPlayMetrics(level, seqnum, cc, audio_only, program_date, width, height, tag_list))); } // function is called by SCRIPT in FLV public function onID3Data(data : ByteArray) : void { var dump : String = "unset"; // we dump the content as hex to get it to the Javascript in the browser. // from lots of searching, we could use base64, but even then, the decode would // not be native, so hex actually seems more efficient dump = Hex.fromArray(data); CONFIG::LOGGING { Log.debug("id3:" + dump); } _hls.dispatchEvent(new HLSEvent(HLSEvent.ID3_UPDATED, dump)); } /** timer function, check/update NetStream state, and append tags if needed **/ private function _checkBuffer(e : Event) : void { var buffer : Number = this.bufferLength; // Log.info("netstream/total:" + super.bufferLength + "/" + this.bufferLength); // Set playback state. no need to check buffer status if seeking if (_seekState != HLSSeekStates.SEEKING) { // check low buffer condition if (buffer <= 0.1) { if (_streamBuffer.reachedEnd) { // Last tag done? Then append sequence end. super.appendBytesAction(NetStreamAppendBytesAction.END_SEQUENCE); super.appendBytes(new ByteArray()); // reach end of playlist + playback complete (as buffer is empty). // stop timer, report event and switch to IDLE mode. _timer.stop(); CONFIG::LOGGING { Log.debug("reached end of VOD playlist, notify playback complete"); } _hls.dispatchEvent(new HLSEvent(HLSEvent.PLAYBACK_COMPLETE)); _setPlaybackState(HLSPlayStates.IDLE); _setSeekState(HLSSeekStates.IDLE); return; } else { // buffer <= 0.1 and not EOS, pause playback super.pause(); } } // if buffer len is below lowBufferLength, get into buffering state if (!_streamBuffer.reachedEnd && buffer < _bufferThresholdController.lowBufferLength) { if (_playbackState == HLSPlayStates.PLAYING) { // low buffer condition and play state. switch to play buffering state _setPlaybackState(HLSPlayStates.PLAYING_BUFFERING); } else if (_playbackState == HLSPlayStates.PAUSED) { // low buffer condition and pause state. switch to paused buffering state _setPlaybackState(HLSPlayStates.PAUSED_BUFFERING); } } // if buffer len is above minBufferLength, get out of buffering state if (buffer >= _bufferThresholdController.minBufferLength || _streamBuffer.reachedEnd) { if (_playbackState == HLSPlayStates.PLAYING_BUFFERING) { CONFIG::LOGGING { Log.debug("resume playback"); } // resume playback in case it was paused, this can happen if buffer was in really low condition (less than 0.1s) super.resume(); _setPlaybackState(HLSPlayStates.PLAYING); } else if (_playbackState == HLSPlayStates.PAUSED_BUFFERING) { _setPlaybackState(HLSPlayStates.PAUSED); } } } }; /** Return the current playback state. **/ public function get playbackState() : String { return _playbackState; }; /** Return the current seek state. **/ public function get seekState() : String { return _seekState; }; /** Return the current playback quality level **/ public function get playbackLevel() : int { return _playbackLevel; }; /** append tags to NetStream **/ public function appendTags(tags : Vector.<FLVTag>) : void { if (_seekState == HLSSeekStates.SEEKING) { /* this is our first injection after seek(), let's flush netstream now this is to avoid black screen during seek command */ super.close(); CONFIG::FLASH_11_1 { try { super.useHardwareDecoder = HLSSettings.useHardwareVideoDecoder; } catch(e : Error) { } } super.play(null); super.appendBytesAction(NetStreamAppendBytesAction.RESET_SEEK); // immediatly pause NetStream, it will be resumed when enough data will be buffered in the NetStream super.pause(); // for each (var tag : FLVTag in tags) { // CONFIG::LOGGING { // Log.debug2('inject type/dts/pts:' + tag.typeString + '/' + tag.dts + '/' + tag.pts); // } // } } // append all tags for each (var tagBuffer : FLVTag in tags) { try { if (tagBuffer.type == FLVTag.DISCONTINUITY) { super.appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN); super.appendBytes(FLVTag.getHeader()); } super.appendBytes(tagBuffer.data); } catch (error : Error) { var hlsError : HLSError = new HLSError(HLSError.TAG_APPENDING_ERROR, null, tagBuffer.type + ": " + error.message); _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, hlsError)); } } if (_seekState == HLSSeekStates.SEEKING) { // dispatch event to mimic NetStream behaviour dispatchEvent(new NetStatusEvent(NetStatusEvent.NET_STATUS, false, false, {code:"NetStream.Seek.Notify", level:"status"})); _setSeekState(HLSSeekStates.SEEKED); } }; /** Change playback state. **/ private function _setPlaybackState(state : String) : void { if (state != _playbackState) { CONFIG::LOGGING { Log.debug('[PLAYBACK_STATE] from ' + _playbackState + ' to ' + state); } _playbackState = state; _hls.dispatchEvent(new HLSEvent(HLSEvent.PLAYBACK_STATE, _playbackState)); } }; /** Change seeking state. **/ private function _setSeekState(state : String) : void { if (state != _seekState) { CONFIG::LOGGING { Log.debug('[SEEK_STATE] from ' + _seekState + ' to ' + state); } _seekState = state; _hls.dispatchEvent(new HLSEvent(HLSEvent.SEEK_STATE, _seekState)); } }; override public function play(...args) : void { var _playStart : Number; if (args.length >= 2) { _playStart = Number(args[1]); } else { _playStart = -1; } CONFIG::LOGGING { Log.info("HLSNetStream:play(" + _playStart + ")"); } seek(_playStart); _setPlaybackState(HLSPlayStates.PLAYING_BUFFERING); } override public function play2(param : NetStreamPlayOptions) : void { CONFIG::LOGGING { Log.info("HLSNetStream:play2(" + param.start + ")"); } seek(param.start); _setPlaybackState(HLSPlayStates.PLAYING_BUFFERING); } /** Pause playback. **/ override public function pause() : void { CONFIG::LOGGING { Log.info("HLSNetStream:pause"); } if (_playbackState == HLSPlayStates.PLAYING) { super.pause(); _setPlaybackState(HLSPlayStates.PAUSED); } else if (_playbackState == HLSPlayStates.PLAYING_BUFFERING) { super.pause(); _setPlaybackState(HLSPlayStates.PAUSED_BUFFERING); } }; /** Resume playback. **/ override public function resume() : void { CONFIG::LOGGING { Log.info("HLSNetStream:resume"); } if (_playbackState == HLSPlayStates.PAUSED) { super.resume(); _setPlaybackState(HLSPlayStates.PLAYING); } else if (_playbackState == HLSPlayStates.PAUSED_BUFFERING) { // dont resume NetStream here, it will be resumed by Timer. this avoids resuming playback while seeking is in progress _setPlaybackState(HLSPlayStates.PLAYING_BUFFERING); } }; /** get Buffer Length **/ override public function get bufferLength() : Number { return netStreamBufferLength + _streamBuffer.bufferLength; }; /** get Back Buffer Length **/ override public function get backBufferLength() : Number { return _streamBuffer.backBufferLength; }; public function get netStreamBufferLength() : Number { if (_seekState == HLSSeekStates.SEEKING) { return 0; } else { return super.bufferLength; } }; /** Start playing data in the buffer. **/ override public function seek(position : Number) : void { CONFIG::LOGGING { Log.info("HLSNetStream:seek(" + position + ")"); } _streamBuffer.seek(position); _setSeekState(HLSSeekStates.SEEKING); /* if HLS was in paused state before seeking, * switch to paused buffering state * otherwise, switch to playing buffering state */ switch(_playbackState) { case HLSPlayStates.PAUSED: case HLSPlayStates.PAUSED_BUFFERING: _setPlaybackState(HLSPlayStates.PAUSED_BUFFERING); break; case HLSPlayStates.PLAYING: case HLSPlayStates.PLAYING_BUFFERING: _setPlaybackState(HLSPlayStates.PLAYING_BUFFERING); break; default: break; } /* always pause NetStream while seeking, even if we are in play state * in that case, NetStream will be resumed during next call to appendTags() */ super.pause(); _timer.start(); }; public override function set client(client : Object) : void { _client.delegate = client; }; public override function get client() : Object { return _client.delegate; } /** Stop playback. **/ override public function close() : void { CONFIG::LOGGING { Log.info("HLSNetStream:close"); } super.close(); _streamBuffer.stop(); _timer.stop(); _setPlaybackState(HLSPlayStates.IDLE); _setSeekState(HLSSeekStates.IDLE); }; public function dispose_() : void { close(); _bufferThresholdController.dispose(); } } }
add useful / commented debug code
HLSNetStream.as: add useful / commented debug code
ActionScript
mpl-2.0
suuhas/flashls,fixedmachine/flashls,Boxie5/flashls,loungelogic/flashls,Corey600/flashls,Boxie5/flashls,tedconf/flashls,aevange/flashls,aevange/flashls,hola/flashls,mangui/flashls,jlacivita/flashls,Peer5/flashls,Peer5/flashls,vidible/vdb-flashls,dighan/flashls,dighan/flashls,NicolasSiver/flashls,hola/flashls,thdtjsdn/flashls,Peer5/flashls,vidible/vdb-flashls,JulianPena/flashls,tedconf/flashls,clappr/flashls,suuhas/flashls,JulianPena/flashls,jlacivita/flashls,neilrackett/flashls,suuhas/flashls,Corey600/flashls,aevange/flashls,Peer5/flashls,NicolasSiver/flashls,codex-corp/flashls,viktorot/flashls,viktorot/flashls,viktorot/flashls,fixedmachine/flashls,clappr/flashls,thdtjsdn/flashls,mangui/flashls,loungelogic/flashls,suuhas/flashls,neilrackett/flashls,codex-corp/flashls,aevange/flashls
a1dd5a9d5c73a6e20da33d81b05e81ed89cac375
exporter/src/main/as/flump/export/Exporter.as
exporter/src/main/as/flump/export/Exporter.as
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.desktop.NativeApplication; import flash.display.NativeMenu; import flash.display.NativeMenuItem; import flash.display.NativeWindow; import flash.display.Stage; import flash.display.StageQuality; import flash.events.Event; import flash.events.MouseEvent; import flash.filesystem.File; import flash.net.SharedObject; import flash.utils.IDataOutput; import flump.executor.Executor; import flump.executor.Future; import flump.export.Ternary; import flump.xfl.ParseError; import flump.xfl.XflLibrary; import mx.collections.ArrayList; import mx.events.CollectionEvent; import mx.events.PropertyChangeEvent; import spark.components.DataGrid; import spark.components.DropDownList; import spark.components.List; import spark.components.Window; import spark.events.GridSelectionEvent; import com.threerings.util.F; import com.threerings.util.Log; import com.threerings.util.StringUtil; import starling.display.Sprite; public class Exporter { public static const NA :NativeApplication = NativeApplication.nativeApplication; public function Exporter (win :ExporterWindow) { Log.setLevel("", Log.INFO); _win = win; _errors = _win.errors; _libraries = _win.libraries; function updatePreviewAndExport (..._) :void { _win.export.enabled = _exportChooser.dir != null && _libraries.selectionLength > 0 && _libraries.selectedItems.some(function (status :DocStatus, ..._) :Boolean { return status.isValid; }); var status :DocStatus = _libraries.selectedItem as DocStatus; _win.preview.enabled = status != null && status.isValid; if (_exportChooser.dir == null) return; _conf.exportDir = _confFile.parent.getRelativePath(_exportChooser.dir, /*useDotDot=*/true); } var fileMenuItem :NativeMenuItem; if (NativeApplication.supportsMenu) { // Grab the existing menu on macs. Use an index to get it as it's not going to be // 'File' in all languages fileMenuItem = NA.menu.getItemAt(1); // Add a separator before the existing close command fileMenuItem.submenu.addItemAt(new NativeMenuItem("Sep", /*separator=*/true), 0); } else { _win.nativeWindow.menu = new NativeMenu(); fileMenuItem = _win.nativeWindow.menu.addSubmenu(new NativeMenu(), "File"); } // Add save and save as by index to work with the existing items on Mac // Mac menus have an existing "Close" item, so everything we add should go ahead of that var newMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("New"), 0); newMenuItem.keyEquivalent = "n"; newMenuItem.addEventListener(Event.SELECT, function (..._) :void { _confFile = null; _conf = new FlumpConf(); setImport(null); updatePublisher(); }); var openMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("Open..."), 1); openMenuItem.keyEquivalent = "o"; openMenuItem.addEventListener(Event.SELECT, function (..._) :void { var file :File = new File(); file.addEventListener(Event.SELECT, function (..._) :void { _confFile = file; openConf(); updatePublisher(); }); file.browseForOpen("Open Flump Configuration"); }); fileMenuItem.submenu.addItemAt(new NativeMenuItem("Sep", /*separator=*/true), 2); const saveMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("Save"), 3); saveMenuItem.keyEquivalent = "s"; function saveConf () :void { Files.write(_confFile, function (out :IDataOutput) :void { // Set directories relative to where this file is being saved. Fall back to absolute // paths if relative paths aren't possible. if (_importChooser.dir != null) { _conf.importDir = _confFile.parent.getRelativePath(_importChooser.dir, /*useDotDot=*/true); if (_conf.importDir == null) _conf.importDir = _importChooser.dir.nativePath; } if (_exportChooser.dir != null) { _conf.exportDir = _confFile.parent.getRelativePath(_exportChooser.dir, /*useDotDot=*/true); if (_conf.exportDir == null) _conf.exportDir = _exportChooser.dir.nativePath; } out.writeUTFBytes(JSON.stringify(_conf, null, /*space=*/2)); }); }; function saveAs (..._) :void { var file :File = new File(); file.addEventListener(Event.SELECT, function (..._) :void { _confFile = file; trace("Conf file is now " + _confFile.nativePath); _settings.data["CONF_FILE"] = _confFile.nativePath; _settings.flush(); saveConf(); }); file.browseForSave("Save Flump Configuration"); }; saveMenuItem.addEventListener(Event.SELECT, function (..._) :void { if (_confFile == null) saveAs(); else saveConf(); }); function openConf () :void { try { _conf = FlumpConf.fromJSON(JSONFormat.readJSON(_confFile)); _win.title = _confFile.name; var dir :String = _confFile.parent.resolvePath(_conf.importDir).nativePath; setImport(new File(dir)); } catch (e :Error) { log.warning("Unable to parse conf", e); _errors.dataProvider.addItem(new ParseError(_confFile.nativePath, ParseError.CRIT, "Unable to read configuration")); _confFile = null; } }; const saveAsMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("Save As..."), 4); saveAsMenuItem.keyEquivalent = "S"; saveAsMenuItem.addEventListener(Event.SELECT, saveAs); if (_settings.data.hasOwnProperty("CONF_FILE")) { _confFile = new File(_settings.data["CONF_FILE"]); openConf(); } var curSelection :DocStatus = null; _libraries.addEventListener(GridSelectionEvent.SELECTION_CHANGE, function (..._) :void { log.info("Changed", "selected", _libraries.selectedIndices); updatePreviewAndExport(); if (curSelection != null) { curSelection.removeEventListener(PropertyChangeEvent.PROPERTY_CHANGE, updatePreviewAndExport); } var newSelection :DocStatus = _libraries.selectedItem as DocStatus; if (newSelection != null) { newSelection.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, updatePreviewAndExport); } curSelection = newSelection; }); _win.reload.addEventListener(MouseEvent.CLICK, function (..._) :void { setImport(_importChooser.dir); updatePreviewAndExport(); }); _win.export.addEventListener(MouseEvent.CLICK, function (..._) :void { for each (var status :DocStatus in _libraries.selectedItems) { exportFlashDocument(status); } }); _win.preview.addEventListener(MouseEvent.CLICK, function (..._) :void { showPreviewWindow(_libraries.selectedItem.lib); }); _importChooser = new DirChooser(null, _win.importRoot, _win.browseImport); _importChooser.changed.add(setImport); _exportChooser = new DirChooser(null, _win.exportRoot, _win.browseExport); _exportChooser.changed.add(updatePreviewAndExport); function updatePublisher (..._) :void { if (_confFile != null) { _importChooser.dir = (_conf.importDir != null) ? _confFile.parent.resolvePath(_conf.importDir) : null; _exportChooser.dir = (_conf.exportDir != null) ? _confFile.parent.resolvePath(_conf.exportDir) : null; } else { _importChooser.dir = null; _exportChooser.dir = null; } if (_exportChooser.dir == null || _conf.exports.length == 0) _publisher = null; else _publisher = new Publisher(_exportChooser.dir, Vector.<ExportConf>(_conf.exports)); var formatNames :Array = []; for each (var export :ExportConf in _conf.exports) formatNames.push(export.name); _win.formatOverview.text = formatNames.join(", "); }; var editFormats :EditFormatsWindow; _win.editFormats.addEventListener(MouseEvent.CLICK, function (..._) :void { if (editFormats == null || editFormats.closed) { editFormats = new EditFormatsWindow(); editFormats.open(); } else editFormats.orderToFront(); var dataProvider :ArrayList = new ArrayList(_conf.exports); dataProvider.addEventListener(CollectionEvent.COLLECTION_CHANGE, updatePublisher); editFormats.exports.dataProvider = dataProvider; editFormats.buttonAdd.addEventListener(MouseEvent.CLICK, function (..._) :void { var export :ExportConf = new ExportConf(); export.name = "format" + (_conf.exports.length+1); if (_conf.exports.length > 0) { export.format = _conf.exports[0].format; } dataProvider.addItem(export); }); editFormats.exports.addEventListener(GridSelectionEvent.SELECTION_CHANGE, function (..._) :void { editFormats.buttonRemove.enabled = (editFormats.exports.selectedItem != null); }); editFormats.buttonRemove.addEventListener(MouseEvent.CLICK, function (..._) :void { for each (var export :ExportConf in editFormats.exports.selectedItems) { dataProvider.removeItem(export); } }); }); updatePublisher(); _win.addEventListener(Event.CLOSE, function (..._) :void { NA.exit(0); }); } protected function setImport (root :File) :void { _libraries.dataProvider.removeAll(); _errors.dataProvider.removeAll(); if (root == null) return; _rootLen = root.nativePath.length + 1; if (_docFinder != null) _docFinder.shutdownNow(); _docFinder = new Executor(); findFlashDocuments(root, _docFinder, true); _win.reload.enabled = true; } protected function showPreviewWindow (lib :XflLibrary) :void { if (_previewController == null || _previewWindow.closed || _previewControls.closed) { _previewWindow = new PreviewWindow(); _previewControls = new PreviewControlsWindow(); _previewWindow.started = function (container :Sprite) :void { _previewController = new PreviewController(lib, container, _previewWindow, _previewControls); } _previewWindow.open(); _previewControls.open(); preventWindowClose(_previewWindow.nativeWindow); preventWindowClose(_previewControls.nativeWindow); } else { _previewController.lib = lib; _previewWindow.nativeWindow.visible = true; _previewControls.nativeWindow.visible = true; } _previewWindow.orderToFront(); _previewControls.orderToFront(); } // Causes a window to be hidden, rather than closed, when its close box is clicked protected static function preventWindowClose (window :NativeWindow) :void { window.addEventListener(Event.CLOSING, function (e :Event) :void { e.preventDefault(); window.visible = false; }); } protected var _previewController :PreviewController; protected var _previewWindow :PreviewWindow; protected var _previewControls :PreviewControlsWindow; protected function findFlashDocuments (base :File, exec :Executor, ignoreXflAtBase :Boolean = false) :void { Files.list(base, exec).succeeded.add(function (files :Array) :void { if (exec.isShutdown) return; for each (var file :File in files) { if (Files.hasExtension(file, "xfl")) { if (ignoreXflAtBase) { _errors.dataProvider.addItem(new ParseError(base.nativePath, ParseError.CRIT, "The import directory can't be an XFL directory, did you mean " + base.parent.nativePath + "?")); } else addFlashDocument(file); return; } } for each (file in files) { if (StringUtil.startsWith(file.name, ".", "RECOVER_")) { continue; // Ignore hidden VCS directories, and recovered backups created by Flash } if (file.isDirectory) findFlashDocuments(file, exec); else addFlashDocument(file); } }); } protected function exportFlashDocument (status :DocStatus) :void { const stage :Stage = NA.activeWindow.stage; const prevQuality :String = stage.quality; stage.quality = StageQuality.BEST; _publisher.publish(status.lib); stage.quality = prevQuality; status.updateModified(Ternary.FALSE); } protected function addFlashDocument (file :File) :void { var name :String = file.nativePath.substring(_rootLen).replace( new RegExp("\\" + File.separator, "g"), "/"); var load :Future; switch (Files.getExtension(file)) { case "xfl": name = name.substr(0, name.lastIndexOf("/")); load = new XflLoader().load(name, file.parent); break; case "fla": name = name.substr(0, name.lastIndexOf(".")); load = new FlaLoader().load(name, file); break; default: // Unsupported file type, ignore return; } const status :DocStatus = new DocStatus(name, _rootLen, Ternary.UNKNOWN, Ternary.UNKNOWN, null); _libraries.dataProvider.addItem(status); load.succeeded.add(function (lib :XflLibrary) :void { status.lib = lib; status.updateModified(Ternary.of(_publisher == null || _publisher.modified(lib))); for each (var err :ParseError in lib.getErrors()) _errors.dataProvider.addItem(err); status.updateValid(Ternary.of(lib.valid)); }); load.failed.add(function (error :Error) :void { trace("Failed to load " + file.nativePath + ": " + error); status.updateValid(Ternary.FALSE); throw error; }); } protected var _rootLen :int; protected var _publisher :Publisher; protected var _docFinder :Executor; protected var _win :ExporterWindow; protected var _libraries :DataGrid; protected var _errors :DataGrid; protected var _exportChooser :DirChooser; protected var _importChooser :DirChooser; protected var _authoredResolution :DropDownList; protected var _conf :FlumpConf = new FlumpConf(); protected var _confFile :File; protected const _settings :SharedObject = SharedObject.getLocal("flump/Exporter"); private static const log :Log = Log.getLog(Exporter); } } import flash.events.EventDispatcher; import flump.export.Ternary; import flump.xfl.XflLibrary; import mx.core.IPropertyChangeNotifier; import mx.events.PropertyChangeEvent; class DocStatus extends EventDispatcher implements IPropertyChangeNotifier { public var path :String; public var modified :String; public var valid :String = QUESTION; public var lib :XflLibrary; public function DocStatus (path :String, rootLen :int, modified :Ternary, valid :Ternary, lib :XflLibrary) { this.lib = lib; this.path = path; _uid = path; updateModified(modified); updateValid(valid); } public function updateValid (newValid :Ternary) :void { changeField("valid", function (..._) :void { if (newValid == Ternary.TRUE) valid = CHECK; else if (newValid == Ternary.FALSE) valid = FROWN; else valid = QUESTION; }); } public function get isValid () :Boolean { return valid == CHECK; } public function updateModified (newModified :Ternary) :void { changeField("modified", function (..._) :void { if (newModified == Ternary.TRUE) modified = CHECK; else if (newModified == Ternary.FALSE) modified = " "; else modified = QUESTION; }); } protected function changeField(fieldName :String, modifier :Function) :void { const oldValue :Object = this[fieldName]; modifier(); const newValue :Object = this[fieldName]; dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, fieldName, oldValue, newValue)); } public function get uid () :String { return _uid; } public function set uid (uid :String) :void { _uid = uid; } protected var _uid :String; protected static const QUESTION :String = "?"; protected static const FROWN :String = "☹"; protected static const CHECK :String = "✓"; }
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.desktop.NativeApplication; import flash.display.NativeMenu; import flash.display.NativeMenuItem; import flash.display.NativeWindow; import flash.display.Stage; import flash.display.StageQuality; import flash.events.Event; import flash.events.MouseEvent; import flash.filesystem.File; import flash.net.SharedObject; import flash.utils.IDataOutput; import flump.executor.Executor; import flump.executor.Future; import flump.export.Ternary; import flump.xfl.ParseError; import flump.xfl.XflLibrary; import mx.collections.ArrayList; import mx.events.CollectionEvent; import mx.events.PropertyChangeEvent; import spark.components.DataGrid; import spark.components.DropDownList; import spark.components.List; import spark.components.Window; import spark.events.GridSelectionEvent; import com.threerings.util.F; import com.threerings.util.Log; import com.threerings.util.StringUtil; import starling.display.Sprite; public class Exporter { public static const NA :NativeApplication = NativeApplication.nativeApplication; public function Exporter (win :ExporterWindow) { Log.setLevel("", Log.INFO); _win = win; _errors = _win.errors; _libraries = _win.libraries; function updatePreviewAndExport (..._) :void { _win.export.enabled = _exportChooser.dir != null && _libraries.selectionLength > 0 && _libraries.selectedItems.some(function (status :DocStatus, ..._) :Boolean { return status.isValid; }); var status :DocStatus = _libraries.selectedItem as DocStatus; _win.preview.enabled = status != null && status.isValid; if (_exportChooser.dir == null) return; _conf.exportDir = _confFile.parent.getRelativePath(_exportChooser.dir, /*useDotDot=*/true); } var fileMenuItem :NativeMenuItem; if (NativeApplication.supportsMenu) { // Grab the existing menu on macs. Use an index to get it as it's not going to be // 'File' in all languages fileMenuItem = NA.menu.getItemAt(1); // Add a separator before the existing close command fileMenuItem.submenu.addItemAt(new NativeMenuItem("Sep", /*separator=*/true), 0); } else { _win.nativeWindow.menu = new NativeMenu(); fileMenuItem = _win.nativeWindow.menu.addSubmenu(new NativeMenu(), "File"); } // Add save and save as by index to work with the existing items on Mac // Mac menus have an existing "Close" item, so everything we add should go ahead of that var newMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("New"), 0); newMenuItem.keyEquivalent = "n"; newMenuItem.addEventListener(Event.SELECT, function (..._) :void { _confFile = null; _conf = new FlumpConf(); setImport(null); updatePublisher(); }); var openMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("Open..."), 1); openMenuItem.keyEquivalent = "o"; openMenuItem.addEventListener(Event.SELECT, function (..._) :void { var file :File = new File(); file.addEventListener(Event.SELECT, function (..._) :void { _confFile = file; openConf(); updatePublisher(); updateWindowTitle(false); }); file.browseForOpen("Open Flump Configuration"); }); fileMenuItem.submenu.addItemAt(new NativeMenuItem("Sep", /*separator=*/true), 2); const saveMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("Save"), 3); saveMenuItem.keyEquivalent = "s"; function saveConf () :void { Files.write(_confFile, function (out :IDataOutput) :void { // Set directories relative to where this file is being saved. Fall back to absolute // paths if relative paths aren't possible. if (_importChooser.dir != null) { _conf.importDir = _confFile.parent.getRelativePath(_importChooser.dir, /*useDotDot=*/true); if (_conf.importDir == null) _conf.importDir = _importChooser.dir.nativePath; } if (_exportChooser.dir != null) { _conf.exportDir = _confFile.parent.getRelativePath(_exportChooser.dir, /*useDotDot=*/true); if (_conf.exportDir == null) _conf.exportDir = _exportChooser.dir.nativePath; } out.writeUTFBytes(JSON.stringify(_conf, null, /*space=*/2)); updateWindowTitle(false); }); }; function saveAs (..._) :void { var file :File = new File(); file.addEventListener(Event.SELECT, function (..._) :void { _confFile = file; trace("Conf file is now " + _confFile.nativePath); _settings.data["CONF_FILE"] = _confFile.nativePath; _settings.flush(); saveConf(); }); file.browseForSave("Save Flump Configuration"); }; saveMenuItem.addEventListener(Event.SELECT, function (..._) :void { if (_confFile == null) saveAs(); else saveConf(); }); function updateWindowTitle (modified :Boolean) :void { var name :String = (_confFile != null) ? _confFile.name : "Untitled"; if (modified) name += "*"; _win.title = name; }; function openConf () :void { try { _conf = FlumpConf.fromJSON(JSONFormat.readJSON(_confFile)); var dir :String = _confFile.parent.resolvePath(_conf.importDir).nativePath; setImport(new File(dir)); } catch (e :Error) { log.warning("Unable to parse conf", e); _errors.dataProvider.addItem(new ParseError(_confFile.nativePath, ParseError.CRIT, "Unable to read configuration")); _confFile = null; } }; const saveAsMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("Save As..."), 4); saveAsMenuItem.keyEquivalent = "S"; saveAsMenuItem.addEventListener(Event.SELECT, saveAs); if (_settings.data.hasOwnProperty("CONF_FILE")) { _confFile = new File(_settings.data["CONF_FILE"]); openConf(); } var curSelection :DocStatus = null; _libraries.addEventListener(GridSelectionEvent.SELECTION_CHANGE, function (..._) :void { log.info("Changed", "selected", _libraries.selectedIndices); updatePreviewAndExport(); if (curSelection != null) { curSelection.removeEventListener(PropertyChangeEvent.PROPERTY_CHANGE, updatePreviewAndExport); } var newSelection :DocStatus = _libraries.selectedItem as DocStatus; if (newSelection != null) { newSelection.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, updatePreviewAndExport); } curSelection = newSelection; }); _win.reload.addEventListener(MouseEvent.CLICK, function (..._) :void { setImport(_importChooser.dir); updatePreviewAndExport(); }); _win.export.addEventListener(MouseEvent.CLICK, function (..._) :void { for each (var status :DocStatus in _libraries.selectedItems) { exportFlashDocument(status); } }); _win.preview.addEventListener(MouseEvent.CLICK, function (..._) :void { showPreviewWindow(_libraries.selectedItem.lib); }); _importChooser = new DirChooser(null, _win.importRoot, _win.browseImport); _importChooser.changed.add(setImport); _exportChooser = new DirChooser(null, _win.exportRoot, _win.browseExport); _exportChooser.changed.add(updatePreviewAndExport); _importChooser.changed.add(F.callback(updateWindowTitle, true)); _exportChooser.changed.add(F.callback(updateWindowTitle, true)); function updatePublisher (..._) :void { if (_confFile != null) { _importChooser.dir = (_conf.importDir != null) ? _confFile.parent.resolvePath(_conf.importDir) : null; _exportChooser.dir = (_conf.exportDir != null) ? _confFile.parent.resolvePath(_conf.exportDir) : null; } else { _importChooser.dir = null; _exportChooser.dir = null; } if (_exportChooser.dir == null || _conf.exports.length == 0) _publisher = null; else _publisher = new Publisher(_exportChooser.dir, Vector.<ExportConf>(_conf.exports)); var formatNames :Array = []; for each (var export :ExportConf in _conf.exports) formatNames.push(export.name); _win.formatOverview.text = formatNames.join(", "); updateWindowTitle(true); }; var editFormats :EditFormatsWindow; _win.editFormats.addEventListener(MouseEvent.CLICK, function (..._) :void { if (editFormats == null || editFormats.closed) { editFormats = new EditFormatsWindow(); editFormats.open(); } else editFormats.orderToFront(); var dataProvider :ArrayList = new ArrayList(_conf.exports); dataProvider.addEventListener(CollectionEvent.COLLECTION_CHANGE, updatePublisher); editFormats.exports.dataProvider = dataProvider; editFormats.buttonAdd.addEventListener(MouseEvent.CLICK, function (..._) :void { var export :ExportConf = new ExportConf(); export.name = "format" + (_conf.exports.length+1); if (_conf.exports.length > 0) { export.format = _conf.exports[0].format; } dataProvider.addItem(export); }); editFormats.exports.addEventListener(GridSelectionEvent.SELECTION_CHANGE, function (..._) :void { editFormats.buttonRemove.enabled = (editFormats.exports.selectedItem != null); }); editFormats.buttonRemove.addEventListener(MouseEvent.CLICK, function (..._) :void { for each (var export :ExportConf in editFormats.exports.selectedItems) { dataProvider.removeItem(export); } }); }); updatePublisher(); updateWindowTitle(false); _win.addEventListener(Event.CLOSE, function (..._) :void { NA.exit(0); }); } protected function setImport (root :File) :void { _libraries.dataProvider.removeAll(); _errors.dataProvider.removeAll(); if (root == null) return; _rootLen = root.nativePath.length + 1; if (_docFinder != null) _docFinder.shutdownNow(); _docFinder = new Executor(); findFlashDocuments(root, _docFinder, true); _win.reload.enabled = true; } protected function showPreviewWindow (lib :XflLibrary) :void { if (_previewController == null || _previewWindow.closed || _previewControls.closed) { _previewWindow = new PreviewWindow(); _previewControls = new PreviewControlsWindow(); _previewWindow.started = function (container :Sprite) :void { _previewController = new PreviewController(lib, container, _previewWindow, _previewControls); } _previewWindow.open(); _previewControls.open(); preventWindowClose(_previewWindow.nativeWindow); preventWindowClose(_previewControls.nativeWindow); } else { _previewController.lib = lib; _previewWindow.nativeWindow.visible = true; _previewControls.nativeWindow.visible = true; } _previewWindow.orderToFront(); _previewControls.orderToFront(); } // Causes a window to be hidden, rather than closed, when its close box is clicked protected static function preventWindowClose (window :NativeWindow) :void { window.addEventListener(Event.CLOSING, function (e :Event) :void { e.preventDefault(); window.visible = false; }); } protected var _previewController :PreviewController; protected var _previewWindow :PreviewWindow; protected var _previewControls :PreviewControlsWindow; protected function findFlashDocuments (base :File, exec :Executor, ignoreXflAtBase :Boolean = false) :void { Files.list(base, exec).succeeded.add(function (files :Array) :void { if (exec.isShutdown) return; for each (var file :File in files) { if (Files.hasExtension(file, "xfl")) { if (ignoreXflAtBase) { _errors.dataProvider.addItem(new ParseError(base.nativePath, ParseError.CRIT, "The import directory can't be an XFL directory, did you mean " + base.parent.nativePath + "?")); } else addFlashDocument(file); return; } } for each (file in files) { if (StringUtil.startsWith(file.name, ".", "RECOVER_")) { continue; // Ignore hidden VCS directories, and recovered backups created by Flash } if (file.isDirectory) findFlashDocuments(file, exec); else addFlashDocument(file); } }); } protected function exportFlashDocument (status :DocStatus) :void { const stage :Stage = NA.activeWindow.stage; const prevQuality :String = stage.quality; stage.quality = StageQuality.BEST; _publisher.publish(status.lib); stage.quality = prevQuality; status.updateModified(Ternary.FALSE); } protected function addFlashDocument (file :File) :void { var name :String = file.nativePath.substring(_rootLen).replace( new RegExp("\\" + File.separator, "g"), "/"); var load :Future; switch (Files.getExtension(file)) { case "xfl": name = name.substr(0, name.lastIndexOf("/")); load = new XflLoader().load(name, file.parent); break; case "fla": name = name.substr(0, name.lastIndexOf(".")); load = new FlaLoader().load(name, file); break; default: // Unsupported file type, ignore return; } const status :DocStatus = new DocStatus(name, _rootLen, Ternary.UNKNOWN, Ternary.UNKNOWN, null); _libraries.dataProvider.addItem(status); load.succeeded.add(function (lib :XflLibrary) :void { status.lib = lib; status.updateModified(Ternary.of(_publisher == null || _publisher.modified(lib))); for each (var err :ParseError in lib.getErrors()) _errors.dataProvider.addItem(err); status.updateValid(Ternary.of(lib.valid)); }); load.failed.add(function (error :Error) :void { trace("Failed to load " + file.nativePath + ": " + error); status.updateValid(Ternary.FALSE); throw error; }); } protected var _rootLen :int; protected var _publisher :Publisher; protected var _docFinder :Executor; protected var _win :ExporterWindow; protected var _libraries :DataGrid; protected var _errors :DataGrid; protected var _exportChooser :DirChooser; protected var _importChooser :DirChooser; protected var _authoredResolution :DropDownList; protected var _conf :FlumpConf = new FlumpConf(); protected var _confFile :File; protected const _settings :SharedObject = SharedObject.getLocal("flump/Exporter"); private static const log :Log = Log.getLog(Exporter); } } import flash.events.EventDispatcher; import flump.export.Ternary; import flump.xfl.XflLibrary; import mx.core.IPropertyChangeNotifier; import mx.events.PropertyChangeEvent; class DocStatus extends EventDispatcher implements IPropertyChangeNotifier { public var path :String; public var modified :String; public var valid :String = QUESTION; public var lib :XflLibrary; public function DocStatus (path :String, rootLen :int, modified :Ternary, valid :Ternary, lib :XflLibrary) { this.lib = lib; this.path = path; _uid = path; updateModified(modified); updateValid(valid); } public function updateValid (newValid :Ternary) :void { changeField("valid", function (..._) :void { if (newValid == Ternary.TRUE) valid = CHECK; else if (newValid == Ternary.FALSE) valid = FROWN; else valid = QUESTION; }); } public function get isValid () :Boolean { return valid == CHECK; } public function updateModified (newModified :Ternary) :void { changeField("modified", function (..._) :void { if (newModified == Ternary.TRUE) modified = CHECK; else if (newModified == Ternary.FALSE) modified = " "; else modified = QUESTION; }); } protected function changeField(fieldName :String, modifier :Function) :void { const oldValue :Object = this[fieldName]; modifier(); const newValue :Object = this[fieldName]; dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, fieldName, oldValue, newValue)); } public function get uid () :String { return _uid; } public function set uid (uid :String) :void { _uid = uid; } protected var _uid :String; protected static const QUESTION :String = "?"; protected static const FROWN :String = "☹"; protected static const CHECK :String = "✓"; }
Put an asterisk in the window title when you have unsaved changes.
Put an asterisk in the window title when you have unsaved changes.
ActionScript
mit
mathieuanthoine/flump,tconkling/flump,mathieuanthoine/flump,funkypandagame/flump,mathieuanthoine/flump,tconkling/flump,funkypandagame/flump
c1eecdc2e06d401bae99506bcd82c7a4980290ea
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.9.rc1"; /** * 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.9"; /** * 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; } } }
update version 3.8.9
update version 3.8.9
ActionScript
agpl-3.0
kaltura/kdp,shvyrev/kdp,shvyrev/kdp,kaltura/kdp,kaltura/kdp,shvyrev/kdp
8c3d546c729a3caa08b4107115f91efff15c6265
src/printf.as
src/printf.as
package { /** * Creates a string with variable substitutions. Very similiar to printf, specially python's printf * @param raw The string to be substituted. * @param rest The objects to be substitued, can be positional or by properties inside the object (in wich case only one object can be passed) * @return The formated and substitued string. * @example * <pre> * * // objects are substitued in the other they appear * * printf("This is an %s lybrary for creating %s", "Actioscript 3.0", "strings"); * // outputs: "This is an Actioscript 3.0 lybrary for creating strings"; * // you can also format numbers: * * printf("You can also display numbers like PI: %f, and format them to a fixed precision, such as PI with 3 decimal places %.3f", Math.PI, Math.PI); * // outputs: " You can also display numbers like PI: 3.141592653589793, and format them to a fixed precision, such as PI with 3 decimal places 3.142" * // Instead of positional (the order of arguments to print f, you can also use propertie of an object): * var userInfo : Object = { "name": "Arthur Debert", "email": "[email protected]", "website":"http://www.stimuli.com.br/", "ocupation": "developer" } * * printf("My name is %(name)s and I am a %(ocupation)s. You can read more on my personal %(website)s, or reach me through my %(email)s", userInfo); * // outputs: "My name is Arthur Debert and I am a developer. You can read more on my personal http://www.stimuli.com.br/, or reach me through my [email protected]" * // you can also use date parts: * var date : Date = new Date(); * printf("Today is %d/%m/%Y", date, date, date) * * </pre> * @see br.com.stimuli.string */ public function printf(raw : String, ...rest) : String{ /** * Pretty ugly! * basicaly * % -> the start of a substitution hole * (some_var_name) -> [optional] used in named substitutions * .xx -> [optional] the precision with witch numbers will be formated * x -> the formatter (string, hexa, float, date part) */ var SUBS_RE : RegExp = /%(?!^%)(\((?P<var_name>[\w]+[\w_\d]+)\))?(?P<padding>[0-9]{1,2})?(\.(?P<precision>[0-9]+))?(?P<formater>[sxofaAbBcdHIjmMpSUwWxXyYZ])/ig; //Return empty string if raw is null, we don't want errors here if( raw == null ){ return ""; } //trace("\n\n" + 'input:"'+ raw+ '" , args:', rest.join(", ")) ; var matches : Array = []; var result : Object = SUBS_RE.exec(raw); var match : Match; var runs : int = 0; var numMatches : int = 0; var numberVariables : int = rest.length; // quick check if we find string subs amongst the text to match (something like %(foo)s var isPositionalSubts : Boolean = !Boolean(raw.match(/%\(\s*[\w\d_]+\s*\)/)); var replacementValue : *; var formater : String; var varName : String; var precision : String; var padding : String; var paddingNum : int; var paddingChar:String; // matched through the string, creating Match objects for easier later reuse while (Boolean(result)){ match = new Match(); match.startIndex = result.index; match.length = String(result[0]).length; match.endIndex = match.startIndex + match.length; match.content = String(result[0]); // try to get substitution properties formater = result["formater"]; varName = result["var_name"]; precision = result["precision"]; padding = result["padding"]; paddingNum = 0; paddingChar = null; //trace('formater:', formater, ', varName:', varName, ', precision:', precision, 'padding:', padding); if (padding){ if (padding.length == 1){ paddingNum = int(padding); paddingChar = " "; }else{ paddingNum = int (padding.substr(-1, 1)); paddingChar = padding.substr(-2, 1); if (paddingChar != "0"){ paddingNum *= int(paddingChar); paddingChar = " "; } } } if (isPositionalSubts){ // by position, grab next subs: replacementValue = rest[matches.length]; }else{ // be hash / properties replacementValue = rest[0] == null ? undefined : rest[0][varName]; } // check for bad variable names if (replacementValue == undefined){ replacementValue = ""; } if (replacementValue != undefined){ // format the string accodingly to the formatter if (formater == STRING_FORMATTER){ match.replacement = padString(String(replacementValue), paddingNum, paddingChar); }else if (formater == FLOAT_FORMATER){ // floats, check if we need to truncate precision if (precision){ match.replacement = padString( Number(replacementValue).toFixed( int(precision)), paddingNum, paddingChar); }else{ match.replacement = padString(String(replacementValue), paddingNum, paddingChar); } }else if (formater == INTEGER_FORMATER){ match.replacement = padString(int(replacementValue).toString(), paddingNum, paddingChar); }else if (formater == OCTAL_FORMATER){ match.replacement = "0" + int(replacementValue).toString(8); }else if (formater == HEXA_FORMATER){ match.replacement = "0x" + int(replacementValue).toString(16); }else if(DATES_FORMATERS.indexOf(formater) > -1){ switch (formater){ case DATE_DAY_FORMATTER: match.replacement = replacementValue["date"]; break; case DATE_FULLYEAR_FORMATTER: match.replacement = replacementValue["fullYear"]; break; case DATE_YEAR_FORMATTER: match.replacement = String(replacementValue["fullYear"]).substr(2, 2); break; case DATE_MONTH_FORMATTER: match.replacement = String(replacementValue["month"] + 1); break; case DATE_HOUR24_FORMATTER: match.replacement = replacementValue["hours"]; break; case DATE_HOUR_FORMATTER: var hours24 : Number = replacementValue["hours"]; match.replacement = (hours24 -12).toString(); break; case DATE_HOUR_AMPM_FORMATTER: match.replacement = (replacementValue["hours"] >= 12 ? "p.m" : "a.m"); break; case DATE_TOLOCALE_FORMATTER: match.replacement = Date(replacementValue).toLocaleString(); break; case DATE_MINUTES_FORMATTER: match.replacement = replacementValue["minutes"]; break; case DATE_SECONDS_FORMATTER: match.replacement = replacementValue["seconds"]; break; } }else{ //no good replacement } matches.push(match); } // just a small check in case we get stuck: kludge! runs ++; if (runs > 10000){ //something is wrong, breaking out break; } numMatches ++; // iterates next match result = SUBS_RE.exec(raw); } // in case there's nothing to substitute, just return the initial string if(matches.length == 0){ //no matches, returning raw return raw; } // now actually do the substitution, keeping a buffer to be joined at //the end for better performance var buffer : Array = []; var lastMatch : Match; // beggininf os string, if it doesn't start with a substitition var previous : String = raw.substr(0, matches[0].startIndex); var subs : String; for each(match in matches){ // finds out the previous string part and the next substitition if (lastMatch){ previous = raw.substring(lastMatch.endIndex , match.startIndex); } buffer.push(previous); buffer.push(match.replacement); lastMatch = match; } // buffer the tail of the string: text after the last substitution buffer.push(raw.substr(match.endIndex, raw.length - match.endIndex)); //trace('returning: "'+ buffer.join("")+'"'); return buffer.join(""); } } // internal usage /** @private */ const BAD_VARIABLE_NUMBER : String = "The number of variables to be replaced and template holes don't match"; /** Converts to a string*/ const STRING_FORMATTER : String = "s"; /** Outputs as a Number, can use the precision specifier: %.2sf will output a float with 2 decimal digits.*/ const FLOAT_FORMATER : String = "f"; /** Outputs as an Integer.*/ const INTEGER_FORMATER : String = "d"; /** Converts to an OCTAL number */ const OCTAL_FORMATER : String = "o"; /** Converts to a Hexa number (includes 0x) */ const HEXA_FORMATER : String = "x"; /** @private */ const DATES_FORMATERS : String = "aAbBcDHIjmMpSUwWxXyYZ"; /** Day of month, from 0 to 30 on <code>Date</code> objects.*/ const DATE_DAY_FORMATTER : String = "D"; /** Full year, e.g. 2007 on <code>Date</code> objects.*/ const DATE_FULLYEAR_FORMATTER : String = "Y"; /** Year, e.g. 07 on <code>Date</code> objects.*/ const DATE_YEAR_FORMATTER : String = "y"; /** Month from 1 to 12 on <code>Date</code> objects.*/ const DATE_MONTH_FORMATTER : String = "m"; /** Hours (0-23) on <code>Date</code> objects.*/ const DATE_HOUR24_FORMATTER : String = "H"; /** Hours 0-12 on <code>Date</code> objects.*/ const DATE_HOUR_FORMATTER : String = "I"; /** a.m or p.m on <code>Date</code> objects.*/ const DATE_HOUR_AMPM_FORMATTER : String = "p"; /** Minutes on <code>Date</code> objects.*/ const DATE_MINUTES_FORMATTER : String = "M"; /** Seconds on <code>Date</code> objects.*/ const DATE_SECONDS_FORMATTER : String = "S"; /** A string rep of a <code>Date</code> object on the current locale.*/ const DATE_TOLOCALE_FORMATTER : String = "c"; var version : String = "$Id$"; /** @private * Internal class that normalizes matching information. */ class Match{ public var startIndex : int; public var endIndex : int; public var length : int; public var content : String; public var replacement : String; public var before : String; public function toString() : String{ return "Match [" + startIndex + " - " + endIndex + "] (" + length + ") " + content + ", replacement:" + replacement + ";"; } } /** @private */ function padString(str:String, paddingNum:int, paddingChar:String=" ") : String { if(paddingChar == null) return str; return new Array(paddingNum + 1).join(paddingChar).concat(str); }
package { /** * Creates a string with variable substitutions. Very similiar to printf, specially python's printf * @param raw The string to be substituted. * @param rest The objects to be substitued, can be positional or by properties inside the object (in wich case only one object can be passed) * @return The formated and substitued string. * @example * <pre> * * // objects are substitued in the other they appear * * printf("This is an %s lybrary for creating %s", "Actioscript 3.0", "strings"); * // outputs: "This is an Actioscript 3.0 lybrary for creating strings"; * // you can also format numbers: * * printf("You can also display numbers like PI: %f, and format them to a fixed precision, such as PI with 3 decimal places %.3f", Math.PI, Math.PI); * // outputs: " You can also display numbers like PI: 3.141592653589793, and format them to a fixed precision, such as PI with 3 decimal places 3.142" * // Instead of positional (the order of arguments to print f, you can also use propertie of an object): * var userInfo : Object = { "name": "Arthur Debert", "email": "[email protected]", "website":"http://www.stimuli.com.br/", "ocupation": "developer" } * * printf("My name is %(name)s and I am a %(ocupation)s. You can read more on my personal %(website)s, or reach me through my %(email)s", userInfo); * // outputs: "My name is Arthur Debert and I am a developer. You can read more on my personal http://www.stimuli.com.br/, or reach me through my [email protected]" * // you can also use date parts: * var date : Date = new Date(); * printf("Today is %d/%m/%Y", date, date, date) * * </pre> * @see br.com.stimuli.string */ public function printf(raw : String, ...rest) : String{ /** * Pretty ugly! * basicaly * % -> the start of a substitution hole * (some_var_name) -> [optional] used in named substitutions * .xx -> [optional] the precision with witch numbers will be formated * x -> the formatter (string, hexa, float, date part) */ var SUBS_RE : RegExp = /%(?!^%)(\((?P<var_name>[\w]+[\w_\d]+)\))?(?P<padding>[0-9]{1,2})?(\.(?P<precision>[0-9]+))?(?P<formater>[sxofaAbBcdHIjmMpSUwWxXyYZ])/ig; //Return empty string if raw is null, we don't want errors here if( raw == null ){ return ""; } //trace("\n\n" + 'input:"'+ raw+ '" , args:', rest.join(", ")) ; var matches : Array = []; var result : Object = SUBS_RE.exec(raw); var match : Match; var runs : int = 0; var numMatches : int = 0; var numberVariables : int = rest.length; // quick check if we find string subs amongst the text to match (something like %(foo)s var isPositionalSubts : Boolean = !Boolean(raw.match(/%\(\s*[\w\d_]+\s*\)/)); var replacementValue : *; var formater : String; var varName : String; var precision : String; var padding : String; var paddingNum : int; var paddingChar:String; // matched through the string, creating Match objects for easier later reuse while (Boolean(result)){ match = new Match(); match.startIndex = result.index; match.length = String(result[0]).length; match.endIndex = match.startIndex + match.length; match.content = String(result[0]); // try to get substitution properties formater = result["formater"]; varName = result["var_name"]; precision = result["precision"]; padding = result["padding"]; paddingNum = 0; paddingChar = null; //trace('formater:', formater, ', varName:', varName, ', precision:', precision, 'padding:', padding); if (padding){ if (padding.length == 1){ paddingNum = int(padding); paddingChar = " "; }else{ paddingNum = int (padding.substr(-1, 1)); paddingChar = padding.substr(-2, 1); if (paddingChar != "0"){ paddingNum *= int(paddingChar); paddingChar = " "; } } } if (isPositionalSubts){ // by position, grab next subs: replacementValue = rest[matches.length]; }else{ // be hash / properties replacementValue = rest[0] == null ? undefined : rest[0][varName]; } // check for bad variable names if (replacementValue == undefined){ replacementValue = ""; } if (replacementValue != undefined){ // format the string accodingly to the formatter if (formater == STRING_FORMATTER){ match.replacement = padString(String(replacementValue), paddingNum, paddingChar); }else if (formater == FLOAT_FORMATER){ // floats, check if we need to truncate precision if (precision){ match.replacement = padString( Number(replacementValue).toFixed( int(precision)), paddingNum, paddingChar); }else{ match.replacement = padString(String(replacementValue), paddingNum, paddingChar); } }else if (formater == INTEGER_FORMATER){ match.replacement = padString(int(replacementValue).toString(), paddingNum, paddingChar); }else if (formater == OCTAL_FORMATER){ match.replacement = "0" + int(replacementValue).toString(8); }else if (formater == HEXA_FORMATER){ match.replacement = "0x" + int(replacementValue).toString(16); }else if(DATES_FORMATERS.indexOf(formater) > -1){ switch (formater){ case DATE_DAY_FORMATTER: match.replacement = replacementValue["date"]; break; case DATE_FULLYEAR_FORMATTER: match.replacement = replacementValue["fullYear"]; break; case DATE_YEAR_FORMATTER: match.replacement = String(replacementValue["fullYear"]).substr(2, 2); break; case DATE_MONTH_FORMATTER: match.replacement = String(replacementValue["month"] + 1); break; case DATE_HOUR24_FORMATTER: match.replacement = replacementValue["hours"]; break; case DATE_HOUR_FORMATTER: var hours24 : Number = replacementValue["hours"]; match.replacement = (hours24 -12).toString(); break; case DATE_HOUR_AMPM_FORMATTER: match.replacement = (replacementValue["hours"] >= 12 ? "p.m" : "a.m"); break; case DATE_TOLOCALE_FORMATTER: match.replacement = Date(replacementValue).toLocaleString(); break; case DATE_MINUTES_FORMATTER: match.replacement = replacementValue["minutes"]; break; case DATE_SECONDS_FORMATTER: match.replacement = replacementValue["seconds"]; break; } }else{ //no good replacement } matches.push(match); } // just a small check in case we get stuck: kludge! runs ++; if (runs > 10000){ //something is wrong, breaking out break; } numMatches ++; // iterates next match result = SUBS_RE.exec(raw); } // in case there's nothing to substitute, just return the initial string if(matches.length == 0){ //no matches, returning raw return raw; } // now actually do the substitution, keeping a buffer to be joined at //the end for better performance var buffer : Array = []; var lastMatch : Match; // beggininf os string, if it doesn't start with a substitition var previous : String = raw.substr(0, matches[0].startIndex); var subs : String; for each(match in matches){ // finds out the previous string part and the next substitition if (lastMatch){ previous = raw.substring(lastMatch.endIndex , match.startIndex); } buffer.push(previous); buffer.push(match.replacement); lastMatch = match; } // buffer the tail of the string: text after the last substitution buffer.push(raw.substr(match.endIndex, raw.length - match.endIndex)); //trace('returning: "'+ buffer.join("")+'"'); return buffer.join(""); } } // internal usage /** @private */ const BAD_VARIABLE_NUMBER : String = "The number of variables to be replaced and template holes don't match"; /** Converts to a string*/ const STRING_FORMATTER : String = "s"; /** Outputs as a Number, can use the precision specifier: %.2sf will output a float with 2 decimal digits.*/ const FLOAT_FORMATER : String = "f"; /** Outputs as an Integer.*/ const INTEGER_FORMATER : String = "d"; /** Converts to an OCTAL number */ const OCTAL_FORMATER : String = "o"; /** Converts to a Hexa number (includes 0x) */ const HEXA_FORMATER : String = "x"; /** @private */ const DATES_FORMATERS : String = "aAbBcDHIjmMpSUwWxXyYZ"; /** Day of month, from 0 to 30 on <code>Date</code> objects.*/ const DATE_DAY_FORMATTER : String = "D"; /** Full year, e.g. 2007 on <code>Date</code> objects.*/ const DATE_FULLYEAR_FORMATTER : String = "Y"; /** Year, e.g. 07 on <code>Date</code> objects.*/ const DATE_YEAR_FORMATTER : String = "y"; /** Month from 1 to 12 on <code>Date</code> objects.*/ const DATE_MONTH_FORMATTER : String = "m"; /** Hours (0-23) on <code>Date</code> objects.*/ const DATE_HOUR24_FORMATTER : String = "H"; /** Hours 0-12 on <code>Date</code> objects.*/ const DATE_HOUR_FORMATTER : String = "I"; /** a.m or p.m on <code>Date</code> objects.*/ const DATE_HOUR_AMPM_FORMATTER : String = "p"; /** Minutes on <code>Date</code> objects.*/ const DATE_MINUTES_FORMATTER : String = "M"; /** Seconds on <code>Date</code> objects.*/ const DATE_SECONDS_FORMATTER : String = "S"; /** A string rep of a <code>Date</code> object on the current locale.*/ const DATE_TOLOCALE_FORMATTER : String = "c"; var version : String = "$Id$"; /** @private * Internal class that normalizes matching information. */ class Match{ public var startIndex : int; public var endIndex : int; public var length : int; public var content : String; public var replacement : String; public var before : String; public function toString() : String{ return "Match [" + startIndex + " - " + endIndex + "] (" + length + ") " + content + ", replacement:" + replacement + ";"; } } /** @private */ function padString(str:String, paddingNum:int, paddingChar:String=" ") : String { if(paddingChar == null) return str; return new Array(paddingNum).join(paddingChar).substr(0,paddingNum-str.length).concat(str); }
fix the padding length
fix the padding length
ActionScript
mit
arthur-debert/printf-as3
29a49cc760521f33b4cad884e1c515115fe2d6f1
exporter/src/main/as/flump/export/Publisher.as
exporter/src/main/as/flump/export/Publisher.as
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.filesystem.File; import flash.filesystem.FileMode; import flash.filesystem.FileStream; import flash.utils.ByteArray; import flump.mold.MovieMold; import flump.xfl.XflLibrary; import com.threerings.util.Log; public class Publisher { public function Publisher(exportDir :File, format :Format, ...formats) { _exportDir = exportDir; _formats.push(format); for each (format in formats) _formats.push(format); } public function modified (lib :XflLibrary) :Boolean { const destDir :File = _exportDir.resolvePath(lib.location); for each (var format :Format in _formats) { var metadata :File = format.getMetadata(destDir); if (!metadata.exists) return true; var stream :FileStream = new FileStream(); stream.open(metadata, FileMode.READ); var bytes :ByteArray = new ByteArray(); stream.readBytes(bytes); stream.close(); try { if (format.extractMd5(bytes) != lib.md5) return true; } catch (e :Error) { log.warning("Hit exception parsing existing metadata; calling it modified", e); return true; } } return false; } public function publish (lib :XflLibrary, authoredDevice :DeviceType) :void { var packers :Vector.<Packer> = new <Packer>[ new Packer(DeviceType.IPHONE_RETINA, authoredDevice, lib), new Packer(DeviceType.IPHONE, authoredDevice, lib) ]; const destDir :File = _exportDir.resolvePath(lib.location); destDir.createDirectory(); for each (var packer :Packer in packers) { for each (var atlas :Atlas in packer.atlases) { atlas.publish(_exportDir); } } const symbolMovies :Vector.<MovieMold> = lib.movies.filter( function (movie :MovieMold, ..._) :Boolean { return movie.symbol != null }); for each (var format :Format in _formats) { var out :FileStream = new FileStream(); out.open(format.getMetadata(destDir), FileMode.WRITE); format.publish(out, lib, symbolMovies, packers, authoredDevice); out.close(); } } private var _exportDir :File; private const _formats :Vector.<Format> = new Vector.<Format>(); private static const log :Log = Log.getLog(Publisher); } }
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.filesystem.File; import flash.filesystem.FileMode; import flash.filesystem.FileStream; import flash.utils.ByteArray; import flump.mold.MovieMold; import flump.xfl.XflLibrary; import com.threerings.util.Log; public class Publisher { public function Publisher(exportDir :File, format :Format, ...formats) { _exportDir = exportDir; _formats.push(format); for each (format in formats) _formats.push(format); } public function modified (lib :XflLibrary) :Boolean { const destDir :File = _exportDir.resolvePath(lib.location); for each (var format :Format in _formats) { var metadata :File = format.getMetadata(destDir); if (!metadata.exists) return true; var stream :FileStream = new FileStream(); stream.open(metadata, FileMode.READ); var bytes :ByteArray = new ByteArray(); stream.readBytes(bytes); stream.close(); try { if (format.extractMd5(bytes) != lib.md5) return true; } catch (e :Error) { log.warning("Hit exception parsing existing metadata; calling it modified", e); return true; } } return false; } public function publish (lib :XflLibrary, authoredDevice :DeviceType) :void { var packers :Vector.<Packer> = new <Packer>[ new Packer(DeviceType.IPHONE_RETINA, authoredDevice, lib), new Packer(DeviceType.IPHONE, authoredDevice, lib) ]; const destDir :File = _exportDir.resolvePath(lib.location); destDir.createDirectory(); // Ensure any previously generated atlases don't linger for each (var file :File in destDir.getDirectoryListing()) { if (file.name.match(/atlas.*\.png/)) file.deleteFile(); } for each (var packer :Packer in packers) { for each (var atlas :Atlas in packer.atlases) { atlas.publish(_exportDir); } } const symbolMovies :Vector.<MovieMold> = lib.movies.filter( function (movie :MovieMold, ..._) :Boolean { return movie.symbol != null }); for each (var format :Format in _formats) { var out :FileStream = new FileStream(); out.open(format.getMetadata(destDir), FileMode.WRITE); format.publish(out, lib, symbolMovies, packers, authoredDevice); out.close(); } } private var _exportDir :File; private const _formats :Vector.<Format> = new Vector.<Format>(); private static const log :Log = Log.getLog(Publisher); } }
Remove old atlases before publishing.
Remove old atlases before publishing. Previously, if a movie was changed to use fewer atlases and re-exported, old atlases would still be around.
ActionScript
mit
tconkling/flump,funkypandagame/flump,funkypandagame/flump,mathieuanthoine/flump,tconkling/flump,mathieuanthoine/flump,mathieuanthoine/flump
7afc78e903572940da6fb30afd9498d6e954bcbd
net/flashpunk/utils/Input.as
net/flashpunk/utils/Input.as
package net.flashpunk.utils { import flash.display.Stage; import flash.events.KeyboardEvent; import flash.events.MouseEvent; import flash.ui.Keyboard; import net.flashpunk.*; /** * Static class updated by Engine. Use for defining and checking keyboard/mouse input. */ public class Input { /** * An updated string containing the last 100 characters pressed on the keyboard. * Useful for creating text input fields, such as highscore entries, etc. */ public static var keyString:String = ""; /** * If the mouse button is down. */ public static var mouseDown:Boolean = false; /** * If the mouse button is up. */ public static var mouseUp:Boolean = true; /** * If the mouse button was pressed this frame. */ public static var mousePressed:Boolean = false; /** * If the mouse button was released this frame. */ public static var mouseReleased:Boolean = false; /** * X position of the mouse on the screen. */ public static function get mouseX():int { return FP.screen.mouseX; } /** * Y position of the mouse on the screen. */ public static function get mouseY():int { return FP.screen.mouseY; } /** * Defines a new input. * @param name String to map the input to. * @param ...keys The keys to use for the Input. */ public static function define(name:String, ...keys):void { _control[name] = Vector.<int>(keys); } /** * If the input or key is held down. * @param input An input name or key to check for. * @return True or false. */ public static function check(input:*):Boolean { if (input is String) { var v:Vector.<int> = _control[input], i:int = v.length; while (i --) { if (v[i] < 0) { if (_keyNum > 0) return true; continue; } if (_key[v[i]]) return true; } return false; } return input < 0 ? _keyNum > 0 : _key[input]; } /** * If the input or key was pressed this frame. * @param input An input name or key to check for. * @return True or false. */ public static function pressed(input:*):Boolean { if (input is String) { var v:Vector.<int> = _control[input], i:int = v.length; while (i --) { if ((v[i] < 0 && _press.length) || _press.indexOf(v[i]) >= 0) return true; } return false; } return (input < 0 && _press.length) || _press.indexOf(input) >= 0; } /** * If the input or key was released this frame. * @param input An input name or key to check for. * @return True or false. */ public static function released(input:*):Boolean { if (input is String) { var v:Vector.<int> = _control[input], i:int = v.length; while (i --) { if ((v[i] < 0 && _release.length) || _release.indexOf(v[i]) >= 0) return true; } return false; } return (input < 0 && _release.length) || _release.indexOf(input) >= 0; } /** * Returns the keys mapped to the input name. * @param name The input name. * @return A Vector of keys. */ public static function keys(name:String):Vector.<int> { return _control[name] as Vector.<int>; } /** @private Called by Engine to enable keyboard input on the stage. */ public static function enable():void { if (!_enabled && FP.stage) { FP.stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown); FP.stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp); FP.stage.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown); FP.stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp); _enabled = true; } } /** @private Called by Engine to update the input. */ public static function update():void { while (_pressNum --) _press[_pressNum] = -1; _pressNum = 0; while (_releaseNum --) _release[_releaseNum] = -1; _releaseNum = 0; if (mousePressed) mousePressed = false; if (mouseReleased) mouseReleased = false; } /** @private Event handler for key press. */ private static function onKeyDown(e:KeyboardEvent):void { // get the keycode var code:int = e.keyCode; // update the keystring if (code == Key.BACKSPACE) keyString = keyString.substring(0, keyString.length - 1); else if ((code > 47 && code < 58) || (code > 64 && code < 91) || code == 32) { if (keyString.length > KEYSTRING_MAX) keyString = keyString.substring(1); var char:String = String.fromCharCode(code); if (e.shiftKey || Keyboard.capsLock) char = char.toLocaleUpperCase(); else char = char.toLocaleLowerCase(); keyString += char; } // update the keystate if (!_key[code]) { _key[code] = true; _keyNum ++; _press[_pressNum ++] = code; } } /** @private Event handler for key release. */ private static function onKeyUp(e:KeyboardEvent):void { // get the keycode and update the keystate var code:int = e.keyCode; if (_key[code]) { _key[code] = false; _keyNum --; _release[_releaseNum ++] = code; } } /** @private Event handler for mouse press. */ private static function onMouseDown(e:MouseEvent):void { if (!mouseDown) { mouseDown = true; mouseUp = false; mousePressed = true; mouseReleased = false; } } /** @private Event handler for mouse release. */ private static function onMouseUp(e:MouseEvent):void { mouseDown = false; mouseUp = true; mousePressed = false; mouseReleased = true; } // Max amount of characters stored by the keystring. /** @private */ private static const KEYSTRING_MAX:uint = 100; // Input information. /** @private */ private static var _enabled:Boolean = false; /** @private */ private static var _key:Vector.<Boolean> = new Vector.<Boolean>(256); /** @private */ private static var _keyNum:int = 0; /** @private */ private static var _press:Vector.<int> = new Vector.<int>(256); /** @private */ private static var _release:Vector.<int> = new Vector.<int>(256); /** @private */ private static var _pressNum:int = 0; /** @private */ private static var _releaseNum:int = 0; /** @private */ private static var _control:Array = []; } }
package net.flashpunk.utils { import flash.display.Stage; import flash.events.KeyboardEvent; import flash.events.MouseEvent; import flash.ui.Keyboard; import net.flashpunk.*; /** * Static class updated by Engine. Use for defining and checking keyboard/mouse input. */ public class Input { /** * An updated string containing the last 100 characters pressed on the keyboard. * Useful for creating text input fields, such as highscore entries, etc. */ public static var keyString:String = ""; /** * If the mouse button is down. */ public static var mouseDown:Boolean = false; /** * If the mouse button is up. */ public static var mouseUp:Boolean = true; /** * If the mouse button was pressed this frame. */ public static var mousePressed:Boolean = false; /** * If the mouse button was released this frame. */ public static var mouseReleased:Boolean = false; /** * If the mouse wheel was moved this frame. */ public static var mouseWheel:Boolean = false; /** * If the mouse wheel was moved this frame, this was the delta. */ public static function get mouseWheelDelta():int { if (mouseWheel) { mouseWheel = false; return _mouseWheelDelta; } else { return 0; } } /** * X position of the mouse on the screen. */ public static function get mouseX():int { return FP.screen.mouseX; } /** * Y position of the mouse on the screen. */ public static function get mouseY():int { return FP.screen.mouseY; } /** * Defines a new input. * @param name String to map the input to. * @param ...keys The keys to use for the Input. */ public static function define(name:String, ...keys):void { _control[name] = Vector.<int>(keys); } /** * If the input or key is held down. * @param input An input name or key to check for. * @return True or false. */ public static function check(input:*):Boolean { if (input is String) { var v:Vector.<int> = _control[input], i:int = v.length; while (i --) { if (v[i] < 0) { if (_keyNum > 0) return true; continue; } if (_key[v[i]]) return true; } return false; } return input < 0 ? _keyNum > 0 : _key[input]; } /** * If the input or key was pressed this frame. * @param input An input name or key to check for. * @return True or false. */ public static function pressed(input:*):Boolean { if (input is String) { var v:Vector.<int> = _control[input], i:int = v.length; while (i --) { if ((v[i] < 0 && _press.length) || _press.indexOf(v[i]) >= 0) return true; } return false; } return (input < 0 && _press.length) || _press.indexOf(input) >= 0; } /** * If the input or key was released this frame. * @param input An input name or key to check for. * @return True or false. */ public static function released(input:*):Boolean { if (input is String) { var v:Vector.<int> = _control[input], i:int = v.length; while (i --) { if ((v[i] < 0 && _release.length) || _release.indexOf(v[i]) >= 0) return true; } return false; } return (input < 0 && _release.length) || _release.indexOf(input) >= 0; } /** * Returns the keys mapped to the input name. * @param name The input name. * @return A Vector of keys. */ public static function keys(name:String):Vector.<int> { return _control[name] as Vector.<int>; } /** @private Called by Engine to enable keyboard input on the stage. */ public static function enable():void { if (!_enabled && FP.stage) { FP.stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown); FP.stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp); FP.stage.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown); FP.stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp); FP.stage.addEventListener(MouseEvent.MOUSE_WHEEL, onMouseWheel); _enabled = true; } } /** @private Called by Engine to update the input. */ public static function update():void { while (_pressNum --) _press[_pressNum] = -1; _pressNum = 0; while (_releaseNum --) _release[_releaseNum] = -1; _releaseNum = 0; if (mousePressed) mousePressed = false; if (mouseReleased) mouseReleased = false; } /** @private Event handler for key press. */ private static function onKeyDown(e:KeyboardEvent):void { // get the keycode var code:int = e.keyCode; // update the keystring if (code == Key.BACKSPACE) keyString = keyString.substring(0, keyString.length - 1); else if ((code > 47 && code < 58) || (code > 64 && code < 91) || code == 32) { if (keyString.length > KEYSTRING_MAX) keyString = keyString.substring(1); var char:String = String.fromCharCode(code); if (e.shiftKey || Keyboard.capsLock) char = char.toLocaleUpperCase(); else char = char.toLocaleLowerCase(); keyString += char; } // update the keystate if (!_key[code]) { _key[code] = true; _keyNum ++; _press[_pressNum ++] = code; } } /** @private Event handler for key release. */ private static function onKeyUp(e:KeyboardEvent):void { // get the keycode and update the keystate var code:int = e.keyCode; if (_key[code]) { _key[code] = false; _keyNum --; _release[_releaseNum ++] = code; } } /** @private Event handler for mouse press. */ private static function onMouseDown(e:MouseEvent):void { if (!mouseDown) { mouseDown = true; mouseUp = false; mousePressed = true; mouseReleased = false; } } /** @private Event handler for mouse release. */ private static function onMouseUp(e:MouseEvent):void { mouseDown = false; mouseUp = true; mousePressed = false; mouseReleased = true; } /** @private Event handler for mouse wheel events */ private static function onMouseWheel(e:MouseEvent):void { mouseWheel = true; _mouseWheelDelta = e.delta; } // Max amount of characters stored by the keystring. /** @private */ private static const KEYSTRING_MAX:uint = 100; // Input information. /** @private */ private static var _enabled:Boolean = false; /** @private */ private static var _key:Vector.<Boolean> = new Vector.<Boolean>(256); /** @private */ private static var _keyNum:int = 0; /** @private */ private static var _press:Vector.<int> = new Vector.<int>(256); /** @private */ private static var _release:Vector.<int> = new Vector.<int>(256); /** @private */ private static var _pressNum:int = 0; /** @private */ private static var _releaseNum:int = 0; /** @private */ private static var _control:Array = []; /** @private */ private static var _mouseWheelDelta:int = 0; } }
add rudimentary support for mouse eheel events in Input system
add rudimentary support for mouse eheel events in Input system
ActionScript
mit
Ken69267/config-stuff,Ken69267/config-stuff,Ken69267/config-stuff,Ken69267/config-stuff,Ken69267/config-stuff
11936f95caaf7f10094348f278a75c17642e72cc
src/justpinegames/Logi/ConsoleItemRenderer.as
src/justpinegames/Logi/ConsoleItemRenderer.as
package justpinegames.Logi { import feathers.controls.List; import feathers.controls.renderers.IListItemRenderer; import feathers.controls.text.BitmapFontTextRenderer; import feathers.core.FeathersControl; import feathers.text.BitmapFontTextFormat; import org.osflash.signals.ISignal; import org.osflash.signals.Signal; import starling.events.Event; import starling.text.BitmapFont; import starling.textures.TextureSmoothing; internal class ConsoleItemRenderer extends FeathersControl implements IListItemRenderer { private static var _format:BitmapFontTextFormat = null; private static var _formatHighlight:BitmapFontTextFormat = null; private var _onChange:Signal = new Signal(ConsoleItemRenderer); private var _data:Object; private var _index:int; private var _owner:List; private var _isSelected:Boolean; private var _label:BitmapFontTextRenderer; public function ConsoleItemRenderer(labelColor:int, labelColorHighlight:int) { _format = _format ? _format : new BitmapFontTextFormat(new BitmapFont(), 16, labelColor); _formatHighlight = _formatHighlight ? _formatHighlight : new BitmapFontTextFormat(new BitmapFont(), 16, labelColorHighlight); _label = new BitmapFontTextRenderer(); _label.addEventListener(Event.ADDED, function(e:Event):void { _label.textFormat = _format; }); _label.smoothing = TextureSmoothing.NONE; this.addChild(_label); } public function get data():Object { return _data; } public function set data(value:Object):void { if (value == null) { return; } _label.text = value.label; _data = value; } public function get index():int { return _index; } public function set index(value:int):void { _index = value; } public function get owner():List { return _owner; } public function set owner(value:List):void { _owner = value; } public function get isSelected():Boolean { return _isSelected; } public function set isSelected(value:Boolean):void { if (_isSelected == value) { return; } if (value) { _label.textFormat = _formatHighlight; } else { _label.textFormat = _format; } _isSelected = value; _onChange.dispatch(this); } public function get onChange():ISignal { return this._onChange; } } }
package justpinegames.Logi { import feathers.controls.List; import feathers.controls.renderers.IListItemRenderer; import feathers.controls.text.BitmapFontTextRenderer; import feathers.core.FeathersControl; import feathers.text.BitmapFontTextFormat; import starling.events.Event; import starling.text.BitmapFont; import starling.textures.TextureSmoothing; internal class ConsoleItemRenderer extends FeathersControl implements IListItemRenderer { private static var _format:BitmapFontTextFormat = null; private static var _formatHighlight:BitmapFontTextFormat = null; private var _data:Object; private var _index:int; private var _owner:List; private var _isSelected:Boolean; private var _label:BitmapFontTextRenderer; [Event(name="change",type="starling.events.Event")] public function ConsoleItemRenderer(labelColor:int, labelColorHighlight:int) { _format = _format ? _format : new BitmapFontTextFormat(new BitmapFont(), 16, labelColor); _formatHighlight = _formatHighlight ? _formatHighlight : new BitmapFontTextFormat(new BitmapFont(), 16, labelColorHighlight); _label = new BitmapFontTextRenderer(); _label.addEventListener(Event.ADDED, function(e:Event):void { _label.textFormat = _format; }); _label.smoothing = TextureSmoothing.NONE; this.addChild(_label); } public function get data():Object { return _data; } public function set data(value:Object):void { if (value == null) { return; } _label.text = value.label; _data = value; } public function get index():int { return _index; } public function set index(value:int):void { _index = value; } public function get owner():List { return _owner; } public function set owner(value:List):void { _owner = value; } public function get isSelected():Boolean { return _isSelected; } public function set isSelected(value:Boolean):void { if (_isSelected == value) { return; } if (value) { _label.textFormat = _formatHighlight; } else { _label.textFormat = _format; } _isSelected = value; dispatchEventWith(Event.CHANGE); } } }
Update src/justpinegames/Logi/ConsoleItemRenderer.as
Update src/justpinegames/Logi/ConsoleItemRenderer.as Removed Signals dependency bringing this library in line with Feathers
ActionScript
mit
justpinegames/Logi,justpinegames/Logi
4b9a95744efe0a6abf7679aa9f07def77af076e6
generator/sources/as3/delegates/QueuedRequestDelegate.as
generator/sources/as3/delegates/QueuedRequestDelegate.as
package com.kaltura.delegates { import com.kaltura.commands.MultiRequest; import com.kaltura.commands.QueuedRequest; import com.kaltura.config.KalturaConfig; import com.kaltura.errors.KalturaError; import com.kaltura.net.KalturaCall; import flash.utils.getDefinitionByName; import flash.utils.getQualifiedClassName; public class QueuedRequestDelegate extends WebDelegateBase { public function QueuedRequestDelegate(call:KalturaCall = null, config:KalturaConfig = null) { super(call, config); } override public function parse( result : XML ) : * { var resArr : Array = new Array(); var resInd:int = 0; // index for scanning result for ( var i:int=0; i<(call as QueuedRequest).calls.length; i++ ) { var callClassName : String = getQualifiedClassName( (call as QueuedRequest).calls[i] ); var commandName : String = callClassName.split("::")[1]; var packageArr : Array = (callClassName.split("::")[0]).split("."); var importFrom : String = packageArr[packageArr.length-1]; var clsName : String ; var cls : Class; var myInst : Object; if (commandName == "MultiRequest") { clsName = "com.kaltura.delegates.MultiRequestDelegate"; cls = getDefinitionByName( clsName ) as Class; myInst = new cls(null , null); // set the call after the constructor, so we don't fire execute() myInst.call = (call as QueuedRequest).calls[i]; } else { clsName = "com.kaltura.delegates."+importFrom+"."+ commandName +"Delegate"; //'com.kaltura.delegates.session.SessionStartDelegate' cls = getDefinitionByName( clsName ) as Class;//(') as Class; myInst = new cls(null , null); } //build the result as a regular result var xml : String = "<result><result>"; if (commandName == "MultiRequest") { // add as many items as the multirequest had var nActions:int = ((call as QueuedRequest).calls[i] as MultiRequest).actions.length; for (var j:int = 0; j<nActions ; j++) { xml += result.result.item[j + resInd].toXMLString(); } // skip to the result of the next call that wasn't part of the MR: resInd+= nActions; } else { xml += result.result.item[resInd].children().toString(); resInd++; } xml +="</result></result>"; // add the item or a matching error: var kErr:KalturaError = validateKalturaResponse(xml); if (kErr == null) { var res : XML = new XML(xml); try { var obj : Object = (myInst as WebDelegateBase).parse( res ); resArr.push( obj ); } catch (e:Error) { kErr = new KalturaError(); kErr.errorCode = String(e.errorID); kErr.errorMsg = e.message; resArr.push( kErr ); } } else { resArr.push(kErr); } } return resArr; } } }
package com.kaltura.delegates { import com.kaltura.commands.MultiRequest; import com.kaltura.commands.QueuedRequest; import com.kaltura.config.KalturaConfig; import com.kaltura.errors.KalturaError; import com.kaltura.net.KalturaCall; import flash.utils.getDefinitionByName; import flash.utils.getQualifiedClassName; public class QueuedRequestDelegate extends WebDelegateBase { public function QueuedRequestDelegate(call:KalturaCall = null, config:KalturaConfig = null) { super(call, config); } override public function parse( result : XML ) : * { var resArr : Array = new Array(); var resInd:int = 0; // index for scanning result for ( var i:int=0; i<(call as QueuedRequest).calls.length; i++ ) { var callClassName : String = getQualifiedClassName( (call as QueuedRequest).calls[i] ); var commandName : String = callClassName.split("::")[1]; var packageArr : Array = (callClassName.split("::")[0]).split("."); var importFrom : String = packageArr[packageArr.length-1]; var clsName : String ; var cls : Class; var myInst : Object; if (commandName == "MultiRequest") { clsName = "com.kaltura.delegates.MultiRequestDelegate"; cls = getDefinitionByName( clsName ) as Class; myInst = new cls(null , null); // set the call after the constructor, so we don't fire execute() myInst.call = (call as QueuedRequest).calls[i]; } else { clsName = "com.kaltura.delegates."+importFrom+"."+ commandName +"Delegate"; //'com.kaltura.delegates.session.SessionStartDelegate' cls = getDefinitionByName( clsName ) as Class;//(') as Class; myInst = new cls(null , null); } //build the result as a regular result var xml : String = "<result><result>"; if (commandName == "MultiRequest") { // add as many items as the multirequest had var nActions:int = ((call as QueuedRequest).calls[i] as MultiRequest).actions.length; for (var j:int = 0; j<nActions ; j++) { xml += result.result.item[j + resInd].toXMLString(); } // skip to the result of the next call that wasn't part of the MR: resInd+= nActions; } else { xml += result.result.item[resInd].children().toXMLString(); resInd++; } xml +="</result></result>"; // add the item or a matching error: var kErr:KalturaError = validateKalturaResponse(xml); if (kErr == null) { var res : XML = new XML(xml); try { var obj : Object = (myInst as WebDelegateBase).parse( res ); resArr.push( obj ); } catch (e:Error) { kErr = new KalturaError(); kErr.errorCode = String(e.errorID); kErr.errorMsg = e.message; resArr.push( kErr ); } } else { resArr.push(kErr); } } return resArr; } } }
fix for report service
fix for report service git-svn-id: 8a2ccb88241e16c78017770bc38d91d6d5396a5a@60459 6b8eccd3-e8c5-4e7d-8186-e12b5326b719
ActionScript
agpl-3.0
ivesbai/server,ivesbai/server,doubleshot/server,DBezemer/server,matsuu/server,DBezemer/server,doubleshot/server,matsuu/server,kaltura/server,ivesbai/server,gale320/server,jorgevbo/server,DBezemer/server,gale320/server,ratliff/server,jorgevbo/server,gale320/server,ratliff/server,jorgevbo/server,ratliff/server,gale320/server,jorgevbo/server,kaltura/server,gale320/server,matsuu/server,DBezemer/server,doubleshot/server,doubleshot/server,DBezemer/server,DBezemer/server,kaltura/server,ivesbai/server,kaltura/server,ivesbai/server,doubleshot/server,jorgevbo/server,ivesbai/server,kaltura/server,gale320/server,ratliff/server,ratliff/server,doubleshot/server,DBezemer/server,ivesbai/server,DBezemer/server,jorgevbo/server,doubleshot/server,gale320/server,matsuu/server,doubleshot/server,matsuu/server,ratliff/server,jorgevbo/server,matsuu/server,matsuu/server,matsuu/server,gale320/server,ivesbai/server,kaltura/server,ratliff/server,ratliff/server,jorgevbo/server
1115c040fa10e61735e639afdf04b17bad5e2608
src/org/mangui/hls/controller/LevelController.as
src/org/mangui/hls/controller/LevelController.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.controller { import org.mangui.hls.constant.HLSLoaderTypes; import org.mangui.hls.constant.HLSMaxLevelCappingMode; import org.mangui.hls.event.HLSEvent; import org.mangui.hls.event.HLSLoadMetrics; import org.mangui.hls.HLS; import org.mangui.hls.HLSSettings; import org.mangui.hls.model.Level; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } /** Class that manages auto level selection * * this is an implementation based on Serial segment fetching method from * http://www.cs.tut.fi/~moncef/publications/rate-adaptation-IC-2011.pdf */ public class LevelController { /** Reference to the HLS controller. **/ private var _hls : HLS; /** switch up threshold **/ private var _switchup : Vector.<Number> = null; /** switch down threshold **/ private var _switchdown : Vector.<Number> = null; /** bitrate array **/ private var _bitrate : Vector.<Number> = null; /** vector of levels with unique dimension with highest bandwidth **/ private var _maxUniqueLevels : Vector.<Level> = null; /** nb level **/ private var _nbLevel : int = 0; private var _lastSegmentDuration : Number; private var _lastFetchDuration : Number; private var lastBandwidth : Number; private var _autoLevelCapping : int = -1; private var _startLevel : int = -1; private var _fpsController : FPSController; /** Create the loader. **/ public function LevelController(hls : HLS) : void { _hls = hls; _fpsController = new FPSController(hls); _hls.addEventListener(HLSEvent.MANIFEST_PARSED, _manifestParsedHandler); _hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestLoadedHandler); _hls.addEventListener(HLSEvent.FRAGMENT_LOADED, _fragmentLoadedHandler); } ; public function dispose() : void { _fpsController.dispose(); _fpsController = null; _hls.removeEventListener(HLSEvent.MANIFEST_PARSED, _manifestParsedHandler); _hls.removeEventListener(HLSEvent.MANIFEST_LOADED, _manifestLoadedHandler); _hls.removeEventListener(HLSEvent.FRAGMENT_LOADED, _fragmentLoadedHandler); } private function _fragmentLoadedHandler(event : HLSEvent) : void { var metrics : HLSLoadMetrics = event.loadMetrics; // only monitor main fragment metrics for level switching if(metrics.type == HLSLoaderTypes.FRAGMENT_MAIN) { lastBandwidth = metrics.bandwidth; _lastSegmentDuration = metrics.duration; _lastFetchDuration = metrics.processing_duration; } } private function _manifestParsedHandler(event : HLSEvent) : void { // upon manifest parsed event, trigger a level switch to load startLevel playlist _hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_SWITCH, _hls.startLevel)); } private function _manifestLoadedHandler(event : HLSEvent) : void { var levels : Vector.<Level> = event.levels; var maxswitchup : Number = 0; var minswitchdwown : Number = Number.MAX_VALUE; _nbLevel = levels.length; _bitrate = new Vector.<Number>(_nbLevel, true); _switchup = new Vector.<Number>(_nbLevel, true); _switchdown = new Vector.<Number>(_nbLevel, true); _lastSegmentDuration = 0; _lastFetchDuration = 0; lastBandwidth = 0; var i : int; for (i = 0; i < _nbLevel; i++) { _bitrate[i] = levels[i].bitrate; } for (i = 0; i < _nbLevel - 1; i++) { _switchup[i] = (_bitrate[i + 1] - _bitrate[i]) / _bitrate[i]; maxswitchup = Math.max(maxswitchup, _switchup[i]); } for (i = 0; i < _nbLevel - 1; i++) { _switchup[i] = Math.min(maxswitchup, 2 * _switchup[i]); CONFIG::LOGGING { Log.debug("_switchup[" + i + "]=" + _switchup[i]); } } for (i = 1; i < _nbLevel; i++) { _switchdown[i] = (_bitrate[i] - _bitrate[i - 1]) / _bitrate[i]; minswitchdwown = Math.min(minswitchdwown, _switchdown[i]); } for (i = 1; i < _nbLevel; i++) { _switchdown[i] = Math.max(2 * minswitchdwown, _switchdown[i]); CONFIG::LOGGING { Log.debug("_switchdown[" + i + "]=" + _switchdown[i]); } } if (HLSSettings.capLevelToStage) { _maxUniqueLevels = _maxLevelsWithUniqueDimensions; } } ; public function getbestlevel(downloadBandwidth : Number) : int { var max_level : int = _maxLevel; for (var i : int = max_level; i >= 0; i--) { if (_bitrate[i] <= downloadBandwidth) { return i; } } return 0; } private function get _maxLevelsWithUniqueDimensions() : Vector.<Level> { var filter : Function = function(l : Level, i : int, v : Vector.<Level>) : Boolean { if (l.width > 0 && l.height > 0) { if (i + 1 < v.length) { var nextLevel : Level = v[i + 1]; if (l.width != nextLevel.width && l.height != nextLevel.height) { return true; } } else { return true; } } return false; }; return _hls.levels.filter(filter); } /** Return the capping/max level value that could be used by automatic level selection algorithm **/ public function get autoLevelCapping() : int { return _autoLevelCapping; } /** set the capping/max level value that could be used by automatic level selection algorithm **/ public function set autoLevelCapping(newLevel : int) : void { _autoLevelCapping = newLevel; } private function get _maxLevel() : int { // if set, _autoLevelCapping takes precedence if(_autoLevelCapping >= 0) { return Math.min(_nbLevel - 1, _autoLevelCapping); } else if (HLSSettings.capLevelToStage) { var maxLevelsCount : int = _maxUniqueLevels.length; if (_hls.stage && maxLevelsCount) { var maxLevel : Level = this._maxUniqueLevels[0], maxLevelIdx : int = maxLevel.index, sWidth : Number = this._hls.stage.stageWidth, sHeight : Number = this._hls.stage.stageHeight, lWidth : int, lHeight : int, i : int; switch (HLSSettings.maxLevelCappingMode) { case HLSMaxLevelCappingMode.UPSCALE: for (i = maxLevelsCount - 1; i >= 0; i--) { maxLevel = this._maxUniqueLevels[i]; maxLevelIdx = maxLevel.index; lWidth = maxLevel.width; lHeight = maxLevel.height; CONFIG::LOGGING { Log.debug("stage size: " + sWidth + "x" + sHeight + " ,level" + maxLevelIdx + " size: " + lWidth + "x" + lHeight); } if (sWidth >= lWidth || sHeight >= lHeight) { break; // from for loop } } break; case HLSMaxLevelCappingMode.DOWNSCALE: for (i = 0; i < maxLevelsCount; i++) { maxLevel = this._maxUniqueLevels[i]; maxLevelIdx = maxLevel.index; lWidth = maxLevel.width; lHeight = maxLevel.height; CONFIG::LOGGING { Log.debug("stage size: " + sWidth + "x" + sHeight + " ,level" + maxLevelIdx + " size: " + lWidth + "x" + lHeight); } if (sWidth <= lWidth || sHeight <= lHeight) { break; // from for loop } } break; } CONFIG::LOGGING { Log.debug("max capped level idx: " + maxLevelIdx); } } return maxLevelIdx; } else { return _nbLevel - 1; } } /** Update the quality level for the next fragment load. **/ public function getnextlevel(current_level : int, buffer : Number) : int { if (_lastFetchDuration == 0 || _lastSegmentDuration == 0) { return 0; } /* rsft : remaining segment fetch time : available time to fetch next segment it depends on the current playback timestamp , the timestamp of the first frame of the next segment and TBMT, indicating a desired latency between the time instant to receive the last byte of a segment to the playback of the first media frame of a segment buffer is start time of next segment TBMT is the buffer size we need to ensure (we need at least 2 segments buffered */ var rsft : Number = 1000 * buffer - 2 * _lastFetchDuration; var sftm : Number = Math.min(_lastSegmentDuration, rsft) / _lastFetchDuration; var max_level : Number = _maxLevel; var switch_to_level : int = current_level; // CONFIG::LOGGING { // Log.info("rsft:" + rsft); // Log.info("sftm:" + sftm); // } // } /* to switch level up : rsft should be greater than switch up condition */ if ((current_level < max_level) && (sftm > (1 + _switchup[current_level]))) { CONFIG::LOGGING { Log.debug("sftm:> 1+_switchup[_level]=" + (1 + _switchup[current_level])); } switch_to_level = current_level + 1; } /* to switch level down : rsft should be smaller than switch up condition, or the current level is greater than max level */ else if ((current_level > max_level && current_level > 0) || (current_level > 0 && (sftm < 1 - _switchdown[current_level]))) { CONFIG::LOGGING { Log.debug("sftm < 1-_switchdown[current_level]=" + _switchdown[current_level]); } var bufferratio : Number = 1000 * buffer / _lastSegmentDuration; /* find suitable level matching current bandwidth, starting from current level when switching level down, we also need to consider that we might need to load two fragments. the condition (bufferratio > 2*_levels[j].bitrate/_lastBandwidth) ensures that buffer time is bigger than than the time to download 2 fragments from level j, if we keep same bandwidth. */ for (var j : int = current_level - 1; j >= 0; j--) { if (_bitrate[j] <= lastBandwidth && (bufferratio > 2 * _bitrate[j] / lastBandwidth)) { switch_to_level = j; break; } if (j == 0) { switch_to_level = 0; } } } // Then we should check if selected level is higher than max_level if so, than take the min of those two switch_to_level = Math.min(max_level, switch_to_level); CONFIG::LOGGING { if (switch_to_level != current_level) { Log.debug("switch to level " + switch_to_level); } } return switch_to_level; } // get level index of first level appearing in the manifest public function get firstLevel() : int { var levels : Vector.<Level> = _hls.levels; for (var i : int = 0; i < levels.length; i++) { if (levels[i].manifest_index == 0) { return i; } } return 0; } /* set the quality level used when starting a fresh playback */ public function set startLevel(level : int) : void { _startLevel = level; }; public function get startLevel() : int { var start_level : int = -1; var levels : Vector.<Level> = _hls.levels; if (levels) { // if set, _startLevel takes precedence if(_startLevel >=0) { return Math.min(levels.length-1,_startLevel); } else if (HLSSettings.startFromLevel === -2) { // playback will start from the first level appearing in Manifest (not sorted by bitrate) return firstLevel; } else if (HLSSettings.startFromLevel === -1 && HLSSettings.startFromBitrate === -1) { /* if startFromLevel is set to -1, it means that effective startup level * will be determined from first segment download bandwidth * let's use lowest bitrate for this download bandwidth assessment * this should speed up playback start time */ return 0; } else { // set up start level as being the lowest non-audio level. for (var i : int = 0; i < levels.length; i++) { if (!levels[i].audio) { start_level = i; break; } } // in case of audio only playlist, force startLevel to 0 if (start_level == -1) { CONFIG::LOGGING { Log.info("playlist is audio-only"); } start_level = 0; } else { if (HLSSettings.startFromBitrate > 0) { start_level = findIndexOfClosestLevel(HLSSettings.startFromBitrate); } else if (HLSSettings.startFromLevel > 0) { // adjust start level using a rule by 3 start_level += Math.round(HLSSettings.startFromLevel * (levels.length - start_level - 1)); } } } CONFIG::LOGGING { Log.debug("start level :" + start_level); } } return start_level; } /** * @param desiredBitrate * @return The index of the level that has a bitrate closest to the desired bitrate. */ private function findIndexOfClosestLevel(desiredBitrate : Number) : int { var levelIndex : int = -1; var minDistance : Number = Number.MAX_VALUE; var levels : Vector.<Level> = _hls.levels; for (var index : int = 0; index < levels.length; index++) { var level : Level = levels[index]; var distance : Number = Math.abs(desiredBitrate - level.bitrate); if (distance < minDistance) { levelIndex = index; minDistance = distance; } } return levelIndex; } public function get seekLevel() : int { var seek_level : int = -1; var levels : Vector.<Level> = _hls.levels; if (HLSSettings.seekFromLevel == -1) { // keep last level return _hls.loadLevel; } // set up seek level as being the lowest non-audio level. for (var i : int = 0; i < levels.length; i++) { if (!levels[i].audio) { seek_level = i; break; } } // in case of audio only playlist, force seek_level to 0 if (seek_level == -1) { seek_level = 0; } else { if (HLSSettings.seekFromLevel > 0) { // adjust start level using a rule by 3 seek_level += Math.round(HLSSettings.seekFromLevel * (levels.length - seek_level - 1)); } } CONFIG::LOGGING { Log.debug("seek level :" + seek_level); } return seek_level; } } }
/* 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.controller { import org.mangui.hls.constant.HLSLoaderTypes; import org.mangui.hls.constant.HLSMaxLevelCappingMode; import org.mangui.hls.event.HLSEvent; import org.mangui.hls.event.HLSLoadMetrics; import org.mangui.hls.HLS; import org.mangui.hls.HLSSettings; import org.mangui.hls.model.Level; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } /** Class that manages auto level selection * * this is an implementation based on Serial segment fetching method from * http://www.cs.tut.fi/~moncef/publications/rate-adaptation-IC-2011.pdf */ public class LevelController { /** Reference to the HLS controller. **/ private var _hls : HLS; /** switch up threshold **/ private var _switchup : Vector.<Number> = null; /** switch down threshold **/ private var _switchdown : Vector.<Number> = null; /** bitrate array **/ private var _bitrate : Vector.<Number> = null; /** vector of levels with unique dimension with highest bandwidth **/ private var _maxUniqueLevels : Vector.<Level> = null; /** nb level **/ private var _nbLevel : int = 0; private var _lastSegmentDuration : Number; private var _lastFetchDuration : Number; private var lastBandwidth : Number; private var _autoLevelCapping : int; private var _startLevel : int = -1; private var _fpsController : FPSController; /** Create the loader. **/ public function LevelController(hls : HLS) : void { _hls = hls; _fpsController = new FPSController(hls); _hls.addEventListener(HLSEvent.MANIFEST_PARSED, _manifestParsedHandler); _hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestLoadedHandler); _hls.addEventListener(HLSEvent.FRAGMENT_LOADED, _fragmentLoadedHandler); } ; public function dispose() : void { _fpsController.dispose(); _fpsController = null; _hls.removeEventListener(HLSEvent.MANIFEST_PARSED, _manifestParsedHandler); _hls.removeEventListener(HLSEvent.MANIFEST_LOADED, _manifestLoadedHandler); _hls.removeEventListener(HLSEvent.FRAGMENT_LOADED, _fragmentLoadedHandler); } private function _fragmentLoadedHandler(event : HLSEvent) : void { var metrics : HLSLoadMetrics = event.loadMetrics; // only monitor main fragment metrics for level switching if(metrics.type == HLSLoaderTypes.FRAGMENT_MAIN) { lastBandwidth = metrics.bandwidth; _lastSegmentDuration = metrics.duration; _lastFetchDuration = metrics.processing_duration; } } private function _manifestParsedHandler(event : HLSEvent) : void { // upon manifest parsed event, trigger a level switch to load startLevel playlist _hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_SWITCH, _hls.startLevel)); } private function _manifestLoadedHandler(event : HLSEvent) : void { var levels : Vector.<Level> = event.levels; var maxswitchup : Number = 0; var minswitchdwown : Number = Number.MAX_VALUE; _nbLevel = levels.length; _bitrate = new Vector.<Number>(_nbLevel, true); _switchup = new Vector.<Number>(_nbLevel, true); _switchdown = new Vector.<Number>(_nbLevel, true); _autoLevelCapping = -1; _lastSegmentDuration = 0; _lastFetchDuration = 0; lastBandwidth = 0; var i : int; for (i = 0; i < _nbLevel; i++) { _bitrate[i] = levels[i].bitrate; } for (i = 0; i < _nbLevel - 1; i++) { _switchup[i] = (_bitrate[i + 1] - _bitrate[i]) / _bitrate[i]; maxswitchup = Math.max(maxswitchup, _switchup[i]); } for (i = 0; i < _nbLevel - 1; i++) { _switchup[i] = Math.min(maxswitchup, 2 * _switchup[i]); CONFIG::LOGGING { Log.debug("_switchup[" + i + "]=" + _switchup[i]); } } for (i = 1; i < _nbLevel; i++) { _switchdown[i] = (_bitrate[i] - _bitrate[i - 1]) / _bitrate[i]; minswitchdwown = Math.min(minswitchdwown, _switchdown[i]); } for (i = 1; i < _nbLevel; i++) { _switchdown[i] = Math.max(2 * minswitchdwown, _switchdown[i]); CONFIG::LOGGING { Log.debug("_switchdown[" + i + "]=" + _switchdown[i]); } } if (HLSSettings.capLevelToStage) { _maxUniqueLevels = _maxLevelsWithUniqueDimensions; } } ; public function getbestlevel(downloadBandwidth : Number) : int { var max_level : int = _maxLevel; for (var i : int = max_level; i >= 0; i--) { if (_bitrate[i] <= downloadBandwidth) { return i; } } return 0; } private function get _maxLevelsWithUniqueDimensions() : Vector.<Level> { var filter : Function = function(l : Level, i : int, v : Vector.<Level>) : Boolean { if (l.width > 0 && l.height > 0) { if (i + 1 < v.length) { var nextLevel : Level = v[i + 1]; if (l.width != nextLevel.width && l.height != nextLevel.height) { return true; } } else { return true; } } return false; }; return _hls.levels.filter(filter); } /** Return the capping/max level value that could be used by automatic level selection algorithm **/ public function get autoLevelCapping() : int { return _autoLevelCapping; } /** set the capping/max level value that could be used by automatic level selection algorithm **/ public function set autoLevelCapping(newLevel : int) : void { _autoLevelCapping = newLevel; } private function get _maxLevel() : int { // if set, _autoLevelCapping takes precedence if(_autoLevelCapping >= 0) { return Math.min(_nbLevel - 1, _autoLevelCapping); } else if (HLSSettings.capLevelToStage) { var maxLevelsCount : int = _maxUniqueLevels.length; if (_hls.stage && maxLevelsCount) { var maxLevel : Level = this._maxUniqueLevels[0], maxLevelIdx : int = maxLevel.index, sWidth : Number = this._hls.stage.stageWidth, sHeight : Number = this._hls.stage.stageHeight, lWidth : int, lHeight : int, i : int; switch (HLSSettings.maxLevelCappingMode) { case HLSMaxLevelCappingMode.UPSCALE: for (i = maxLevelsCount - 1; i >= 0; i--) { maxLevel = this._maxUniqueLevels[i]; maxLevelIdx = maxLevel.index; lWidth = maxLevel.width; lHeight = maxLevel.height; CONFIG::LOGGING { Log.debug("stage size: " + sWidth + "x" + sHeight + " ,level" + maxLevelIdx + " size: " + lWidth + "x" + lHeight); } if (sWidth >= lWidth || sHeight >= lHeight) { break; // from for loop } } break; case HLSMaxLevelCappingMode.DOWNSCALE: for (i = 0; i < maxLevelsCount; i++) { maxLevel = this._maxUniqueLevels[i]; maxLevelIdx = maxLevel.index; lWidth = maxLevel.width; lHeight = maxLevel.height; CONFIG::LOGGING { Log.debug("stage size: " + sWidth + "x" + sHeight + " ,level" + maxLevelIdx + " size: " + lWidth + "x" + lHeight); } if (sWidth <= lWidth || sHeight <= lHeight) { break; // from for loop } } break; } CONFIG::LOGGING { Log.debug("max capped level idx: " + maxLevelIdx); } } return maxLevelIdx; } else { return _nbLevel - 1; } } /** Update the quality level for the next fragment load. **/ public function getnextlevel(current_level : int, buffer : Number) : int { if (_lastFetchDuration == 0 || _lastSegmentDuration == 0) { return 0; } /* rsft : remaining segment fetch time : available time to fetch next segment it depends on the current playback timestamp , the timestamp of the first frame of the next segment and TBMT, indicating a desired latency between the time instant to receive the last byte of a segment to the playback of the first media frame of a segment buffer is start time of next segment TBMT is the buffer size we need to ensure (we need at least 2 segments buffered */ var rsft : Number = 1000 * buffer - 2 * _lastFetchDuration; var sftm : Number = Math.min(_lastSegmentDuration, rsft) / _lastFetchDuration; var max_level : Number = _maxLevel; var switch_to_level : int = current_level; // CONFIG::LOGGING { // Log.info("rsft:" + rsft); // Log.info("sftm:" + sftm); // } // } /* to switch level up : rsft should be greater than switch up condition */ if ((current_level < max_level) && (sftm > (1 + _switchup[current_level]))) { CONFIG::LOGGING { Log.debug("sftm:> 1+_switchup[_level]=" + (1 + _switchup[current_level])); } switch_to_level = current_level + 1; } /* to switch level down : rsft should be smaller than switch up condition, or the current level is greater than max level */ else if ((current_level > max_level && current_level > 0) || (current_level > 0 && (sftm < 1 - _switchdown[current_level]))) { CONFIG::LOGGING { Log.debug("sftm < 1-_switchdown[current_level]=" + _switchdown[current_level]); } var bufferratio : Number = 1000 * buffer / _lastSegmentDuration; /* find suitable level matching current bandwidth, starting from current level when switching level down, we also need to consider that we might need to load two fragments. the condition (bufferratio > 2*_levels[j].bitrate/_lastBandwidth) ensures that buffer time is bigger than than the time to download 2 fragments from level j, if we keep same bandwidth. */ for (var j : int = current_level - 1; j >= 0; j--) { if (_bitrate[j] <= lastBandwidth && (bufferratio > 2 * _bitrate[j] / lastBandwidth)) { switch_to_level = j; break; } if (j == 0) { switch_to_level = 0; } } } // Then we should check if selected level is higher than max_level if so, than take the min of those two switch_to_level = Math.min(max_level, switch_to_level); CONFIG::LOGGING { if (switch_to_level != current_level) { Log.debug("switch to level " + switch_to_level); } } return switch_to_level; } // get level index of first level appearing in the manifest public function get firstLevel() : int { var levels : Vector.<Level> = _hls.levels; for (var i : int = 0; i < levels.length; i++) { if (levels[i].manifest_index == 0) { return i; } } return 0; } /* set the quality level used when starting a fresh playback */ public function set startLevel(level : int) : void { _startLevel = level; }; public function get startLevel() : int { var start_level : int = -1; var levels : Vector.<Level> = _hls.levels; if (levels) { // if set, _startLevel takes precedence if(_startLevel >=0) { return Math.min(levels.length-1,_startLevel); } else if (HLSSettings.startFromLevel === -2) { // playback will start from the first level appearing in Manifest (not sorted by bitrate) return firstLevel; } else if (HLSSettings.startFromLevel === -1 && HLSSettings.startFromBitrate === -1) { /* if startFromLevel is set to -1, it means that effective startup level * will be determined from first segment download bandwidth * let's use lowest bitrate for this download bandwidth assessment * this should speed up playback start time */ return 0; } else { // set up start level as being the lowest non-audio level. for (var i : int = 0; i < levels.length; i++) { if (!levels[i].audio) { start_level = i; break; } } // in case of audio only playlist, force startLevel to 0 if (start_level == -1) { CONFIG::LOGGING { Log.info("playlist is audio-only"); } start_level = 0; } else { if (HLSSettings.startFromBitrate > 0) { start_level = findIndexOfClosestLevel(HLSSettings.startFromBitrate); } else if (HLSSettings.startFromLevel > 0) { // adjust start level using a rule by 3 start_level += Math.round(HLSSettings.startFromLevel * (levels.length - start_level - 1)); } } } CONFIG::LOGGING { Log.debug("start level :" + start_level); } } return start_level; } /** * @param desiredBitrate * @return The index of the level that has a bitrate closest to the desired bitrate. */ private function findIndexOfClosestLevel(desiredBitrate : Number) : int { var levelIndex : int = -1; var minDistance : Number = Number.MAX_VALUE; var levels : Vector.<Level> = _hls.levels; for (var index : int = 0; index < levels.length; index++) { var level : Level = levels[index]; var distance : Number = Math.abs(desiredBitrate - level.bitrate); if (distance < minDistance) { levelIndex = index; minDistance = distance; } } return levelIndex; } public function get seekLevel() : int { var seek_level : int = -1; var levels : Vector.<Level> = _hls.levels; if (HLSSettings.seekFromLevel == -1) { // keep last level return _hls.loadLevel; } // set up seek level as being the lowest non-audio level. for (var i : int = 0; i < levels.length; i++) { if (!levels[i].audio) { seek_level = i; break; } } // in case of audio only playlist, force seek_level to 0 if (seek_level == -1) { seek_level = 0; } else { if (HLSSettings.seekFromLevel > 0) { // adjust start level using a rule by 3 seek_level += Math.round(HLSSettings.seekFromLevel * (levels.length - seek_level - 1)); } } CONFIG::LOGGING { Log.debug("seek level :" + seek_level); } return seek_level; } } }
remove forced level capping on new manifest load
remove forced level capping on new manifest load
ActionScript
mpl-2.0
jlacivita/flashls,Corey600/flashls,NicolasSiver/flashls,codex-corp/flashls,thdtjsdn/flashls,clappr/flashls,neilrackett/flashls,thdtjsdn/flashls,clappr/flashls,hola/flashls,mangui/flashls,Corey600/flashls,tedconf/flashls,fixedmachine/flashls,neilrackett/flashls,vidible/vdb-flashls,hola/flashls,mangui/flashls,dighan/flashls,NicolasSiver/flashls,JulianPena/flashls,vidible/vdb-flashls,loungelogic/flashls,codex-corp/flashls,fixedmachine/flashls,JulianPena/flashls,Boxie5/flashls,dighan/flashls,tedconf/flashls,loungelogic/flashls,jlacivita/flashls,Boxie5/flashls
349e93c4fdeefb6b4c4a68071311dccb5672bdaf
test/src/FRESteamWorksTest.as
test/src/FRESteamWorksTest.as
/* * FRESteamWorks.h * This file is part of FRESteamWorks. * * Created by David ´Oldes´ Oliva on 3/29/12. * Contributors: Ventero <http://github.com/Ventero> * Copyright (c) 2012 Amanita Design. All rights reserved. * Copyright (c) 2012-2013 Level Up Labs, LLC. All rights reserved. */ package { import com.amanitadesign.steam.FRESteamWorks; import com.amanitadesign.steam.SteamConstants; import com.amanitadesign.steam.SteamEvent; import com.amanitadesign.steam.WorkshopConstants; import flash.desktop.NativeApplication; import flash.display.SimpleButton; import flash.display.Sprite; import flash.events.Event; import flash.events.MouseEvent; import flash.text.TextField; import flash.utils.ByteArray; public class FRESteamWorksTest extends Sprite { public var Steamworks:FRESteamWorks = new FRESteamWorks(); public var tf:TextField; private var _buttonPos:int = 5; public function FRESteamWorksTest() { tf = new TextField(); tf.x = 160; tf.width = stage.stageWidth - tf.x; tf.height = stage.stageHeight; addChild(tf); addButton("Check stats/achievements", checkAchievements); addButton("Toggle achievement", toggleAchievement); addButton("Toggle cloud enabled", toggleCloudEnabled); addButton("Toggle file", toggleFile); addButton("Publish file", publishFile); addButton("Show Friends overlay", activateOverlay); Steamworks.addEventListener(SteamEvent.STEAM_RESPONSE, onSteamResponse); NativeApplication.nativeApplication.addEventListener(Event.EXITING, onExit); try { Steamworks.useCrashHandler(480, "1.0", "Feb 20 2013", "21:42:20"); if(!Steamworks.init()){ log("STEAMWORKS API is NOT available"); return; } log("STEAMWORKS API is available\n"); log("User ID: " + Steamworks.getUserID()); log("Persona name: " + Steamworks.getPersonaName()); log("isCloudEnabledForApp() == "+Steamworks.isCloudEnabledForApp() ); log("getFileCount() == "+Steamworks.getFileCount() ); log("fileExists('test.txt') == "+Steamworks.fileExists('test.txt') ); Steamworks.resetAllStats(true); } catch(e:Error) { log("*** ERROR ***"); log(e.message); log(e.getStackTrace()); } } private function log(value:String):void{ tf.appendText(value+"\n"); tf.scrollV = tf.maxScrollV; } public function writeFileToCloud(fileName:String, data:String):Boolean { var dataOut:ByteArray = new ByteArray(); dataOut.writeUTFBytes(data); return Steamworks.fileWrite(fileName, dataOut); } public function readFileFromCloud(fileName:String):String { var dataIn:ByteArray = new ByteArray(); var result:String; dataIn.position = 0; dataIn.length = Steamworks.getFileSize(fileName); if(dataIn.length>0 && Steamworks.fileRead(fileName,dataIn)){ result = dataIn.readUTFBytes(dataIn.length); } return result; } private function checkAchievements(e:Event = null):void { if(!Steamworks.isReady) return; // current stats and achievement ids are from steam example app log("isAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.isAchievement("ACH_WIN_ONE_GAME")); log("isAchievement('ACH_TRAVEL_FAR_SINGLE') == "+Steamworks.isAchievement("ACH_TRAVEL_FAR_SINGLE")); log("setStatFloat('FeetTraveled') == "+Steamworks.setStatFloat('FeetTraveled', 21.3)); log("setStatInt('NumGames', 2) == "+Steamworks.setStatInt('NumGames', 2)); Steamworks.storeStats(); log("getStatInt('NumGames') == "+Steamworks.getStatInt('NumGames')); log("getStatFloat('FeetTraveled') == "+Steamworks.getStatFloat('FeetTraveled')); } private function toggleAchievement(e:Event = null):void{ if(!Steamworks.isReady) return; var result:Boolean = Steamworks.isAchievement("ACH_WIN_ONE_GAME"); log("isAchievement('ACH_WIN_ONE_GAME') == " + result); if(!result) { log("setAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.setAchievement("ACH_WIN_ONE_GAME")); } else { log("clearAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.clearAchievement("ACH_WIN_ONE_GAME")); } } private function toggleCloudEnabled(e:Event = null):void { if(!Steamworks.isReady) return; var enabled:Boolean = Steamworks.isCloudEnabledForApp(); log("isCloudEnabledForApp() == " + enabled); log("setCloudEnabledForApp(" + !enabled + ") == " + Steamworks.setCloudEnabledForApp(!enabled)); log("isCloudEnabledForApp() == " + Steamworks.isCloudEnabledForApp()); } private function toggleFile(e:Event = null):void { if(!Steamworks.isReady) return; var result:Boolean = Steamworks.fileExists('test.txt'); log("fileExists('test.txt') == " + result); if(result){ log("readFileFromCloud('test.txt') == "+readFileFromCloud('test.txt') ); log("fileDelete('test.txt') == "+Steamworks.fileDelete('test.txt')); } else { log("writeFileToCloud('test.txt','click') == "+writeFileToCloud('test.txt','click')); } } private function publishFile(e:Event = null):void { if(!Steamworks.isReady) return; var res:Boolean = Steamworks.publishWorkshopFile("test.txt", "", 480, "Test.txt", "Test.txt", WorkshopConstants.VISIBILITY_Private, ["TestTag"], WorkshopConstants.FILETYPE_Community); log("publishWorkshopFile('test.txt' ...) == " + res); } private function activateOverlay(e:Event = null):void { if(!Steamworks.isReady) return; log("activateGameOverlay('Friends') == " + Steamworks.activateGameOverlay("Friends")); } private function onSteamResponse(e:SteamEvent):void{ switch(e.req_type){ case SteamConstants.RESPONSE_OnUserStatsStored: log("RESPONSE_OnUserStatsStored: "+e.response); break; case SteamConstants.RESPONSE_OnUserStatsReceived: log("RESPONSE_OnUserStatsReceived: "+e.response); break; case SteamConstants.RESPONSE_OnAchievementStored: log("RESPONSE_OnAchievementStored: "+e.response); break; default: log("STEAMresponse type:"+e.req_type+" response:"+e.response); } } private function onExit(e:Event):void{ log("Exiting application, cleaning up"); Steamworks.dispose(); } private function addButton(label:String, callback:Function):void { var button:Sprite = new Sprite(); button.graphics.beginFill(0xaaaaaa); button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5); button.graphics.endFill(); button.buttonMode = true; button.useHandCursor = true; button.addEventListener(MouseEvent.CLICK, callback); button.x = 5; button.y = _buttonPos; _buttonPos += button.height + 5; var text:TextField = new TextField(); text.text = label; text.width = 140; text.height = 25; text.x = 5; text.y = 5; text.mouseEnabled = false; button.addChild(text); addChild(button); } } }
/* * FRESteamWorks.h * This file is part of FRESteamWorks. * * Created by David ´Oldes´ Oliva on 3/29/12. * Contributors: Ventero <http://github.com/Ventero> * Copyright (c) 2012 Amanita Design. All rights reserved. * Copyright (c) 2012-2013 Level Up Labs, LLC. All rights reserved. */ package { import com.amanitadesign.steam.FRESteamWorks; import com.amanitadesign.steam.SteamConstants; import com.amanitadesign.steam.SteamEvent; import com.amanitadesign.steam.WorkshopConstants; import flash.desktop.NativeApplication; import flash.display.SimpleButton; import flash.display.Sprite; import flash.display.StageDisplayState; import flash.events.Event; import flash.events.MouseEvent; import flash.text.TextField; import flash.utils.ByteArray; public class FRESteamWorksTest extends Sprite { public var Steamworks:FRESteamWorks = new FRESteamWorks(); public var tf:TextField; private var _buttonPos:int = 5; public function FRESteamWorksTest() { tf = new TextField(); tf.x = 160; tf.width = stage.stageWidth - tf.x; tf.height = stage.stageHeight; addChild(tf); addButton("Check stats/achievements", checkAchievements); addButton("Toggle achievement", toggleAchievement); addButton("Toggle cloud enabled", toggleCloudEnabled); addButton("Toggle file", toggleFile); addButton("Publish file", publishFile); addButton("Toggle fullscreen", toggleFullscreen); addButton("Show Friends overlay", activateOverlay); Steamworks.addEventListener(SteamEvent.STEAM_RESPONSE, onSteamResponse); NativeApplication.nativeApplication.addEventListener(Event.EXITING, onExit); try { Steamworks.useCrashHandler(480, "1.0", "Feb 20 2013", "21:42:20"); if(!Steamworks.init()){ log("STEAMWORKS API is NOT available"); return; } log("STEAMWORKS API is available\n"); log("User ID: " + Steamworks.getUserID()); log("Persona name: " + Steamworks.getPersonaName()); log("isCloudEnabledForApp() == "+Steamworks.isCloudEnabledForApp() ); log("getFileCount() == "+Steamworks.getFileCount() ); log("fileExists('test.txt') == "+Steamworks.fileExists('test.txt') ); Steamworks.resetAllStats(true); } catch(e:Error) { log("*** ERROR ***"); log(e.message); log(e.getStackTrace()); } } private function log(value:String):void{ tf.appendText(value+"\n"); tf.scrollV = tf.maxScrollV; } public function writeFileToCloud(fileName:String, data:String):Boolean { var dataOut:ByteArray = new ByteArray(); dataOut.writeUTFBytes(data); return Steamworks.fileWrite(fileName, dataOut); } public function readFileFromCloud(fileName:String):String { var dataIn:ByteArray = new ByteArray(); var result:String; dataIn.position = 0; dataIn.length = Steamworks.getFileSize(fileName); if(dataIn.length>0 && Steamworks.fileRead(fileName,dataIn)){ result = dataIn.readUTFBytes(dataIn.length); } return result; } private function checkAchievements(e:Event = null):void { if(!Steamworks.isReady) return; // current stats and achievement ids are from steam example app log("isAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.isAchievement("ACH_WIN_ONE_GAME")); log("isAchievement('ACH_TRAVEL_FAR_SINGLE') == "+Steamworks.isAchievement("ACH_TRAVEL_FAR_SINGLE")); log("setStatFloat('FeetTraveled') == "+Steamworks.setStatFloat('FeetTraveled', 21.3)); log("setStatInt('NumGames', 2) == "+Steamworks.setStatInt('NumGames', 2)); Steamworks.storeStats(); log("getStatInt('NumGames') == "+Steamworks.getStatInt('NumGames')); log("getStatFloat('FeetTraveled') == "+Steamworks.getStatFloat('FeetTraveled')); } private function toggleAchievement(e:Event = null):void{ if(!Steamworks.isReady) return; var result:Boolean = Steamworks.isAchievement("ACH_WIN_ONE_GAME"); log("isAchievement('ACH_WIN_ONE_GAME') == " + result); if(!result) { log("setAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.setAchievement("ACH_WIN_ONE_GAME")); } else { log("clearAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.clearAchievement("ACH_WIN_ONE_GAME")); } } private function toggleCloudEnabled(e:Event = null):void { if(!Steamworks.isReady) return; var enabled:Boolean = Steamworks.isCloudEnabledForApp(); log("isCloudEnabledForApp() == " + enabled); log("setCloudEnabledForApp(" + !enabled + ") == " + Steamworks.setCloudEnabledForApp(!enabled)); log("isCloudEnabledForApp() == " + Steamworks.isCloudEnabledForApp()); } private function toggleFile(e:Event = null):void { if(!Steamworks.isReady) return; var result:Boolean = Steamworks.fileExists('test.txt'); log("fileExists('test.txt') == " + result); if(result){ log("readFileFromCloud('test.txt') == "+readFileFromCloud('test.txt') ); log("fileDelete('test.txt') == "+Steamworks.fileDelete('test.txt')); } else { log("writeFileToCloud('test.txt','click') == "+writeFileToCloud('test.txt','click')); } } private function publishFile(e:Event = null):void { if(!Steamworks.isReady) return; var res:Boolean = Steamworks.publishWorkshopFile("test.txt", "", 480, "Test.txt", "Test.txt", WorkshopConstants.VISIBILITY_Private, ["TestTag"], WorkshopConstants.FILETYPE_Community); log("publishWorkshopFile('test.txt' ...) == " + res); } private function toggleFullscreen(e:Event = null):void { if(stage.displayState == StageDisplayState.NORMAL) stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE; else stage.displayState = StageDisplayState.NORMAL; } private function activateOverlay(e:Event = null):void { if(!Steamworks.isReady) return; log("activateGameOverlay('Friends') == " + Steamworks.activateGameOverlay("Friends")); } private function onSteamResponse(e:SteamEvent):void{ switch(e.req_type){ case SteamConstants.RESPONSE_OnUserStatsStored: log("RESPONSE_OnUserStatsStored: "+e.response); break; case SteamConstants.RESPONSE_OnUserStatsReceived: log("RESPONSE_OnUserStatsReceived: "+e.response); break; case SteamConstants.RESPONSE_OnAchievementStored: log("RESPONSE_OnAchievementStored: "+e.response); break; default: log("STEAMresponse type:"+e.req_type+" response:"+e.response); } } private function onExit(e:Event):void{ log("Exiting application, cleaning up"); Steamworks.dispose(); } private function addButton(label:String, callback:Function):void { var button:Sprite = new Sprite(); button.graphics.beginFill(0xaaaaaa); button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5); button.graphics.endFill(); button.buttonMode = true; button.useHandCursor = true; button.addEventListener(MouseEvent.CLICK, callback); button.x = 5; button.y = _buttonPos; _buttonPos += button.height + 5; var text:TextField = new TextField(); text.text = label; text.width = 140; text.height = 25; text.x = 5; text.y = 5; text.mouseEnabled = false; button.addChild(text); addChild(button); } } }
Add fullscreen toggle button to test app
Add fullscreen toggle button to test app
ActionScript
bsd-2-clause
Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks
d4ced7bb13087a6b7ed8f31cd50887ab6ecd29ee
src/main/actionscript/com/castlabs/dash/utils/Console.as
src/main/actionscript/com/castlabs/dash/utils/Console.as
/* * Copyright (c) 2014 castLabs GmbH * * 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.castlabs.dash.utils { import flash.events.TimerEvent; import flash.external.ExternalInterface; import flash.utils.Timer; public class Console { private static const ERROR:String = "error"; private static const WARN:String = "warn"; private static const INFO:String = "info"; private static const DEBUG:String = "debug"; private var enabled:Boolean = false; private var events:Array = []; public function Console() { } public function enable():void { enabled = true; var timer:Timer = new Timer(2000); // 2 second timer.addEventListener(TimerEvent.TIMER, send); timer.start(); } private function send(event:TimerEvent):void { if (events.length == 0) { return; } ExternalInterface.call("handleEvents", events); while (events.length > 0) { events.pop(); } } public function error(message:String):void { log(ERROR, message); } public function warn(message:String):void { log(WARN, message); } public function info(message:String):void { log(INFO, message); } public function debug(message:String):void { log(DEBUG, message); } public function logAndBuildError(message:String):Error { log(ERROR, message); return new Error(message); } public function log(level:String, message:String):void { if (!enabled) { return; } trace(message); events.push({ id: "log", level: level, message: message }); } public function appendRealUserBandwidth(bandwidth:Number):void { appendUserBandwidth("real", bandwidth); } public function appendAverageUserBandwidth(bandwidth:Number):void { appendUserBandwidth("average", bandwidth); } public function appendUserBandwidth(type:String, bandwidth:Number):void { if (!enabled) { return; } events.push({ id: "appendUserBandwidth", dataset: type, bandwidth: bandwidth }); } public function appendVideoBandwidth(bandwidth:Number):void { appendMediaBandwidth("video", bandwidth); } public function appendAudioBandwidth(bandwidth:Number):void { appendMediaBandwidth("audio", bandwidth); } public function appendMediaBandwidth(type:String, bandwidth:Number):void { if (!enabled) { return; } events.push({ id: "appendMediaBandwidth", dataset: type, bandwidth: bandwidth }); } } }
/* * Copyright (c) 2014 castLabs GmbH * * 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.castlabs.dash.utils { import flash.events.TimerEvent; import flash.external.ExternalInterface; import flash.utils.Timer; public class Console { private static const ERROR:String = "error"; private static const WARN:String = "warn"; private static const INFO:String = "info"; private static const DEBUG:String = "debug"; private var enabled:Boolean = false; private var events:Array = []; public function Console() { } public function enable():void { enabled = true; var timer:Timer = new Timer(2000); // 2 second timer.addEventListener(TimerEvent.TIMER, send); timer.start(); } private function send(event:TimerEvent):void { if (events.length == 0) { return; } if (ExternalInterface.available) ExternalInterface.call("handleEvents", events); while (events.length > 0) { events.pop(); } } public function error(message:String):void { log(ERROR, message); } public function warn(message:String):void { log(WARN, message); } public function info(message:String):void { log(INFO, message); } public function debug(message:String):void { log(DEBUG, message); } public function logAndBuildError(message:String):Error { log(ERROR, message); return new Error(message); } public function log(level:String, message:String):void { if (!enabled) { return; } trace(message); events.push({ id: "log", level: level, message: message }); } public function appendRealUserBandwidth(bandwidth:Number):void { appendUserBandwidth("real", bandwidth); } public function appendAverageUserBandwidth(bandwidth:Number):void { appendUserBandwidth("average", bandwidth); } public function appendUserBandwidth(type:String, bandwidth:Number):void { if (!enabled) { return; } events.push({ id: "appendUserBandwidth", dataset: type, bandwidth: bandwidth }); } public function appendVideoBandwidth(bandwidth:Number):void { appendMediaBandwidth("video", bandwidth); } public function appendAudioBandwidth(bandwidth:Number):void { appendMediaBandwidth("audio", bandwidth); } public function appendMediaBandwidth(type:String, bandwidth:Number):void { if (!enabled) { return; } events.push({ id: "appendMediaBandwidth", dataset: type, bandwidth: bandwidth }); } } }
Check ExternalInterface availability
Check ExternalInterface availability
ActionScript
mpl-2.0
XamanSoft/dashas,XamanSoft/dashas,XamanSoft/dashas
967b1d321231e53e70c482cc442a9e52a6483d58
lib/src/com/amanitadesign/steam/SteamConstants.as
lib/src/com/amanitadesign/steam/SteamConstants.as
/* * SteamConstants.as * This file is part of FRESteamWorks. * * Created by David ´Oldes´ Oliva on 3/29/12. * Contributors: Ventero <http://github.com/Ventero> * Copyright (c) 2012 Amanita Design. All rights reserved. * Copyright (c) 2012-2013 Level Up Labs, LLC. All rights reserved. */ package com.amanitadesign.steam { public class SteamConstants { /* response values */ public static const RESPONSE_OK:int = 0; public static const RESPONSE_FAILED:int = 1; /* response types */ public static const RESPONSE_OnUserStatsReceived:int = 0; public static const RESPONSE_OnUserStatsStored:int = 1; public static const RESPONSE_OnAchievementStored:int = 2; public static const RESPONSE_OnGameOverlayActivated:int = 3; public static const RESPONSE_OnFileShared:int = 4; public static const RESPONSE_OnUGCDownload:int = 5; public static const RESPONSE_OnPublishWorkshopFile:int = 6; public static const RESPONSE_OnDeletePublishedFile:int = 7; public static const RESPONSE_OnGetPublishedFileDetails:int = 8; public static const RESPONSE_OnEnumerateUserPublishedFiles:int = 9; public static const RESPONSE_OnEnumeratePublishedWorkshopFiles:int = 10; public static const RESPONSE_OnEnumerateUserSubscribedFiles:int = 11; public static const RESPONSE_OnEnumerateUserSharedWorkshopFiles:int = 12; public static const RESPONSE_OnEnumeratePublishedFilesByUserAction:int = 13; public static const RESPONSE_OnCommitPublishedFileUpdate:int = 14; public static const RESPONSE_OnSubscribePublishedFile:int = 15; public static const RESPONSE_OnUnsubscribePublishedFile:int = 16; public static const RESPONSE_OnGetPublishedItemVoteDetails:int = 17; public static const RESPONSE_OnUpdateUserPublishedItemVote:int = 18; public static const RESPONSE_OnSetUserPublishedFileActio:int = 19; } }
/* * SteamConstants.as * This file is part of FRESteamWorks. * * Created by David ´Oldes´ Oliva on 3/29/12. * Contributors: Ventero <http://github.com/Ventero> * Copyright (c) 2012 Amanita Design. All rights reserved. * Copyright (c) 2012-2013 Level Up Labs, LLC. All rights reserved. */ package com.amanitadesign.steam { public class SteamConstants { /* response values */ public static const RESPONSE_OK:int = 0; public static const RESPONSE_FAILED:int = 1; /* response types */ public static const RESPONSE_OnUserStatsReceived:int = 0; public static const RESPONSE_OnUserStatsStored:int = 1; public static const RESPONSE_OnAchievementStored:int = 2; public static const RESPONSE_OnGameOverlayActivated:int = 3; public static const RESPONSE_OnFileShared:int = 4; public static const RESPONSE_OnUGCDownload:int = 5; public static const RESPONSE_OnPublishWorkshopFile:int = 6; public static const RESPONSE_OnDeletePublishedFile:int = 7; public static const RESPONSE_OnGetPublishedFileDetails:int = 8; public static const RESPONSE_OnEnumerateUserPublishedFiles:int = 9; public static const RESPONSE_OnEnumeratePublishedWorkshopFiles:int = 10; public static const RESPONSE_OnEnumerateUserSubscribedFiles:int = 11; public static const RESPONSE_OnEnumerateUserSharedWorkshopFiles:int = 12; public static const RESPONSE_OnEnumeratePublishedFilesByUserAction:int = 13; public static const RESPONSE_OnCommitPublishedFileUpdate:int = 14; public static const RESPONSE_OnSubscribePublishedFile:int = 15; public static const RESPONSE_OnUnsubscribePublishedFile:int = 16; public static const RESPONSE_OnGetPublishedItemVoteDetails:int = 17; public static const RESPONSE_OnUpdateUserPublishedItemVote:int = 18; public static const RESPONSE_OnSetUserPublishedFileAction:int = 19; } }
Fix typo
[lib] Fix typo
ActionScript
bsd-2-clause
Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks
76f77b97481b8e5d38540bf76df5b15a5cb6fba0
src/as/com/threerings/util/ObjectMarshaller.as
src/as/com/threerings/util/ObjectMarshaller.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.net.ObjectEncoding; import flash.geom.Point; import flash.geom.Rectangle; import flash.system.ApplicationDomain; import flash.utils.ByteArray; import flash.utils.Endian; import flash.utils.IExternalizable; import flash.utils.getQualifiedSuperclassName; // function import import com.threerings.io.TypedArray; /** * Utility methods for transforming flash objects into byte[]. */ public class ObjectMarshaller { /** * Encode the specified object as either a byte[] or a byte[][] (see below). * The specific mechanism of encoding is not important, * as long as decode returns a clone of the original object. * * No validation is done to verify that the object can be serialized. * * Currently, cycles in the object graph are preserved on the other end. * * @param encodeArrayElements if true and the obj is an Array, each element is * encoded separately, returning a byte[][] instead of a byte[]. */ public static function encode ( obj :Object, encodeArrayElements :Boolean = false) :Object { if (obj == null) { return null; } if (encodeArrayElements && obj is Array) { var src :Array = (obj as Array); var dest :TypedArray = TypedArray.create(ByteArray); for (var ii :int = 0; ii < src.length; ii++) { dest.push(encode(src[ii], false)); } return dest; } // TODO: Our own encoding, that takes into account // the ApplicationDomain.. ACK var bytes :ByteArray = new ByteArray(); bytes.endian = Endian.BIG_ENDIAN; bytes.objectEncoding = ObjectEncoding.AMF3; bytes.writeObject(obj); return bytes; } /** * Validate the value and encode it. Arrays are not broken-up. */ public static function validateAndEncode (obj :Object) :ByteArray { validateValue(obj); return encode(obj, false) as ByteArray; } /** * Decode the specified byte[] or byte[][] back into a flash Object. */ public static function decode (encoded :Object) :Object { if (encoded == null) { return null; } if (encoded is TypedArray) { var src :TypedArray = (encoded as TypedArray); var dest :Array = []; for (var ii :int = 0; ii < src.length; ii++) { dest.push(decode(src[ii] as ByteArray)); } return dest; } var bytes :ByteArray = (encoded as ByteArray); // re-set the position in case we're decoding the actual same byte // array used to encode (and not a network reconstruction) bytes.position = 0; // TODO: Our own decoding, that takes into account // the ApplicationDomain.. ACK bytes.endian = Endian.BIG_ENDIAN; bytes.objectEncoding = ObjectEncoding.AMF3; return bytes.readObject(); } /** * Validate that the value is kosher for encoding, or throw an ArgumentError if it's not. */ public static function validateValue (value :Object) :void // throws ArgumentError { var s :String = getValidationError(value); if (s != null) { throw new ArgumentError(s); } } /** * Get the String reason why this value is not encodable, or null if no error. */ public static function getValidationError (value :Object) :String { if (value == null) { return null; } else if (value is IExternalizable) { return "IExternalizable is not yet supported"; } else if (value is Array) { if (ClassUtil.getClassName(value) != "Array") { // We can't allow arrays to be serialized as IExternalizables // because we need to know element values (opaquely) on the // server. Also, we don't allow other types because we wouldn't // create the right class on the other side. return "Custom array subclasses are not supported"; } // then, continue on with the sub-properties check (below) } else { var type :String = typeof(value); if (type == "number" || type == "string" || type == "boolean" ) { return null; // kosher! } if (-1 != VALID_CLASSES.indexOf(ClassUtil.getClass(value))) { return null; // kosher } if (!Util.isPlainObject(value)) { return "Non-simple properties may not be set."; } // fall through and verify the plain object's sub-properties } // check sub-properties (of arrays and objects) for each (var arrValue :Object in value) { var s :String = getValidationError(arrValue); if (s != null) { return s; } } return null; // it all checks out! } /** Non-simple classes that we allow, as long as they are not subclassed. */ protected static const VALID_CLASSES :Array = [ ByteArray, Point, Rectangle ]; } }
// // $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.net.ObjectEncoding; import flash.geom.Point; import flash.geom.Rectangle; import flash.system.ApplicationDomain; import flash.utils.ByteArray; import flash.utils.Dictionary; import flash.utils.Endian; import flash.utils.IExternalizable; import flash.utils.getQualifiedSuperclassName; // function import import com.threerings.io.TypedArray; /** * Utility methods for transforming flash objects into byte[]. */ public class ObjectMarshaller { /** * Encode the specified object as either a byte[] or a byte[][] (see below). * The specific mechanism of encoding is not important, * as long as decode returns a clone of the original object. * * No validation is done to verify that the object can be serialized. * * Currently, cycles in the object graph are preserved on the other end. * * @param encodeArrayElements if true and the obj is an Array, each element is * encoded separately, returning a byte[][] instead of a byte[]. */ public static function encode ( obj :Object, encodeArrayElements :Boolean = false) :Object { if (obj == null) { return null; } if (encodeArrayElements && obj is Array) { var src :Array = (obj as Array); var dest :TypedArray = TypedArray.create(ByteArray); for (var ii :int = 0; ii < src.length; ii++) { dest.push(encode(src[ii], false)); } return dest; } // TODO: Our own encoding, that takes into account // the ApplicationDomain.. ACK var bytes :ByteArray = new ByteArray(); bytes.endian = Endian.BIG_ENDIAN; bytes.objectEncoding = ObjectEncoding.AMF3; bytes.writeObject(obj); return bytes; } /** * Validate the value and encode it. Arrays are not broken-up. */ public static function validateAndEncode (obj :Object) :ByteArray { validateValue(obj); return encode(obj, false) as ByteArray; } /** * Decode the specified byte[] or byte[][] back into a flash Object. */ public static function decode (encoded :Object) :Object { if (encoded == null) { return null; } if (encoded is TypedArray) { var src :TypedArray = (encoded as TypedArray); var dest :Array = []; for (var ii :int = 0; ii < src.length; ii++) { dest.push(decode(src[ii] as ByteArray)); } return dest; } var bytes :ByteArray = (encoded as ByteArray); // re-set the position in case we're decoding the actual same byte // array used to encode (and not a network reconstruction) bytes.position = 0; // TODO: Our own decoding, that takes into account // the ApplicationDomain.. ACK bytes.endian = Endian.BIG_ENDIAN; bytes.objectEncoding = ObjectEncoding.AMF3; return bytes.readObject(); } /** * Validate that the value is kosher for encoding, or throw an ArgumentError if it's not. */ public static function validateValue (value :Object) :void // throws ArgumentError { var s :String = getValidationError(value); if (s != null) { throw new ArgumentError(s); } } /** * Get the String reason why this value is not encodable, or null if no error. */ public static function getValidationError (value :Object) :String { if (value == null) { return null; } else if (value is IExternalizable) { return "IExternalizable is not yet supported"; } else if (value is Array) { if (ClassUtil.getClassName(value) != "Array") { // We can't allow arrays to be serialized as IExternalizables // because we need to know element values (opaquely) on the // server. Also, we don't allow other types because we wouldn't // create the right class on the other side. return "Custom array subclasses are not supported"; } // then, continue on with the sub-properties check (below) } else if (value is Dictionary) { if (ClassUtil.getClassName(value) != "flash.utils.Dictionary") { return "Custom Dictionary subclasses are not supported"; } // check all the keys for (var key :* in value) { var se :String = getValidationError(key); if (se != null) { return se; } } // then, continue on with sub-property check (below) } else { var type :String = typeof(value); if (type == "number" || type == "string" || type == "boolean" ) { return null; // kosher! } if (-1 != VALID_CLASSES.indexOf(ClassUtil.getClass(value))) { return null; // kosher } if (!Util.isPlainObject(value)) { return "Non-simple properties may not be set."; } // fall through and verify the plain object's sub-properties } // check sub-properties (of arrays and objects) for each (var arrValue :Object in value) { var s :String = getValidationError(arrValue); if (s != null) { return s; } } return null; // it all checks out! } /** Non-simple classes that we allow, as long as they are not subclassed. */ protected static const VALID_CLASSES :Array = [ ByteArray, Point, Rectangle ]; } }
Support Dictionary, too.
Support Dictionary, too. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4972 542714f4-19e9-0310-aa3c-eee0fc999fb1
ActionScript
lgpl-2.1
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
6a88a997c16457c4d64f346d38df7565661bca63
src/com/google/analytics/core/DomainNameMode.as
src/com/google/analytics/core/DomainNameMode.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 { /** * The domain name mode enumeration class. */ public class DomainNameMode { /** * @private */ private var _value:int; /** * @private */ private var _name:String; /** * Creates a new DomainNameMode instance. * @param value The enumeration value representation. * @param name The enumeration name representation. */ public function DomainNameMode( value:int = 0, name:String = "" ) { _value = value; _name = name; } /** * Returns the primitive value of the object. * @return the primitive value of the object. */ public function valueOf():int { return _value; } /** * Returns the String representation of the object. * @return the String representation of the object. */ public function toString():String { return _name; } /** * Determinates the "none" DomainNameMode value. * <p>"none" is used in the following two situations :</p> * <p>- You want to disable tracking across hosts.</p> * <p>- You want to set up tracking across two separate domains.</p> * <p>Cross- domain tracking requires configuration of the setAllowLinker() and link() methods.</p> */ public static const none:DomainNameMode = new DomainNameMode( 0, "none" ); /** * Attempts to automaticaly resolve the domain name. */ public static const auto:DomainNameMode = new DomainNameMode( 1, "auto" ); /** * Custom is used to set explicitly to your domain name if your website spans multiple hostnames, * and you want to track visitor behavior across all hosts. * <p>For example, if you have two hosts : <code>server1.example.com</code> and <code>server2.example.com</code>, * you would set the domain name as follows : * <pre class="prettyprint"> * pageTracker.setDomainName( new Domain( DomainName.custom, ".example.com" ) ) ; * </pre> */ public static const custom:DomainNameMode = new DomainNameMode( 2, "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.core { /** * The domain name mode enumeration class. */ public class DomainNameMode { /** * @private */ private var _value:int; /** * @private */ private var _name:String; /** * Creates a new DomainNameMode instance. * @param value The enumeration value representation. * @param name The enumeration name representation. */ public function DomainNameMode( value:int = 0, name:String = "" ) { _value = value; _name = name; } /** * Returns the primitive value of the object. * @return the primitive value of the object. */ public function valueOf():int { return _value; } /** * Returns the String representation of the object. * @return the String representation of the object. */ public function toString():String { return _name; } /** * Determinates the "none" DomainNameMode value. * <p>"none" is used in the following two situations :</p> * <p>- You want to disable tracking across hosts.</p> * <p>- You want to set up tracking across two separate domains.</p> * <p>Cross- domain tracking requires configuration of the setAllowLinker() and link() methods.</p> */ public static const none:DomainNameMode = new DomainNameMode( 0, "none" ); /** * Attempts to automaticaly resolve the domain name. */ public static const auto:DomainNameMode = new DomainNameMode( 1, "auto" ); /** * Custom is used to set explicitly to your domain name if your website spans multiple hostnames, * and you want to track visitor behavior across all hosts. * <p>For example, if you have two hosts : <code>server1.example.com</code> and <code>server2.example.com</code>, * you would set the domain name as follows : * <pre class="prettyprint"> * pageTracker.setDomainName( new Domain( DomainName.custom, ".example.com" ) ) ; * </p> */ public static const custom:DomainNameMode = new DomainNameMode( 2, "custom" ); } }
fix comment for asdoc
fix comment for asdoc
ActionScript
apache-2.0
jisobkim/gaforflash,mrthuanvn/gaforflash,Miyaru/gaforflash,Vigmar/gaforflash,Vigmar/gaforflash,jisobkim/gaforflash,DimaBaliakin/gaforflash,soumavachakraborty/gaforflash,Miyaru/gaforflash,jeremy-wischusen/gaforflash,mrthuanvn/gaforflash,drflash/gaforflash,soumavachakraborty/gaforflash,dli-iclinic/gaforflash,jeremy-wischusen/gaforflash,dli-iclinic/gaforflash,drflash/gaforflash,DimaBaliakin/gaforflash
050be7db1ce4c1531df8f5265a27fddcaf0d0ff3
activities/module-2/series-measuring/ComponentMultimeter.as
activities/module-2/series-measuring/ComponentMultimeter.as
package { import flash.display.MovieClip; public class ComponentMultimeter extends MovieClip { public var expandOnFocus:ExpandOnFocus; private var startX:Number; private var startY:Number; private var hitAreaMC:MovieClip = null; public function ComponentMultimeter() { super(); trace('ENTER ComponentMultimeter'); //trace('component breadboard ' +stage.this.x+' '+stage.this.y); expandOnFocus = new ExpandOnFocus(this,2.1,10,-10, this.hitAreaMC); // give breadboard rollover behavior this.visible = true; } public function putOnStage(value1:Number,value2:Number) { this.startX=value1; this.startY=value2; } public function setStartX(value:Number) { this.startX = value; } public function setStartY(value:Number) { this.startY = value; } public function getVisibility() { return this.visible; } public function setHitArea(target:MovieClip):void { this.hitAreaMC = target; } //visibility can be set from the javascript as follows: //flash.sendCommand('set_multimeter_visiblity','true'); // //or in flash with //circuit.getMultimeter().setVisibility('true'); public function setVisibility(statStr:String) { switch((statStr).toLowerCase()) { case "true": case "1": case "yes": default: this.visible = true; break; case "false": case "0": case "no": this.visible = false; } } } }
package { import flash.display.MovieClip; public class ComponentMultimeter extends MovieClip { public var expandOnFocus:ExpandOnFocus; private var startX:Number; private var startY:Number; private var hitAreaMC:MovieClip = null; public function ComponentMultimeter() { super(); trace('ENTER ComponentMultimeter'); //trace('component breadboard ' +stage.this.x+' '+stage.this.y); expandOnFocus = new ExpandOnFocus(this,2.1,10,-10, this.hitAreaMC); // give breadboard rollover behavior this.visible = true; } public function putOnStage(value1:Number,value2:Number) { this.startX=value1; this.startY=value2; } public function setStartX(value:Number) { this.startX = value; } public function setStartY(value:Number) { this.startY = value; } public function getVisibility() { return this.visible; } public function setHitArea(target:MovieClip):void { this.hitAreaMC = target; } //visibility can be set from the javascript as follows: //flash.sendCommand('set_multimeter_visibility','true'); // //or in flash with //circuit.getMultimeter().setVisibility('true'); public function setVisibility(statStr:String) { switch((statStr).toLowerCase()) { case "true": case "1": case "yes": default: this.visible = true; break; case "false": case "0": case "no": this.visible = false; } } } }
correct typo for word "visibility" in a comment
correct typo for word "visibility" in a comment
ActionScript
apache-2.0
concord-consortium/sparks,concord-consortium/sparks,concord-consortium/sparks,concord-consortium/sparks,concord-consortium/sparks
170cf7cc09d10eba4b2e3bfe8cf231decaa78260
as3/smartform/src/com/rpath/raf/util/UIHelper.as
as3/smartform/src/com/rpath/raf/util/UIHelper.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.raf.util { import flash.utils.Dictionary; import mx.collections.ArrayCollection; import spark.components.Application; import mx.core.FlexGlobals; import mx.core.IFlexDisplayObject; import mx.formatters.NumberBaseRoundType; import mx.formatters.NumberFormatter; import mx.managers.PopUpManager; import mx.managers.PopUpManagerChildList; public class UIHelper { public static function checkBooleans(...args):Boolean { for each (var b:* in args) { if (b is Array || b is ArrayCollection) { for each (var c:* in b) { // allow for nested arrays checkBooleans(c); } } else { if (!b) return false; } } return true; } public static function checkOneOf(...args):Boolean { for each (var b:* in args) { if (b) return true; } return false; } public static function formattedDate(unixTimestamp:Number):String { if (isNaN(unixTimestamp)) return ""; var date:Date = new Date(unixTimestamp * 1000); /* * Note that we add 1 to month b/c January is 0 in Flex */ return padLeft(date.getMonth() +1) + "/" + padLeft(date.getDate()) + "/" + padLeft(date.getFullYear()) + " " + padLeft(date.getHours()) + ":" + padLeft(date.getMinutes()) + ":" + padLeft(date.getSeconds()); } public static function padLeft(number:Number):String { var strNum:String = number.toString(); if (number.toString().length == 1) strNum = "0" + strNum; return strNum; } /** * Replace \r\n with \n, replace \r with \n */ public static function processCarriageReturns(value:String):String { if (!value) return value; var cr:String = String.fromCharCode(13); var crRegex:RegExp = new RegExp(cr, "gm"); var crnl:String = String.fromCharCode(13, 10); var crnlRegex:RegExp = new RegExp(crnl, "gm"); // process CRNL first value = value.replace(crnlRegex, '\n'); // process CR value = value.replace(crRegex, '\n'); return value; } private static var popupModelMap:Dictionary = new Dictionary(true); private static var popupOwnerMap:Dictionary = new Dictionary(true); public static function createPopup(clazz:Class):* { var popup:Object = PopUpManager.createPopUp(FlexGlobals.topLevelApplication as Application, clazz, false, PopUpManagerChildList.APPLICATION) as clazz; return popup as IFlexDisplayObject; } public static function createSingletonPopupForModel(clazz:Class, model:Object, owner:Object=null):* { var popup:Object; popup = popupForModel(model); if (popup == null) { popup = PopUpManager.createPopUp(FlexGlobals.topLevelApplication as Application, clazz, false, PopUpManagerChildList.APPLICATION) as clazz; popupModelMap[model] = popup; if (owner) { popupOwnerMap[popup] = owner; } } return popup as IFlexDisplayObject; } public static function popupForModel(model:Object):* { return popupModelMap[model]; } public static function removePopupForModel(model:Object):void { var popup:IFlexDisplayObject = popupModelMap[model]; if (popup) { delete popupModelMap[model]; delete popupOwnerMap[popup]; } } public static function removePopupsForOwner(owner:Object):void { for (var popup:* in popupOwnerMap) { if (popupOwnerMap[popup] === owner) { delete popupOwnerMap[popup]; // scan the model map too for (var model:* in popupModelMap) { if (popupModelMap[model] === popup) { delete popupModelMap[model]; } } } } } public static function popupsForOwner(owner:Object):Array { var result:Array = []; for (var popup:* in popupOwnerMap) { if (popupOwnerMap[popup] === owner) { result.push(popup); } } return result; } public static function closePopupsForOwner(owner:Object):void { for each (var popup:* in UIHelper.popupsForOwner(owner)) { PopUpManager.removePopUp(popup); } removePopupsForOwner(owner); } // make bytes human readable public static function humanReadableSize(bytes:Number, precision:int=1):String { var s:String = bytes + ' bytes'; var nf:NumberFormatter = new NumberFormatter(); nf.precision = precision; nf.useThousandsSeparator = true; nf.useNegativeSign = true; nf.rounding = NumberBaseRoundType.NEAREST; if (bytes > 1073741824) { s = nf.format((bytes / 1073741824.0)) + ' GB' + ' (' + (s) + ')'; } else if (bytes > 1048576) { s = nf.format((bytes / 1048576.0)) + ' MB' + ' (' + (s) + ')'; } else if (bytes > 1024) { s = nf.format((bytes / 1024.0)) + ' KB' + ' (' + (s) + ')'; } return s; } } }
/* # # 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.raf.util { import flash.utils.Dictionary; import mx.collections.ArrayCollection; import spark.components.Application; import mx.core.FlexGlobals; import mx.core.IFlexDisplayObject; import mx.formatters.NumberBaseRoundType; import mx.formatters.NumberFormatter; import mx.managers.PopUpManager; import mx.managers.PopUpManagerChildList; public class UIHelper { public static function checkBooleans(...args):Boolean { for each (var b:* in args) { if (b is Array || b is ArrayCollection) { for each (var c:* in b) { // allow for nested arrays checkBooleans(c); } } else { if (!b) return false; } } return true; } public static function checkOneOf(...args):Boolean { for each (var b:* in args) { if (b is Array || b is ArrayCollection) { for each (var c:* in b) { // allow for nested arrays if (checkOneOf(c)) return true; } } else if (b) { return true; } } return false; } public static function formattedDate(unixTimestamp:Number):String { if (isNaN(unixTimestamp)) return ""; var date:Date = new Date(unixTimestamp * 1000); /* * Note that we add 1 to month b/c January is 0 in Flex */ return padLeft(date.getMonth() +1) + "/" + padLeft(date.getDate()) + "/" + padLeft(date.getFullYear()) + " " + padLeft(date.getHours()) + ":" + padLeft(date.getMinutes()) + ":" + padLeft(date.getSeconds()); } public static function padLeft(number:Number):String { var strNum:String = number.toString(); if (number.toString().length == 1) strNum = "0" + strNum; return strNum; } /** * Replace \r\n with \n, replace \r with \n */ public static function processCarriageReturns(value:String):String { if (!value) return value; var cr:String = String.fromCharCode(13); var crRegex:RegExp = new RegExp(cr, "gm"); var crnl:String = String.fromCharCode(13, 10); var crnlRegex:RegExp = new RegExp(crnl, "gm"); // process CRNL first value = value.replace(crnlRegex, '\n'); // process CR value = value.replace(crRegex, '\n'); return value; } private static var popupModelMap:Dictionary = new Dictionary(true); private static var popupOwnerMap:Dictionary = new Dictionary(true); public static function createPopup(clazz:Class):* { var popup:Object = PopUpManager.createPopUp(FlexGlobals.topLevelApplication as Application, clazz, false, PopUpManagerChildList.APPLICATION) as clazz; return popup as IFlexDisplayObject; } public static function createSingletonPopupForModel(clazz:Class, model:Object, owner:Object=null):* { var popup:Object; popup = popupForModel(model); if (popup == null) { popup = PopUpManager.createPopUp(FlexGlobals.topLevelApplication as Application, clazz, false, PopUpManagerChildList.APPLICATION) as clazz; popupModelMap[model] = popup; if (owner) { popupOwnerMap[popup] = owner; } } return popup as IFlexDisplayObject; } public static function popupForModel(model:Object):* { return popupModelMap[model]; } public static function removePopupForModel(model:Object):void { var popup:IFlexDisplayObject = popupModelMap[model]; if (popup) { delete popupModelMap[model]; delete popupOwnerMap[popup]; } } public static function removePopupsForOwner(owner:Object):void { for (var popup:* in popupOwnerMap) { if (popupOwnerMap[popup] === owner) { delete popupOwnerMap[popup]; // scan the model map too for (var model:* in popupModelMap) { if (popupModelMap[model] === popup) { delete popupModelMap[model]; } } } } } public static function popupsForOwner(owner:Object):Array { var result:Array = []; for (var popup:* in popupOwnerMap) { if (popupOwnerMap[popup] === owner) { result.push(popup); } } return result; } public static function closePopupsForOwner(owner:Object):void { for each (var popup:* in UIHelper.popupsForOwner(owner)) { PopUpManager.removePopUp(popup); } removePopupsForOwner(owner); } // make bytes human readable public static function humanReadableSize(bytes:Number, precision:int=1):String { var s:String = bytes + ' bytes'; var nf:NumberFormatter = new NumberFormatter(); nf.precision = precision; nf.useThousandsSeparator = true; nf.useNegativeSign = true; nf.rounding = NumberBaseRoundType.NEAREST; if (bytes > 1073741824) { s = nf.format((bytes / 1073741824.0)) + ' GB' + ' (' + (s) + ')'; } else if (bytes > 1048576) { s = nf.format((bytes / 1048576.0)) + ' MB' + ' (' + (s) + ')'; } else if (bytes > 1024) { s = nf.format((bytes / 1024.0)) + ' KB' + ' (' + (s) + ')'; } return s; } } }
Allow UIHelper.checkOneOf to recurse arrays
Allow UIHelper.checkOneOf to recurse arrays
ActionScript
apache-2.0
sassoftware/smartform
7c291f387d8af2946b6407ef5a5cde2cb58958f3
src/main/as/flump/export/PackedTexture.as
src/main/as/flump/export/PackedTexture.as
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.display.DisplayObject; import flash.display.Sprite; import flash.geom.Point; import flash.geom.Rectangle; import flump.xfl.XflTexture; public class PackedTexture { public const holder :Sprite = new Sprite(); public var tex :XflTexture; public var offset :Point; public var w :int, h :int, a :int; public var atlasX :int, atlasY :int; public var atlasRotated :Boolean; public function PackedTexture (tex :XflTexture, image :DisplayObject) { this.tex = tex; holder.addChild(image); const bounds :Rectangle = image.getBounds(holder); offset = new Point(bounds.x, bounds.y); w = Math.ceil(bounds.width); h = Math.ceil(bounds.height); a = w * h; } public function toString () :String { return "a " + a + " w " + w + " h " + h + " atlas " + atlasX + ", " + atlasY; } } }
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.display.DisplayObject; import flash.display.Sprite; import flash.geom.Point; import flash.geom.Rectangle; import flump.xfl.XflTexture; public class PackedTexture { public const holder :Sprite = new Sprite(); public var tex :XflTexture; public var offset :Point; public var w :int, h :int, a :int; public var atlasX :int, atlasY :int; public var atlasRotated :Boolean; public function PackedTexture (tex :XflTexture, image :DisplayObject) { this.tex = tex; holder.addChild(image); const bounds :Rectangle = image.getBounds(holder); image.x = -bounds.x; image.y = -bounds.y; offset = new Point(bounds.x, bounds.y); w = Math.ceil(bounds.width); h = Math.ceil(bounds.height); a = w * h; } public function toString () :String { return "a " + a + " w " + w + " h " + h + " atlas " + atlasX + ", " + atlasY; } } }
Move the images by their offset
Move the images by their offset
ActionScript
mit
funkypandagame/flump,tconkling/flump,funkypandagame/flump,tconkling/flump,mathieuanthoine/flump,mathieuanthoine/flump,mathieuanthoine/flump
da6a29f8995950eabb3698f0059570aca5b1258d
exporter/src/main/as/flump/export/DisplayCreator.as
exporter/src/main/as/flump/export/DisplayCreator.as
// // Flump - Copyright 2013 Flump Authors package flump.export { import aspire.util.Map; import aspire.util.maps.ValueComputingMap; import flash.utils.Dictionary; import flump.display.ImageCreator; import flump.display.Library; import flump.display.Movie; import flump.display.MovieCreator; import flump.display.SymbolCreator; import flump.export.texturepacker.TexturePacker; import flump.mold.AtlasMold; import flump.mold.AtlasTextureMold; import flump.mold.KeyframeMold; import flump.mold.LayerMold; import flump.mold.MovieMold; import flump.xfl.XflLibrary; import flump.xfl.XflTexture; import starling.display.DisplayObject; import starling.display.Image; import starling.textures.Texture; public class DisplayCreator implements Library { public function DisplayCreator (lib :XflLibrary) { _lib = lib; const atlases :Vector.<Atlas> = TexturePacker.withLib(lib).createAtlases(); for each (var atlas :Atlas in atlases) { var atlastMold :AtlasMold = atlas.toMold(); var baseTexture :Texture = AtlasUtil.toTexture(atlas); _baseTextures.push(baseTexture); for each (var atlasTexture :AtlasTextureMold in atlastMold.textures) { var tex :Texture = Texture.fromTexture(baseTexture, atlasTexture.bounds); _creators[atlasTexture.symbol] = new ImageCreator(tex, atlasTexture.origin, atlasTexture.symbol); } } for each (var movieMold :MovieMold in lib.movies) { _creators[movieMold.id] = new MovieCreator(movieMold, lib.frameRate); } } public function getSymbolCreator (symbol :String) :SymbolCreator { return _creators[symbol]; } public function get imageSymbols () :Vector.<String> { // Vector.map can't be used to create a Vector of a new type const symbols :Vector.<String> = new <String>[]; for each (var tex :XflTexture in _lib.textures) { symbols.push(tex.symbol); } return symbols; } public function get movieSymbols () :Vector.<String> { // Vector.map can't be used to create a Vector of a new type const symbols :Vector.<String> = new <String>[]; for each (var movie :MovieMold in _lib.movies) { symbols.push(movie.id); } return symbols; } public function get isNamespaced () :Boolean { return false; } public function createDisplayObject (id :String) :DisplayObject { var creator :SymbolCreator = _creators[id]; return creator.create(this); } public function createImage (id :String) :Image { return Image(createDisplayObject(id)); } public function getImageTexture (id :String) :Texture { return ImageCreator(_creators[id]).texture; } public function createMovie (name :String) :Movie { return new Movie(_lib.getItem(name, MovieMold), _lib.frameRate, this); } public function getMemoryUsage (id :String, subtex :Dictionary = null) :int { if (id == null) return 0; const tex :Texture = getStarlingTexture(id); if (tex != null) { const usage :int = 4 * tex.width * tex.height; if (subtex != null && !subtex.hasOwnProperty(id)) subtex[id] = usage; return usage; } const mold :MovieMold = _lib.getItem(id, MovieMold); if (subtex == null) subtex = new Dictionary(); for each (var layer :LayerMold in mold.layers) { for each (var kf :KeyframeMold in layer.keyframes) getMemoryUsage(kf.ref, subtex); } var subtexUsage :int = 0; for (var texName :String in subtex) subtexUsage += subtex[texName]; return subtexUsage; } public function dispose () :void { if (_baseTextures != null) { for each (var tex :Texture in _baseTextures) { tex.dispose(); } _baseTextures = null; _creators = null; } } /** * Gets the maximum number of pixels drawn in a single frame by the given id. If it's * a texture, that's just the number of pixels in the texture. For a movie, it's the frame with * the largest set of textures present in its keyframe. For movies inside movies, the frame * drawn usage is the maximum that movie can draw. We're trying to get the worst case here. */ public function getMaxDrawn (id :String) :int { return _maxDrawn.get(id); } protected function loadTexture (symbol :String) :DisplayObject { return ImageCreator(_creators[symbol]).create(this); } protected function calcMaxDrawn (id :String) :int { if (id == null) return 0; const tex :Texture = getStarlingTexture(id); if (tex != null) return tex.width * tex.height; const mold :MovieMold = _lib.getItem(id, MovieMold); var maxDrawn :int = 0; for (var ii :int = 0; ii < mold.frames; ii++) { var drawn :int = 0; for each (var layer :LayerMold in mold.layers) { var kf :KeyframeMold = layer.keyframeForFrame(ii); drawn += kf.visible ? getMaxDrawn(kf.ref) : 0; } maxDrawn = Math.max(maxDrawn, drawn); } return maxDrawn; } private function getStarlingTexture (symbol :String) :Texture { var imageCreator :ImageCreator = _creators[symbol] as ImageCreator; return (imageCreator != null ? imageCreator.texture : null); } protected const _maxDrawn :Map = ValueComputingMap.newMapOf(String, calcMaxDrawn); protected var _baseTextures :Vector.<Texture> = new <Texture>[]; protected var _creators :Dictionary = new Dictionary(); // <name, ImageCreator|MovieCreator> protected var _lib :XflLibrary; } }
// // Flump - Copyright 2013 Flump Authors package flump.export { import aspire.util.Map; import aspire.util.maps.ValueComputingMap; import flash.utils.Dictionary; import flump.display.ImageCreator; import flump.display.Library; import flump.display.Movie; import flump.display.MovieCreator; import flump.display.SymbolCreator; import flump.export.texturepacker.TexturePacker; import flump.mold.AtlasMold; import flump.mold.AtlasTextureMold; import flump.mold.KeyframeMold; import flump.mold.LayerMold; import flump.mold.MovieMold; import flump.xfl.XflLibrary; import flump.xfl.XflTexture; import starling.display.DisplayObject; import starling.display.Image; import starling.textures.Texture; public class DisplayCreator implements Library { public function DisplayCreator (lib :XflLibrary) { _lib = lib; const atlases :Vector.<Atlas> = TexturePacker.withLib(lib).createAtlases(); for each (var atlas :Atlas in atlases) { var atlastMold :AtlasMold = atlas.toMold(); var baseTexture :Texture = AtlasUtil.toTexture(atlas); _baseTextures.push(baseTexture); for each (var atlasTexture :AtlasTextureMold in atlastMold.textures) { var tex :Texture = Texture.fromTexture(baseTexture, atlasTexture.bounds); _creators[atlasTexture.symbol] = new ImageCreator(tex, atlasTexture.origin, atlasTexture.symbol); } } for each (var movieMold :MovieMold in lib.movies) { _creators[movieMold.id] = new MovieCreator(movieMold, lib.frameRate); } } public function getSymbolCreator (symbol :String) :SymbolCreator { return _creators[symbol]; } public function get imageSymbols () :Vector.<String> { // Vector.map can't be used to create a Vector of a new type const symbols :Vector.<String> = new <String>[]; for each (var tex :XflTexture in _lib.textures) { symbols.push(tex.symbol); } return symbols; } public function get movieSymbols () :Vector.<String> { // Vector.map can't be used to create a Vector of a new type const symbols :Vector.<String> = new <String>[]; for each (var movie :MovieMold in _lib.movies) { symbols.push(movie.id); } return symbols; } public function get isNamespaced () :Boolean { return false; } public function get baseTextures () :Vector.<Texture> { return _baseTextures; } public function createDisplayObject (id :String) :DisplayObject { var creator :SymbolCreator = _creators[id]; return creator.create(this); } public function createImage (id :String) :Image { return Image(createDisplayObject(id)); } public function getImageTexture (id :String) :Texture { return ImageCreator(_creators[id]).texture; } public function createMovie (name :String) :Movie { return new Movie(_lib.getItem(name, MovieMold), _lib.frameRate, this); } public function getMemoryUsage (id :String, subtex :Dictionary = null) :int { if (id == null) return 0; const tex :Texture = getStarlingTexture(id); if (tex != null) { const usage :int = 4 * tex.width * tex.height; if (subtex != null && !subtex.hasOwnProperty(id)) subtex[id] = usage; return usage; } const mold :MovieMold = _lib.getItem(id, MovieMold); if (subtex == null) subtex = new Dictionary(); for each (var layer :LayerMold in mold.layers) { for each (var kf :KeyframeMold in layer.keyframes) getMemoryUsage(kf.ref, subtex); } var subtexUsage :int = 0; for (var texName :String in subtex) subtexUsage += subtex[texName]; return subtexUsage; } public function dispose () :void { if (_baseTextures != null) { for each (var tex :Texture in _baseTextures) { tex.dispose(); } _baseTextures = null; _creators = null; } } /** * Gets the maximum number of pixels drawn in a single frame by the given id. If it's * a texture, that's just the number of pixels in the texture. For a movie, it's the frame with * the largest set of textures present in its keyframe. For movies inside movies, the frame * drawn usage is the maximum that movie can draw. We're trying to get the worst case here. */ public function getMaxDrawn (id :String) :int { return _maxDrawn.get(id); } protected function loadTexture (symbol :String) :DisplayObject { return ImageCreator(_creators[symbol]).create(this); } protected function calcMaxDrawn (id :String) :int { if (id == null) return 0; const tex :Texture = getStarlingTexture(id); if (tex != null) return tex.width * tex.height; const mold :MovieMold = _lib.getItem(id, MovieMold); var maxDrawn :int = 0; for (var ii :int = 0; ii < mold.frames; ii++) { var drawn :int = 0; for each (var layer :LayerMold in mold.layers) { var kf :KeyframeMold = layer.keyframeForFrame(ii); drawn += kf.visible ? getMaxDrawn(kf.ref) : 0; } maxDrawn = Math.max(maxDrawn, drawn); } return maxDrawn; } private function getStarlingTexture (symbol :String) :Texture { var imageCreator :ImageCreator = _creators[symbol] as ImageCreator; return (imageCreator != null ? imageCreator.texture : null); } protected const _maxDrawn :Map = ValueComputingMap.newMapOf(String, calcMaxDrawn); protected var _baseTextures :Vector.<Texture> = new <Texture>[]; protected var _creators :Dictionary = new Dictionary(); // <name, ImageCreator|MovieCreator> protected var _lib :XflLibrary; } }
Add missing DisplayCreator.baseTextures
exporter: Add missing DisplayCreator.baseTextures
ActionScript
mit
tconkling/flump,tconkling/flump
a2225c5dcf6e2cf3c7290a2c59e120bbf0dc20a2
lib/src_linux/com/amanitadesign/steam/FRESteamWorks.as
lib/src_linux/com/amanitadesign/steam/FRESteamWorks.as
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; 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; public function FRESteamWorks (target:IEventDispatcher = null) { _file = File.applicationDirectory.resolvePath(PATH); _process = new NativeProcess(); 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); _process.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, eventDispatched); _process.addEventListener(IOErrorEvent.STANDARD_OUTPUT_IO_ERROR, errorCallback); } public function init():Boolean { trace("Init called"); if(!_file.exists) return false; startProcess(); if(!_process.running) return false; callWrapper(AIRSteam_Init); isReady = readBoolResponse(); if(isReady) _tm = setInterval(runCallbacks, 100); return isReady; } private function callWrapper(funcName:int, params:Array = null):void{ if(!_process.running) startProcess(); trace("Calling: " + funcName + "//" + params); var stdin:IDataOutput = _process.standardInput; stdin.writeUTFBytes(funcName + "\n"); if(!params) return; 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"); } } } private function waitForData(output:IDataInput):uint { while(!output.bytesAvailable) { // wait } 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); trace(response + "//" + (response == "t")); 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); trace(response); 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) trace(response); 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) trace(response); return response; } private function eventDispatched(e:ProgressEvent):void { var stderr:IDataInput = _process.standardError; var avail:uint = stderr.bytesAvailable; var data:String = stderr.readUTFBytes(avail); trace("Got progress event, data available: " + avail); trace("Content: " + data); 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]); trace("Got event: " + req_type + "//" + response); var steamEvent:SteamEvent = new SteamEvent(SteamEvent.STEAM_RESPONSE, req_type, response); dispatchEvent(steamEvent); } } private function errorCallback(e:IOErrorEvent):void { // the process doesn't accept our input anymore, try to restart it if(_process.running) { _process.closeInput(); _process.exit(); } startProcess(); } public function requestStats():Boolean { trace("requestStats called"); callWrapper(AIRSteam_RequestStats); return readBoolResponse(); } public function runCallbacks():Boolean { trace("runCallbacks called"); callWrapper(AIRSteam_RunCallbacks); return true; } public function setAchievement(id:String):Boolean { trace("setAchievement called"); callWrapper(AIRSteam_SetAchievement, [id]); return readBoolResponse(); } public function clearAchievement(id:String):Boolean { trace("clearAchievement called"); callWrapper(AIRSteam_ClearAchievement, [id]); return readBoolResponse(); } public function isAchievement(id:String):Boolean { trace("isAchievement called"); callWrapper(AIRSteam_IsAchievement, [id]); return readBoolResponse(); } public function getStatInt(id:String):int { trace("getStatInt called"); callWrapper(AIRSteam_GetStatInt, [id]); return readIntResponse(); } public function getStatFloat(id:String):Number { trace("getStatFloat called"); callWrapper(AIRSteam_GetStatFloat, [id]); return readFloatResponse(); } public function setStatInt(id:String, value:int):Boolean { trace("setStatInt called"); callWrapper(AIRSteam_SetStatInt, [id, value]); return readBoolResponse(); } public function setStatFloat(id:String, value:Number):Boolean { trace("setStatFloat called"); callWrapper(AIRSteam_SetStatFloat, [id, value]); return readBoolResponse(); } public function storeStats():Boolean { trace("storeStats called"); callWrapper(AIRSteam_StoreStats); return readBoolResponse(); } public function resetAllStats(bAchievementsToo:Boolean):Boolean { trace("resetAllStats called"); callWrapper(AIRSteam_ResetAllStats, [bAchievementsToo]); return readBoolResponse(); } public function getFileCount():int { trace("getFileCount called"); callWrapper(AIRSteam_GetFileCount); return readIntResponse(); } public function getFileSize(fileName:String):int { trace("getFileSize called"); callWrapper(AIRSteam_GetFileSize, [fileName]); return readIntResponse(); } public function fileExists(fileName:String):Boolean { trace("fileExists called"); callWrapper(AIRSteam_FileExists, [fileName]); return readBoolResponse(); } public function fileWrite(fileName:String, data:ByteArray):Boolean { trace("fileWrite called"); callWrapper(AIRSteam_FileWrite, [fileName, data]); return readBoolResponse(); } public function fileRead(fileName:String, data:ByteArray):Boolean { trace("fileRead called"); callWrapper(AIRSteam_FileRead, [fileName]); var success:Boolean = readBoolResponse(); if(success) { var content:String = readStringResponse(); data.writeUTFBytes(content); data.position = 0; } return success; } public function fileDelete(fileName:String):Boolean { trace("fileDelete called"); callWrapper(AIRSteam_FileDelete, [fileName]); return readBoolResponse(); } public function isCloudEnabledForApp():Boolean { trace("isCloudEnabledForApp called"); callWrapper(AIRSteam_IsCloudEnabledForApp); return readBoolResponse(); } public function setCloudEnabledForApp(enabled:Boolean):Boolean { trace("setCloudEnabledForApp called"); callWrapper(AIRSteam_SetCloudEnabledForApp, [enabled]); return readBoolResponse(); } } }
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; 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; public function FRESteamWorks (target:IEventDispatcher = null) { _file = File.applicationDirectory.resolvePath(PATH); _process = new NativeProcess(); 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); _process.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, eventDispatched); _process.addEventListener(IOErrorEvent.STANDARD_OUTPUT_IO_ERROR, errorCallback); } public function init():Boolean { if(!_file.exists) return false; startProcess(); if(!_process.running) return false; callWrapper(AIRSteam_Init); isReady = readBoolResponse(); if(isReady) _tm = setInterval(runCallbacks, 100); return isReady; } private function callWrapper(funcName:int, params:Array = null):void{ if(!_process.running) startProcess(); var stdin:IDataOutput = _process.standardInput; stdin.writeUTFBytes(funcName + "\n"); if(!params) return; 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"); } } } private function waitForData(output:IDataInput):uint { while(!output.bytesAvailable) { // wait } 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); } } private function errorCallback(e:IOErrorEvent):void { // the process doesn't accept our input anymore, try to restart it if(_process.running) { _process.closeInput(); _process.exit(); } startProcess(); } public function requestStats():Boolean { callWrapper(AIRSteam_RequestStats); return readBoolResponse(); } public function runCallbacks():Boolean { callWrapper(AIRSteam_RunCallbacks); return true; } public function setAchievement(id:String):Boolean { callWrapper(AIRSteam_SetAchievement, [id]); return readBoolResponse(); } public function clearAchievement(id:String):Boolean { callWrapper(AIRSteam_ClearAchievement, [id]); return readBoolResponse(); } public function isAchievement(id:String):Boolean { callWrapper(AIRSteam_IsAchievement, [id]); return readBoolResponse(); } public function getStatInt(id:String):int { callWrapper(AIRSteam_GetStatInt, [id]); return readIntResponse(); } public function getStatFloat(id:String):Number { callWrapper(AIRSteam_GetStatFloat, [id]); return readFloatResponse(); } public function setStatInt(id:String, value:int):Boolean { callWrapper(AIRSteam_SetStatInt, [id, value]); return readBoolResponse(); } public function setStatFloat(id:String, value:Number):Boolean { callWrapper(AIRSteam_SetStatFloat, [id, value]); return readBoolResponse(); } public function storeStats():Boolean { callWrapper(AIRSteam_StoreStats); return readBoolResponse(); } public function resetAllStats(bAchievementsToo:Boolean):Boolean { callWrapper(AIRSteam_ResetAllStats, [bAchievementsToo]); return readBoolResponse(); } public function getFileCount():int { callWrapper(AIRSteam_GetFileCount); return readIntResponse(); } public function getFileSize(fileName:String):int { callWrapper(AIRSteam_GetFileSize, [fileName]); return readIntResponse(); } public function fileExists(fileName:String):Boolean { callWrapper(AIRSteam_FileExists, [fileName]); return readBoolResponse(); } public function fileWrite(fileName:String, data:ByteArray):Boolean { callWrapper(AIRSteam_FileWrite, [fileName, data]); return readBoolResponse(); } public function fileRead(fileName:String, data:ByteArray):Boolean { callWrapper(AIRSteam_FileRead, [fileName]); var success:Boolean = readBoolResponse(); if(success) { var content:String = readStringResponse(); data.writeUTFBytes(content); data.position = 0; } return success; } public function fileDelete(fileName:String):Boolean { callWrapper(AIRSteam_FileDelete, [fileName]); return readBoolResponse(); } public function isCloudEnabledForApp():Boolean { callWrapper(AIRSteam_IsCloudEnabledForApp); return readBoolResponse(); } public function setCloudEnabledForApp(enabled:Boolean):Boolean { callWrapper(AIRSteam_SetCloudEnabledForApp, [enabled]); return readBoolResponse(); } } }
Remove debug traces
Remove debug traces
ActionScript
bsd-2-clause
Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks
963f5c90ee0a1e21d5b45f6a21a2d356b85b46b4
src/avm1lib/AVM1Broadcaster.as
src/avm1lib/AVM1Broadcaster.as
/** * Copyright 2014 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package avm1lib { public class AVM1Broadcaster { public static function initialize(obj: Object): void { obj._listeners = []; obj.broadcastMessage = _broadcastMessage; obj.addListener = _addListener; obj.removeListener = _removeListener; } } } function _broadcastMessage(eventName: String): void { var args: Array = Array.prototype.slice.call(arguments, 1); var listeners: Array = this._listeners; for (var i: int = 0; i < listeners.length; i++) { var listener: Object = listeners[i]; if (!(eventName in listener)) { continue; } listener[eventName].apply(listener, args); } } function _addListener(listener: Object): void { if (this._broadcastEventsRegistrationNeeded) { this._broadcastEventsRegistrationNeeded = false; for (var i: int = 0; i < this._broadcastEvents.length; i++) { (function (subject: Object, eventName: String): void { subject[eventName] = function handler(): void { _broadcastMessage.apply(subject, [eventName].concat(arguments)); }; })(this, this._broadcastEvents[i]); } } this._listeners.push(listener); } function _removeListener(listener: Object): Boolean { var i: int = this._listeners.indexOf(listener); if (i < 0) { return false; } this._listeners.splice(i, 1); return true; }
/** * Copyright 2014 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package avm1lib { public class AVM1Broadcaster { public static function initialize(obj: Object): void { obj._listeners = []; obj.broadcastMessage = _broadcastMessage; obj.addListener = _addListener; obj.removeListener = _removeListener; } } } function _broadcastMessage(eventName: String, ...args): void { var listeners: Array = this._listeners; for (var i: int = 0; i < listeners.length; i++) { var listener: Object = listeners[i]; if (!(eventName in listener)) { continue; } listener[eventName].apply(listener, args); } } function _addListener(listener: Object): void { if (this._broadcastEventsRegistrationNeeded) { this._broadcastEventsRegistrationNeeded = false; for (var i: int = 0; i < this._broadcastEvents.length; i++) { (function (subject: Object, eventName: String): void { subject[eventName] = function handler(): void { _broadcastMessage.apply(subject, [eventName].concat(arguments)); }; })(this, this._broadcastEvents[i]); } } this._listeners.push(listener); } function _removeListener(listener: Object): Boolean { var i: int = this._listeners.indexOf(listener); if (i < 0) { return false; } this._listeners.splice(i, 1); return true; }
Fix AVM1 event broadcaster to correctly pass on arguments to listeners
Fix AVM1 event broadcaster to correctly pass on arguments to listeners Using `Array.prototype.slice.call(arguments, 1)` didn't work at all, but `...args` does.
ActionScript
apache-2.0
tschneidereit/shumway,tschneidereit/shumway,mozilla/shumway,tschneidereit/shumway,mozilla/shumway,yurydelendik/shumway,mozilla/shumway,mbebenita/shumway,yurydelendik/shumway,mozilla/shumway,mozilla/shumway,mbebenita/shumway,mbebenita/shumway,mozilla/shumway,mbebenita/shumway,mozilla/shumway,mbebenita/shumway,yurydelendik/shumway,yurydelendik/shumway,yurydelendik/shumway,tschneidereit/shumway,yurydelendik/shumway,yurydelendik/shumway,mbebenita/shumway,mbebenita/shumway,tschneidereit/shumway,tschneidereit/shumway,tschneidereit/shumway,yurydelendik/shumway,mozilla/shumway,tschneidereit/shumway,mbebenita/shumway
d4ec3c5bba9790ca93abf349f36312d5c9c7dbd2
src/aerys/minko/type/KeyboardManager.as
src/aerys/minko/type/KeyboardManager.as
package aerys.minko.type { import flash.events.IEventDispatcher; import flash.events.KeyboardEvent; public final class KeyboardManager { private var _keys : Array = []; public function KeyboardManager() { } public function bind(dispatcher : IEventDispatcher) : void { dispatcher.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler); dispatcher.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler); } public function unbind(dispatcher : IEventDispatcher) : void { dispatcher.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler); dispatcher.removeEventListener(KeyboardEvent.KEY_UP, keyUpHandler); } private function keyDownHandler(event : KeyboardEvent) : void { _keys[event.keyCode] = true; } private function keyUpHandler(event : KeyboardEvent) : void { _keys[event.keyCode] = false; } public function keyIsDown(keyCode : uint) : Boolean { return !!_keys[keyCode]; } } }
package aerys.minko.type { import flash.events.IEventDispatcher; import flash.events.KeyboardEvent; public final class KeyboardManager { public static const NO_KEY : uint = uint(-1); private var _keys : Array = []; private var _downSignals : Array = []; private var _upSignals : Array = []; private var _keyDown : Signal = new Signal('KeyboardManager.keyDown'); private var _keyUp : Signal = new Signal('KeyboardManager.keyDown'); public function KeyboardManager() { } public function bind(dispatcher : IEventDispatcher) : void { dispatcher.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler); dispatcher.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler); } public function unbind(dispatcher : IEventDispatcher) : void { dispatcher.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler); dispatcher.removeEventListener(KeyboardEvent.KEY_UP, keyUpHandler); } public function keyDown(keyCode : uint = 0xffffffff) : Signal { if (keyCode == NO_KEY) return _keyDown; else return _downSignals[keyCode] || (_downSignals[keyCode] = new Signal('KeyDown[' + keyCode + ']')); } public function keyUp(keyCode : uint = 0xffffffff) : Signal { if (keyCode == NO_KEY) return _keyUp; else return _upSignals[keyCode] || (_upSignals[keyCode] = new Signal('KeyUp[' + keyCode + ']')); } private function keyDownHandler(event : KeyboardEvent) : void { var keyCode : uint = event.keyCode; var signal : Signal = _downSignals[keyCode] as Signal; _keys[keyCode] = true; if (signal != null) signal.execute(this, keyCode); } private function keyUpHandler(event : KeyboardEvent) : void { var keyCode : uint = event.keyCode; var signal : Signal = _upSignals[keyCode] as Signal; _keys[keyCode] = false; if (signal != null) signal.execute(this, keyCode); } public function keyIsDown(keyCode : uint) : Boolean { return !!_keys[keyCode]; } } }
add (per key) up/down signals to KeyboardManager
add (per key) up/down signals to KeyboardManager
ActionScript
mit
aerys/minko-as3
543efdfbb1180cb4123c34177fa6b061d6085d36
src/com/esri/builder/supportClasses/LabelUtil.as
src/com/esri/builder/supportClasses/LabelUtil.as
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008-2013 Esri. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //////////////////////////////////////////////////////////////////////////////// package com.esri.builder.supportClasses { import mx.core.FlexGlobals; import spark.utils.LabelUtil; public final class LabelUtil { public static function findLongestLabelItem(items:Array, labelField:String = null, labelFunction:Function = null):Object { var longestItem:Object; var currentItemWidth:Number; var longestItemLabelWidth:Number = 0; var currentItemLabel:String; for each (var item:Object in items) { currentItemLabel = itemToLabel(item, labelField, labelFunction); currentItemWidth = FlexGlobals.topLevelApplication.measureText(currentItemLabel).width; if (currentItemWidth > longestItemLabelWidth) { longestItemLabelWidth = currentItemWidth; longestItem = item; } } return longestItem; } private static function itemToLabel(item:Object, labelField:String = null, labelFunction:Function = null):String { return spark.utils.LabelUtil.itemToLabel(item, labelField, labelFunction); } } }
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008-2013 Esri. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //////////////////////////////////////////////////////////////////////////////// package com.esri.builder.supportClasses { import mx.core.FlexGlobals; import mx.utils.StringUtil; import spark.utils.LabelUtil; public final class LabelUtil { public static function findLongestLabelItem(items:Array, labelField:String = null, labelFunction:Function = null):Object { var longestItem:Object; var currentItemWidth:Number; var longestItemLabelWidth:Number = 0; var currentItemLabel:String; for each (var item:Object in items) { currentItemLabel = itemToLabel(item, labelField, labelFunction); currentItemWidth = FlexGlobals.topLevelApplication.measureText(currentItemLabel).width; if (currentItemWidth > longestItemLabelWidth) { longestItemLabelWidth = currentItemWidth; longestItem = item; } } return longestItem; } private static function itemToLabel(item:Object, labelField:String = null, labelFunction:Function = null):String { return spark.utils.LabelUtil.itemToLabel(item, labelField, labelFunction); } public static function generateUniqueLabel(fileNameTemplate:String, usedNames:Array, isUniqueFunction:Function = null):String { var currentID:int = 1; var uniqueLabel:String; var uniquenessFunction:Function = isUniqueFunction != null ? isUniqueFunction : isNameUnique; do { uniqueLabel = StringUtil.substitute(fileNameTemplate, currentID++); } while (!uniquenessFunction(uniqueLabel, usedNames)); return uniqueLabel; } private static function isNameUnique(name:String, usedNames:Array):Boolean { return usedNames.indexOf(name) == -1; } } }
Add utility to generate unique label.
Add utility to generate unique label.
ActionScript
apache-2.0
Esri/arcgis-viewer-builder-flex
85a8aea93f43f6f5a8eec988510c358da66b941c
tests/examplefiles/as3_test.as
tests/examplefiles/as3_test.as
import flash.events.MouseEvent; import com.example.programmingas3.playlist.PlayList; import com.example.programmingas3.playlist.Song; import com.example.programmingas3.playlist.SortProperty; // constants for the different "states" of the song form private static const ADD_SONG:uint = 1; private static const SONG_DETAIL:uint = 2; private var playList:PlayList = new PlayList(); private function initApp():void { // set the initial state of the song form, for adding a new song setFormState(ADD_SONG); // prepopulate the list with a few songs playList.addSong(new Song("Nessun Dorma", "Luciano Pavarotti", 1990, "nessundorma.mp3", ["90's", "Opera"])); playList.addSong(new Song("Come Undone", "Duran Duran", 1993, "comeundone.mp3", ["90's", "Pop"])); playList.addSong(new Song("Think of Me", "Sarah Brightman", 1987, "thinkofme.mp3", ["Showtunes"])); playList.addSong(new Song("Unbelievable", "EMF", 1991, "unbelievable.mp3", ["90's", "Pop"])); songList.dataProvider = playList.songList; } private function sortList(sortField:SortProperty):void { // Make all the sort type buttons enabled. // The active one will be grayed-out below sortByTitle.selected = false; sortByArtist.selected = false; sortByYear.selected = false; switch (sortField) { case SortProperty.TITLE: sortByTitle.selected = true; break; case SortProperty.ARTIST: sortByArtist.selected = true; break; case SortProperty.YEAR: sortByYear.selected = true; break; } playList.sortList(sortField); refreshList(); } private function refreshList():void { // remember which song was selected var selectedSong:Song = Song(songList.selectedItem); // re-assign the song list as the dataprovider to get the newly sorted list // and force the List control to refresh itself songList.dataProvider = playList.songList; // reset the song selection if (selectedSong != null) { songList.selectedItem = selectedSong; } } private function songSelectionChange():void { if (songList.selectedIndex != -1) { setFormState(SONG_DETAIL); } else { setFormState(ADD_SONG); } } private function addNewSong():void { // gather the values from the form and add the new song var title:String = newSongTitle.text; var artist:String = newSongArtist.text; var year:uint = newSongYear.value; var filename:String = newSongFilename.text; var genres:Array = newSongGenres.selectedItems; playList.addSong(new Song(title, artist, year, filename, genres)); refreshList(); // clear out the "add song" form fields setFormState(ADD_SONG); } private function songListLabel(item:Object):String { return item.toString(); } private function setFormState(state:uint):void { // set the form title and control state switch (state) { case ADD_SONG: formTitle.text = "Add New Song"; // show the submit button submitSongData.visible = true; showAddControlsBtn.visible = false; // clear the form fields newSongTitle.text = ""; newSongArtist.text = ""; newSongYear.value = (new Date()).fullYear; newSongFilename.text = ""; newSongGenres.selectedIndex = -1; // deselect the currently selected song (if any) songList.selectedIndex = -1; break; case SONG_DETAIL: formTitle.text = "Song Details"; // populate the form with the selected item's data var selectedSong:Song = Song(songList.selectedItem); newSongTitle.text = selectedSong.title; newSongArtist.text = selectedSong.artist; newSongYear.value = selectedSong.year; newSongFilename.text = selectedSong.filename; newSongGenres.selectedItems = selectedSong.genres; // hide the submit button submitSongData.visible = false; showAddControlsBtn.visible = true; break; } }
import flash.events.MouseEvent; import com.example.programmingas3.playlist.PlayList; import com.example.programmingas3.playlist.Song; import com.example.programmingas3.playlist.SortProperty; // constants for the different "states" of the song form private static const ADD_SONG:uint = 1; private static const SONG_DETAIL:uint = 2; private var playList:PlayList = new PlayList.<T>(); private function initApp():void { // set the initial state of the song form, for adding a new song setFormState(ADD_SONG); // prepopulate the list with a few songs playList.addSong(new Song("Nessun Dorma", "Luciano Pavarotti", 1990, "nessundorma.mp3", ["90's", "Opera"])); playList.addSong(new Song("Come Undone", "Duran Duran", 1993, "comeundone.mp3", ["90's", "Pop"])); playList.addSong(new Song("Think of Me", "Sarah Brightman", 1987, "thinkofme.mp3", ["Showtunes"])); playList.addSong(new Song("Unbelievable", "EMF", 1991, "unbelievable.mp3", ["90's", "Pop"])); songList.dataProvider = playList.songList; } private function sortList(sortField:SortProperty.<T>):void { // Make all the sort type buttons enabled. // The active one will be grayed-out below sortByTitle.selected = false; sortByArtist.selected = false; sortByYear.selected = false; switch (sortField) { case SortProperty.TITLE: sortByTitle.selected = true; break; case SortProperty.ARTIST: sortByArtist.selected = true; break; case SortProperty.YEAR: sortByYear.selected = true; break; } playList.sortList(sortField); refreshList(); } private function refreshList():void { // remember which song was selected var selectedSong:Song = Song(songList.selectedItem); // re-assign the song list as the dataprovider to get the newly sorted list // and force the List control to refresh itself songList.dataProvider = playList.songList; // reset the song selection if (selectedSong != null) { songList.selectedItem = selectedSong; } } private function songSelectionChange():void { if (songList.selectedIndex != -1) { setFormState(SONG_DETAIL); } else { setFormState(ADD_SONG); } } private function addNewSong():void { // gather the values from the form and add the new song var title:String = newSongTitle.text; var artist:String = newSongArtist.text; var year:uint = newSongYear.value; var filename:String = newSongFilename.text; var genres:Array = newSongGenres.selectedItems; playList.addSong(new Song(title, artist, year, filename, genres)); refreshList(); // clear out the "add song" form fields setFormState(ADD_SONG); } private function songListLabel(item:Object):String { return item.toString(); } private function setFormState(state:uint):void { // set the form title and control state switch (state) { case ADD_SONG: formTitle.text = "Add New Song"; // show the submit button submitSongData.visible = true; showAddControlsBtn.visible = false; // clear the form fields newSongTitle.text = ""; newSongArtist.text = ""; newSongYear.value = (new Date()).fullYear; newSongFilename.text = ""; newSongGenres.selectedIndex = -1; // deselect the currently selected song (if any) songList.selectedIndex = -1; break; case SONG_DETAIL: formTitle.text = "Song Details"; // populate the form with the selected item's data var selectedSong:Song = Song(songList.selectedItem); newSongTitle.text = selectedSong.title; newSongArtist.text = selectedSong.artist; newSongYear.value = selectedSong.year; newSongFilename.text = selectedSong.filename; newSongGenres.selectedItems = selectedSong.genres; // hide the submit button submitSongData.visible = false; showAddControlsBtn.visible = true; break; } }
Add type generics to AS3 test file.
Add type generics to AS3 test file.
ActionScript
bsd-2-clause
tomstuart/pygments,tomstuart/pygments,tomstuart/pygments,tomstuart/pygments,tomstuart/pygments,tomstuart/pygments,tomstuart/pygments,tomstuart/pygments,tomstuart/pygments,tomstuart/pygments,tomstuart/pygments,tomstuart/pygments,tomstuart/pygments,tomstuart/pygments,tomstuart/pygments
9164e501e8ecd9a1df7918da17be22e681cfe343
WEB-INF/lps/lfc/kernel/swf9/LFCApplication.as
WEB-INF/lps/lfc/kernel/swf9/LFCApplication.as
/** * LFCApplication.as * * @copyright Copyright 2007, 2008, 2009 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic swf9 * @author Henry Minsky &lt;[email protected]&gt; */ public class LFCApplication { // 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.DisplayObject; import flash.display.Sprite; import flash.display.Stage; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.Event; import flash.events.FocusEvent; import flash.system.Capabilities; }# // The application sprite static public var _sprite:Sprite; public static function addChild(child:DisplayObject):DisplayObject { return _sprite.addChild(child); } public static function removeChild(child:DisplayObject):DisplayObject { return _sprite.removeChild(child); } public static function setChildIndex(child:DisplayObject, index:int):void { _sprite.setChildIndex(child, index); } // Allow anyone access to the stage object (see ctor below) public static var stage:Stage = null; // global tabEnabled flag for TextField public static var textfieldTabEnabled:Boolean = false; public function LFCApplication (sprite:Sprite) { LFCApplication._sprite = sprite; // wait for the ADDED_TO_STAGE event before continuing to init LFCApplication._sprite.addEventListener(Event.ADDED_TO_STAGE, initLFC); } private function initLFC(event:Event = null) :void { LFCApplication._sprite.removeEventListener(Event.ADDED_TO_STAGE, initLFC); // Allow anyone to access the stage object LFCApplication.stage = LFCApplication._sprite.stage; runToplevelDefinitions() if (Capabilities.playerType == "ActiveX") { // Workaround for ActiveX control swallowing browser focus events stage.addEventListener(Event.ACTIVATE, allKeysUp); // workaround for flash player bug FP-1355 LFCApplication.textfieldTabEnabled = true; stage.addEventListener(FocusEvent.KEY_FOCUS_CHANGE, preventFocusChange); } // 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"; // Register for callbacks from the kernel LzMouseKernel.setCallback(lz.ModeManager, 'rawMouseEvent'); LzMouseKernel.initCursor(); LzKeyboardKernel.setCallback(lz.Keys, '__keyEvent'); } private function allKeysUp(event:Event):void { lz.Keys.__allKeysUp('flash activate'); } private function preventFocusChange(event:FocusEvent):void { if (event.keyCode == 9) { event.preventDefault(); } } public function runToplevelDefinitions() { // overridden by swf9 script compiler } } // Resource library // contains {ptype, class, frames, width, height} // ptype is one of "ar" (app relative) or "sr" (system relative) var LzResourceLibrary :Object = {};
/** * LFCApplication.as * * @copyright Copyright 2007, 2008, 2009 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic swf9 * @author Henry Minsky &lt;[email protected]&gt; */ public class LFCApplication { // 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.DisplayObject; import flash.display.Sprite; import flash.display.Stage; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.Event; import flash.events.FocusEvent; import flash.system.Capabilities; }# // The application sprite static public var _sprite:Sprite; public static function addChild(child:DisplayObject):DisplayObject { return _sprite.addChild(child); } public static function removeChild(child:DisplayObject):DisplayObject { return _sprite.removeChild(child); } public static function setChildIndex(child:DisplayObject, index:int):void { _sprite.setChildIndex(child, index); } // Allow anyone access to the stage object (see ctor below) public static var stage:Stage = null; // global tabEnabled flag for TextField public static var textfieldTabEnabled:Boolean = false; public function LFCApplication (sprite:Sprite) { LFCApplication._sprite = sprite; // wait for the ADDED_TO_STAGE event before continuing to init LFCApplication._sprite.addEventListener(Event.ADDED_TO_STAGE, initLFC); } private function initLFC(event:Event = null) :void { LFCApplication._sprite.removeEventListener(Event.ADDED_TO_STAGE, initLFC); // Allow anyone to access the stage object LFCApplication.stage = LFCApplication._sprite.stage; runToplevelDefinitions() if (Capabilities.playerType == "ActiveX") { // Workaround for ActiveX control swallowing browser focus events stage.addEventListener(Event.ACTIVATE, allKeysUp); // workaround for flash player bug FP-1355 LFCApplication.textfieldTabEnabled = true; stage.addEventListener(FocusEvent.KEY_FOCUS_CHANGE, preventFocusChange); } // 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"; // Register for callbacks from the kernel LzMouseKernel.setCallback(lz.ModeManager, 'rawMouseEvent'); LzMouseKernel.initCursor(); LzKeyboardKernel.setCallback(lz.Keys, '__keyEvent'); } private function allKeysUp(event:Event):void { lz.Keys.__allKeysUp(); } private function preventFocusChange(event:FocusEvent):void { if (event.keyCode == 9) { event.preventDefault(); } } public function runToplevelDefinitions() { // overridden by swf9 script compiler } } // Resource library // contains {ptype, class, frames, width, height} // ptype is one of "ar" (app relative) or "sr" (system relative) var LzResourceLibrary :Object = {};
Change 20090901-hqm-5 by [email protected] on 2009-09-01 11:49:48 EDT in /Users/hqm/openlaszlo/trunk-clean for http://svn.openlaszlo.org/openlaszlo/trunk
Change 20090901-hqm-5 by [email protected] on 2009-09-01 11:49:48 EDT in /Users/hqm/openlaszlo/trunk-clean for http://svn.openlaszlo.org/openlaszlo/trunk Summary: fix for swf10 error when using context menu New Features: Bugs Fixed: LPP-8438 Technical Reviewer: max QA Reviewer: andre Doc Reviewer: (pending) Documentation: Release Notes: Details: + remove extra arg from call to LzKeysService.__allKeysUp Tests: In Windows IE7, no longer get runtime error when showing context menu in app git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@14640 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
ActionScript
epl-1.0
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
4138edbb3ff5fc10d5738f197d06d539657acf2b
src/playbacks/flash/Player.as
src/playbacks/flash/Player.as
package { import flash.external.ExternalInterface; import flash.display.*; import flash.events.*; import flash.geom.Rectangle; import flash.media.StageVideoAvailability; import flash.media.StageVideo; import flash.media.SoundTransform; import flash.media.Video; import flash.net.NetConnection; import flash.net.NetStream; import flash.system.Security; import flash.utils.Timer; import flash.utils.setTimeout; public class Player extends MovieClip { private var _video:Video; private var _stageVideo:StageVideo; private var _ns:NetStream; private var _nc:NetConnection; private var totalTime:Number; private var playbackId:String; private var playbackState:String; private var videoVolumeTransform:SoundTransform; private var isOnStageVideo:Boolean = false; private var heartbeat:Timer = new Timer(500); private var source:String; public function Player() { Security.allowDomain('*'); Security.allowInsecureDomain('*'); playbackId = LoaderInfo(this.root.loaderInfo).parameters.playbackId; playbackState = "IDLE"; _video = new Video(); setupCallbacks(); setTimeout(flashReady, 50); } private function flashReady(): void { _triggerEvent('flashready'); setupStage(); } private function onConnectionStatus(e:NetStatusEvent):void { if (e.info.code == "NetConnection.Connect.Success"){ setupNetStream(); } } private function setupNetStream():void { videoVolumeTransform = new SoundTransform(); videoVolumeTransform.volume = 1; createNetStream(); _stageVideo.attachNetStream(_ns); _ns.play(source); } private function createNetStream():void { _ns = new NetStream(_nc); _ns.client = this; _ns.soundTransform = videoVolumeTransform; _ns.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); _ns.bufferTime = 10; _ns.inBufferSeek = true; _ns.maxPauseBufferTime = 3600; _ns.backBufferTime = 3600; } private function setupStage():void { stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; stage.fullScreenSourceRect = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); stage.displayState = StageDisplayState.NORMAL; stage.addEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY, _onStageVideoAvailability); stage.addEventListener(Event.RESIZE, _onResize); } private function setupNetConnection():void { _nc = new NetConnection(); _nc.client = this; _nc.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler); _nc.addEventListener(NetStatusEvent.NET_STATUS, onConnectionStatus); _nc.connect(null); } private function setupCallbacks():void { ExternalInterface.addCallback("setVideoSize", setVideoSize); ExternalInterface.addCallback("playerPlay", playerPlay); ExternalInterface.addCallback("playerPause", playerPause); ExternalInterface.addCallback("playerStop", playerStop); ExternalInterface.addCallback("playerSeek", playerSeek); ExternalInterface.addCallback("playerVolume", playerVolume); ExternalInterface.addCallback("playerResume", playerResume); ExternalInterface.addCallback("getState", getState); ExternalInterface.addCallback("getPosition", getPosition); ExternalInterface.addCallback("getDuration", getDuration); ExternalInterface.addCallback("getBytesLoaded", getBytesLoaded); ExternalInterface.addCallback("getBytesTotal", getBytesTotal); } private function getBytesTotal():Number { return _ns.bytesTotal; } private function getBytesLoaded():Number { return _ns.bytesLoaded; } private function netStatusHandler(event:NetStatusEvent):void { if (event.info.code === "NetStream.Buffer.Full") { playbackState = "PLAYING"; _ns.bufferTime = 15; } else if (isBuffering(event.info.code)) { playbackState = "PLAYING_BUFFERING"; } else if (event.info.code == "NetStream.Video.DimensionChange") { setVideoSize(stage.stageWidth, stage.stageHeight); } else if (event.info.code == "NetStream.Play.Stop") { playbackState = "ENDED"; heartbeat.stop(); } else if (event.info.code == "NetStream.Buffer.Empty") { _ns.bufferTime = 5; } _triggerEvent('statechanged'); } private function isBuffering(code:String):Boolean { return Boolean(code == "NetStream.Buffer.Empty" && playbackState != "ENDED" || code == "NetStream.SeekStart.Notify" || code == "NetStream.Play.Start"); } private function _onResize(event:Event):void { setVideoSize(stage.stageWidth, stage.stageHeight); } private function onHeartbeat( event:TimerEvent ):void { _triggerEvent('progress'); _triggerEvent('timeupdate'); } private function playerPlay(url:String):void { source = url; setupNetConnection(); heartbeat.addEventListener( TimerEvent.TIMER, onHeartbeat ); heartbeat.start(); } private function playerPause():void { _ns.pause(); if (_ns.bytesLoaded == _ns.bytesTotal) { heartbeat.stop(); } playbackState = "PAUSED"; } private function playerStop():void { _ns.pause(); _ns.seek(0); heartbeat.stop(); playbackState = "IDLE"; } private function playerSeek(position:Number):void { _ns.seek(position); } private function playerResume():void { playbackState = "PLAYING"; _ns.resume(); heartbeat.start(); } private function playerVolume(level:Number):void { videoVolumeTransform.volume = level/100; _ns.soundTransform = videoVolumeTransform; } private function getState():String { return playbackState; } private function getPosition():Number { return _ns.time; } private function getDuration():Number { return totalTime; } private function setVideoSize(width:Number, height:Number):void { stage.fullScreenSourceRect = new Rectangle(0, 0, width, height); var rect:Rectangle = new Rectangle(0,0, width, height);// resizeRectangle(stage.stageWidth, stage.stageHeight, width, height); _video.width = rect.width; _video.height = rect.height; _video.x = rect.x; _video.y = rect.y; if (isOnStageVideo) { _stageVideo.viewPort = rect; } } public static function resizeRectangle(videoWidth : Number, videoHeight : Number, containerWidth : Number, containerHeight : Number) : Rectangle { var rect : Rectangle = new Rectangle(); var xscale : Number = containerWidth / videoWidth; var yscale : Number = containerHeight / videoHeight; if (xscale >= yscale) { rect.width = Math.min(videoWidth * yscale, containerWidth); rect.height = videoHeight * yscale; } else { rect.width = Math.min(videoWidth * xscale, containerWidth); rect.height = videoHeight * xscale; } rect.width = Math.ceil(rect.width); rect.height = Math.ceil(rect.height); rect.x = Math.round((containerWidth - rect.width) / 2); rect.y = Math.round((containerHeight - rect.height) / 2); return rect; } private function _triggerEvent(name: String):void { ExternalInterface.call('Clappr.Mediator.trigger("' + playbackId + ':' + name +'")'); } private function _enableStageVideo():void { if (_stageVideo == null) { _stageVideo = stage.stageVideos[0]; _stageVideo.viewPort = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); } if (_video.parent) { removeChild(_video); } _stageVideo.attachNetStream(_ns); } private function _disableStageVideo():void { _video.attachNetStream(_ns); _video.smoothing = true; addChild(_video); } private function _onStageVideoAvailability(evt:StageVideoAvailabilityEvent):void { if (evt.availability && stage.stageVideos.length > 0) { _enableStageVideo(); isOnStageVideo = true; } else { _disableStageVideo(); } } public function onMetaData(info:Object):void { totalTime = info.duration; _triggerEvent('timeupdate'); receivedMeta(info); } public function receivedMeta(data:Object):void { setVideoSize(stage.stageWidth, stage.stageHeight); } public function onBWDone(...rest):void { setVideoSize(stage.stageWidth, stage.stageHeight); } public function asyncErrorHandler(event:AsyncErrorEvent):void { } public function onFCSubscribe(info:Object):void { } public function cuePointHandler(infoObject:Object):void { } public function onFI(infoObject:Object):void { } public function onPlayStatus(infoObject:Object):void { } } }
package { import flash.external.ExternalInterface; import flash.display.*; import flash.events.*; import flash.geom.Rectangle; import flash.media.StageVideoAvailability; import flash.media.StageVideo; import flash.media.SoundTransform; import flash.media.Video; import flash.net.NetConnection; import flash.net.NetStream; import flash.system.Security; import flash.utils.Timer; import flash.utils.setTimeout; public class Player extends MovieClip { private var _video:Video; private var _stageVideo:StageVideo; private var _ns:NetStream; private var _nc:NetConnection; private var totalTime:Number; private var playbackId:String; private var playbackState:String; private var videoVolumeTransform:SoundTransform; private var isOnStageVideo:Boolean = false; private var heartbeat:Timer = new Timer(500); private var source:String; public function Player() { Security.allowDomain('*'); Security.allowInsecureDomain('*'); playbackId = LoaderInfo(this.root.loaderInfo).parameters.playbackId; playbackState = "IDLE"; _video = new Video(); setupCallbacks(); setupStage(); } private function flashReady(): void { _triggerEvent('flashready'); } private function onConnectionStatus(e:NetStatusEvent):void { if (e.info.code == "NetConnection.Connect.Success"){ setupNetStream(); } } private function setupNetStream():void { videoVolumeTransform = new SoundTransform(); videoVolumeTransform.volume = 1; createNetStream(); _stageVideo.attachNetStream(_ns); _ns.play(source); } private function createNetStream():void { _ns = new NetStream(_nc); _ns.client = this; _ns.soundTransform = videoVolumeTransform; _ns.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); _ns.bufferTime = 10; _ns.inBufferSeek = true; _ns.maxPauseBufferTime = 3600; _ns.backBufferTime = 3600; } private function setupStage():void { stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; stage.fullScreenSourceRect = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); stage.displayState = StageDisplayState.NORMAL; stage.addEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY, _onStageVideoAvailability); stage.addEventListener(Event.RESIZE, _onResize); } private function setupNetConnection():void { _nc = new NetConnection(); _nc.client = this; _nc.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler); _nc.addEventListener(NetStatusEvent.NET_STATUS, onConnectionStatus); _nc.connect(null); } private function setupCallbacks():void { ExternalInterface.addCallback("setVideoSize", setVideoSize); ExternalInterface.addCallback("playerPlay", playerPlay); ExternalInterface.addCallback("playerPause", playerPause); ExternalInterface.addCallback("playerStop", playerStop); ExternalInterface.addCallback("playerSeek", playerSeek); ExternalInterface.addCallback("playerVolume", playerVolume); ExternalInterface.addCallback("playerResume", playerResume); ExternalInterface.addCallback("getState", getState); ExternalInterface.addCallback("getPosition", getPosition); ExternalInterface.addCallback("getDuration", getDuration); ExternalInterface.addCallback("getBytesLoaded", getBytesLoaded); ExternalInterface.addCallback("getBytesTotal", getBytesTotal); } private function getBytesTotal():Number { return _ns.bytesTotal; } private function getBytesLoaded():Number { return _ns.bytesLoaded; } private function netStatusHandler(event:NetStatusEvent):void { if (event.info.code === "NetStream.Buffer.Full") { playbackState = "PLAYING"; _ns.bufferTime = 15; } else if (isBuffering(event.info.code)) { playbackState = "PLAYING_BUFFERING"; } else if (event.info.code == "NetStream.Video.DimensionChange") { setVideoSize(stage.stageWidth, stage.stageHeight); } else if (event.info.code == "NetStream.Play.Stop") { playbackState = "ENDED"; heartbeat.stop(); } else if (event.info.code == "NetStream.Buffer.Empty") { _ns.bufferTime = 5; } _triggerEvent('statechanged'); } private function isBuffering(code:String):Boolean { return Boolean(code == "NetStream.Buffer.Empty" && playbackState != "ENDED" || code == "NetStream.SeekStart.Notify" || code == "NetStream.Play.Start"); } private function _onResize(event:Event):void { setVideoSize(stage.stageWidth, stage.stageHeight); } private function onHeartbeat( event:TimerEvent ):void { _triggerEvent('progress'); _triggerEvent('timeupdate'); } private function playerPlay(url:String):void { source = url; setupNetConnection(); heartbeat.addEventListener( TimerEvent.TIMER, onHeartbeat ); heartbeat.start(); } private function playerPause():void { _ns.pause(); if (_ns.bytesLoaded == _ns.bytesTotal) { heartbeat.stop(); } playbackState = "PAUSED"; } private function playerStop():void { _ns.pause(); _ns.seek(0); heartbeat.stop(); playbackState = "IDLE"; } private function playerSeek(position:Number):void { _ns.seek(position); } private function playerResume():void { playbackState = "PLAYING"; _ns.resume(); heartbeat.start(); } private function playerVolume(level:Number):void { videoVolumeTransform.volume = level/100; _ns.soundTransform = videoVolumeTransform; } private function getState():String { return playbackState; } private function getPosition():Number { return _ns.time; } private function getDuration():Number { return totalTime; } private function setVideoSize(width:Number, height:Number):void { stage.fullScreenSourceRect = new Rectangle(0, 0, width, height); var rect:Rectangle = new Rectangle(0,0, width, height);// resizeRectangle(stage.stageWidth, stage.stageHeight, width, height); _video.width = rect.width; _video.height = rect.height; _video.x = rect.x; _video.y = rect.y; if (isOnStageVideo) { _stageVideo.viewPort = rect; } } public static function resizeRectangle(videoWidth : Number, videoHeight : Number, containerWidth : Number, containerHeight : Number) : Rectangle { var rect : Rectangle = new Rectangle(); var xscale : Number = containerWidth / videoWidth; var yscale : Number = containerHeight / videoHeight; if (xscale >= yscale) { rect.width = Math.min(videoWidth * yscale, containerWidth); rect.height = videoHeight * yscale; } else { rect.width = Math.min(videoWidth * xscale, containerWidth); rect.height = videoHeight * xscale; } rect.width = Math.ceil(rect.width); rect.height = Math.ceil(rect.height); rect.x = Math.round((containerWidth - rect.width) / 2); rect.y = Math.round((containerHeight - rect.height) / 2); return rect; } private function _triggerEvent(name: String):void { ExternalInterface.call('Clappr.Mediator.trigger("' + playbackId + ':' + name +'")'); } private function _enableStageVideo():void { if (_stageVideo == null) { _stageVideo = stage.stageVideos[0]; _stageVideo.viewPort = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); } if (_video.parent) { removeChild(_video); } _stageVideo.attachNetStream(_ns); } private function _disableStageVideo():void { _video.attachNetStream(_ns); _video.smoothing = true; addChild(_video); } private function _onStageVideoAvailability(evt:StageVideoAvailabilityEvent):void { if (evt.availability && stage.stageVideos.length > 0) { _enableStageVideo(); isOnStageVideo = true; } else { _disableStageVideo(); } flashReady(); } public function onMetaData(info:Object):void { totalTime = info.duration; _triggerEvent('timeupdate'); receivedMeta(info); } public function receivedMeta(data:Object):void { setVideoSize(stage.stageWidth, stage.stageHeight); } public function onBWDone(...rest):void { setVideoSize(stage.stageWidth, stage.stageHeight); } public function asyncErrorHandler(event:AsyncErrorEvent):void { } public function onFCSubscribe(info:Object):void { } public function cuePointHandler(infoObject:Object):void { } public function onFI(infoObject:Object):void { } public function onPlayStatus(infoObject:Object):void { } } }
call setupStage() before flashReady() (fixes #320)
flash: call setupStage() before flashReady() (fixes #320)
ActionScript
bsd-3-clause
Pyrotoxin/clappr,leandromoreira/clappr,tarkanlar/clappr,shakin/clappr,dayvson/clappr,Metrakit/clappr,tarkanlar/clappr,Peer5/clappr,tjenkinson/clappr,burakkp/clappr,wxmfront/clappr,jfairley/clappr,irongomme/clappr,tjenkinson/clappr,wxmfront/clappr,Peer5/clappr,burakkp/clappr,dayvson/clappr,clappr/clappr,Pyrotoxin/clappr,kelonye/clappr,burakkp/clappr,MariadeAnton/clappr,Peer5/clappr,clappr/clappr,kelonye/clappr,irongomme/clappr,Metrakit/clappr,flavioribeiro/clappr,tarkanlar/clappr,jfairley/clappr,flavioribeiro/clappr,MariadeAnton/clappr,Metrakit/clappr,MariadeAnton/clappr,jfairley/clappr,wxmfront/clappr,clappr/clappr,tjenkinson/clappr,leandromoreira/clappr,dayvson/clappr,shakin/clappr,kelonye/clappr,shakin/clappr,Pyrotoxin/clappr,leandromoreira/clappr,irongomme/clappr,flavioribeiro/clappr
b0030eef74f856533ce45dad746e2737c88d765c
src/flash/media/SoundMixer.as
src/flash/media/SoundMixer.as
package flash.media { import Object; import flash.utils.ByteArray; import flash.media.SoundTransform; public final class SoundMixer { public function SoundMixer() {} public static native function stopAll():void; public static native function computeSpectrum(outputArray:ByteArray, FFTMode:Boolean = false, stretchFactor:int = 0):void; public static native function get bufferTime():int; public static native function set bufferTime(bufferTime:int):void; public static native function get soundTransform():SoundTransform; public static native function set soundTransform(sndTransform:SoundTransform):void; public static native function areSoundsInaccessible():Boolean; public static native function get audioPlaybackMode():String; public static native function set audioPlaybackMode(value:String):void; public static native function get useSpeakerphoneForVoice():Boolean; public static native function set useSpeakerphoneForVoice(value:Boolean):void; } }
/* * Copyright 2014 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package flash.media { import flash.utils.ByteArray; [native(cls='SoundMixerClass')] public final class SoundMixer { public static native function get bufferTime():int; public static native function set bufferTime(bufferTime:int):void; public static native function get soundTransform():SoundTransform; public static native function set soundTransform(sndTransform:SoundTransform):void; public static native function get audioPlaybackMode():String; public static native function set audioPlaybackMode(value:String):void; public static native function get useSpeakerphoneForVoice():Boolean; public static native function set useSpeakerphoneForVoice(value:Boolean):void; public static native function stopAll():void; public static native function computeSpectrum(outputArray:ByteArray, FFTMode:Boolean = false, stretchFactor:int = 0):void; public static native function areSoundsInaccessible():Boolean; public function SoundMixer() {} } }
Implement as3 part of SoundMixer
Implement as3 part of SoundMixer
ActionScript
apache-2.0
mozilla/shumway,mozilla/shumway,mozilla/shumway,tschneidereit/shumway,yurydelendik/shumway,tschneidereit/shumway,mbebenita/shumway,mbebenita/shumway,mozilla/shumway,mozilla/shumway,mbebenita/shumway,mozilla/shumway,tschneidereit/shumway,tschneidereit/shumway,mbebenita/shumway,mozilla/shumway,mbebenita/shumway,tschneidereit/shumway,tschneidereit/shumway,yurydelendik/shumway,yurydelendik/shumway,yurydelendik/shumway,mbebenita/shumway,yurydelendik/shumway,yurydelendik/shumway,mbebenita/shumway,yurydelendik/shumway,yurydelendik/shumway,mozilla/shumway,tschneidereit/shumway,tschneidereit/shumway,mbebenita/shumway
1cf36f21a2869dd7f4e288a9dd771ae1623bcb89
dolly-framework/src/main/actionscript/dolly/Cloner.as
dolly-framework/src/main/actionscript/dolly/Cloner.as
package dolly { import dolly.core.dolly_internal; import dolly.core.errors.CloningError; import dolly.core.metadata.MetadataName; import org.as3commons.reflect.Accessor; import org.as3commons.reflect.AccessorAccess; import org.as3commons.reflect.Field; import org.as3commons.reflect.Type; use namespace dolly_internal; public class Cloner { private static function isTypeCloneable(type:Type):Boolean { return type.hasMetadata(MetadataName.CLONEABLE); } dolly_internal static function findAllWritableFieldsForType(type:Type):Vector.<Field> { const result:Vector.<Field> = new Vector.<Field>(); for each(var field:Field in type.properties) { if (!(field is Accessor) || (field as Accessor).access == AccessorAccess.READ_WRITE) { result.push(field); } } return result; } public static function clone(source:*):* { const type:Type = Type.forInstance(source); if (!isTypeCloneable(type)) { throw new CloningError( CloningError.CLASS_IS_NOT_CLONEABLE_MESSAGE, CloningError.CLASS_IS_NOT_CLONEABLE_CODE ); } const clone:* = new (type.clazz)(); // Find all public writable fields in a hierarchy of a source object // and assign their values to a clone object. const fieldsToClone:Vector.<Field> = findAllWritableFieldsForType(type); var name:String; for each(var field:Field in fieldsToClone) { name = field.name; clone[name] = source[name]; } return clone; } } }
package dolly { import dolly.core.dolly_internal; import dolly.core.errors.CloningError; import dolly.core.metadata.MetadataName; import org.as3commons.reflect.Accessor; import org.as3commons.reflect.AccessorAccess; import org.as3commons.reflect.Field; import org.as3commons.reflect.Type; use namespace dolly_internal; public class Cloner { private static function isTypeCloneable(type:Type):Boolean { return type.hasMetadata(MetadataName.CLONEABLE); } dolly_internal static function findAllWritableFieldsForType(type:Type):Vector.<Field> { const result:Vector.<Field> = new Vector.<Field>(); for each(var field:Field in type.properties) { if (!(field is Accessor) || (field as Accessor).access == AccessorAccess.READ_WRITE) { result.push(field); } } return result; } public static function clone(source:*):* { const type:Type = Type.forInstance(source); if (!isTypeCloneable(type)) { throw new CloningError( CloningError.CLASS_IS_NOT_CLONEABLE_MESSAGE, CloningError.CLASS_IS_NOT_CLONEABLE_CODE ); } const clonedInstance:* = new (type.clazz)(); // Find all public writable fields in a hierarchy of a source object // and assign their values to a clone object. const fieldsToClone:Vector.<Field> = findAllWritableFieldsForType(type); var name:String; for each(var field:Field in fieldsToClone) { name = field.name; clonedInstance[name] = source[name]; } return clonedInstance; } } }
Rename local variable in method Cloner.clone().
Rename local variable in method Cloner.clone().
ActionScript
mit
Yarovoy/dolly
384ad67f19aa3ad58c5358555bae5c4cdc987fed
swfcat.as
swfcat.as
package { import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; 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; [Embed(source="badge.png")] private var BadgeImage:Class; public function puts(s:String):void { output_text.appendText(s + "\n"); output_text.scrollV = output_text.maxScrollV; } public function swfcat() { // Absolute positioning. stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; output_text = new TextField(); output_text.width = stage.stageWidth; output_text.height = stage.stageHeight; output_text.background = true; output_text.backgroundColor = 0x001f0f; output_text.textColor = 0x44cc44; puts("Starting."); // Wait until the query string parameters are loaded. this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete); } private function loaderinfo_complete(e:Event):void { var fac_spec:String; puts("Parameters loaded."); if (this.loaderInfo.parameters["debug"]) addChild(output_text); else addChild(new BadgeImage()); 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.display.StageAlign; import flash.display.StageScaleMode; 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 }; private const DEFAULT_FACILITATOR_ADDR:Object = { host: "173.255.221.44", port: 9002 }; // 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; [Embed(source="badge.png")] private var BadgeImage:Class; public function puts(s:String):void { output_text.appendText(s + "\n"); output_text.scrollV = output_text.maxScrollV; } public function swfcat() { // Absolute positioning. stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; output_text = new TextField(); output_text.width = stage.stageWidth; output_text.height = stage.stageHeight; output_text.background = true; output_text.backgroundColor = 0x001f0f; output_text.textColor = 0x44cc44; puts("Starting."); // Wait until the query string parameters are loaded. this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete); } private function loaderinfo_complete(e:Event):void { var fac_spec:String; puts("Parameters loaded."); if (this.loaderInfo.parameters["debug"]) addChild(output_text); else addChild(new BadgeImage()); fac_spec = this.loaderInfo.parameters["facilitator"]; if (fac_spec) { 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; } } else { fac_addr = DEFAULT_FACILITATOR_ADDR; } 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); }); } }
Put the default facilitator address inside the SWF.
Put the default facilitator address inside the SWF.
ActionScript
mit
arlolra/flashproxy,arlolra/flashproxy,arlolra/flashproxy,glamrock/flashproxy,infinity0/flashproxy,arlolra/flashproxy,glamrock/flashproxy,infinity0/flashproxy,infinity0/flashproxy,infinity0/flashproxy,infinity0/flashproxy,infinity0/flashproxy,arlolra/flashproxy,glamrock/flashproxy,arlolra/flashproxy,arlolra/flashproxy,glamrock/flashproxy,glamrock/flashproxy,glamrock/flashproxy
8cbe73a8a7fe16100f56ea8d51b1a35f4228144f
test/src/FRESteamWorksTest.as
test/src/FRESteamWorksTest.as
/* * FRESteamWorks.h * This file is part of FRESteamWorks. * * Created by David ´Oldes´ Oliva on 3/29/12. * Contributors: Ventero <http://github.com/Ventero> * Copyright (c) 2012 Amanita Design. All rights reserved. * Copyright (c) 2012-2013 Level Up Labs, LLC. All rights reserved. */ package { import com.amanitadesign.steam.FRESteamWorks; import com.amanitadesign.steam.SteamConstants; import com.amanitadesign.steam.SteamEvent; import com.amanitadesign.steam.WorkshopConstants; import flash.desktop.NativeApplication; import flash.display.SimpleButton; import flash.display.Sprite; import flash.display.StageDisplayState; import flash.events.Event; import flash.events.MouseEvent; import flash.text.TextField; import flash.utils.ByteArray; public class FRESteamWorksTest extends Sprite { public var Steamworks:FRESteamWorks = new FRESteamWorks(); public var tf:TextField; private var _buttonPos:int = 5; public function FRESteamWorksTest() { tf = new TextField(); tf.x = 160; tf.width = stage.stageWidth - tf.x; tf.height = stage.stageHeight; addChild(tf); addButton("Check stats/achievements", checkAchievements); addButton("Toggle achievement", toggleAchievement); addButton("Toggle cloud enabled", toggleCloudEnabled); addButton("Toggle file", toggleFile); addButton("Publish file", publishFile); addButton("Toggle fullscreen", toggleFullscreen); addButton("Show Friends overlay", activateOverlay); Steamworks.addEventListener(SteamEvent.STEAM_RESPONSE, onSteamResponse); NativeApplication.nativeApplication.addEventListener(Event.EXITING, onExit); try { Steamworks.useCrashHandler(480, "1.0", "Feb 20 2013", "21:42:20"); if(!Steamworks.init()){ log("STEAMWORKS API is NOT available"); return; } log("STEAMWORKS API is available\n"); log("User ID: " + Steamworks.getUserID()); log("App ID: " + Steamworks.getAppID()); log("Persona name: " + Steamworks.getPersonaName()); log("isCloudEnabledForApp() == "+Steamworks.isCloudEnabledForApp() ); log("getFileCount() == "+Steamworks.getFileCount() ); log("fileExists('test.txt') == "+Steamworks.fileExists('test.txt') ); Steamworks.resetAllStats(true); } catch(e:Error) { log("*** ERROR ***"); log(e.message); log(e.getStackTrace()); } } private function log(value:String):void{ tf.appendText(value+"\n"); tf.scrollV = tf.maxScrollV; } public function writeFileToCloud(fileName:String, data:String):Boolean { var dataOut:ByteArray = new ByteArray(); dataOut.writeUTFBytes(data); return Steamworks.fileWrite(fileName, dataOut); } public function readFileFromCloud(fileName:String):String { var dataIn:ByteArray = new ByteArray(); var result:String; dataIn.position = 0; dataIn.length = Steamworks.getFileSize(fileName); if(dataIn.length>0 && Steamworks.fileRead(fileName,dataIn)){ result = dataIn.readUTFBytes(dataIn.length); } return result; } private function checkAchievements(e:Event = null):void { if(!Steamworks.isReady) return; // current stats and achievement ids are from steam example app log("isAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.isAchievement("ACH_WIN_ONE_GAME")); log("isAchievement('ACH_TRAVEL_FAR_SINGLE') == "+Steamworks.isAchievement("ACH_TRAVEL_FAR_SINGLE")); log("setStatFloat('FeetTraveled') == "+Steamworks.setStatFloat('FeetTraveled', 21.3)); log("setStatInt('NumGames', 2) == "+Steamworks.setStatInt('NumGames', 2)); Steamworks.storeStats(); log("getStatInt('NumGames') == "+Steamworks.getStatInt('NumGames')); log("getStatFloat('FeetTraveled') == "+Steamworks.getStatFloat('FeetTraveled')); } private function toggleAchievement(e:Event = null):void{ if(!Steamworks.isReady) return; var result:Boolean = Steamworks.isAchievement("ACH_WIN_ONE_GAME"); log("isAchievement('ACH_WIN_ONE_GAME') == " + result); if(!result) { log("setAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.setAchievement("ACH_WIN_ONE_GAME")); } else { log("clearAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.clearAchievement("ACH_WIN_ONE_GAME")); } } private function toggleCloudEnabled(e:Event = null):void { if(!Steamworks.isReady) return; var enabled:Boolean = Steamworks.isCloudEnabledForApp(); log("isCloudEnabledForApp() == " + enabled); log("setCloudEnabledForApp(" + !enabled + ") == " + Steamworks.setCloudEnabledForApp(!enabled)); log("isCloudEnabledForApp() == " + Steamworks.isCloudEnabledForApp()); } private function toggleFile(e:Event = null):void { if(!Steamworks.isReady) return; var result:Boolean = Steamworks.fileExists('test.txt'); log("fileExists('test.txt') == " + result); if(result){ log("readFileFromCloud('test.txt') == "+readFileFromCloud('test.txt') ); log("fileDelete('test.txt') == "+Steamworks.fileDelete('test.txt')); } else { log("writeFileToCloud('test.txt','click') == "+writeFileToCloud('test.txt','click')); } } private function publishFile(e:Event = null):void { if(!Steamworks.isReady) return; var res:Boolean = Steamworks.publishWorkshopFile("test.txt", "", 480, "Test.txt", "Test.txt", WorkshopConstants.VISIBILITY_Private, ["TestTag"], WorkshopConstants.FILETYPE_Community); log("publishWorkshopFile('test.txt' ...) == " + res); } private function toggleFullscreen(e:Event = null):void { if(stage.displayState == StageDisplayState.NORMAL) stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE; else stage.displayState = StageDisplayState.NORMAL; } private function activateOverlay(e:Event = null):void { if(!Steamworks.isReady) return; log("activateGameOverlay('Friends') == " + Steamworks.activateGameOverlay("Friends")); } private function onSteamResponse(e:SteamEvent):void{ switch(e.req_type){ case SteamConstants.RESPONSE_OnUserStatsStored: log("RESPONSE_OnUserStatsStored: "+e.response); break; case SteamConstants.RESPONSE_OnUserStatsReceived: log("RESPONSE_OnUserStatsReceived: "+e.response); break; case SteamConstants.RESPONSE_OnAchievementStored: log("RESPONSE_OnAchievementStored: "+e.response); break; default: log("STEAMresponse type:"+e.req_type+" response:"+e.response); } } private function onExit(e:Event):void{ log("Exiting application, cleaning up"); Steamworks.dispose(); } private function addButton(label:String, callback:Function):void { var button:Sprite = new Sprite(); button.graphics.beginFill(0xaaaaaa); button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5); button.graphics.endFill(); button.buttonMode = true; button.useHandCursor = true; button.addEventListener(MouseEvent.CLICK, callback); button.x = 5; button.y = _buttonPos; _buttonPos += button.height + 5; var text:TextField = new TextField(); text.text = label; text.width = 140; text.height = 25; text.x = 5; text.y = 5; text.mouseEnabled = false; button.addChild(text); addChild(button); } } }
/* * FRESteamWorks.h * This file is part of FRESteamWorks. * * Created by David ´Oldes´ Oliva on 3/29/12. * Contributors: Ventero <http://github.com/Ventero> * Copyright (c) 2012 Amanita Design. All rights reserved. * Copyright (c) 2012-2013 Level Up Labs, LLC. All rights reserved. */ package { import com.amanitadesign.steam.FRESteamWorks; import com.amanitadesign.steam.SteamConstants; import com.amanitadesign.steam.SteamEvent; import com.amanitadesign.steam.WorkshopConstants; import flash.desktop.NativeApplication; import flash.display.SimpleButton; import flash.display.Sprite; import flash.display.StageDisplayState; import flash.events.Event; import flash.events.MouseEvent; import flash.text.TextField; import flash.utils.ByteArray; public class FRESteamWorksTest extends Sprite { public var Steamworks:FRESteamWorks = new FRESteamWorks(); public var tf:TextField; private var _buttonPos:int = 5; private var _appId:uint; public function FRESteamWorksTest() { tf = new TextField(); tf.x = 160; tf.width = stage.stageWidth - tf.x; tf.height = stage.stageHeight; addChild(tf); addButton("Check stats/achievements", checkAchievements); addButton("Toggle achievement", toggleAchievement); addButton("Toggle cloud enabled", toggleCloudEnabled); addButton("Toggle file", toggleFile); addButton("Publish file", publishFile); addButton("Toggle fullscreen", toggleFullscreen); addButton("Show Friends overlay", activateOverlay); Steamworks.addEventListener(SteamEvent.STEAM_RESPONSE, onSteamResponse); NativeApplication.nativeApplication.addEventListener(Event.EXITING, onExit); try { //Steamworks.useCrashHandler(480, "1.0", "Feb 20 2013", "21:42:20"); if(!Steamworks.init()){ log("STEAMWORKS API is NOT available"); return; } log("STEAMWORKS API is available\n"); log("User ID: " + Steamworks.getUserID()); _appId = Steamworks.getAppID(); log("App ID: " + _appId); log("Persona name: " + Steamworks.getPersonaName()); log("isCloudEnabledForApp() == "+Steamworks.isCloudEnabledForApp() ); log("getFileCount() == "+Steamworks.getFileCount() ); log("fileExists('test.txt') == "+Steamworks.fileExists('test.txt') ); Steamworks.resetAllStats(true); } catch(e:Error) { log("*** ERROR ***"); log(e.message); log(e.getStackTrace()); } } private function log(value:String):void{ tf.appendText(value+"\n"); tf.scrollV = tf.maxScrollV; } public function writeFileToCloud(fileName:String, data:String):Boolean { var dataOut:ByteArray = new ByteArray(); dataOut.writeUTFBytes(data); return Steamworks.fileWrite(fileName, dataOut); } public function readFileFromCloud(fileName:String):String { var dataIn:ByteArray = new ByteArray(); var result:String; dataIn.position = 0; dataIn.length = Steamworks.getFileSize(fileName); if(dataIn.length>0 && Steamworks.fileRead(fileName,dataIn)){ result = dataIn.readUTFBytes(dataIn.length); } return result; } private function checkAchievements(e:Event = null):void { if(!Steamworks.isReady) return; // current stats and achievement ids are from steam example app log("isAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.isAchievement("ACH_WIN_ONE_GAME")); log("isAchievement('ACH_TRAVEL_FAR_SINGLE') == "+Steamworks.isAchievement("ACH_TRAVEL_FAR_SINGLE")); log("setStatFloat('FeetTraveled') == "+Steamworks.setStatFloat('FeetTraveled', 21.3)); log("setStatInt('NumGames', 2) == "+Steamworks.setStatInt('NumGames', 2)); Steamworks.storeStats(); log("getStatInt('NumGames') == "+Steamworks.getStatInt('NumGames')); log("getStatFloat('FeetTraveled') == "+Steamworks.getStatFloat('FeetTraveled')); } private function toggleAchievement(e:Event = null):void{ if(!Steamworks.isReady) return; var result:Boolean = Steamworks.isAchievement("ACH_WIN_ONE_GAME"); log("isAchievement('ACH_WIN_ONE_GAME') == " + result); if(!result) { log("setAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.setAchievement("ACH_WIN_ONE_GAME")); } else { log("clearAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.clearAchievement("ACH_WIN_ONE_GAME")); } } private function toggleCloudEnabled(e:Event = null):void { if(!Steamworks.isReady) return; var enabled:Boolean = Steamworks.isCloudEnabledForApp(); log("isCloudEnabledForApp() == " + enabled); log("setCloudEnabledForApp(" + !enabled + ") == " + Steamworks.setCloudEnabledForApp(!enabled)); log("isCloudEnabledForApp() == " + Steamworks.isCloudEnabledForApp()); } private function toggleFile(e:Event = null):void { if(!Steamworks.isReady) return; var result:Boolean = Steamworks.fileExists('test.txt'); log("fileExists('test.txt') == " + result); if(result){ log("readFileFromCloud('test.txt') == "+readFileFromCloud('test.txt') ); log("fileDelete('test.txt') == "+Steamworks.fileDelete('test.txt')); } else { log("writeFileToCloud('test.txt','click') == "+writeFileToCloud('test.txt','click')); } } private function publishFile(e:Event = null):void { if(!Steamworks.isReady) return; var res:Boolean = Steamworks.publishWorkshopFile("test.txt", "", _appId, "Test.txt", "Test.txt", WorkshopConstants.VISIBILITY_Private, ["TestTag"], WorkshopConstants.FILETYPE_Community); log("publishWorkshopFile('test.txt' ...) == " + res); } private function toggleFullscreen(e:Event = null):void { if(stage.displayState == StageDisplayState.NORMAL) stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE; else stage.displayState = StageDisplayState.NORMAL; } private function activateOverlay(e:Event = null):void { if(!Steamworks.isReady) return; log("activateGameOverlay('Friends') == " + Steamworks.activateGameOverlay("Friends")); } private function onSteamResponse(e:SteamEvent):void{ switch(e.req_type){ case SteamConstants.RESPONSE_OnUserStatsStored: log("RESPONSE_OnUserStatsStored: "+e.response); break; case SteamConstants.RESPONSE_OnUserStatsReceived: log("RESPONSE_OnUserStatsReceived: "+e.response); break; case SteamConstants.RESPONSE_OnAchievementStored: log("RESPONSE_OnAchievementStored: "+e.response); break; default: log("STEAMresponse type:"+e.req_type+" response:"+e.response); } } private function onExit(e:Event):void{ log("Exiting application, cleaning up"); Steamworks.dispose(); } private function addButton(label:String, callback:Function):void { var button:Sprite = new Sprite(); button.graphics.beginFill(0xaaaaaa); button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5); button.graphics.endFill(); button.buttonMode = true; button.useHandCursor = true; button.addEventListener(MouseEvent.CLICK, callback); button.x = 5; button.y = _buttonPos; _buttonPos += button.height + 5; var text:TextField = new TextField(); text.text = label; text.width = 140; text.height = 25; text.x = 5; text.y = 5; text.mouseEnabled = false; button.addChild(text); addChild(button); } } }
Use correct app ID for file publishing
Use correct app ID for file publishing
ActionScript
bsd-2-clause
Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks
5125c1de52375b66ca4bb8c3acc857cd78b0d0ca
src/org/flintparticles/common/debug/FrameTimer.as
src/org/flintparticles/common/debug/FrameTimer.as
/* * FLINT PARTICLE SYSTEM * ..................... * * Author: Richard Lord * Copyright (c) Richard Lord 2008-2010 * http://flintparticles.org * * * Licence Agreement * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.flintparticles.common.debug { import flash.events.Event; import flash.text.TextField; import flash.utils.getTimer; /** * Displays the current framerate. The framerate displayed is an average of * the last ten frames. Simply create an instance of this class and place it * on the stage. */ public class FrameTimer extends TextField { private var _times:Vector.<int>; /** * Creates a FrameTimer. * * @param color The color to use for the text display. */ public function FrameTimer( color:uint = 0xFFFFFF ) { textColor = color; _times = new Vector.<int>(); addEventListener( Event.ENTER_FRAME, onEnterFrame1, false, 0, true ); } private function onEnterFrame1( ev:Event ):void { if ( _times.push( getTimer() ) > 9 ) { removeEventListener( Event.ENTER_FRAME, onEnterFrame1 ); addEventListener( Event.ENTER_FRAME, onEnterFrame2, false, 0, true ); } } private function onEnterFrame2( ev:Event ):void { var t:Number; _times.push( t = getTimer() ); text = ( Math.round( 10000 / ( t - _times.shift() ) ) ).toString() + " fps"; } } }
/* * FLINT PARTICLE SYSTEM * ..................... * * Author: Richard Lord * Copyright (c) Richard Lord 2008-2010 * http://flintparticles.org * * * Licence Agreement * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.flintparticles.common.debug { import flash.events.Event; import flash.text.TextField; import flash.utils.getTimer; /** * Displays the current framerate. The framerate displayed is an average of * the last ten frames. Simply create an instance of this class and place it * on the stage. */ public class FrameTimer extends TextField { private var _times:Vector.<int>; /** * Creates a FrameTimer. * * @param color The color to use for the text display. */ public function FrameTimer( color:uint = 0xFFFFFF ) { textColor = color; _times = new Vector.<int>(); addEventListener( Event.ENTER_FRAME, onEnterFrame1, false, 0, true ); } private function onEnterFrame1( ev:Event ):void { if ( _times.push( getTimer() ) > 29 ) { removeEventListener( Event.ENTER_FRAME, onEnterFrame1 ); addEventListener( Event.ENTER_FRAME, onEnterFrame2, false, 0, true ); } } private function onEnterFrame2( ev:Event ):void { var t:Number; _times.push( t = getTimer() ); text = ( Math.round( 30000 / ( t - _times.shift() ) ) ).toString() + " fps"; } } }
Extend frames averaged in FrameTimer
Extend frames averaged in FrameTimer
ActionScript
mit
richardlord/Flint
9a5c3ec151b2ed8d9b6ed2df9a5bb998895c4f14
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 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); }); } }
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; [SWF(width="400", height="300")] 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); }); } }
Embed the movie width/height in the SWF.
Embed the movie width/height in the SWF.
ActionScript
mit
arlolra/flashproxy,glamrock/flashproxy,arlolra/flashproxy,infinity0/flashproxy,arlolra/flashproxy,arlolra/flashproxy,infinity0/flashproxy,infinity0/flashproxy,arlolra/flashproxy,glamrock/flashproxy,arlolra/flashproxy,glamrock/flashproxy,glamrock/flashproxy,infinity0/flashproxy,glamrock/flashproxy,arlolra/flashproxy,infinity0/flashproxy,infinity0/flashproxy,glamrock/flashproxy
25e2e026ede28979b5cdf32a2678f241f5a1fbf2
swfcat.as
swfcat.as
package { import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.text.TextField; import flash.text.TextFormat; import flash.net.Socket; import flash.net.URLLoader; import flash.net.URLLoaderDataFormat; import flash.net.URLRequest; import flash.net.URLRequestMethod; import flash.net.URLVariables; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.utils.setTimeout; public class swfcat extends Sprite { private const RTMFP_URL:String = "rtmfp://tor-facilitator.bamsoftware.com"; private const DEFAULT_FACILITATOR_ADDR:Object = { host: "tor-facilitator.bamsoftware.com", port: 9002 }; /* Local Tor client to use in case of RTMFP connection. */ private const DEFAULT_LOCAL_TOR_CLIENT_ADDR:Object = { host: "127.0.0.1", port: 9002 }; private const MAX_NUM_PROXY_PAIRS:uint = 100; // Milliseconds. private const FACILITATOR_POLL_INTERVAL:int = 1000; // Bytes per second. Set to undefined to disable limit. public static const RATE_LIMIT:Number = undefined; // Seconds. private static const RATE_LIMIT_HISTORY:Number = 5.0; /* TextField for debug output. */ private var output_text:TextField; /* UI shown when debug is off. */ private var badge:Badge; /* Proxy pairs currently connected (up to MAX_NUM_PROXY_PAIRS). */ private var proxy_pairs:Array; private var fac_addr:Object; private var local_addr:Object; public var debug:Boolean; public var rate_limit:RateLimit; public function puts(s:String):void { if (output_text) { output_text.appendText(s + "\n"); output_text.scrollV = output_text.maxScrollV; } } public function swfcat() { // Absolute positioning. stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; badge = new Badge(); proxy_pairs = []; if (RATE_LIMIT) rate_limit = new BucketRateLimit(RATE_LIMIT * RATE_LIMIT_HISTORY, RATE_LIMIT_HISTORY); else rate_limit = new RateUnlimit(); // Wait until the query string parameters are loaded. this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete); } private function loaderinfo_complete(e:Event):void { debug = this.loaderInfo.parameters["debug"]; if (debug || this.loaderInfo.parameters["client"]) { output_text = new TextField(); output_text.width = stage.stageWidth; output_text.height = stage.stageHeight; output_text.background = true; output_text.backgroundColor = 0x001f0f; output_text.textColor = 0x44cc44; addChild(output_text); } else { addChild(badge); } puts("Parameters loaded."); fac_addr = get_param_addr("facilitator", DEFAULT_FACILITATOR_ADDR); if (!fac_addr) { puts("Error: Facilitator spec must be in the form \"host:port\"."); return; } local_addr = get_param_addr("local", DEFAULT_LOCAL_TOR_CLIENT_ADDR); if (!local_addr) { puts("Error: Local spec must be in the form \"host:port\"."); return; } if (this.loaderInfo.parameters["client"]) client_main(); else proxy_main(); } /* Get an address structure from the given movie parameter, or the given default. Returns null on error. */ private function get_param_addr(param:String, default_addr:Object):Object { var spec:String; spec = this.loaderInfo.parameters[param]; if (spec) return parse_addr_spec(spec); else return default_addr; } /* The main logic begins here, after start-up issues are taken care of. */ private function proxy_main():void { var fac_url:String; var loader:URLLoader; if (proxy_pairs.length >= MAX_NUM_PROXY_PAIRS) { setTimeout(proxy_main, FACILITATOR_POLL_INTERVAL); return; } loader = new URLLoader(); /* Get the x-www-form-urlencoded values. */ loader.dataFormat = URLLoaderDataFormat.VARIABLES; loader.addEventListener(Event.COMPLETE, fac_complete); loader.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("Facilitator: I/O error: " + e.text + "."); }); loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("Facilitator: security error: " + e.text + "."); }); fac_url = "http://" + encodeURIComponent(fac_addr.host) + ":" + encodeURIComponent(fac_addr.port) + "/"; puts("Facilitator: connecting to " + fac_url + "."); loader.load(new URLRequest(fac_url)); } private function fac_complete(e:Event):void { var loader:URLLoader; var client_spec:String; var relay_spec:String; var proxy_pair:Object; setTimeout(proxy_main, FACILITATOR_POLL_INTERVAL); loader = e.target as URLLoader; client_spec = loader.data.client; if (client_spec == "") { puts("No clients."); return; } else if (!client_spec) { puts("Error: missing \"client\" in response."); return; } relay_spec = loader.data.relay; if (!relay_spec) { puts("Error: missing \"relay\" in response."); return; } puts("Facilitator: got client:\"" + client_spec + "\" " + "relay:\"" + relay_spec + "\"."); try { proxy_pair = make_proxy_pair(client_spec, relay_spec); } catch (e:ArgumentError) { puts("Error: " + e); return; } proxy_pairs.push(proxy_pair); proxy_pair.addEventListener(Event.COMPLETE, function(e:Event):void { proxy_pair.log("Complete."); /* Delete from the list of active proxy pairs. */ proxy_pairs.splice(proxy_pairs.indexOf(proxy_pair), 1); badge.proxy_end(); }); proxy_pair.connect(); badge.proxy_begin(); } private function client_main():void { var rs:RTMFPSocket; rs = new RTMFPSocket(RTMFP_URL); rs.addEventListener(Event.COMPLETE, function (e:Event):void { puts("Got RTMFP id " + rs.id); register(rs); }); rs.addEventListener(RTMFPSocket.ACCEPT_EVENT, client_accept); rs.listen(); } private function client_accept(e:Event):void { var rs:RTMFPSocket; var s_t:Socket; var proxy_pair:ProxyPair; rs = e.target as RTMFPSocket; s_t = new Socket(); puts("Got RTMFP connection from " + rs.peer_id); proxy_pair = new ProxyPair(this, rs, function ():void { /* Do nothing; already connected. */ }, s_t, function ():void { s_t.connect(local_addr.host, local_addr.port); }); proxy_pair.connect(); } private function register(rs:RTMFPSocket):void { var fac_url:String; var loader:URLLoader; var request:URLRequest; loader = new URLLoader(); loader.addEventListener(Event.COMPLETE, function (e:Event):void { puts("Facilitator: registered."); }); loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("Facilitator: security error: " + e.text + "."); rs.close(); }); loader.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("Facilitator: I/O error: " + e.text + "."); rs.close(); }); fac_url = "http://" + encodeURIComponent(fac_addr.host) + ":" + encodeURIComponent(fac_addr.port) + "/"; request = new URLRequest(fac_url); request.method = URLRequestMethod.POST; request.data = new URLVariables(); request.data["client"] = rs.id; puts("Facilitator: connecting to " + fac_url + "."); loader.load(request); } private function make_proxy_pair(client_spec:String, relay_spec:String):ProxyPair { var proxy_pair:ProxyPair; var addr_c:Object; var addr_r:Object; var s_c:*; var s_r:Socket; addr_r = swfcat.parse_addr_spec(relay_spec); if (!addr_r) throw new ArgumentError("Relay spec must be in the form \"host:port\"."); addr_c = swfcat.parse_addr_spec(client_spec); if (addr_c) { s_c = new Socket(); s_r = new Socket(); proxy_pair = new ProxyPair(this, s_c, function ():void { s_c.connect(addr_c.host, addr_c.port); }, s_r, function ():void { s_r.connect(addr_r.host, addr_r.port); }); proxy_pair.set_name("<" + addr_c.host + ":" + addr_c.port + "," + addr_r.host + ":" + addr_r.port + ">"); return proxy_pair; } if (client_spec.match(/^[0-9A-Fa-f]{64}$/)) { s_c = new RTMFPSocket(RTMFP_URL); s_r = new Socket(); proxy_pair = new ProxyPair(this, s_c, function ():void { s_c.connect(client_spec); }, s_r, function ():void { s_r.connect(addr_r.host, addr_r.port); }); proxy_pair.set_name("<" + client_spec.substr(0, 4) + "...," + addr_r.host + ":" + addr_r.port + ">"); return proxy_pair; } throw new ArgumentError("Can't parse client spec \"" + client_spec + "\"."); } /* Parse an address in the form "host:port". Returns an Object with keys "host" (String) and "port" (int). Returns null on error. */ private static function parse_addr_spec(spec:String):Object { var parts:Array; var addr:Object; parts = spec.split(":", 2); if (parts.length != 2 || !parseInt(parts[1])) return null; addr = {} addr.host = parts[0]; addr.port = parseInt(parts[1]); return addr; } } } import flash.text.TextFormat; import flash.text.TextField; import flash.utils.getTimer; class Badge extends flash.display.Sprite { /* Number of proxy pairs currently connected. */ private var num_proxy_pairs:int = 0; /* Number of proxy pairs ever connected. */ private var total_proxy_pairs:int = 0; [Embed(source="badge.png")] private var BadgeImage:Class; private var tot_client_count_tf:TextField; private var tot_client_count_fmt:TextFormat; private var cur_client_count_tf:TextField; private var cur_client_count_fmt:TextFormat; public function Badge() { /* Setup client counter for badge. */ tot_client_count_fmt = new TextFormat(); tot_client_count_fmt.color = 0xFFFFFF; tot_client_count_fmt.align = "center"; tot_client_count_fmt.font = "courier-new"; tot_client_count_fmt.bold = true; tot_client_count_fmt.size = 10; tot_client_count_tf = new TextField(); tot_client_count_tf.width = 20; tot_client_count_tf.height = 17; tot_client_count_tf.background = false; tot_client_count_tf.defaultTextFormat = tot_client_count_fmt; tot_client_count_tf.x=47; tot_client_count_tf.y=0; cur_client_count_fmt = new TextFormat(); cur_client_count_fmt.color = 0xFFFFFF; cur_client_count_fmt.align = "center"; cur_client_count_fmt.font = "courier-new"; cur_client_count_fmt.bold = true; cur_client_count_fmt.size = 10; cur_client_count_tf = new TextField(); cur_client_count_tf.width = 20; cur_client_count_tf.height = 17; cur_client_count_tf.background = false; cur_client_count_tf.defaultTextFormat = cur_client_count_fmt; cur_client_count_tf.x=47; cur_client_count_tf.y=6; addChild(new BadgeImage()); addChild(tot_client_count_tf); addChild(cur_client_count_tf); /* Update the client counter on badge. */ update_client_count(); } public function proxy_begin():void { num_proxy_pairs++; total_proxy_pairs++; update_client_count(); } public function proxy_end():void { num_proxy_pairs--; update_client_count(); } private function update_client_count():void { /* Update total client count. */ if (String(total_proxy_pairs).length == 1) tot_client_count_tf.text = "0" + String(total_proxy_pairs); else tot_client_count_tf.text = String(total_proxy_pairs); /* Update current client count. */ cur_client_count_tf.text = ""; for(var i:Number = 0; i < num_proxy_pairs; i++) cur_client_count_tf.appendText("."); } } class RateLimit { public function RateLimit() { } public function update(n:Number):Boolean { return true; } public function when():Number { return 0.0; } public function is_limited():Boolean { return false; } } class RateUnlimit extends RateLimit { public function RateUnlimit() { } public override function update(n:Number):Boolean { return true; } public override function when():Number { return 0.0; } public override function is_limited():Boolean { return false; } } class BucketRateLimit extends RateLimit { private var amount:Number; private var capacity:Number; private var time:Number; private var last_update:uint; public function BucketRateLimit(capacity:Number, time:Number) { this.amount = 0.0; /* capacity / time is the rate we are aiming for. */ this.capacity = capacity; this.time = time; this.last_update = getTimer(); } private function age():void { var now:uint; var delta:Number; now = getTimer(); delta = (now - last_update) / 1000.0; last_update = now; amount -= delta * capacity / time; if (amount < 0.0) amount = 0.0; } public override function update(n:Number):Boolean { age(); amount += n; return amount <= capacity; } public override function when():Number { age(); return (amount - capacity) / (capacity / time); } public override function is_limited():Boolean { age(); return amount > capacity; } }
package { import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.text.TextField; import flash.text.TextFormat; import flash.net.Socket; import flash.net.URLLoader; import flash.net.URLLoaderDataFormat; import flash.net.URLRequest; import flash.net.URLRequestMethod; import flash.net.URLVariables; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.utils.setTimeout; public class swfcat extends Sprite { private const RTMFP_URL:String = "rtmfp://tor-facilitator.bamsoftware.com"; private const DEFAULT_FACILITATOR_ADDR:Object = { host: "tor-facilitator.bamsoftware.com", port: 9002 }; /* Local Tor client to use in case of RTMFP connection. */ private const DEFAULT_LOCAL_TOR_CLIENT_ADDR:Object = { host: "127.0.0.1", port: 9002 }; private const MAX_NUM_PROXY_PAIRS:uint = 100; // Milliseconds. private const FACILITATOR_POLL_INTERVAL:int = 1000; // Bytes per second. Set to undefined to disable limit. public static const RATE_LIMIT:Number = undefined; // Seconds. private static const RATE_LIMIT_HISTORY:Number = 5.0; /* TextField for debug output. */ private var output_text:TextField; /* UI shown when debug is off. */ private var badge:Badge; /* Proxy pairs currently connected (up to MAX_NUM_PROXY_PAIRS). */ private var proxy_pairs:Array; private var fac_addr:Object; private var local_addr:Object; public var debug:Boolean; public var rate_limit:RateLimit; public function puts(s:String):void { if (output_text) { output_text.appendText(s + "\n"); output_text.scrollV = output_text.maxScrollV; } } public function swfcat() { // Absolute positioning. stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; badge = new Badge(); proxy_pairs = []; if (RATE_LIMIT) rate_limit = new BucketRateLimit(RATE_LIMIT * RATE_LIMIT_HISTORY, RATE_LIMIT_HISTORY); else rate_limit = new RateUnlimit(); // Wait until the query string parameters are loaded. this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete); } private function loaderinfo_complete(e:Event):void { debug = this.loaderInfo.parameters["debug"]; if (debug || this.loaderInfo.parameters["client"]) { output_text = new TextField(); output_text.width = stage.stageWidth; output_text.height = stage.stageHeight; output_text.background = true; output_text.backgroundColor = 0x001f0f; output_text.textColor = 0x44cc44; addChild(output_text); } else { addChild(badge); } puts("Parameters loaded."); fac_addr = get_param_addr("facilitator", DEFAULT_FACILITATOR_ADDR); if (!fac_addr) { puts("Error: Facilitator spec must be in the form \"host:port\"."); return; } local_addr = get_param_addr("local", DEFAULT_LOCAL_TOR_CLIENT_ADDR); if (!local_addr) { puts("Error: Local spec must be in the form \"host:port\"."); return; } if (this.loaderInfo.parameters["client"]) client_main(); else proxy_main(); } /* Get an address structure from the given movie parameter, or the given default. Returns null on error. */ private function get_param_addr(param:String, default_addr:Object):Object { var spec:String; spec = this.loaderInfo.parameters[param]; if (spec) return parse_addr_spec(spec); else return default_addr; } /* Are circumstances such that we should self-disable and not be a proxy? We take a best-effort guess as to whether this device runs on a battery or the data transfer might be expensive. */ private function should_disable():Boolean { return false; } /* The main logic begins here, after start-up issues are taken care of. */ private function proxy_main():void { var fac_url:String; var loader:URLLoader; if (should_disable()) { puts("Disabling self."); return; } if (proxy_pairs.length >= MAX_NUM_PROXY_PAIRS) { setTimeout(proxy_main, FACILITATOR_POLL_INTERVAL); return; } loader = new URLLoader(); /* Get the x-www-form-urlencoded values. */ loader.dataFormat = URLLoaderDataFormat.VARIABLES; loader.addEventListener(Event.COMPLETE, fac_complete); loader.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("Facilitator: I/O error: " + e.text + "."); }); loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("Facilitator: security error: " + e.text + "."); }); fac_url = "http://" + encodeURIComponent(fac_addr.host) + ":" + encodeURIComponent(fac_addr.port) + "/"; puts("Facilitator: connecting to " + fac_url + "."); loader.load(new URLRequest(fac_url)); } private function fac_complete(e:Event):void { var loader:URLLoader; var client_spec:String; var relay_spec:String; var proxy_pair:Object; setTimeout(proxy_main, FACILITATOR_POLL_INTERVAL); loader = e.target as URLLoader; client_spec = loader.data.client; if (client_spec == "") { puts("No clients."); return; } else if (!client_spec) { puts("Error: missing \"client\" in response."); return; } relay_spec = loader.data.relay; if (!relay_spec) { puts("Error: missing \"relay\" in response."); return; } puts("Facilitator: got client:\"" + client_spec + "\" " + "relay:\"" + relay_spec + "\"."); try { proxy_pair = make_proxy_pair(client_spec, relay_spec); } catch (e:ArgumentError) { puts("Error: " + e); return; } proxy_pairs.push(proxy_pair); proxy_pair.addEventListener(Event.COMPLETE, function(e:Event):void { proxy_pair.log("Complete."); /* Delete from the list of active proxy pairs. */ proxy_pairs.splice(proxy_pairs.indexOf(proxy_pair), 1); badge.proxy_end(); }); proxy_pair.connect(); badge.proxy_begin(); } private function client_main():void { var rs:RTMFPSocket; rs = new RTMFPSocket(RTMFP_URL); rs.addEventListener(Event.COMPLETE, function (e:Event):void { puts("Got RTMFP id " + rs.id); register(rs); }); rs.addEventListener(RTMFPSocket.ACCEPT_EVENT, client_accept); rs.listen(); } private function client_accept(e:Event):void { var rs:RTMFPSocket; var s_t:Socket; var proxy_pair:ProxyPair; rs = e.target as RTMFPSocket; s_t = new Socket(); puts("Got RTMFP connection from " + rs.peer_id); proxy_pair = new ProxyPair(this, rs, function ():void { /* Do nothing; already connected. */ }, s_t, function ():void { s_t.connect(local_addr.host, local_addr.port); }); proxy_pair.connect(); } private function register(rs:RTMFPSocket):void { var fac_url:String; var loader:URLLoader; var request:URLRequest; loader = new URLLoader(); loader.addEventListener(Event.COMPLETE, function (e:Event):void { puts("Facilitator: registered."); }); loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("Facilitator: security error: " + e.text + "."); rs.close(); }); loader.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("Facilitator: I/O error: " + e.text + "."); rs.close(); }); fac_url = "http://" + encodeURIComponent(fac_addr.host) + ":" + encodeURIComponent(fac_addr.port) + "/"; request = new URLRequest(fac_url); request.method = URLRequestMethod.POST; request.data = new URLVariables(); request.data["client"] = rs.id; puts("Facilitator: connecting to " + fac_url + "."); loader.load(request); } private function make_proxy_pair(client_spec:String, relay_spec:String):ProxyPair { var proxy_pair:ProxyPair; var addr_c:Object; var addr_r:Object; var s_c:*; var s_r:Socket; addr_r = swfcat.parse_addr_spec(relay_spec); if (!addr_r) throw new ArgumentError("Relay spec must be in the form \"host:port\"."); addr_c = swfcat.parse_addr_spec(client_spec); if (addr_c) { s_c = new Socket(); s_r = new Socket(); proxy_pair = new ProxyPair(this, s_c, function ():void { s_c.connect(addr_c.host, addr_c.port); }, s_r, function ():void { s_r.connect(addr_r.host, addr_r.port); }); proxy_pair.set_name("<" + addr_c.host + ":" + addr_c.port + "," + addr_r.host + ":" + addr_r.port + ">"); return proxy_pair; } if (client_spec.match(/^[0-9A-Fa-f]{64}$/)) { s_c = new RTMFPSocket(RTMFP_URL); s_r = new Socket(); proxy_pair = new ProxyPair(this, s_c, function ():void { s_c.connect(client_spec); }, s_r, function ():void { s_r.connect(addr_r.host, addr_r.port); }); proxy_pair.set_name("<" + client_spec.substr(0, 4) + "...," + addr_r.host + ":" + addr_r.port + ">"); return proxy_pair; } throw new ArgumentError("Can't parse client spec \"" + client_spec + "\"."); } /* Parse an address in the form "host:port". Returns an Object with keys "host" (String) and "port" (int). Returns null on error. */ private static function parse_addr_spec(spec:String):Object { var parts:Array; var addr:Object; parts = spec.split(":", 2); if (parts.length != 2 || !parseInt(parts[1])) return null; addr = {} addr.host = parts[0]; addr.port = parseInt(parts[1]); return addr; } } } import flash.text.TextFormat; import flash.text.TextField; import flash.utils.getTimer; class Badge extends flash.display.Sprite { /* Number of proxy pairs currently connected. */ private var num_proxy_pairs:int = 0; /* Number of proxy pairs ever connected. */ private var total_proxy_pairs:int = 0; [Embed(source="badge.png")] private var BadgeImage:Class; private var tot_client_count_tf:TextField; private var tot_client_count_fmt:TextFormat; private var cur_client_count_tf:TextField; private var cur_client_count_fmt:TextFormat; public function Badge() { /* Setup client counter for badge. */ tot_client_count_fmt = new TextFormat(); tot_client_count_fmt.color = 0xFFFFFF; tot_client_count_fmt.align = "center"; tot_client_count_fmt.font = "courier-new"; tot_client_count_fmt.bold = true; tot_client_count_fmt.size = 10; tot_client_count_tf = new TextField(); tot_client_count_tf.width = 20; tot_client_count_tf.height = 17; tot_client_count_tf.background = false; tot_client_count_tf.defaultTextFormat = tot_client_count_fmt; tot_client_count_tf.x=47; tot_client_count_tf.y=0; cur_client_count_fmt = new TextFormat(); cur_client_count_fmt.color = 0xFFFFFF; cur_client_count_fmt.align = "center"; cur_client_count_fmt.font = "courier-new"; cur_client_count_fmt.bold = true; cur_client_count_fmt.size = 10; cur_client_count_tf = new TextField(); cur_client_count_tf.width = 20; cur_client_count_tf.height = 17; cur_client_count_tf.background = false; cur_client_count_tf.defaultTextFormat = cur_client_count_fmt; cur_client_count_tf.x=47; cur_client_count_tf.y=6; addChild(new BadgeImage()); addChild(tot_client_count_tf); addChild(cur_client_count_tf); /* Update the client counter on badge. */ update_client_count(); } public function proxy_begin():void { num_proxy_pairs++; total_proxy_pairs++; update_client_count(); } public function proxy_end():void { num_proxy_pairs--; update_client_count(); } private function update_client_count():void { /* Update total client count. */ if (String(total_proxy_pairs).length == 1) tot_client_count_tf.text = "0" + String(total_proxy_pairs); else tot_client_count_tf.text = String(total_proxy_pairs); /* Update current client count. */ cur_client_count_tf.text = ""; for(var i:Number = 0; i < num_proxy_pairs; i++) cur_client_count_tf.appendText("."); } } class RateLimit { public function RateLimit() { } public function update(n:Number):Boolean { return true; } public function when():Number { return 0.0; } public function is_limited():Boolean { return false; } } class RateUnlimit extends RateLimit { public function RateUnlimit() { } public override function update(n:Number):Boolean { return true; } public override function when():Number { return 0.0; } public override function is_limited():Boolean { return false; } } class BucketRateLimit extends RateLimit { private var amount:Number; private var capacity:Number; private var time:Number; private var last_update:uint; public function BucketRateLimit(capacity:Number, time:Number) { this.amount = 0.0; /* capacity / time is the rate we are aiming for. */ this.capacity = capacity; this.time = time; this.last_update = getTimer(); } private function age():void { var now:uint; var delta:Number; now = getTimer(); delta = (now - last_update) / 1000.0; last_update = now; amount -= delta * capacity / time; if (amount < 0.0) amount = 0.0; } public override function update(n:Number):Boolean { age(); amount += n; return amount <= capacity; } public override function when():Number { age(); return (amount - capacity) / (capacity / time); } public override function is_limited():Boolean { age(); return amount > capacity; } }
Add a dummy should_disable function.
Add a dummy should_disable function. This function controls whether the flash proxy will disable itself, which we'll do roughly whenever we're running on a mobile browser.
ActionScript
mit
glamrock/flashproxy,arlolra/flashproxy,arlolra/flashproxy,arlolra/flashproxy,infinity0/flashproxy,glamrock/flashproxy,glamrock/flashproxy,arlolra/flashproxy,infinity0/flashproxy,glamrock/flashproxy,arlolra/flashproxy,arlolra/flashproxy,infinity0/flashproxy,infinity0/flashproxy,glamrock/flashproxy,arlolra/flashproxy,glamrock/flashproxy,infinity0/flashproxy,infinity0/flashproxy
6abb6a1d79edfe8e88c3e30b15512ee718f2b85e
as3/xobjas3-test/src/tests/TestBasics.as
as3/xobjas3-test/src/tests/TestBasics.as
/* # # Copyright (c) 2009 rPath, Inc. # # This program is distributed under the terms of the MIT License as found # in a file called LICENSE. If it is not present, the license # is always available at http://www.opensource.org/licenses/mit-license.php. # # This program is distributed in the hope that it will be useful, but # without any waranty; without even the implied warranty of merchantability # or fitness for a particular purpose. See the MIT License for full details. */ package tests { import com.rpath.xobj.*; import tests.models.*; import flash.xml.XMLDocument; public class TestBasics extends TestBase { /** testSimple * test basic decoding behavior of a simple XML document */ public function testSimple():void { var typedDecoder:XObjXMLDecoder = new XObjXMLDecoder(); var xmlInput:XMLDocument = new XMLDocument(testData.simple); var o:* = typedDecoder.decodeXML(xmlInput); assertTrue("top is object", o.top is Object); assertTrue("attr1 value", o.top.attr1 == "anattr"); assertTrue("attr2 value", o.top.attr2 == "another"); assertTrue("prop value", o.top.prop == "something"); assertTrue("subelement.subaattr value", o.top.subelement.subattr == "2"); assertTrue("subelement is Object", o.top.subelement is Object); } /** testComplex * Slightly more complex test with a repeated element that results in an * Array property */ public function testComplex():void { var typedDecoder:XObjXMLDecoder = new XObjXMLDecoder(); var xmlInput:XMLDocument = new XMLDocument(testData.complex); var o:* = typedDecoder.decodeXML(xmlInput); assertTrue(o.top is Object); assertTrue(o.top.prop.subprop is Array); // check array content for (var i:int=0; i<o.top.prop.subprop.length; i++) { assertTrue(o.top.prop.subprop[i] is XObjString); assertTrue(o.top.prop.subprop[i].toString() == ['asdf', 'fdsa', 'zxcv '][i]); } var typedEncoder:XObjXMLEncoder = new XObjXMLEncoder(); var xmlOutput:XMLDocument = typedEncoder.encodeObject(o.top, null, "top"); assertTrue("encode matches input", compareXML(xmlOutput, xmlInput)); } /** testNamespaces * test namespaces and prefixes are correctly mapped to properties on decode * and that they are correctly mapped back to prefixed tags on encode. * Also check that encoding is symmetrical with decoding. * This particular test case has an element tag that defines the namespace * that itself is declared within - a specific edge case. */ public function testNamespaces():void { var typedDecoder:XObjXMLDecoder = new XObjXMLDecoder(); var xmlInput:XMLDocument = new XMLDocument(testData.namespaces); var o:* = typedDecoder.decodeXML(xmlInput); assertTrue(o.top.other_tag.other_val == '1') assertTrue(o.top.other2_tag.val == '2') var typedEncoder:XObjXMLEncoder = new XObjXMLEncoder(); var xmlOutput:XMLDocument = typedEncoder.encodeObject(o.top, null, "top"); assertTrue("encode matches input", compareXML(xmlOutput, xmlInput)); } /** testMappedNamespaces * test that we can specify a local prefix other3 for a given namespace * allowing us to write code that is insulated from the arbitrary prefixes * a given document might choose. */ public function testMappedNamespaces():void { var typedDecoder:XObjXMLDecoder = new XObjXMLDecoder(null, { other3 : 'http://other/other2'}); var xmlInput:XMLDocument = new XMLDocument(testData.namespaces); var o:* = typedDecoder.decodeXML(xmlInput); assertTrue(o.top.other_tag.other_val == '1') assertTrue(o.top.other3_tag.val == '2') var typedEncoder:XObjXMLEncoder = new XObjXMLEncoder(); var xmlOutput:XMLDocument = typedEncoder.encodeObject(o.top, null, "top"); // check that we remap to original prefixes on the way back out assertTrue("encode matches input", compareXML(xmlOutput, xmlInput)); } /** testExplicitNamespace * test that when a namespace is redundantly declared as both default and * by prefix in the XML, that the result is strictly prefixed on output * This is to ensure documents conformant to an XMLSchema that uses * attributeFormDefault = qualified and elementFormDefault = qualified * are encoded correctly for the schema. * * Note that we *always* do this, since an unqualified schema requirement * will be satisified by a qualified XML document. */ public function testExplicitNamespace():void { var typedDecoder:XObjXMLDecoder = new XObjXMLDecoder(); var xmlInput:XMLDocument = new XMLDocument(testData.explicitns); var o:* = typedDecoder.decodeXML(xmlInput); assertTrue(o.ns_top.ns_element.ns_attr == 'foo') var typedEncoder:XObjXMLEncoder = new XObjXMLEncoder(); var xmlOutput:XMLDocument = typedEncoder.encodeObject(o.ns_top, null, "ns_top", o._xobj.elements[0].qname); var expectedString:String = '<ns:top xmlns:ns="http://somens.xsd">' + '<ns:element ns:attr="foo"/>' + '</ns:top>'; // check that we remap to original prefixes on the way back out assertTrue("encode is fully qualified", compareXMLtoString(xmlOutput, expectedString)); } /** testObjectTree * test that we can construct a new object graph and encode it as XML. * test that we can then decode it and get back a new graph with correctly * typed ActionScript objects. */ public function testObjectTree():void { var t:Top = new Top(); t.prop = 'abc'; t.middle = new Middle(); t.middle.tag = 123; t.bottom = null; var typeMap:* = {top:Top}; var typedEncoder:XObjXMLEncoder = new XObjXMLEncoder(typeMap); var xmlOutput:XMLDocument = typedEncoder.encodeObject(t); var expectedString:String = '<top>'+ '<bottom/>'+ '<middle>'+ '<tag>123</tag>'+ '</middle>'+ '<prop>abc</prop>'+ '</top>'; assertTrue(compareXMLtoString(xmlOutput, expectedString)); var typedDecoder:XObjXMLDecoder = new XObjXMLDecoder(typeMap); var xmlInput:XMLDocument = xmlOutput; var o:* = typedDecoder.decodeXML(xmlInput); assertTrue(o.top is Top); assertTrue(o.top.middle is Middle); assertTrue(o.top.middle.tag == 123); assertTrue(o.top.middle.foo() == 123); assertTrue(o.top.bottom == null); // reencode and check round-trip xmlOutput = typedEncoder.encodeObject(o.top); assertTrue("encode matches input", compareXML(xmlOutput, xmlInput)); } /** testObjectTreeNulls * test that we can construct a new object graph and encode it as XML. * test that we can then decode it and get back a new graph with correctly * typed ActionScript objects. */ public function testObjectTreeNulls():void { var t:Top = new Top(); t.prop = 'abc'; t.middle = new Middle(); t.middle.tag = 123; t.bottom = null; var typeMap:* = {top:Top}; var typedEncoder:XObjXMLEncoder = new XObjXMLEncoder(typeMap); typedEncoder.encodeNullElements = false; var xmlOutput:XMLDocument = typedEncoder.encodeObject(t); var expectedString:String = '<top>'+ '<middle>'+ '<tag>123</tag>'+ '</middle>'+ '<prop>abc</prop>'+ '</top>'; assertTrue(compareXMLtoString(xmlOutput, expectedString)); var typedDecoder:XObjXMLDecoder = new XObjXMLDecoder(typeMap); var xmlInput:XMLDocument = xmlOutput; var o:* = typedDecoder.decodeXML(xmlInput); assertTrue(o.top is Top); assertTrue(o.top.middle is Middle); assertTrue(o.top.middle.tag == 123); assertTrue(o.top.middle.foo() == 123); assertTrue(o.top.bottom == null); // reencode and check round-trip xmlOutput = typedEncoder.encodeObject(o.top); assertTrue("encode matches input", compareXML(xmlOutput, xmlInput)); } public function testId():void { } /** * Ensure boolean data is handled properly */ public function testBoolean():void { var obj:TestableObject = new TestableObject(); obj.someVal = "someval"; obj.booleanVar = true; var typeMap:* = {obj: TestableObject}; var typedEncoder:XObjXMLEncoder = new XObjXMLEncoder(typeMap); var xmlOutput:XMLDocument = typedEncoder.encodeObject(obj); // neither the Transient nor the xobjTransient vars should be there var expectedString:String = '<obj>'+ '<booleanVar>true</booleanVar>'+ '<someVal>someval</someVal>'+ '</obj>'; assertTrue(compareXMLtoString(xmlOutput, expectedString)); // now decode it and validate var typedDecoder:XObjXMLDecoder = new XObjXMLDecoder(typeMap); var xmlInput:XMLDocument = xmlOutput; var o:* = typedDecoder.decodeXML(xmlInput); assertTrue(o.obj is TestableObject); assertTrue(o.obj.someVal =="someval"); assertTrue(o.obj.booleanVar); // reencode and check round-trip xmlOutput = typedEncoder.encodeObject(o.obj); assertTrue("encode matches input", compareXML(xmlOutput, xmlInput)); } public function testNumericStrings():void { var obj:TestableObject = new TestableObject(); obj.someVal = "1.0"; // make sure someVal is a string so this is a valid test assertTrue(obj.someVal is String); obj.booleanVar = true; var typeMap:* = {obj: TestableObject}; var typedEncoder:XObjXMLEncoder = new XObjXMLEncoder(typeMap); var xmlOutput:XMLDocument = typedEncoder.encodeObject(obj); // neither the Transient nor the xobjTransient vars should be there var expectedString:String = '<obj>'+ '<booleanVar>true</booleanVar>'+ '<someVal>1.0</someVal>'+ '</obj>'; assertTrue(compareXMLtoString(xmlOutput, expectedString)); // now decode it and validate var typedDecoder:XObjXMLDecoder = new XObjXMLDecoder(typeMap); var xmlInput:XMLDocument = xmlOutput; var o:* = typedDecoder.decodeXML(xmlInput); assertTrue(o.obj is TestableObject); assertTrue(o.obj.someVal == "1.0"); assertTrue(o.obj.booleanVar); // reencode and check round-trip xmlOutput = typedEncoder.encodeObject(o.obj); assertTrue("encode matches input", compareXML(xmlOutput, xmlInput)); } public function testStringNumerics():void { var obj:TestableNumericObject = new TestableNumericObject(); obj.someNumber = 1.1; // make sure someNumber is a Number so this is a valid test assertTrue(obj.someNumber is Number); obj.booleanVar = true; var typeMap:* = {obj: TestableNumericObject}; var typedEncoder:XObjXMLEncoder = new XObjXMLEncoder(typeMap); var xmlOutput:XMLDocument = typedEncoder.encodeObject(obj); // neither the Transient nor the xobjTransient vars should be there var expectedString:String = '<obj>'+ '<booleanVar>true</booleanVar>'+ '<someNumber>1.1</someNumber>'+ '</obj>'; assertTrue(compareXMLtoString(xmlOutput, expectedString)); // now decode it and validate var typedDecoder:XObjXMLDecoder = new XObjXMLDecoder(typeMap); var xmlInput:XMLDocument = xmlOutput; var o:* = typedDecoder.decodeXML(xmlInput); assertTrue(o.obj is TestableNumericObject); assertTrue(o.obj.someNumber == 1.1); assertTrue(o.obj.booleanVar); // reencode and check round-trip xmlOutput = typedEncoder.encodeObject(o.obj); assertTrue("encode matches input", compareXML(xmlOutput, xmlInput)); } public function testStringNumerics2():void { var obj:TestableNumericObject = new TestableNumericObject(); obj.someNumber = 0.5; // make sure someNumber is a Number so this is a valid test assertTrue(obj.someNumber is Number); obj.booleanVar = true; var typeMap:* = {obj: TestableNumericObject}; var typedEncoder:XObjXMLEncoder = new XObjXMLEncoder(typeMap); var xmlOutput:XMLDocument = typedEncoder.encodeObject(obj); // neither the Transient nor the xobjTransient vars should be there var expectedString:String = '<obj>'+ '<booleanVar>true</booleanVar>'+ '<someNumber>0.5</someNumber>'+ '</obj>'; assertTrue(compareXMLtoString(xmlOutput, expectedString)); // now decode it and validate var typedDecoder:XObjXMLDecoder = new XObjXMLDecoder(typeMap); var xmlInput:XMLDocument = xmlOutput; var o:* = typedDecoder.decodeXML(xmlInput); assertTrue(o.obj is TestableNumericObject); assertTrue(o.obj.someNumber == 0.5); assertTrue(o.obj.booleanVar); // reencode and check round-trip xmlOutput = typedEncoder.encodeObject(o.obj); assertTrue("encode matches input", compareXML(xmlOutput, xmlInput)); } } }
/* # # Copyright (c) 2009 rPath, Inc. # # This program is distributed under the terms of the MIT License as found # in a file called LICENSE. If it is not present, the license # is always available at http://www.opensource.org/licenses/mit-license.php. # # This program is distributed in the hope that it will be useful, but # without any waranty; without even the implied warranty of merchantability # or fitness for a particular purpose. See the MIT License for full details. */ package tests { import com.rpath.xobj.*; import tests.models.*; import flash.xml.XMLDocument; public class TestBasics extends TestBase { /** testSimple * test basic decoding behavior of a simple XML document */ public function testSimple():void { var typedDecoder:XObjXMLDecoder = new XObjXMLDecoder(); var xmlInput:XMLDocument = new XMLDocument(testData.simple); var o:* = typedDecoder.decodeXML(xmlInput); assertTrue("top is object", o.top is Object); assertTrue("attr1 value", o.top.attr1 == "anattr"); assertTrue("attr2 value", o.top.attr2 == "another"); assertTrue("prop value", o.top.prop == "something"); assertTrue("subelement.subaattr value", o.top.subelement.subattr == "2"); assertTrue("subelement is Object", o.top.subelement is Object); } /** testComplex * Slightly more complex test with a repeated element that results in an * Array property */ public function testComplex():void { var typedDecoder:XObjXMLDecoder = new XObjXMLDecoder({prop: Array}); var xmlInput:XMLDocument = new XMLDocument(testData.complex); var o:* = typedDecoder.decodeXML(xmlInput); assertTrue(o.top is Object); assertTrue(o.top.prop is Array); // check array content for (var i:int=0; i<o.top.prop.length; i++) { assertTrue(o.top.prop[i] is XObjString); assertTrue(o.top.prop[i].toString() == ['asdf', 'fdsa', 'zxcv '][i]); } var typedEncoder:XObjXMLEncoder = new XObjXMLEncoder({subprop: XObjString}); var xmlOutput:XMLDocument = typedEncoder.encodeObject(o.top, null, "top"); assertTrue("encode matches input", compareXML(xmlOutput, xmlInput)); } /** testNamespaces * test namespaces and prefixes are correctly mapped to properties on decode * and that they are correctly mapped back to prefixed tags on encode. * Also check that encoding is symmetrical with decoding. * This particular test case has an element tag that defines the namespace * that itself is declared within - a specific edge case. */ public function testNamespaces():void { var typedDecoder:XObjXMLDecoder = new XObjXMLDecoder(); var xmlInput:XMLDocument = new XMLDocument(testData.namespaces); var o:* = typedDecoder.decodeXML(xmlInput); assertTrue(o.top.other_tag.other_val == '1') assertTrue(o.top.other2_tag.val == '2') var typedEncoder:XObjXMLEncoder = new XObjXMLEncoder(); var xmlOutput:XMLDocument = typedEncoder.encodeObject(o.top, null, "top"); assertTrue("encode matches input", compareXML(xmlOutput, xmlInput)); } /** testMappedNamespaces * test that we can specify a local prefix other3 for a given namespace * allowing us to write code that is insulated from the arbitrary prefixes * a given document might choose. */ public function testMappedNamespaces():void { var typedDecoder:XObjXMLDecoder = new XObjXMLDecoder(null, { other3 : 'http://other/other2'}); var xmlInput:XMLDocument = new XMLDocument(testData.namespaces); var o:* = typedDecoder.decodeXML(xmlInput); assertTrue(o.top.other_tag.other_val == '1') assertTrue(o.top.other3_tag.val == '2') var typedEncoder:XObjXMLEncoder = new XObjXMLEncoder(); var xmlOutput:XMLDocument = typedEncoder.encodeObject(o.top, null, "top"); // check that we remap to original prefixes on the way back out assertTrue("encode matches input", compareXML(xmlOutput, xmlInput)); } /** testExplicitNamespace * test that when a namespace is redundantly declared as both default and * by prefix in the XML, that the result is strictly prefixed on output * This is to ensure documents conformant to an XMLSchema that uses * attributeFormDefault = qualified and elementFormDefault = qualified * are encoded correctly for the schema. * * Note that we *always* do this, since an unqualified schema requirement * will be satisified by a qualified XML document. */ public function testExplicitNamespace():void { var typedDecoder:XObjXMLDecoder = new XObjXMLDecoder(); var xmlInput:XMLDocument = new XMLDocument(testData.explicitns); var o:* = typedDecoder.decodeXML(xmlInput); assertTrue(o.ns_top.ns_element.ns_attr == 'foo') var typedEncoder:XObjXMLEncoder = new XObjXMLEncoder(); var xmlOutput:XMLDocument = typedEncoder.encodeObject(o.ns_top, null, "ns_top", o._xobj.elements[0].qname); var expectedString:String = '<ns:top xmlns:ns="http://somens.xsd">' + '<ns:element ns:attr="foo"/>' + '</ns:top>'; // check that we remap to original prefixes on the way back out assertTrue("encode is fully qualified", compareXMLtoString(xmlOutput, expectedString)); } /** testObjectTree * test that we can construct a new object graph and encode it as XML. * test that we can then decode it and get back a new graph with correctly * typed ActionScript objects. */ public function testObjectTree():void { var t:Top = new Top(); t.prop = 'abc'; t.middle = new Middle(); t.middle.tag = 123; t.bottom = null; var typeMap:* = {top:Top}; var typedEncoder:XObjXMLEncoder = new XObjXMLEncoder(typeMap); var xmlOutput:XMLDocument = typedEncoder.encodeObject(t); var expectedString:String = '<top>'+ '<bottom/>'+ '<middle>'+ '<tag>123</tag>'+ '</middle>'+ '<prop>abc</prop>'+ '</top>'; assertTrue(compareXMLtoString(xmlOutput, expectedString)); var typedDecoder:XObjXMLDecoder = new XObjXMLDecoder(typeMap); var xmlInput:XMLDocument = xmlOutput; var o:* = typedDecoder.decodeXML(xmlInput); assertTrue(o.top is Top); assertTrue(o.top.middle is Middle); assertTrue(o.top.middle.tag == 123); assertTrue(o.top.middle.foo() == 123); assertTrue(o.top.bottom == null); // reencode and check round-trip xmlOutput = typedEncoder.encodeObject(o.top); assertTrue("encode matches input", compareXML(xmlOutput, xmlInput)); } /** testObjectTreeNulls * test that we can construct a new object graph and encode it as XML. * test that we can then decode it and get back a new graph with correctly * typed ActionScript objects. */ public function testObjectTreeNulls():void { var t:Top = new Top(); t.prop = 'abc'; t.middle = new Middle(); t.middle.tag = 123; t.bottom = null; var typeMap:* = {top:Top}; var typedEncoder:XObjXMLEncoder = new XObjXMLEncoder(typeMap); typedEncoder.encodeNullElements = false; var xmlOutput:XMLDocument = typedEncoder.encodeObject(t); var expectedString:String = '<top>'+ '<middle>'+ '<tag>123</tag>'+ '</middle>'+ '<prop>abc</prop>'+ '</top>'; assertTrue(compareXMLtoString(xmlOutput, expectedString)); var typedDecoder:XObjXMLDecoder = new XObjXMLDecoder(typeMap); var xmlInput:XMLDocument = xmlOutput; var o:* = typedDecoder.decodeXML(xmlInput); assertTrue(o.top is Top); assertTrue(o.top.middle is Middle); assertTrue(o.top.middle.tag == 123); assertTrue(o.top.middle.foo() == 123); assertTrue(o.top.bottom == null); // reencode and check round-trip xmlOutput = typedEncoder.encodeObject(o.top); assertTrue("encode matches input", compareXML(xmlOutput, xmlInput)); } public function testId():void { } /** * Ensure boolean data is handled properly */ public function testBoolean():void { var obj:TestableObject = new TestableObject(); obj.someVal = "someval"; obj.booleanVar = true; var typeMap:* = {obj: TestableObject}; var typedEncoder:XObjXMLEncoder = new XObjXMLEncoder(typeMap); var xmlOutput:XMLDocument = typedEncoder.encodeObject(obj); // neither the Transient nor the xobjTransient vars should be there var expectedString:String = '<obj>'+ '<booleanVar>true</booleanVar>'+ '<someVal>someval</someVal>'+ '</obj>'; assertTrue(compareXMLtoString(xmlOutput, expectedString)); // now decode it and validate var typedDecoder:XObjXMLDecoder = new XObjXMLDecoder(typeMap); var xmlInput:XMLDocument = xmlOutput; var o:* = typedDecoder.decodeXML(xmlInput); assertTrue(o.obj is TestableObject); assertTrue(o.obj.someVal =="someval"); assertTrue(o.obj.booleanVar); // reencode and check round-trip xmlOutput = typedEncoder.encodeObject(o.obj); assertTrue("encode matches input", compareXML(xmlOutput, xmlInput)); } public function testNumericStrings():void { var obj:TestableObject = new TestableObject(); obj.someVal = "1.0"; // make sure someVal is a string so this is a valid test assertTrue(obj.someVal is String); obj.booleanVar = true; var typeMap:* = {obj: TestableObject}; var typedEncoder:XObjXMLEncoder = new XObjXMLEncoder(typeMap); var xmlOutput:XMLDocument = typedEncoder.encodeObject(obj); // neither the Transient nor the xobjTransient vars should be there var expectedString:String = '<obj>'+ '<booleanVar>true</booleanVar>'+ '<someVal>1.0</someVal>'+ '</obj>'; assertTrue(compareXMLtoString(xmlOutput, expectedString)); // now decode it and validate var typedDecoder:XObjXMLDecoder = new XObjXMLDecoder(typeMap); var xmlInput:XMLDocument = xmlOutput; var o:* = typedDecoder.decodeXML(xmlInput); assertTrue(o.obj is TestableObject); assertTrue(o.obj.someVal == "1.0"); assertTrue(o.obj.booleanVar); // reencode and check round-trip xmlOutput = typedEncoder.encodeObject(o.obj); assertTrue("encode matches input", compareXML(xmlOutput, xmlInput)); } public function testStringNumerics():void { var obj:TestableNumericObject = new TestableNumericObject(); obj.someNumber = 1.1; // make sure someNumber is a Number so this is a valid test assertTrue(obj.someNumber is Number); obj.booleanVar = true; var typeMap:* = {obj: TestableNumericObject}; var typedEncoder:XObjXMLEncoder = new XObjXMLEncoder(typeMap); var xmlOutput:XMLDocument = typedEncoder.encodeObject(obj); // neither the Transient nor the xobjTransient vars should be there var expectedString:String = '<obj>'+ '<booleanVar>true</booleanVar>'+ '<someNumber>1.1</someNumber>'+ '</obj>'; assertTrue(compareXMLtoString(xmlOutput, expectedString)); // now decode it and validate var typedDecoder:XObjXMLDecoder = new XObjXMLDecoder(typeMap); var xmlInput:XMLDocument = xmlOutput; var o:* = typedDecoder.decodeXML(xmlInput); assertTrue(o.obj is TestableNumericObject); assertTrue(o.obj.someNumber == 1.1); assertTrue(o.obj.booleanVar); // reencode and check round-trip xmlOutput = typedEncoder.encodeObject(o.obj); assertTrue("encode matches input", compareXML(xmlOutput, xmlInput)); } public function testStringNumerics2():void { var obj:TestableNumericObject = new TestableNumericObject(); obj.someNumber = 0.5; // make sure someNumber is a Number so this is a valid test assertTrue(obj.someNumber is Number); obj.booleanVar = true; var typeMap:* = {obj: TestableNumericObject}; var typedEncoder:XObjXMLEncoder = new XObjXMLEncoder(typeMap); var xmlOutput:XMLDocument = typedEncoder.encodeObject(obj); // neither the Transient nor the xobjTransient vars should be there var expectedString:String = '<obj>'+ '<booleanVar>true</booleanVar>'+ '<someNumber>0.5</someNumber>'+ '</obj>'; assertTrue(compareXMLtoString(xmlOutput, expectedString)); // now decode it and validate var typedDecoder:XObjXMLDecoder = new XObjXMLDecoder(typeMap); var xmlInput:XMLDocument = xmlOutput; var o:* = typedDecoder.decodeXML(xmlInput); assertTrue(o.obj is TestableNumericObject); assertTrue(o.obj.someNumber == 0.5); assertTrue(o.obj.booleanVar); // reencode and check round-trip xmlOutput = typedEncoder.encodeObject(o.obj); assertTrue("encode matches input", compareXML(xmlOutput, xmlInput)); } } }
Fix for testComplex
Fix for testComplex
ActionScript
apache-2.0
sassoftware/xobj,sassoftware/xobj,sassoftware/xobj,sassoftware/xobj
9b3d960762c65d70ac9a45f99957703c6334d3ab
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[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]; } } }
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(_localToWorldTransforms[_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
54f3fdb3e6fc2632ba1965284378c0053902181c
src/as/com/threerings/io/streamers/ArrayStreamer.as
src/as/com/threerings/io/streamers/ArrayStreamer.as
package com.threerings.io.streamers { import com.threerings.util.ClassUtil; import com.threerings.io.ArrayMask; import com.threerings.io.ObjectInputStream; import com.threerings.io.ObjectOutputStream; import com.threerings.io.Streamer; import com.threerings.io.Translations; import com.threerings.io.TypedArray; /** * A Streamer for Array objects. */ public class ArrayStreamer extends Streamer { public function ArrayStreamer (jname :String = "[Ljava.lang.Object;") { super(TypedArray, jname); var secondChar :String = jname.charAt(1); if (secondChar === "[") { // if we're a multi-dimensional array then we need a delegate _delegate = Streamer.getStreamerByJavaName(jname.substring(1)); _isFinal = true; // it just is } else if (secondChar === "L") { // form is "[L<class>;" var baseClass :String = jname.substring(2, jname.length - 1); baseClass = Translations.getFromServer(baseClass); _elementType = ClassUtil.getClassByName(baseClass); _isFinal = ClassUtil.isFinal(_elementType); } else if (secondChar === "I") { _elementType = int; } else if (secondChar === "Z") { _elementType = Boolean; } else { Log.getLog(this).warning("Other array types are " + "currently not handled yet [jname=" + jname + "]."); throw new Error("Unimplemented bit"); } } override public function isStreamerFor (obj :Object) :Boolean { if (obj is TypedArray) { // TypedArrays need the same element type return ((obj as TypedArray).getJavaType() === _jname); } else { // any other array is streamed as Object[] return (obj is Array) && (_jname === "[Ljava.lang.Object;"); } } override public function isStreamerForClass (clazz :Class) :Boolean { if (clazz == TypedArray) { return false; // TODO: we're kinda fucked for finding a streamer // by class for TypedArrays here. The caller should be passing // the java name. } else { return ClassUtil.isAssignableAs(Array, clazz) && (_jname === "[Ljava.lang.Object;"); } } override public function createObject (ins :ObjectInputStream) :Object { var ta :TypedArray = new TypedArray(_jname); ta.length = ins.readInt(); return ta; } override public function writeObject (obj :Object, out :ObjectOutputStream) :void { var arr :Array = (obj as Array); var ii :int; out.writeInt(arr.length); if (_elementType == int) { for (ii = 0; ii < arr.length; ii++) { out.writeInt(arr[ii] as int); } } else if (_isFinal) { var mask :ArrayMask = new ArrayMask(arr.length); for (ii = 0; ii < arr.length; ii++) { if (arr[ii] != null) { mask.setBit(ii); } } mask.writeTo(out); // now write the populated elements for (ii = 0; ii < arr.length; ii++) { var element :Object = arr[ii]; if (element != null) { out.writeBareObjectImpl(element, _delegate); } } } else { for (ii = 0; ii < arr.length; ii++) { out.writeObject(arr[ii]); } } } override public function readObject (obj :Object, ins :ObjectInputStream) :void { var arr :Array = (obj as Array); var ii :int; if (_elementType == int) { for (ii = 0; ii < arr.length; ii++) { arr[ii] = ins.readInt(); } } else if (_isFinal) { var mask :ArrayMask = new ArrayMask(); mask.readFrom(ins); for (ii = 0; ii < length; ii++) { if (mask.isSet(ii)) { var target :Object; if (_delegate == null) { target = new _elementType(); } else { target = _delegate.createObject(ins); } ins.readBareObjectImpl(target, _delegate); this[ii] = target; } } } else { for (ii = 0; ii < arr.length; ii++) { arr[ii] = ins.readObject(); } } } /** A streamer for our elements. */ protected var _delegate :Streamer; /** If this is the final dimension of the array, the element type. */ protected var _elementType :Class; /** Whether we're final or not: true if we're not the final dimension * or if the element type is final. */ protected var _isFinal :Boolean; } }
package com.threerings.io.streamers { import com.threerings.util.ClassUtil; import com.threerings.io.ArrayMask; import com.threerings.io.ObjectInputStream; import com.threerings.io.ObjectOutputStream; import com.threerings.io.Streamer; import com.threerings.io.Translations; import com.threerings.io.TypedArray; /** * A Streamer for Array objects. */ public class ArrayStreamer extends Streamer { public function ArrayStreamer (jname :String = "[Ljava.lang.Object;") { super(TypedArray, jname); var secondChar :String = jname.charAt(1); if (secondChar === "[") { // if we're a multi-dimensional array then we need a delegate _delegate = Streamer.getStreamerByJavaName(jname.substring(1)); _isFinal = true; // it just is } else if (secondChar === "L") { // form is "[L<class>;" var baseClass :String = jname.substring(2, jname.length - 1); baseClass = Translations.getFromServer(baseClass); _elementType = ClassUtil.getClassByName(baseClass); _isFinal = ClassUtil.isFinal(_elementType); } else if (secondChar === "I") { _elementType = int; } else if (secondChar === "Z") { _elementType = Boolean; } else { Log.getLog(this).warning("Other array types are " + "currently not handled yet [jname=" + jname + "]."); throw new Error("Unimplemented bit"); } } override public function isStreamerFor (obj :Object) :Boolean { if (obj is TypedArray) { // TypedArrays need the same element type return ((obj as TypedArray).getJavaType() === _jname); } else { // any other array is streamed as Object[] return (obj is Array) && (_jname === "[Ljava.lang.Object;"); } } override public function isStreamerForClass (clazz :Class) :Boolean { if (clazz == TypedArray) { return false; // TODO: we're kinda fucked for finding a streamer // by class for TypedArrays here. The caller should be passing // the java name. } else { return ClassUtil.isAssignableAs(Array, clazz) && (_jname === "[Ljava.lang.Object;"); } } override public function createObject (ins :ObjectInputStream) :Object { var ta :TypedArray = new TypedArray(_jname); ta.length = ins.readInt(); return ta; } override public function writeObject (obj :Object, out :ObjectOutputStream) :void { var arr :Array = (obj as Array); var ii :int; out.writeInt(arr.length); if (_elementType == int) { for (ii = 0; ii < arr.length; ii++) { out.writeInt(arr[ii] as int); } } else if (_elementType == Boolean) { for (ii = 0; ii < arr.length; ii++) { out.writeBoolean(arr[ii] as Boolean); } } else if (_isFinal) { var mask :ArrayMask = new ArrayMask(arr.length); for (ii = 0; ii < arr.length; ii++) { if (arr[ii] != null) { mask.setBit(ii); } } mask.writeTo(out); // now write the populated elements for (ii = 0; ii < arr.length; ii++) { var element :Object = arr[ii]; if (element != null) { out.writeBareObjectImpl(element, _delegate); } } } else { for (ii = 0; ii < arr.length; ii++) { out.writeObject(arr[ii]); } } } override public function readObject (obj :Object, ins :ObjectInputStream) :void { var arr :Array = (obj as Array); var ii :int; if (_elementType == int) { for (ii = 0; ii < arr.length; ii++) { arr[ii] = ins.readInt(); } } else if (_elementType == Boolean) { for (ii = 0; ii < arr.length; ii++) { arr[ii] = ins.readBoolean(); } } else if (_isFinal) { var mask :ArrayMask = new ArrayMask(); mask.readFrom(ins); for (ii = 0; ii < length; ii++) { if (mask.isSet(ii)) { var target :Object; if (_delegate == null) { target = new _elementType(); } else { target = _delegate.createObject(ins); } ins.readBareObjectImpl(target, _delegate); this[ii] = target; } } } else { for (ii = 0; ii < arr.length; ii++) { arr[ii] = ins.readObject(); } } } /** A streamer for our elements. */ protected var _delegate :Streamer; /** If this is the final dimension of the array, the element type. */ protected var _elementType :Class; /** Whether we're final or not: true if we're not the final dimension * or if the element type is final. */ protected var _isFinal :Boolean; } }
Implement Boolean array streaming.
Implement Boolean array streaming. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4319 542714f4-19e9-0310-aa3c-eee0fc999fb1
ActionScript
lgpl-2.1
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
6508abbc1136d77bd46210989101f396e77c3c2d
src/as/com/threerings/crowd/data/BodyObject.as
src/as/com/threerings/crowd/data/BodyObject.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.crowd.data { import com.threerings.util.Byte; import com.threerings.util.Name; import com.threerings.presents.data.ClientObject; import com.threerings.presents.data.InvocationCodes; import com.threerings.crowd.chat.data.ChatCodes; import com.threerings.io.ObjectInputStream; import com.threerings.io.ObjectOutputStream; /** * The basic user object class for Crowd users. Bodies have a username, a * location and a status. */ public class BodyObject extends ClientObject { // AUTO-GENERATED: FIELDS START /** The field name of the <code>username</code> field. */ public static const USERNAME :String = "username"; /** The field name of the <code>location</code> field. */ public static const LOCATION :String = "location"; /** The field name of the <code>status</code> field. */ public static const STATUS :String = "status"; /** The field name of the <code>awayMessage</code> field. */ public static const AWAY_MESSAGE :String = "awayMessage"; // AUTO-GENERATED: FIELDS END /** * The username associated with this body object. This should not be used * directly; in general {@link #getVisibleName} should be used unless you * specifically know that you want the username. */ public var username :Name; /** * The oid of the place currently occupied by this body or -1 if they * currently occupy no place. */ public var location :int = -1; /** * The user's current status ({@link OccupantInfo#ACTIVE}, etc.). */ public var status :int; /** * If non-null, this contains a message to be auto-replied whenever * another user delivers a tell message to this user. */ public var awayMessage :String; /** * Checks whether or not this user has access to the specified * feature. Currently used by the chat system to regulate access to * chat broadcasts but also forms the basis of an extensible * fine-grained permissions system. * * @return null if the user has access, a fully-qualified translatable * message string indicating the reason for denial of access (or just * {@link InvocationCodes#ACCESS_DENIED} if you don't want to be * specific). */ public function checkAccess (feature :String, context :Object) :String { // our default access control policy; how quaint if (ChatCodes.BROADCAST_ACCESS == feature) { return getTokens().isAdmin() ? null : InvocationCodes.ACCESS_DENIED; } else if (ChatCodes.CHAT_ACCESS == feature) { return null; } else { return InvocationCodes.ACCESS_DENIED; } } /** * Returns this user's access control tokens. */ public function getTokens () :TokenRing { return new TokenRing(); } /** * Returns the name that should be displayed to other users and used for * the chat system. The default is to use {@link #username}. */ public function getVisibleName () :Name { return username; } // // AUTO-GENERATED: METHODS START // /** // * Requests that the <code>username</code> field be set to the // * specified value. The local value will be updated immediately and an // * event will be propagated through the system to notify all listeners // * that the attribute did change. Proxied copies of this object (on // * clients) will apply the value change when they received the // * attribute changed notification. // */ // public function setUsername (value :Name) :void // { // var ovalue :Name = this.username; // requestAttributeChange( // USERNAME, value, ovalue); // this.username = value; // } // // /** // * Requests that the <code>location</code> field be set to the // * specified value. The local value will be updated immediately and an // * event will be propagated through the system to notify all listeners // * that the attribute did change. Proxied copies of this object (on // * clients) will apply the value change when they received the // * attribute changed notification. // */ // public function setLocation (value :int) :void // { // var ovalue :int = this.location; // requestAttributeChange( // LOCATION, value, ovalue); // this.location = value; // } // // /** // * Requests that the <code>status</code> field be set to the // * specified value. The local value will be updated immediately and an // * event will be propagated through the system to notify all listeners // * that the attribute did change. Proxied copies of this object (on // * clients) will apply the value change when they received the // * attribute changed notification. // */ // public function setStatus (value :int) :void // { // var ovalue :int = this.status; // requestAttributeChange( // STATUS, Byte.valueOf(value), Byte.valueOf(ovalue)); // this.status = value; // } // // /** // * Requests that the <code>awayMessage</code> field be set to the // * specified value. The local value will be updated immediately and an // * event will be propagated through the system to notify all listeners // * that the attribute did change. Proxied copies of this object (on // * clients) will apply the value change when they received the // * attribute changed notification. // */ // public function setAwayMessage (value :String) :void // { // var ovalue :String = this.awayMessage; // requestAttributeChange( // AWAY_MESSAGE, value, ovalue); // this.awayMessage = value; // } // // AUTO-GENERATED: METHODS END // // override public function writeObject (out :ObjectOutputStream) :void // { // super.writeObject(out); // // out.writeObject(username); // out.writeInt(location); // out.writeByte(status); // out.writeField(awayMessage); // } override public function readObject (ins :ObjectInputStream) :void { super.readObject(ins); username = (ins.readObject() as Name); location = ins.readInt(); status = ins.readByte(); awayMessage = (ins.readField(String) as String); } } }
// // $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.crowd.data { import com.threerings.util.Byte; import com.threerings.util.Name; import com.threerings.presents.data.ClientObject; import com.threerings.presents.data.InvocationCodes; import com.threerings.crowd.chat.data.ChatCodes; import com.threerings.io.ObjectInputStream; import com.threerings.io.ObjectOutputStream; /** * The basic user object class for Crowd users. Bodies have a username, a * location and a status. */ public class BodyObject extends ClientObject { // AUTO-GENERATED: FIELDS START /** The field name of the <code>username</code> field. */ public static const USERNAME :String = "username"; /** The field name of the <code>location</code> field. */ public static const LOCATION :String = "location"; /** The field name of the <code>status</code> field. */ public static const STATUS :String = "status"; /** The field name of the <code>awayMessage</code> field. */ public static const AWAY_MESSAGE :String = "awayMessage"; // AUTO-GENERATED: FIELDS END /** * The username associated with this body object. This should not be used * directly; in general {@link #getVisibleName} should be used unless you * specifically know that you want the username. */ public var username :Name; /** * The oid of the place currently occupied by this body or -1 if they * currently occupy no place. */ public var location :int = -1; /** * The user's current status ({@link OccupantInfo#ACTIVE}, etc.). */ public var status :int; /** * If non-null, this contains a message to be auto-replied whenever * another user delivers a tell message to this user. */ public var awayMessage :String; /** * Checks whether or not this user has access to the specified * feature. Currently used by the chat system to regulate access to * chat broadcasts but also forms the basis of an extensible * fine-grained permissions system. * * @return null if the user has access, a fully-qualified translatable * message string indicating the reason for denial of access (or just * {@link InvocationCodes#ACCESS_DENIED} if you don't want to be * specific). */ public function checkAccess (feature :String, context :Object) :String { // our default access control policy; how quaint if (ChatCodes.BROADCAST_ACCESS == feature) { return getTokens().isAdmin() ? null : InvocationCodes.ACCESS_DENIED; } else if (ChatCodes.CHAT_ACCESS == feature) { return null; } else { return InvocationCodes.ACCESS_DENIED; } } /** * Returns this user's access control tokens. */ public function getTokens () :TokenRing { return new TokenRing(); } /** * Returns the name that should be displayed to other users and used for * the chat system. The default is to use {@link #username}. */ public function getVisibleName () :Name { return username; } // // AUTO-GENERATED: METHODS START // /** // * Requests that the <code>username</code> field be set to the // * specified value. The local value will be updated immediately and an // * event will be propagated through the system to notify all listeners // * that the attribute did change. Proxied copies of this object (on // * clients) will apply the value change when they received the // * attribute changed notification. // */ // public function setUsername (value :Name) :void // { // var ovalue :Name = this.username; // requestAttributeChange( // USERNAME, value, ovalue); // this.username = value; // } // // /** // * Requests that the <code>location</code> field be set to the // * specified value. The local value will be updated immediately and an // * event will be propagated through the system to notify all listeners // * that the attribute did change. Proxied copies of this object (on // * clients) will apply the value change when they received the // * attribute changed notification. // */ // public function setLocation (value :int) :void // { // var ovalue :int = this.location; // requestAttributeChange( // LOCATION, value, ovalue); // this.location = value; // } // // /** // * Requests that the <code>status</code> field be set to the // * specified value. The local value will be updated immediately and an // * event will be propagated through the system to notify all listeners // * that the attribute did change. Proxied copies of this object (on // * clients) will apply the value change when they received the // * attribute changed notification. // */ // public function setStatus (value :int) :void // { // var ovalue :int = this.status; // requestAttributeChange( // STATUS, Byte.valueOf(value), Byte.valueOf(ovalue)); // this.status = value; // } // // /** // * Requests that the <code>awayMessage</code> field be set to the // * specified value. The local value will be updated immediately and an // * event will be propagated through the system to notify all listeners // * that the attribute did change. Proxied copies of this object (on // * clients) will apply the value change when they received the // * attribute changed notification. // */ // public function setAwayMessage (value :String) :void // { // var ovalue :String = this.awayMessage; // requestAttributeChange( // AWAY_MESSAGE, value, ovalue); // this.awayMessage = value; // } // // AUTO-GENERATED: METHODS END // // override public function writeObject (out :ObjectOutputStream) :void // { // super.writeObject(out); // // out.writeObject(username); // out.writeInt(location); // out.writeByte(status); // out.writeField(awayMessage); // } override public function who () :String { var who :String = username.toString() + " (" + getOid(); if (status != OccupantInfo.ACTIVE) { who += (" " + OccupantInfo.X_STATUS[status]); } who += ")"; return who; } override public function readObject (ins :ObjectInputStream) :void { super.readObject(ins); username = (ins.readObject() as Name); location = ins.readInt(); status = ins.readByte(); awayMessage = (ins.readField(String) as String); } } }
Implement bodyObject's proper who().
Implement bodyObject's proper who(). git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4627 542714f4-19e9-0310-aa3c-eee0fc999fb1
ActionScript
lgpl-2.1
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
26795e5f73bfc0cfdea08fb859a38b5e336348c5
src/aerys/minko/scene/controller/animation/MasterAnimationController.as
src/aerys/minko/scene/controller/animation/MasterAnimationController.as
/** * Created with IntelliJ IDEA. * User: promethe * Date: 12/04/13 * Time: 20:03 * To change this template use File | Settings | File Templates. */ package aerys.minko.scene.controller.animation { import flash.utils.Dictionary; import aerys.minko.ns.minko_animation; import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.controller.IRebindableController; public class MasterAnimationController extends AbstractController implements IAnimationController, IRebindableController { use namespace minko_animation; minko_animation var _animations : Vector.<IAnimationController>; private var _isPlaying : Boolean; private var _labelNames : Vector.<String>; private var _labelTimes : Vector.<Number>; public function get numLabels() : uint { return _labelNames.length; } public function get isPlaying() : Boolean { return _isPlaying; } public function MasterAnimationController(animations : Vector.<IAnimationController>) { super(); _animations = animations.concat(); _labelNames = new <String>[]; _labelTimes = new <Number>[]; } public function addLabel(name : String, time : Number) : IAnimationController { if (_labelNames.indexOf(name) >= 0) throw new Error('A label with the same name already exists.'); _labelNames.push(name); _labelTimes.push(time); var numAnimations : uint = _animations.length; for (var animationId : uint = 0; animationId < numAnimations; ++animationId) _animations[animationId].addLabel(name, time); return this; } public function removeLabel(name : String) : IAnimationController { var index : int = _labelNames.indexOf(name); if (index < 0) throw new Error('The time label named \'' + name + '\' does not exist.'); var numLabels : uint = _labelNames.length - 1; _labelNames[index] = _labelNames[numLabels]; _labelNames.length = numLabels; _labelTimes[index] = _labelTimes[numLabels]; _labelTimes.length = numLabels; var numAnimations : uint = _animations.length; for (var animationId : uint = 0; animationId < numAnimations; ++animationId) _animations[animationId].removeLabel(name); return this; } public function seek(time : Object) : IAnimationController { var numAnimations : uint = _animations.length; for (var animationId : uint = 0; animationId < numAnimations; ++animationId) _animations[animationId].seek(time); return this; } public function play() : IAnimationController { var numAnimations : uint = _animations.length; _isPlaying = true; for (var animationId : uint = 0; animationId < numAnimations; ++animationId) _animations[animationId].play(); return this; } public function stop() : IAnimationController { var numAnimations : uint = _animations.length; _isPlaying = false; for (var animationId : uint = 0; animationId < numAnimations; ++animationId) _animations[animationId].stop(); return this; } public function setPlaybackWindow(beginTime : Object = null, endTime : Object = null) : IAnimationController { var numAnimations : uint = _animations.length; for (var animationId : uint = 0; animationId < numAnimations; ++animationId) _animations[animationId].setPlaybackWindow(beginTime, endTime); return this; } public function resetPlaybackWindow() : IAnimationController { var numAnimations : uint = _animations.length; for (var animationId : uint = 0; animationId < numAnimations; ++animationId) _animations[animationId].resetPlaybackWindow(); return this; } public function getLabelName(index : uint) : String { return _labelNames[index]; } public function getLabelTime(index : uint) : Number { return _labelTimes[index]; } public function getLabelTimeByName(name : String) : Number { var index : int = _labelNames.indexOf(name); if (index < 0) throw new Error('The time label named \'' + name + '\' does not exist.'); return _labelTimes[index]; } override public function clone():AbstractController { var newController : MasterAnimationController = new MasterAnimationController(_animations); newController._labelNames = _labelNames; newController._labelTimes = _labelTimes; return newController; } public function rebindDependencies(nodeMap : Dictionary, controllerMap : Dictionary) : void { var newAnimations : Vector.<IAnimationController> = new Vector.<IAnimationController>(); for(var i : int = 0; i < _animations.length; ++i) { var newController : IAnimationController = controllerMap[_animations[i]] as IAnimationController; if (newController) newAnimations.push(newController); } _animations = newAnimations; } public function changeLabel(oldName : String, newName : String) : IAnimationController { var index : int = _labelNames.indexOf(oldName); if (index < 0) throw new Error('The time label named \'' + oldName + '\' does not exist.'); _labelNames[index] = newName; return this; } public function setTimeForLabel(name : String, newTime : Number) : IAnimationController { var index : int = _labelNames.indexOf(name); if (index < 0) throw new Error('The time label named \'' + name + '\' does not exist.'); _labelTimes[index] = newTime; return this; } } }
/** * Created with IntelliJ IDEA. * User: promethe * Date: 12/04/13 * Time: 20:03 * To change this template use File | Settings | File Templates. */ package aerys.minko.scene.controller.animation { import flash.utils.Dictionary; import aerys.minko.ns.minko_animation; import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.controller.IRebindableController; public class MasterAnimationController extends AbstractController implements IAnimationController, IRebindableController { use namespace minko_animation; minko_animation var _animations : Vector.<IAnimationController>; private var _isPlaying : Boolean; private var _labelNames : Vector.<String>; private var _labelTimes : Vector.<Number>; public function get numLabels() : uint { return _labelNames.length; } public function get isPlaying() : Boolean { return _isPlaying; } public function MasterAnimationController(animations : Vector.<IAnimationController>) { super(); _animations = animations.concat(); _labelNames = new <String>[]; _labelTimes = new <Number>[]; } public function addLabel(name : String, time : Number) : IAnimationController { if (_labelNames.indexOf(name) >= 0) throw new Error('A label with the same name already exists.'); _labelNames.push(name); _labelTimes.push(time); var numAnimations : uint = _animations.length; for (var animationId : uint = 0; animationId < numAnimations; ++animationId) _animations[animationId].addLabel(name, time); return this; } public function removeLabel(name : String) : IAnimationController { var index : int = _labelNames.indexOf(name); if (index < 0) throw new Error('The time label named \'' + name + '\' does not exist.'); var numLabels : uint = _labelNames.length - 1; _labelNames[index] = _labelNames[numLabels]; _labelNames.length = numLabels; _labelTimes[index] = _labelTimes[numLabels]; _labelTimes.length = numLabels; var numAnimations : uint = _animations.length; for (var animationId : uint = 0; animationId < numAnimations; ++animationId) _animations[animationId].removeLabel(name); return this; } public function seek(time : Object) : IAnimationController { var numAnimations : uint = _animations.length; for (var animationId : uint = 0; animationId < numAnimations; ++animationId) _animations[animationId].seek(time); return this; } public function play() : IAnimationController { var numAnimations : uint = _animations.length; _isPlaying = true; for (var animationId : uint = 0; animationId < numAnimations; ++animationId) _animations[animationId].play(); return this; } public function stop() : IAnimationController { var numAnimations : uint = _animations.length; _isPlaying = false; for (var animationId : uint = 0; animationId < numAnimations; ++animationId) _animations[animationId].stop(); return this; } public function setPlaybackWindow(beginTime : Object = null, endTime : Object = null) : IAnimationController { var numAnimations : uint = _animations.length; for (var animationId : uint = 0; animationId < numAnimations; ++animationId) _animations[animationId].setPlaybackWindow(beginTime, endTime); return this; } public function resetPlaybackWindow() : IAnimationController { var numAnimations : uint = _animations.length; for (var animationId : uint = 0; animationId < numAnimations; ++animationId) _animations[animationId].resetPlaybackWindow(); return this; } public function getLabelName(index : uint) : String { return _labelNames[index]; } public function getLabelTime(index : uint) : Number { return _labelTimes[index]; } public function getLabelTimeByName(name : String) : Number { var index : int = _labelNames.indexOf(name); if (index < 0) throw new Error('The time label named \'' + name + '\' does not exist.'); return _labelTimes[index]; } override public function clone():AbstractController { var newController : MasterAnimationController = new MasterAnimationController(_animations); newController._labelNames = _labelNames; newController._labelTimes = _labelTimes; return newController; } public function rebindDependencies(nodeMap : Dictionary, controllerMap : Dictionary) : void { var newAnimations : Vector.<IAnimationController> = new Vector.<IAnimationController>(); for(var i : int = 0; i < _animations.length; ++i) { var newController : IAnimationController = controllerMap[_animations[i]] as IAnimationController; if (newController) newAnimations.push(newController); } _animations = newAnimations; } public function changeLabel(oldName : String, newName : String) : IAnimationController { var index : int = _labelNames.indexOf(oldName); if (index < 0) throw new Error('The time label named \'' + oldName + '\' does not exist.'); _labelNames[index] = newName; var numAnimations : uint = _animations.length; for (var animationId : uint = 0; animationId < numAnimations; ++animationId) _animations[animationId].changeLabel(oldName, newName); return this; } public function setTimeForLabel(name : String, newTime : Number) : IAnimationController { var index : int = _labelNames.indexOf(name); if (index < 0) throw new Error('The time label named \'' + name + '\' does not exist.'); _labelTimes[index] = newTime; var numAnimations : uint = _animations.length; for (var animationId : uint = 0; animationId < numAnimations; ++animationId) _animations[animationId].setTimeForLabel(name, newTime); return this; } } }
Fix label modification on masterAnimationContoller
Fix label modification on masterAnimationContoller
ActionScript
mit
aerys/minko-as3
9bf72378569864bf84f9b6762f00412bc4ec2cf6
src/aerys/minko/scene/node/texture/BitmapTexture.as
src/aerys/minko/scene/node/texture/BitmapTexture.as
package aerys.minko.scene.node.texture { import aerys.minko.render.effect.basic.BasicStyle; import aerys.minko.render.ressource.TextureRessource; import aerys.minko.scene.action.texture.TextureAction; import aerys.minko.scene.node.AbstractScene; import flash.display.BitmapData; import flash.display.DisplayObject; import flash.geom.Matrix; /** * The BitmapTexture class enables the use of BitmapData objects as * textures. * * @author Jean-Marc Le Roux * */ public class BitmapTexture extends AbstractScene implements ITexture { private var _version : uint = 0; private var _data : BitmapData = null; private var _mipmapping : Boolean = false; private var _styleProp : int = -1; private var _matrix : Matrix = new Matrix(); private var _ressource : TextureRessource = new TextureRessource(); public function get version() : uint { return _version; } public function get styleProperty() : int { return _styleProp; } public function set styleProperty(value : int) : void { _styleProp = value; } public function get ressource() : TextureRessource { return _ressource; } protected function get bitmapData() : BitmapData { return _data; } public function updateFromBitmapData(value : BitmapData, smooth : Boolean = true) : void { var size : int = 1; var w : int = value.width; var h : int = value.height; while (size < w || size < h) size <<= 1; if (!_data || _data.width != size || _data.height != size) _data = new BitmapData(size, size, value.transparent, 0); if (size != w || size != h) { _matrix.identity(); _matrix.scale(size / value.width, size / value.height); _data.draw(value, _matrix, null, null, null, smooth); } else { _data.draw(value, null, null, null, null, smooth); } ++_version; _ressource.setContentFromBitmapData(_data, _mipmapping); } public function BitmapTexture(bitmapData : BitmapData = null, mipmapping : Boolean = true) { _mipmapping = mipmapping; if (bitmapData) updateFromBitmapData(bitmapData); _styleProp = BasicStyle.DIFFUSE; actions[0] = TextureAction.textureAction; } public static function fromDisplayObject(source : DisplayObject, size : int = 0, smooth : Boolean = false) : BitmapTexture { var matrix : Matrix = null; var bmp : BitmapData = new BitmapData(size || source.width, size || source.height, true, 0); if (size) { matrix = new Matrix(); matrix.scale(source.width / size, source.height / size); } bmp.draw(source, matrix, null, null, null, smooth); return new BitmapTexture(bmp); } } }
package aerys.minko.scene.node.texture { import aerys.minko.render.effect.basic.BasicStyle; import aerys.minko.render.ressource.TextureRessource; import aerys.minko.scene.action.texture.TextureAction; import aerys.minko.scene.node.AbstractScene; import flash.display.BitmapData; import flash.display.DisplayObject; import flash.geom.Matrix; /** * The BitmapTexture class enables the use of BitmapData objects as * textures. * * @author Jean-Marc Le Roux * */ public class BitmapTexture extends AbstractScene implements ITexture { private var _version : uint = 0; private var _data : BitmapData = null; private var _mipmapping : Boolean = false; private var _styleProp : int = -1; private var _matrix : Matrix = new Matrix(); private var _ressource : TextureRessource = new TextureRessource(); public function get version() : uint { return _version; } public function get styleProperty() : int { return _styleProp; } public function set styleProperty(value : int) : void { _styleProp = value; } public function get ressource() : TextureRessource { return _ressource; } protected function get bitmapData() : BitmapData { return _data; } public function updateFromBitmapData(value : BitmapData, smooth : Boolean = true) : void { var size : int = 1; var w : int = value.width; var h : int = value.height; while (size < w || size < h) size <<= 1; if (!_data || _data.width != size || _data.height != size) _data = new BitmapData(size, size, value.transparent, 0); if (size != w || size != h) { _matrix.identity(); _matrix.scale(size / value.width, size / value.height); _data.draw(value, _matrix, null, null, null, smooth); } else { _data.draw(value, null, null, null, null, smooth); } ++_version; _ressource.setContentFromBitmapData(_data, _mipmapping); } public function BitmapTexture(bitmapData : BitmapData = null, mipmapping : Boolean = true, styleProp : int = -1) { _mipmapping = mipmapping; if (bitmapData) updateFromBitmapData(bitmapData); _styleProp = styleProp != -1 ? styleProp : BasicStyle.DIFFUSE; actions[0] = TextureAction.textureAction; } public static function fromDisplayObject(source : DisplayObject, size : int = 0, smooth : Boolean = false) : BitmapTexture { var matrix : Matrix = null; var bmp : BitmapData = new BitmapData(size || source.width, size || source.height, true, 0); if (size) { matrix = new Matrix(); matrix.scale(source.width / size, source.height / size); } bmp.draw(source, matrix, null, null, null, smooth); return new BitmapTexture(bmp); } } }
Add optional argument to BitmapTexture to set texture type
Add optional argument to BitmapTexture to set texture type
ActionScript
mit
aerys/minko-as3
3ca747fdfef6e24c4dd261868be9a0e3eddbc297
src/control/ExportDataCommand.as
src/control/ExportDataCommand.as
package control { import com.adobe.serialization.json.JSON; import dragonBones.objects.DataParser; import dragonBones.utils.ConstValues; import flash.display.BitmapData; import flash.display.MovieClip; import flash.events.Event; import flash.events.IOErrorEvent; import flash.geom.Matrix; import flash.net.FileReference; import flash.utils.ByteArray; import message.Message; import message.MessageDispatcher; import model.ImportDataProxy; import model.JSFLProxy; import model.XMLDataProxy; import utils.BitmapDataUtil; import utils.GlobalConstValues; import utils.PNGEncoder; import utils.xmlToObject; import zero.zip.Zip; public class ExportDataCommand { public static const instance:ExportDataCommand = new ExportDataCommand(); private var _fileREF:FileReference; private var _exportType:uint; private var _isExporting:Boolean; private var _exportScale:Number; private var _importDataProxy:ImportDataProxy; private var _xmlDataProxy:XMLDataProxy; private var _bitmapData:BitmapData; public function ExportDataCommand() { _fileREF = new FileReference(); _importDataProxy = ImportDataProxy.getInstance(); } public function export(exportType:uint, exportScale:Number):void { if(_isExporting) { return; } _isExporting = true; _exportType = exportType; _exportScale = exportScale; switch(_exportType) { case 0: case 2: case 5: _exportScale = 1; break; } exportStart(); } private function exportStart():void { var dataBytes:ByteArray; var zip:Zip; var date:Date; _xmlDataProxy = _importDataProxy.xmlDataProxy; _bitmapData = _importDataProxy.textureAtlas.bitmapData; if(_exportScale != 1) { _xmlDataProxy = _xmlDataProxy.clone(); var subBitmapDataDic:Object; var movieClip:MovieClip = _importDataProxy.textureAtlas.movieClip; if(movieClip && movieClip.totalFrames >= 3) { subBitmapDataDic = {}; for each (var displayName:String in _xmlDataProxy.getSubTextureListFromDisplayList()) { movieClip.gotoAndStop(movieClip.totalFrames); movieClip.gotoAndStop(displayName); subBitmapDataDic[displayName] = movieClip.getChildAt(0); } } else { subBitmapDataDic = BitmapDataUtil.getSubBitmapDataDic( _bitmapData, _xmlDataProxy.getSubTextureRectMap() ); } _xmlDataProxy.scaleData(_exportScale); _bitmapData = BitmapDataUtil.getMergeBitmapData( subBitmapDataDic, _xmlDataProxy.getSubTextureRectMap(), _xmlDataProxy.textureAtlasWidth, _xmlDataProxy.textureAtlasHeight, _exportScale ); } var isSWF:Boolean = _exportType == 0 || _exportType == 2 || _exportType == 5; var isXML:Boolean = _exportType == 2 || _exportType == 3 || _exportType == 4; switch(_exportType) { case 0: try { dataBytes = getSWFBytes(); if(dataBytes) { exportSave( DataParser.compressData( xmlToObject(_xmlDataProxy.xml, GlobalConstValues.XML_LIST_NAMES), xmlToObject(_xmlDataProxy.textureAtlasXML, GlobalConstValues.XML_LIST_NAMES), dataBytes ), _importDataProxy.data.name + GlobalConstValues.SWF_SUFFIX ); return; } break; } catch(_e:Error) { break; } case 1: try { dataBytes = getPNGBytes(); if(dataBytes) { exportSave( DataParser.compressData( xmlToObject(_xmlDataProxy.xml, GlobalConstValues.XML_LIST_NAMES), xmlToObject(_xmlDataProxy.textureAtlasXML, GlobalConstValues.XML_LIST_NAMES), dataBytes ), _importDataProxy.data.name + GlobalConstValues.PNG_SUFFIX ); return; } break; } catch(_e:Error) { break; } case 2: case 3: case 5: case 6: try { if(isSWF) { dataBytes = getSWFBytes(); } else { dataBytes = getPNGBytes(); } if(dataBytes) { date = new Date(); zip = new Zip(); zip.add( dataBytes, GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + (isSWF?GlobalConstValues.SWF_SUFFIX:GlobalConstValues.PNG_SUFFIX), date ); _xmlDataProxy.setImagePath(GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + GlobalConstValues.PNG_SUFFIX); if(isXML) { zip.add( _xmlDataProxy.xml.toXMLString(), GlobalConstValues.DRAGON_BONES_DATA_NAME + GlobalConstValues.XML_SUFFIX, date ); zip.add( _xmlDataProxy.textureAtlasXML.toXMLString(), GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + GlobalConstValues.XML_SUFFIX, date ); } else { zip.add( com.adobe.serialization.json.JSON.encode(xmlToObject(_xmlDataProxy.xml, GlobalConstValues.XML_LIST_NAMES)), GlobalConstValues.DRAGON_BONES_DATA_NAME + GlobalConstValues.JSON_SUFFIX, date ); zip.add( com.adobe.serialization.json.JSON.encode(xmlToObject(_xmlDataProxy.textureAtlasXML, GlobalConstValues.XML_LIST_NAMES)), GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + GlobalConstValues.JSON_SUFFIX, date ); } exportSave( zip.encode(), _importDataProxy.data.name + GlobalConstValues.ZIP_SUFFIX ); zip.clear(); return; } break; } catch(_e:Error) { break; } case 4: case 7: try { date = new Date(); zip = new Zip(); if(_xmlDataProxy == _importDataProxy.xmlDataProxy) { _xmlDataProxy = _xmlDataProxy.clone(); } _xmlDataProxy.changePath(); subBitmapDataDic = BitmapDataUtil.getSubBitmapDataDic( _bitmapData, _xmlDataProxy.getSubTextureRectMap() ); for(var subTextureName:String in subBitmapDataDic) { var subBitmapData:BitmapData = subBitmapDataDic[subTextureName]; zip.add( PNGEncoder.encode(subBitmapData), GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + "/" + subTextureName + GlobalConstValues.PNG_SUFFIX, date ); subBitmapData.dispose(); } if(isXML) { zip.add( _xmlDataProxy.xml.toXMLString(), GlobalConstValues.DRAGON_BONES_DATA_NAME + GlobalConstValues.XML_SUFFIX, date ); zip.add( _xmlDataProxy.textureAtlasXML.toXMLString(), GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + GlobalConstValues.XML_SUFFIX, date ); } else { zip.add( com.adobe.serialization.json.JSON.encode(xmlToObject(_xmlDataProxy.xml, GlobalConstValues.XML_LIST_NAMES)), GlobalConstValues.DRAGON_BONES_DATA_NAME + GlobalConstValues.JSON_SUFFIX, date ); zip.add( com.adobe.serialization.json.JSON.encode(xmlToObject(_xmlDataProxy.textureAtlasXML, GlobalConstValues.XML_LIST_NAMES)), GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + GlobalConstValues.JSON_SUFFIX, date ); } exportSave( zip.encode(), _importDataProxy.data.name + GlobalConstValues.ZIP_SUFFIX ); zip.clear(); return; } catch(_e:Error) { break; } default: break; } _isExporting = false; MessageDispatcher.dispatchEvent(MessageDispatcher.EXPORT_ERROR); } private function getSWFBytes():ByteArray { if(_importDataProxy.textureAtlas.movieClip) { return _importDataProxy.textureBytes; } return null; } private function getPNGBytes():ByteArray { if(_importDataProxy.textureAtlas.movieClip) { return PNGEncoder.encode(_bitmapData); } else { if(_bitmapData && _bitmapData != _importDataProxy.textureAtlas.bitmapData) { return PNGEncoder.encode(_bitmapData); } return _importDataProxy.textureBytes; } return null; } private function exportSave(fileData:ByteArray, fileName:String):void { MessageDispatcher.dispatchEvent(MessageDispatcher.EXPORT, fileName); _fileREF.addEventListener(Event.CANCEL, onFileSaveHandler); _fileREF.addEventListener(Event.COMPLETE, onFileSaveHandler); _fileREF.addEventListener(IOErrorEvent.IO_ERROR, onFileSaveHandler); _fileREF.save(fileData, fileName); } private function onFileSaveHandler(e:Event):void { _fileREF.removeEventListener(Event.CANCEL, onFileSaveHandler); _fileREF.removeEventListener(Event.COMPLETE, onFileSaveHandler); _fileREF.removeEventListener(IOErrorEvent.IO_ERROR, onFileSaveHandler); _isExporting = false; switch(e.type) { case Event.CANCEL: MessageDispatcher.dispatchEvent(MessageDispatcher.EXPORT_CANCEL); break; case IOErrorEvent.IO_ERROR: MessageDispatcher.dispatchEvent(MessageDispatcher.EXPORT_ERROR); break; case Event.COMPLETE: if(_bitmapData && _bitmapData != _importDataProxy.textureAtlas.bitmapData) { _bitmapData.dispose(); _bitmapData = null; } MessageDispatcher.dispatchEvent(MessageDispatcher.EXPORT_COMPLETE); break; } } } }
package control { import com.adobe.serialization.json.JSON; import dragonBones.objects.DataParser; import dragonBones.utils.ConstValues; import flash.display.BitmapData; import flash.display.MovieClip; import flash.events.Event; import flash.events.IOErrorEvent; import flash.geom.Matrix; import flash.geom.Point; import flash.geom.Rectangle; import flash.net.FileReference; import flash.utils.ByteArray; import message.Message; import message.MessageDispatcher; import model.ImportDataProxy; import model.JSFLProxy; import model.XMLDataProxy; import utils.BitmapDataUtil; import utils.GlobalConstValues; import utils.PNGEncoder; import utils.xmlToObject; import zero.zip.Zip; public class ExportDataCommand { public static const instance:ExportDataCommand = new ExportDataCommand(); private var _fileREF:FileReference; private var _isExporting:Boolean; private var _scale:Number; private var _exportType:uint; private var _backgroundColor:uint; private var _importDataProxy:ImportDataProxy; private var _xmlDataProxy:XMLDataProxy; private var _bitmapData:BitmapData; public function ExportDataCommand() { _fileREF = new FileReference(); _importDataProxy = ImportDataProxy.getInstance(); } public function export(exportType:uint, scale:Number, backgroundColor:uint = 0):void { if(_isExporting) { return; } _isExporting = true; _exportType = exportType; _scale = scale; switch(_exportType) { case 0: case 2: case 5: _scale = 1; break; } _backgroundColor = backgroundColor; exportStart(); } private function exportStart():void { var dataBytes:ByteArray; var zip:Zip; var date:Date; _xmlDataProxy = _importDataProxy.xmlDataProxy; _bitmapData = _importDataProxy.textureAtlas.bitmapData; if(_scale != 1) { _xmlDataProxy = _xmlDataProxy.clone(); var subBitmapDataDic:Object; var movieClip:MovieClip = _importDataProxy.textureAtlas.movieClip; if(movieClip && movieClip.totalFrames >= 3) { subBitmapDataDic = {}; for each (var displayName:String in _xmlDataProxy.getSubTextureListFromDisplayList()) { movieClip.gotoAndStop(movieClip.totalFrames); movieClip.gotoAndStop(displayName); subBitmapDataDic[displayName] = movieClip.getChildAt(0); } } else { subBitmapDataDic = BitmapDataUtil.getSubBitmapDataDic( _bitmapData, _xmlDataProxy.getSubTextureRectMap() ); } _xmlDataProxy.scaleData(_scale); _bitmapData = BitmapDataUtil.getMergeBitmapData( subBitmapDataDic, _xmlDataProxy.getSubTextureRectMap(), _xmlDataProxy.textureAtlasWidth, _xmlDataProxy.textureAtlasHeight, _scale ); } var isSWF:Boolean = _exportType == 0 || _exportType == 2 || _exportType == 5; var isXML:Boolean = _exportType == 2 || _exportType == 3 || _exportType == 4; switch(_exportType) { case 0: try { dataBytes = getSWFBytes(); if(dataBytes) { exportSave( DataParser.compressData( xmlToObject(_xmlDataProxy.xml, GlobalConstValues.XML_LIST_NAMES), xmlToObject(_xmlDataProxy.textureAtlasXML, GlobalConstValues.XML_LIST_NAMES), dataBytes ), _importDataProxy.data.name + GlobalConstValues.SWF_SUFFIX ); return; } break; } catch(_e:Error) { break; } case 1: try { dataBytes = getPNGBytes(_backgroundColor); if(dataBytes) { exportSave( DataParser.compressData( xmlToObject(_xmlDataProxy.xml, GlobalConstValues.XML_LIST_NAMES), xmlToObject(_xmlDataProxy.textureAtlasXML, GlobalConstValues.XML_LIST_NAMES), dataBytes ), _importDataProxy.data.name + GlobalConstValues.PNG_SUFFIX ); return; } break; } catch(_e:Error) { break; } case 2: case 3: case 5: case 6: try { if(isSWF) { dataBytes = getSWFBytes(); } else { dataBytes = getPNGBytes(_backgroundColor); } if(dataBytes) { date = new Date(); zip = new Zip(); zip.add( dataBytes, GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + (isSWF?GlobalConstValues.SWF_SUFFIX:GlobalConstValues.PNG_SUFFIX), date ); _xmlDataProxy.setImagePath(GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + GlobalConstValues.PNG_SUFFIX); if(isXML) { zip.add( _xmlDataProxy.xml.toXMLString(), GlobalConstValues.DRAGON_BONES_DATA_NAME + GlobalConstValues.XML_SUFFIX, date ); zip.add( _xmlDataProxy.textureAtlasXML.toXMLString(), GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + GlobalConstValues.XML_SUFFIX, date ); } else { zip.add( com.adobe.serialization.json.JSON.encode(xmlToObject(_xmlDataProxy.xml, GlobalConstValues.XML_LIST_NAMES)), GlobalConstValues.DRAGON_BONES_DATA_NAME + GlobalConstValues.JSON_SUFFIX, date ); zip.add( com.adobe.serialization.json.JSON.encode(xmlToObject(_xmlDataProxy.textureAtlasXML, GlobalConstValues.XML_LIST_NAMES)), GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + GlobalConstValues.JSON_SUFFIX, date ); } exportSave( zip.encode(), _importDataProxy.data.name + GlobalConstValues.ZIP_SUFFIX ); zip.clear(); return; } break; } catch(_e:Error) { break; } case 4: case 7: try { date = new Date(); zip = new Zip(); if(_xmlDataProxy == _importDataProxy.xmlDataProxy) { _xmlDataProxy = _xmlDataProxy.clone(); } _xmlDataProxy.changePath(); subBitmapDataDic = BitmapDataUtil.getSubBitmapDataDic( _bitmapData, _xmlDataProxy.getSubTextureRectMap() ); for(var subTextureName:String in subBitmapDataDic) { var subBitmapData:BitmapData = subBitmapDataDic[subTextureName]; zip.add( PNGEncoder.encode(subBitmapData), GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + "/" + subTextureName + GlobalConstValues.PNG_SUFFIX, date ); subBitmapData.dispose(); } if(isXML) { zip.add( _xmlDataProxy.xml.toXMLString(), GlobalConstValues.DRAGON_BONES_DATA_NAME + GlobalConstValues.XML_SUFFIX, date ); zip.add( _xmlDataProxy.textureAtlasXML.toXMLString(), GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + GlobalConstValues.XML_SUFFIX, date ); } else { zip.add( com.adobe.serialization.json.JSON.encode(xmlToObject(_xmlDataProxy.xml, GlobalConstValues.XML_LIST_NAMES)), GlobalConstValues.DRAGON_BONES_DATA_NAME + GlobalConstValues.JSON_SUFFIX, date ); zip.add( com.adobe.serialization.json.JSON.encode(xmlToObject(_xmlDataProxy.textureAtlasXML, GlobalConstValues.XML_LIST_NAMES)), GlobalConstValues.TEXTURE_ATLAS_DATA_NAME + GlobalConstValues.JSON_SUFFIX, date ); } exportSave( zip.encode(), _importDataProxy.data.name + GlobalConstValues.ZIP_SUFFIX ); zip.clear(); return; } catch(_e:Error) { break; } default: break; } _isExporting = false; MessageDispatcher.dispatchEvent(MessageDispatcher.EXPORT_ERROR); } private function getSWFBytes():ByteArray { if(_importDataProxy.textureAtlas.movieClip) { return _importDataProxy.textureBytes; } return null; } private function getPNGBytes(color:uint = 0):ByteArray { if(color) { var bitmapData:BitmapData = new BitmapData(_bitmapData.width, _bitmapData.height, true, color); bitmapData.draw(_bitmapData); var byteArray:ByteArray = PNGEncoder.encode(bitmapData); bitmapData.dispose(); return byteArray; } else if(_importDataProxy.textureAtlas.movieClip) { return PNGEncoder.encode(_bitmapData); } else { if(_bitmapData && _bitmapData != _importDataProxy.textureAtlas.bitmapData) { return PNGEncoder.encode(_bitmapData); } return _importDataProxy.textureBytes; } return null; } private function exportSave(fileData:ByteArray, fileName:String):void { MessageDispatcher.dispatchEvent(MessageDispatcher.EXPORT, fileName); _fileREF.addEventListener(Event.CANCEL, onFileSaveHandler); _fileREF.addEventListener(Event.COMPLETE, onFileSaveHandler); _fileREF.addEventListener(IOErrorEvent.IO_ERROR, onFileSaveHandler); _fileREF.save(fileData, fileName); } private function onFileSaveHandler(e:Event):void { _fileREF.removeEventListener(Event.CANCEL, onFileSaveHandler); _fileREF.removeEventListener(Event.COMPLETE, onFileSaveHandler); _fileREF.removeEventListener(IOErrorEvent.IO_ERROR, onFileSaveHandler); _isExporting = false; switch(e.type) { case Event.CANCEL: MessageDispatcher.dispatchEvent(MessageDispatcher.EXPORT_CANCEL); break; case IOErrorEvent.IO_ERROR: MessageDispatcher.dispatchEvent(MessageDispatcher.EXPORT_ERROR); break; case Event.COMPLETE: if(_bitmapData && _bitmapData != _importDataProxy.textureAtlas.bitmapData) { _bitmapData.dispose(); _bitmapData = null; } MessageDispatcher.dispatchEvent(MessageDispatcher.EXPORT_COMPLETE); break; } } } }
add export background color
add export background color
ActionScript
mit
DragonBones/DesignPanel
73b5d0a2a6c40d0377c4074b2d17c4924c90a50b
src/flash/text/TextField.as
src/flash/text/TextField.as
package flash.text { import flash.display.DisplayObject; import flash.display.InteractiveObject; import flash.geom.Rectangle; [native(cls='TextFieldClass')] public class TextField extends InteractiveObject { public static native function isFontCompatible(fontName: String, fontStyle: String): Boolean; public function TextField() {} public native function get alwaysShowSelection(): Boolean; public native function set alwaysShowSelection(value: Boolean): void; public native function get antiAliasType(): String; public native function set antiAliasType(antiAliasType: String): void; public native function get autoSize(): String; public native function set autoSize(value: String): void; public native function get background(): Boolean; public native function set background(value: Boolean): void; public native function get backgroundColor(): uint; public native function set backgroundColor(value: uint): void; public native function get border(): Boolean; public native function set border(value: Boolean): void; public native function get borderColor(): uint; public native function set borderColor(value: uint): void; public native function get bottomScrollV(): int; public native function get caretIndex(): int; public native function get condenseWhite(): Boolean; public native function set condenseWhite(value: Boolean): void; public native function get defaultTextFormat(): TextFormat; public native function set defaultTextFormat(format: TextFormat): void; public native function get embedFonts(): Boolean; public native function set embedFonts(value: Boolean): void; public native function get gridFitType(): String; public native function set gridFitType(gridFitType: String): void; public native function get htmlText(): String; public native function set htmlText(value: String): void; public native function get length(): int; public native function get textInteractionMode(): String; public native function get maxChars(): int; public native function set maxChars(value: int): void; public native function get maxScrollH(): int; public native function get maxScrollV(): int; public native function get mouseWheelEnabled(): Boolean; public native function set mouseWheelEnabled(value: Boolean): void; public native function get multiline(): Boolean; public native function set multiline(value: Boolean): void; public native function get numLines(): int; public native function get displayAsPassword(): Boolean; public native function set displayAsPassword(value: Boolean): void; public native function get restrict(): String; public native function set restrict(value: String): void; public native function get scrollH(): int; public native function set scrollH(value: int): void; public native function get scrollV(): int; public native function set scrollV(value: int): void; public native function get selectable(): Boolean; public native function set selectable(value: Boolean): void; public function get selectedText(): String { return text.substring(selectionBeginIndex, selectionEndIndex); } public native function get selectionBeginIndex(): int; public native function get selectionEndIndex(): int; public native function get sharpness(): Number; public native function set sharpness(value: Number): void; public native function get styleSheet(): StyleSheet; public native function set styleSheet(value: StyleSheet): void; public native function get text(): String; public native function set text(value: String): void; public native function get textColor(): uint; public native function set textColor(value: uint): void; public native function get textHeight(): Number; public native function get textWidth(): Number; public native function get thickness(): Number; public native function set thickness(value: Number): void; public native function get type(): String; public native function set type(value: String): void; public native function get wordWrap(): Boolean; public native function set wordWrap(value: Boolean): void; public native function get useRichTextClipboard(): Boolean; public native function set useRichTextClipboard(value: Boolean): void; public function appendText(newText: String): void { var beginIndex: uint = text.length; replaceText(beginIndex, beginIndex, newText); } public native function getCharBoundaries(charIndex: int): Rectangle; public native function getCharIndexAtPoint(x: Number, y: Number): int; public native function getFirstCharInParagraph(charIndex: int): int; public native function getLineIndexAtPoint(x: Number, y: Number): int; public native function getLineIndexOfChar(charIndex: int): int; public native function getLineLength(lineIndex: int): int; public native function getLineMetrics(lineIndex: int): TextLineMetrics; public native function getLineOffset(lineIndex: int): int; public native function getLineText(lineIndex: int): String; public native function getParagraphLength(charIndex: int): int; public native function getTextFormat(beginIndex: int = -1, endIndex: int = -1): TextFormat; public native function getTextRuns(beginIndex: int = 0, endIndex: int = 2147483647): Array; public native function getRawText(): String; public function getXMLText(beginIndex: int = 0, endIndex: int = 2147483647): String { notImplemented("getXMLText"); return ""; } public function insertXMLText(beginIndex: int, endIndex: int, richText: String, pasting: Boolean = false): void { notImplemented("insertXMLText"); } public native function replaceSelectedText(value: String): void; public native function replaceText(beginIndex: int, endIndex: int, newText: String): void; public native function setSelection(beginIndex: int, endIndex: int): void; public native function setTextFormat(format: TextFormat, beginIndex: int = -1, endIndex: int = -1): void; public native function getImageReference(id: String): DisplayObject; internal function copyRichText(): String { notImplemented("copyRichText"); return ""; } internal function pasteRichText(richText: String): Boolean { notImplemented("pasteRichText"); return false; } } }
/* * Copyright 2014 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package flash.text { import flash.display.DisplayObject; import flash.display.InteractiveObject; import flash.geom.Rectangle; [native(cls='TextFieldClass')] public class TextField extends InteractiveObject { public static native function isFontCompatible(fontName: String, fontStyle: String): Boolean; public function TextField() {} public native function get alwaysShowSelection(): Boolean; public native function set alwaysShowSelection(value: Boolean): void; public native function get antiAliasType(): String; public native function set antiAliasType(antiAliasType: String): void; public native function get autoSize(): String; public native function set autoSize(value: String): void; public native function get background(): Boolean; public native function set background(value: Boolean): void; public native function get backgroundColor(): uint; public native function set backgroundColor(value: uint): void; public native function get border(): Boolean; public native function set border(value: Boolean): void; public native function get borderColor(): uint; public native function set borderColor(value: uint): void; public native function get bottomScrollV(): int; public native function get caretIndex(): int; public native function get condenseWhite(): Boolean; public native function set condenseWhite(value: Boolean): void; public native function get defaultTextFormat(): TextFormat; public native function set defaultTextFormat(format: TextFormat): void; public native function get embedFonts(): Boolean; public native function set embedFonts(value: Boolean): void; public native function get gridFitType(): String; public native function set gridFitType(gridFitType: String): void; public native function get htmlText(): String; public native function set htmlText(value: String): void; public native function get length(): int; public native function get textInteractionMode(): String; public native function get maxChars(): int; public native function set maxChars(value: int): void; public native function get maxScrollH(): int; public native function get maxScrollV(): int; public native function get mouseWheelEnabled(): Boolean; public native function set mouseWheelEnabled(value: Boolean): void; public native function get multiline(): Boolean; public native function set multiline(value: Boolean): void; public native function get numLines(): int; public native function get displayAsPassword(): Boolean; public native function set displayAsPassword(value: Boolean): void; public native function get restrict(): String; public native function set restrict(value: String): void; public native function get scrollH(): int; public native function set scrollH(value: int): void; public native function get scrollV(): int; public native function set scrollV(value: int): void; public native function get selectable(): Boolean; public native function set selectable(value: Boolean): void; public function get selectedText(): String { return text.substring(selectionBeginIndex, selectionEndIndex); } public native function get selectionBeginIndex(): int; public native function get selectionEndIndex(): int; public native function get sharpness(): Number; public native function set sharpness(value: Number): void; public native function get styleSheet(): StyleSheet; public native function set styleSheet(value: StyleSheet): void; public native function get text(): String; public native function set text(value: String): void; public native function get textColor(): uint; public native function set textColor(value: uint): void; public native function get textHeight(): Number; public native function get textWidth(): Number; public native function get thickness(): Number; public native function set thickness(value: Number): void; public native function get type(): String; public native function set type(value: String): void; public native function get wordWrap(): Boolean; public native function set wordWrap(value: Boolean): void; public native function get useRichTextClipboard(): Boolean; public native function set useRichTextClipboard(value: Boolean): void; public function appendText(newText: String): void { var beginIndex: uint = text.length; replaceText(beginIndex, beginIndex, newText); } public native function getCharBoundaries(charIndex: int): Rectangle; public native function getCharIndexAtPoint(x: Number, y: Number): int; public native function getFirstCharInParagraph(charIndex: int): int; public native function getLineIndexAtPoint(x: Number, y: Number): int; public native function getLineIndexOfChar(charIndex: int): int; public native function getLineLength(lineIndex: int): int; public native function getLineMetrics(lineIndex: int): TextLineMetrics; public native function getLineOffset(lineIndex: int): int; public native function getLineText(lineIndex: int): String; public native function getParagraphLength(charIndex: int): int; public native function getTextFormat(beginIndex: int = -1, endIndex: int = -1): TextFormat; public native function getTextRuns(beginIndex: int = 0, endIndex: int = 2147483647): Array; public native function getRawText(): String; public function getXMLText(beginIndex: int = 0, endIndex: int = 2147483647): String { notImplemented("getXMLText"); return ""; } public function insertXMLText(beginIndex: int, endIndex: int, richText: String, pasting: Boolean = false): void { notImplemented("insertXMLText"); } public native function replaceSelectedText(value: String): void; public native function replaceText(beginIndex: int, endIndex: int, newText: String): void; public native function setSelection(beginIndex: int, endIndex: int): void; public native function setTextFormat(format: TextFormat, beginIndex: int = -1, endIndex: int = -1): void; public native function getImageReference(id: String): DisplayObject; internal function copyRichText(): String { notImplemented("copyRichText"); return ""; } internal function pasteRichText(richText: String): Boolean { notImplemented("pasteRichText"); return false; } } }
Add license header to flash/text/TextField
Add license header to flash/text/TextField
ActionScript
apache-2.0
mbebenita/shumway,mbebenita/shumway,yurydelendik/shumway,tschneidereit/shumway,mbebenita/shumway,mbebenita/shumway,tschneidereit/shumway,mbebenita/shumway,mozilla/shumway,tschneidereit/shumway,yurydelendik/shumway,tschneidereit/shumway,tschneidereit/shumway,yurydelendik/shumway,mozilla/shumway,yurydelendik/shumway,tschneidereit/shumway,mbebenita/shumway,mozilla/shumway,mozilla/shumway,tschneidereit/shumway,yurydelendik/shumway,mozilla/shumway,yurydelendik/shumway,tschneidereit/shumway,mbebenita/shumway,mozilla/shumway,mbebenita/shumway,mozilla/shumway,yurydelendik/shumway,yurydelendik/shumway,mozilla/shumway
d112866720ae596ff8295f171476bc61636fe7de
src/flails/resource/Record.as
src/flails/resource/Record.as
/** * Copyright (c) 2009 Lance Carlson * See LICENSE for full license information. */ package flails.resource { import flash.events.EventDispatcher; dynamic public class Record extends EventDispatcher { public function Record(attributes:Object=null) { trace("initializing Record with attributes " + attributes) if (attributes != null) { setAttributes(attributes); } } public function setAttributes(attributes:Object):void { trace("setting the record's attributes"); for (var key:String in attributes) { trace("setting " + key + " with " + attributes[key]); this[key] = attributes[key]; } } /* public function resource():Resource { return new Resource(type, this.constructor); } public function save():Request { return resource().update(this.id, sanitized()); } private function sanitized():Record { var sanitizedRecord:Record = this; delete sanitizedRecord["id"]; deleteBelongsToAssociations(sanitizedRecord); return sanitizedRecord; } private function belongsToKeys():Array { var belongsToKeys:Array = new Array; for (var key:String in this) { var matches:Array = key.match(/^(.*)_id$/); if (matches != null) { belongsToKeys.push(String(matches[1])); } } return belongsToKeys; } private function setBelongsToAssociations():void { belongsToKeys().forEach(function(belongsToKey:String, index:int, array:Array):void { this[belongsToKey] = function():Request { return Resource.forName(belongsToKey).findByID(this[belongsToKey + "_id"]); } }); } private function deleteBelongsToAssociations(record:Record):Record { belongsToKeys().forEach(function(belongsToKey:String, index:int, array:Array):void { delete record[belongsToKey]; }); return record; } */ /* public static function create(json:Object):Object { var type:String = findType(json); var record:Object = json[type]; record = assignRequiredAttributes(record, type); record = assignFunctions(record); record = assignBelongsToAssociations(record); return record; }*/ /* private static function sanitizeObject(unsanitized:Object):Object { delete unsanitized._type; delete unsanitized._model; delete unsanitized.save; unsanitized = deleteBelongsToAssociations(unsanitized); return unsanitized; } */ /* private static function camelize(lowerCaseAndUnderscoredWord:String):String { var firstLetterLowerCase:String = lowerCaseAndUnderscoredWord.charAt(0).toLowerCase() + lowerCaseAndUnderscoredWord.slice(1); return firstLetterLowerCase.replace(/_(.)/g, function():String { return arguments[1].toUpperCase(); }); }*/ /* public function updateAttributes(attributes:Object):Request { return this["model"].update(this["id"], attributes); return new Request("post"); }*/ } }
/** * Copyright (c) 2009 Lance Carlson * See LICENSE for full license information. */ package flails.resource { import flash.events.EventDispatcher; dynamic public class Record extends EventDispatcher { public function Record(attributes:Object=null) { trace("initializing Record with attributes " + attributes) if (attributes != null) { setAttributes(attributes); } } public function setAttributes(attributes:Object):Record { trace("setting the record's attributes"); for (var key:String in attributes) { trace("setting " + key + " with " + attributes[key]); this[key] = attributes[key]; } return this; } /* public function resource():Resource { return new Resource(type, this.constructor); } public function save():Request { return resource().update(this.id, sanitized()); } private function sanitized():Record { var sanitizedRecord:Record = this; delete sanitizedRecord["id"]; deleteBelongsToAssociations(sanitizedRecord); return sanitizedRecord; } private function belongsToKeys():Array { var belongsToKeys:Array = new Array; for (var key:String in this) { var matches:Array = key.match(/^(.*)_id$/); if (matches != null) { belongsToKeys.push(String(matches[1])); } } return belongsToKeys; } private function setBelongsToAssociations():void { belongsToKeys().forEach(function(belongsToKey:String, index:int, array:Array):void { this[belongsToKey] = function():Request { return Resource.forName(belongsToKey).findByID(this[belongsToKey + "_id"]); } }); } private function deleteBelongsToAssociations(record:Record):Record { belongsToKeys().forEach(function(belongsToKey:String, index:int, array:Array):void { delete record[belongsToKey]; }); return record; } */ /* public static function create(json:Object):Object { var type:String = findType(json); var record:Object = json[type]; record = assignRequiredAttributes(record, type); record = assignFunctions(record); record = assignBelongsToAssociations(record); return record; }*/ /* private static function sanitizeObject(unsanitized:Object):Object { delete unsanitized._type; delete unsanitized._model; delete unsanitized.save; unsanitized = deleteBelongsToAssociations(unsanitized); return unsanitized; } */ /* private static function camelize(lowerCaseAndUnderscoredWord:String):String { var firstLetterLowerCase:String = lowerCaseAndUnderscoredWord.charAt(0).toLowerCase() + lowerCaseAndUnderscoredWord.slice(1); return firstLetterLowerCase.replace(/_(.)/g, function():String { return arguments[1].toUpperCase(); }); }*/ /* public function updateAttributes(attributes:Object):Request { return this["model"].update(this["id"], attributes); return new Request("post"); }*/ } }
Return the Record upon calling setAttributes().
Return the Record upon calling setAttributes().
ActionScript
mit
lancecarlson/flails,lancecarlson/flails
48fbe0a66fee0291a83faf87c61755e2aba2d5b8
test/trace/values.as
test/trace/values.as
// This ActionScript file defines a list of values that are considered // important for checking various ActionScript operations. // It defines 2 variables: // - "values": The array of values to be checked // - "names": The array of corresponding string representations for values. // It's suggested to use these instead of using values directly to // avoid spurious toString and valueOf calls. printall = new Object (); printall.valueOf = function () { trace ("valueOf called"); return this; }; printall.toString = function () { trace ("toString called"); return this; }; printtostring = new Object (); printtostring.toString = function () { trace ("toString called with " + arguments); return this; }; printvalueof = new Object (); printvalueof.valueOf = function () { trace ("valueOf called with " + arguments); return this; }; nothing = new Object (); nothing.__proto__ = undefined; values = [ undefined, null, true, false, 0, 1, 0.5, -1, -0.5, Infinity, -Infinity, NaN, "", "0", "-0", "0.0", "1", "Hello World!", "true", "_level0", "äöü", this, new Object (), new Date (), new String (), Function, printall, printtostring, printvalueof, nothing ]; var l = values.length; var v = function () { trace (this.nr + ": valueOf!"); return this.v; }; var s = function () { trace (this.nr + ": toString!"); return this.v; }; for (i = 0; i < l; i++) { var o = new Object (); o.nr = i; o.valueOf = v; o.toString = s; o.v = values[i]; values.push (o); }; names = []; for (i = 0; i < values.length; i++) { names[i] = "(" + i + ") " + values[i] + " (" + typeof (values[i]) + ")"; };
// This ActionScript file defines a list of values that are considered // important for checking various ActionScript operations. // It defines 2 variables: // - "values": The array of values to be checked // - "names": The array of corresponding string representations for values. // It's suggested to use these instead of using values directly to // avoid spurious toString and valueOf calls. printall = new Object (); printall.valueOf = function () { trace ("valueOf called"); return this; }; printall.toString = function () { trace ("toString called"); return this; }; printtostring = new Object (); printtostring.toString = function () { trace ("toString called with " + arguments); return this; }; printvalueof = new Object (); printvalueof.valueOf = function () { trace ("valueOf called with " + arguments); return this; }; nothing = new Object (); nothing.__proto__ = undefined; values = [ undefined, null, true, false, 0, 1, 0.5, -1, -0.5, Infinity, -Infinity, NaN, "", "0", "-0", "0.0", "1", "Hello World!", "true", "_level0", "äöü", this, new Object (), new Date (1239752134235.94), new String (), Function, printall, printtostring, printvalueof, nothing ]; var l = values.length; var v = function () { trace (this.nr + ": valueOf!"); return this.v; }; var s = function () { trace (this.nr + ": toString!"); return this.v; }; for (i = 0; i < l; i++) { var o = new Object (); o.nr = i; o.valueOf = v; o.toString = s; o.v = values[i]; values.push (o); }; names = []; for (i = 0; i < values.length; i++) { names[i] = "(" + i + ") " + values[i] + " (" + typeof (values[i]) + ")"; };
Change values.as to use a specific date
Change values.as to use a specific date
ActionScript
lgpl-2.1
freedesktop-unofficial-mirror/swfdec__swfdec,mltframework/swfdec,mltframework/swfdec,freedesktop-unofficial-mirror/swfdec__swfdec,freedesktop-unofficial-mirror/swfdec__swfdec
51cf6b65bec7c91b21172fff6224855f503e01fa
src/as/com/threerings/flex/FlexWrapper.as
src/as/com/threerings/flex/FlexWrapper.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 mx.core.UIComponent; /** * Wraps a non-Flex component for use in Flex. */ public class FlexWrapper extends UIComponent { public function FlexWrapper (object :DisplayObject) { // don't capture mouse events in this wrapper mouseEnabled = false; addChild(object); width = object.width; height = object.height; } } }
// // $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 mx.core.UIComponent; /** * Wraps a non-Flex component for use in Flex. */ public class FlexWrapper extends UIComponent { public function FlexWrapper (object :DisplayObject, inheritSize :Boolean = false) { // don't capture mouse events in this wrapper mouseEnabled = false; addChild(object); if (inheritSize) { width = object.width; height = object.height; } } } }
Make this optional, and not the default. Turns out a bunch of shit makes the wrapper size a little bigger, and some things seem to freak out when the wrapper has a size, even when includeInLayout=false. Flex you very much.
Make this optional, and not the default. Turns out a bunch of shit makes the wrapper size a little bigger, and some things seem to freak out when the wrapper has a size, even when includeInLayout=false. Flex you very much. git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@616 ed5b42cb-e716-0410-a449-f6a68f950b19
ActionScript
lgpl-2.1
threerings/nenya,threerings/nenya
7acdfe2922f4f7eb5cd5db6ae4e664b7f10fc48c
src/CameraMan.as
src/CameraMan.as
package { import flash.display.Sprite; import flash.display.StageScaleMode; import flash.display.StageAlign; import flash.geom.Point; import flash.external.ExternalInterface; import flash.display.Bitmap; import flash.display.BitmapData; import flash.media.Camera; import flash.media.Video; import flash.utils.ByteArray; import mx.graphics.codec.JPEGEncoder; import flash.events.Event; import flash.events.HTTPStatusEvent; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.net.URLLoader; import flash.net.URLRequest; public class CameraMan extends Sprite { private var videoface:Video; private var cam:Camera; private var photo:BitmapData; private var sendto:String; private var movieSize:Point; public function CameraMan() { stage.align = StageAlign.TOP_LEFT; trace("START ME UP"); this.loaderInfo.addEventListener("init", init); if (ExternalInterface.available) { ExternalInterface.addCallback("takePhoto", takePhoto); ExternalInterface.addCallback("sendPhoto", sendPhoto); } } public function init(event:Event) : void { trace("initizing"); sendto = this.loaderInfo.parameters.sendto; trace("Sending to " + sendto); movieSize = new Point(this.loaderInfo.width, this.loaderInfo.height); trace("Movie size is " + this.loaderInfo.width + ", " + this.loaderInfo.height); this.initCamera(); } public function initCamera() : void { videoface = new Video(movieSize.x, movieSize.y); this.addChild(videoface); trace("Video is " + videoface.videoWidth + ", " + videoface.videoHeight); cam = Camera.getCamera(); cam.setMode(movieSize.x, movieSize.y, 15); videoface.attachCamera(cam); trace("Video w/ camera is " + videoface.videoWidth + ", " + videoface.videoHeight); } public function takePhoto() : void { // freeze image try { photo = new BitmapData(videoface.videoWidth, videoface.videoHeight, false); photo.draw(videoface); // Swap the video for the captured bitmap. var bitty:Bitmap = new Bitmap(photo); this.addChild(bitty); this.removeChild(videoface); } catch(err:Error) { trace(err.name + " " + err.message); } if (ExternalInterface.available) { ExternalInterface.call('cameraman._tookPhoto'); } } public function sendPhoto() : void { try { // produce image file var peggy:JPEGEncoder = new JPEGEncoder(75.0); var image:ByteArray = peggy.encode(photo); // send image file to server var req:URLRequest = new URLRequest(); req.url = this.sendto; req.method = "POST"; req.contentType = peggy.contentType; req.data = image; var http:URLLoader = new URLLoader(); http.addEventListener("complete", sentPhoto); http.addEventListener("ioError", sendingIOError); http.addEventListener("securityError", sendingSecurityError); http.addEventListener("httpStatus", sendingHttpStatus); http.load(req); } catch(err:Error) { trace(err.name + " " + err.message); } } public function sendingHttpStatus(event:HTTPStatusEvent) : void { trace("HTTPStatus: " + event.status + " " + event.target); } public function sendingIOError(event:IOErrorEvent) : void { trace("IOError: " + event.type + " " + event.text + " " + event.target + " " + event.target.bytesLoaded); } public function sendingSecurityError(event:SecurityErrorEvent) : void { trace("SecurityError: " + event.text + " " + event.target); } public function sentPhoto(event:Event) : void { var url:String = event.target.data; if (ExternalInterface.available) ExternalInterface.call('cameraman._sentPhoto', url); } } }
package { import flash.display.Sprite; import flash.display.StageScaleMode; import flash.display.StageAlign; import flash.geom.Point; import flash.external.ExternalInterface; import flash.display.Bitmap; import flash.display.BitmapData; import flash.media.Camera; import flash.media.Video; import flash.utils.ByteArray; import mx.graphics.codec.JPEGEncoder; import flash.events.Event; import flash.events.HTTPStatusEvent; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.net.URLLoader; import flash.net.URLRequest; public class CameraMan extends Sprite { private var videoface:Video; private var cam:Camera; private var photo:BitmapData; private var sendto:String; private var movieSize:Point; public function CameraMan() { stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; trace("START ME UP"); this.loaderInfo.addEventListener("init", init); if (ExternalInterface.available) { ExternalInterface.addCallback("takePhoto", takePhoto); ExternalInterface.addCallback("sendPhoto", sendPhoto); } } public function init(event:Event) : void { trace("initizing"); sendto = this.loaderInfo.parameters.sendto; movieSize = new Point(this.loaderInfo.width, this.loaderInfo.height); trace("Movie size is " + this.loaderInfo.width + ", " + this.loaderInfo.height); cam = Camera.getCamera(); cam.setMode(movieSize.x, movieSize.y, 15); trace("Camera size is " + cam.width + ", " + cam.height); videoface = new Video(cam.width, cam.height); videoface.attachCamera(cam); this.addChild(videoface); } public function takePhoto() : void { // freeze image try { photo = new BitmapData(videoface.videoWidth, videoface.videoHeight, false); photo.draw(videoface); // Swap the video for the captured bitmap. var bitty:Bitmap = new Bitmap(photo); this.addChild(bitty); this.removeChild(videoface); } catch(err:Error) { trace(err.name + " " + err.message); } if (ExternalInterface.available) { ExternalInterface.call('cameraman._tookPhoto'); } } public function sendPhoto() : void { try { // produce image file var peggy:JPEGEncoder = new JPEGEncoder(75.0); var image:ByteArray = peggy.encode(photo); // send image file to server var req:URLRequest = new URLRequest(); req.url = this.sendto; req.method = "POST"; req.contentType = peggy.contentType; req.data = image; var http:URLLoader = new URLLoader(); http.addEventListener("complete", sentPhoto); http.addEventListener("ioError", sendingIOError); http.addEventListener("securityError", sendingSecurityError); http.addEventListener("httpStatus", sendingHttpStatus); http.load(req); } catch(err:Error) { trace(err.name + " " + err.message); } } public function sendingHttpStatus(event:HTTPStatusEvent) : void { trace("HTTPStatus: " + event.status + " " + event.target); } public function sendingIOError(event:IOErrorEvent) : void { trace("IOError: " + event.type + " " + event.text + " " + event.target + " " + event.target.bytesLoaded); } public function sendingSecurityError(event:SecurityErrorEvent) : void { trace("SecurityError: " + event.text + " " + event.target); } public function sentPhoto(event:Event) : void { var url:String = event.target.data; if (ExternalInterface.available) ExternalInterface.call('cameraman._sentPhoto', url); } } }
Adjust how the video and camera are created to reality
Adjust how the video and camera are created to reality
ActionScript
mit
markpasc/cameraman
2d5d4ec1f006d17da2e28bf2ba12c5c9a15c8c9e
src/com/google/analytics/core/DocumentInfo.as
src/com/google/analytics/core/DocumentInfo.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]>. */ package com.google.analytics.core { import com.google.analytics.external.AdSenseGlobals; import com.google.analytics.utils.Environment; import com.google.analytics.utils.Variables; import com.google.analytics.v4.Configuration; /** * The DocumentInfo class. */ public class DocumentInfo { private var _config:Configuration; private var _info:Environment; private var _adSense:AdSenseGlobals; private var _pageURL:String; private var _utmr:String; /** * Creates a new DocumentInfo instance. */ public function DocumentInfo( config:Configuration, info:Environment, formatedReferrer:String, pageURL:String = null, adSense:AdSenseGlobals = null ) { _config = config; _info = info; _utmr = formatedReferrer; _pageURL = pageURL; _adSense = adSense; } /** * Generates hit id for revenue per page tracking for AdSense. * <p>This method first examines the DOM for existing hid.</p> * <p>If there is already a hid in DOM, then this method will return the existing hid.</p> * <p>If there isn't any hid in DOM, then this method will generate a new hid, and both stores it in DOM, and returns it to the caller.</p> * @return hid used by AdSense for revenue per page tracking */ private function _generateHitId():Number { var hid:Number; //have hid in DOM if( _adSense.hid && (_adSense.hid != "") ) { hid = Number( _adSense.hid ); } //doesn't have hid in DOM else { hid = Math.round( Math.random() * 0x7fffffff ); _adSense.hid = String( hid ); } return hid; } /** * This method will collect and return the page URL information based on * the page URL specified by the user if present. If there is no parameter, * the URL of the HTML page embedding the SWF will be sent. If * ExternalInterface.avaliable=false, a default of "/" will be used. * * @private * @param {String} opt_pageURL (Optional) User-specified Page URL to assign * metrics to at the back-end. * * @return {String} Final page URL to assign metrics to at the back-end. */ private function _renderPageURL( pageURL:String = "" ):String { var pathname:String = _info.locationPath; var search:String = _info.locationSearch; if( !pageURL || (pageURL == "") ) { pageURL = pathname + unescape( search ); if ( pageURL == "" ) { pageURL = "/"; } } return pageURL; } /** * Page title, which is a URL-encoded string. * <p><b>Example :</b></p> * <pre class="prettyprint">utmdt=analytics%20page%20test</pre> */ public function get utmdt():String { return _info.documentTitle; } /** * Hit id for revenue per page tracking for AdSense. * <p><b>Example :<b><code class="prettyprint">utmhid=2059107202</code></p> */ public function get utmhid():String { return String( _generateHitId() ); } /** * Referral, complete URL. * <p><b>Example :<b><code class="prettyprint">utmr=http://www.example.com/aboutUs/index.php?var=selected</code></p> */ public function get utmr():String { if( !_utmr ) { return "-"; } return _utmr; } /** * Page request of the current page. * <p><b>Example :<b><code class="prettyprint">utmp=/testDirectory/myPage.html</code></p> */ public function get utmp():String { return _renderPageURL( _pageURL ); } /** * Returns a Variables object representation. * @return a Variables object representation. */ public function toVariables():Variables { var variables:Variables = new Variables(); variables.URIencode = true; if( _config.detectTitle && ( utmdt != "") ) { variables.utmdt = utmdt; } variables.utmhid = utmhid; variables.utmr = utmr; variables.utmp = utmp; 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]>. */ package com.google.analytics.core { import com.google.analytics.external.AdSenseGlobals; import com.google.analytics.utils.Environment; import com.google.analytics.utils.Variables; import com.google.analytics.v4.Configuration; /** * The DocumentInfo class. */ public class DocumentInfo { private var _config:Configuration; private var _info:Environment; private var _adSense:AdSenseGlobals; private var _pageURL:String; private var _utmr:String; /** * Creates a new DocumentInfo instance. */ public function DocumentInfo( config:Configuration, info:Environment, formatedReferrer:String, pageURL:String = null, adSense:AdSenseGlobals = null ) { _config = config; _info = info; _utmr = formatedReferrer; _pageURL = pageURL; _adSense = adSense; } /** * Generates hit id for revenue per page tracking for AdSense. * <p>This method first examines the DOM for existing hid.</p> * <p>If there is already a hid in DOM, then this method will return the existing hid.</p> * <p>If there isn't any hid in DOM, then this method will generate a new hid, and both stores it in DOM, and returns it to the caller.</p> * @return hid used by AdSense for revenue per page tracking */ private function _generateHitId():Number { var hid:Number; //have hid in DOM if( _adSense.hid && (_adSense.hid != "") ) { hid = Number( _adSense.hid ); } //doesn't have hid in DOM else { hid = Math.round( Math.random() * 0x7fffffff ); _adSense.hid = String( hid ); } return hid; } /** * This method will collect and return the page URL information based on * the page URL specified by the user if present. If there is no parameter, * the URL of the HTML page embedding the SWF will be sent. If * ExternalInterface.avaliable=false, a default of "/" will be used. * * @private * @param {String} opt_pageURL (Optional) User-specified Page URL to assign * metrics to at the back-end. * * @return {String} Final page URL to assign metrics to at the back-end. */ private function _renderPageURL( pageURL:String = "" ):String { var pathname:String = _info.locationPath; var search:String = _info.locationSearch; if( !pageURL || (pageURL == "") ) { pageURL = pathname + unescape( search ); if ( pageURL == "" ) { pageURL = "/"; } } return pageURL; } /** * Page title, which is a URL-encoded string. * <p><b>Example :</b></p> * <pre class="prettyprint">utmdt=analytics%20page%20test</pre> */ public function get utmdt():String { return _info.documentTitle; } /** * Hit id for revenue per page tracking for AdSense. * <p><b>Example :</b><code class="prettyprint">utmhid=2059107202</code></p> */ public function get utmhid():String { return String( _generateHitId() ); } /** * Referral, complete URL. * <p><b>Example :</b><code class="prettyprint">utmr=http://www.example.com/aboutUs/index.php?var=selected</code></p> */ public function get utmr():String { if( !_utmr ) { return "-"; } return _utmr; } /** * Page request of the current page. * <p><b>Example :</b><code class="prettyprint">utmp=/testDirectory/myPage.html</code></p> */ public function get utmp():String { return _renderPageURL( _pageURL ); } /** * Returns a Variables object representation. * @return a Variables object representation. */ public function toVariables():Variables { var variables:Variables = new Variables(); variables.URIencode = true; if( _config.detectTitle && ( utmdt != "") ) { variables.utmdt = utmdt; } variables.utmhid = utmhid; variables.utmr = utmr; variables.utmp = utmp; 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(); } } }
fix comment for asdoc
fix comment for asdoc
ActionScript
apache-2.0
minimedj/gaforflash,minimedj/gaforflash,nsdevaraj/gaforflash,nsdevaraj/gaforflash
2428c5fa51f469bdd7f7deb5660bad22fed5784e
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 com.google.analytics.core.ga_internal; import com.google.analytics.debug.DebugConfiguration; import com.google.analytics.external.HTMLDOM; import core.strings.userAgent; import core.uri; 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:String; 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 { _protocol = ""; if( _url != "" ) { var url:uri = new uri( _url ); _protocol = url.scheme; } } /** * 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 == "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 == "http") || (protocol == "https") ) { var url:uri = new uri( _url.toLowerCase() ); return url.host; } if( protocol == "file" ) { return "localhost"; } return ""; } /** * Indicates if the application is running in AIR. */ public function isAIR():Boolean { 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():String { 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 com.google.analytics.core.ga_internal; import com.google.analytics.debug.DebugConfiguration; import com.google.analytics.external.HTMLDOM; import core.strings.userAgent; import core.uri; import core.version; 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:String; 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:core.version; if( app == "" ) { if( isAIR() ) { app = "AIR"; } else { app = "Flash"; } } if( version == "" ) { v = flashVersion; } else { v = getVersionFromString( version ); } _url = url; _appName = app; _appVersion = v; _debug = debug; _dom = dom; } /** * @private */ private function _findProtocol():void { _protocol = ""; if( _url != "" ) { var url:uri = new uri( _url ); _protocol = url.scheme; } } /** * 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 == "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 == "http") || (protocol == "https") ) { var url:uri = new uri( _url.toLowerCase() ); return url.host; } if( protocol == "file" ) { return "localhost"; } return ""; } /** * Indicates if the application is running in AIR. */ public function isAIR():Boolean { 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 = getVersionFromString( 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():String { 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; } } }
replace class Version by core.version
replace class Version by core.version
ActionScript
apache-2.0
mrthuanvn/gaforflash,Vigmar/gaforflash,jeremy-wischusen/gaforflash,Vigmar/gaforflash,drflash/gaforflash,drflash/gaforflash,Miyaru/gaforflash,DimaBaliakin/gaforflash,jeremy-wischusen/gaforflash,soumavachakraborty/gaforflash,DimaBaliakin/gaforflash,soumavachakraborty/gaforflash,jisobkim/gaforflash,dli-iclinic/gaforflash,Miyaru/gaforflash,jisobkim/gaforflash,mrthuanvn/gaforflash,dli-iclinic/gaforflash
64cefe66a948045f02e48ef6a0d77097b52c3760
src/org/mangui/chromeless/ChromelessPlayer.as
src/org/mangui/chromeless/ChromelessPlayer.as
package org.mangui.chromeless { import flash.net.URLStream; import org.mangui.hls.model.Level; import org.mangui.hls.*; import org.mangui.hls.utils.*; import flash.display.*; import flash.events.*; import flash.external.ExternalInterface; import flash.geom.Rectangle; import flash.media.Video; import flash.media.SoundTransform; import flash.media.StageVideo; import flash.media.StageVideoAvailability; import flash.utils.setTimeout; // import com.sociodox.theminer.*; public class ChromelessPlayer extends Sprite { /** reference to the framework. **/ private var _hls : HLS; /** Sheet to place on top of the video. **/ private var _sheet : Sprite; /** Reference to the stage video element. **/ private var _stageVideo : StageVideo = null; /** Reference to the video element. **/ private var _video : Video = null; /** Video size **/ private var _videoWidth : int = 0; private var _videoHeight : int = 0; /** current media position */ private var _media_position : Number; private var _duration : Number; /** URL autoload feature */ private var _autoLoad : Boolean = false; /** Initialization. **/ public function ChromelessPlayer() { // Set stage properties stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; stage.fullScreenSourceRect = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); stage.addEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY, _onStageVideoState); stage.addEventListener(Event.RESIZE, _onStageResize); // Draw sheet for catching clicks _sheet = new Sprite(); _sheet.graphics.beginFill(0x000000, 0); _sheet.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight); _sheet.addEventListener(MouseEvent.CLICK, _clickHandler); _sheet.buttonMode = true; addChild(_sheet); // Connect getters to JS. ExternalInterface.addCallback("getLevel", _getLevel); ExternalInterface.addCallback("getLevels", _getLevels); ExternalInterface.addCallback("getAutoLevel", _getAutoLevel); ExternalInterface.addCallback("getMetrics", _getMetrics); ExternalInterface.addCallback("getDuration", _getDuration); ExternalInterface.addCallback("getPosition", _getPosition); ExternalInterface.addCallback("getPlaybackState", _getPlaybackState); ExternalInterface.addCallback("getSeekState", _getSeekState); ExternalInterface.addCallback("getType", _getType); ExternalInterface.addCallback("getmaxBufferLength", _getmaxBufferLength); ExternalInterface.addCallback("getminBufferLength", _getminBufferLength); ExternalInterface.addCallback("getlowBufferLength", _getlowBufferLength); ExternalInterface.addCallback("getbufferLength", _getbufferLength); ExternalInterface.addCallback("getLogDebug", _getLogDebug); ExternalInterface.addCallback("getLogDebug2", _getLogDebug2); ExternalInterface.addCallback("getCapLeveltoStage", _getCapLeveltoStage); ExternalInterface.addCallback("getflushLiveURLCache", _getflushLiveURLCache); ExternalInterface.addCallback("getstartFromLevel", _getstartFromLevel); ExternalInterface.addCallback("getseekFromLowestLevel", _getseekFromLevel); ExternalInterface.addCallback("getJSURLStream", _getJSURLStream); ExternalInterface.addCallback("getPlayerVersion", _getPlayerVersion); ExternalInterface.addCallback("getAudioTrackList", _getAudioTrackList); ExternalInterface.addCallback("getAudioTrackId", _getAudioTrackId); // Connect calls to JS. ExternalInterface.addCallback("playerLoad", _load); ExternalInterface.addCallback("playerPlay", _play); ExternalInterface.addCallback("playerPause", _pause); ExternalInterface.addCallback("playerResume", _resume); ExternalInterface.addCallback("playerSeek", _seek); ExternalInterface.addCallback("playerStop", _stop); ExternalInterface.addCallback("playerVolume", _volume); ExternalInterface.addCallback("playerSetLevel", _setLevel); ExternalInterface.addCallback("playerSmoothSetLevel", _smoothSetLevel); ExternalInterface.addCallback("playerSetmaxBufferLength", _setmaxBufferLength); ExternalInterface.addCallback("playerSetminBufferLength", _setminBufferLength); ExternalInterface.addCallback("playerSetlowBufferLength", _setlowBufferLength); ExternalInterface.addCallback("playerSetflushLiveURLCache", _setflushLiveURLCache); ExternalInterface.addCallback("playerSetstartFromLevel", _setstartFromLevel); ExternalInterface.addCallback("playerSetseekFromLevel", _setseekFromLevel); ExternalInterface.addCallback("playerSetLogDebug", _setLogDebug); ExternalInterface.addCallback("playerSetLogDebug2", _setLogDebug2); ExternalInterface.addCallback("playerCapLeveltoStage", _setCapLeveltoStage); ExternalInterface.addCallback("playerSetAudioTrack", _setAudioTrack); ExternalInterface.addCallback("playerSetJSURLStream", _setJSURLStream); setTimeout(_pingJavascript, 50); }; /** Notify javascript the framework is ready. **/ private function _pingJavascript() : void { ExternalInterface.call("onHLSReady", ExternalInterface.objectID); }; /** Forward events from the framework. **/ private function _completeHandler(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onComplete"); } }; private function _errorHandler(event : HLSEvent) : void { if (ExternalInterface.available) { var hlsError : HLSError = event.error; ExternalInterface.call("onError", hlsError.code, hlsError.url, hlsError.msg); } }; private function _fragmentHandler(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onFragment", event.metrics.bandwidth, event.metrics.level, stage.stageWidth); } }; private function _manifestHandler(event : HLSEvent) : void { _duration = event.levels[_hls.startlevel].duration; if (_autoLoad) { _play(); } if (ExternalInterface.available) { ExternalInterface.call("onManifest", _duration); } }; private function _mediaTimeHandler(event : HLSEvent) : void { _duration = event.mediatime.duration; _media_position = event.mediatime.position; if (ExternalInterface.available) { ExternalInterface.call("onPosition", event.mediatime.position, event.mediatime.duration, event.mediatime.live_sliding,event.mediatime.buffer, event.mediatime.program_date); } var videoWidth : int = _video ? _video.videoWidth : _stageVideo.videoWidth; var videoHeight : int = _video ? _video.videoHeight : _stageVideo.videoHeight; if (videoWidth && videoHeight) { var changed : Boolean = _videoWidth != videoWidth || _videoHeight != videoHeight; if (changed) { _videoHeight = videoHeight; _videoWidth = videoWidth; _resize(); if (ExternalInterface.available) { ExternalInterface.call("onVideoSize", _videoWidth, _videoHeight); } } } }; private function _stateHandler(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onState", event.state); } }; private function _levelSwitchHandler(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onSwitch", event.level); } }; private function _audioTracksListChange(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onAudioTracksListChange", _getAudioTrackList()); } } private function _audioTrackChange(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onAudioTrackChange", event.audioTrack); } } /** Javascript getters. **/ private function _getLevel() : int { return _hls.level; }; private function _getLevels() : Vector.<Level> { return _hls.levels; }; private function _getAutoLevel() : Boolean { return _hls.autolevel; }; private function _getMetrics() : Object { return _hls.metrics; }; private function _getDuration() : Number { return _duration; }; private function _getPosition() : Number { return _hls.position; }; private function _getPlaybackState() : String { return _hls.playbackState; }; private function _getSeekState() : String { return _hls.seekState; }; private function _getType() : String { return _hls.type; }; private function _getbufferLength() : Number { return _hls.bufferLength; }; private function _getmaxBufferLength() : Number { return HLSSettings.maxBufferLength; }; private function _getminBufferLength() : Number { return HLSSettings.minBufferLength; }; private function _getlowBufferLength() : Number { return HLSSettings.lowBufferLength; }; private function _getflushLiveURLCache() : Boolean { return HLSSettings.flushLiveURLCache; }; private function _getstartFromLevel() : int { return HLSSettings.startFromLevel; }; private function _getseekFromLevel() : int { return HLSSettings.seekFromLevel; }; private function _getLogDebug() : Boolean { return HLSSettings.logDebug; }; private function _getLogDebug2() : Boolean { return HLSSettings.logDebug2; }; private function _getCapLeveltoStage() : Boolean { return HLSSettings.capLevelToStage; }; private function _getJSURLStream() : Boolean { return (_hls.URLstream is JSURLStream); }; private function _getPlayerVersion() : Number { return 2; }; private function _getAudioTrackList() : Array { var list : Array = []; var vec : Vector.<HLSAudioTrack> = _hls.audioTracks; for (var i : Object in vec) { list.push(vec[i]); } return list; }; private function _getAudioTrackId() : int { return _hls.audioTrack; }; /** Javascript calls. **/ private function _load(url : String) : void { _hls.load(url); }; private function _play() : void { _hls.stream.play(); }; private function _pause() : void { _hls.stream.pause(); }; private function _resume() : void { _hls.stream.resume(); }; private function _seek(position : Number) : void { _hls.stream.seek(position); }; private function _stop() : void { _hls.stream.close(); }; private function _volume(percent : Number) : void { _hls.stream.soundTransform = new SoundTransform(percent / 100); }; private function _setLevel(level : int) : void { _smoothSetLevel(level); if (!isNaN(_media_position) && level != -1) { _hls.stream.seek(_media_position); } }; private function _smoothSetLevel(level : int) : void { if (level != _hls.level) { _hls.level = level; } }; private function _setmaxBufferLength(new_len : Number) : void { HLSSettings.maxBufferLength = new_len; }; private function _setminBufferLength(new_len : Number) : void { HLSSettings.minBufferLength = new_len; }; private function _setlowBufferLength(new_len : Number) : void { HLSSettings.lowBufferLength = new_len; }; private function _setflushLiveURLCache(flushLiveURLCache : Boolean) : void { HLSSettings.flushLiveURLCache = flushLiveURLCache; }; private function _setstartFromLevel(startFromLevel : int) : void { HLSSettings.startFromLevel = startFromLevel; }; private function _setseekFromLevel(seekFromLevel : int) : void { HLSSettings.seekFromLevel = seekFromLevel; }; private function _setLogDebug(debug : Boolean) : void { HLSSettings.logDebug = debug; }; private function _setLogDebug2(debug2 : Boolean) : void { HLSSettings.logDebug2 = debug2; }; private function _setCapLeveltoStage(value : Boolean) : void { HLSSettings.capLevelToStage = value; }; private function _setJSURLStream(jsURLstream : Boolean) : void { if (jsURLstream) { _hls.URLstream = JSURLStream as Class; } else { _hls.URLstream = URLStream as Class; } }; private function _setAudioTrack(val : int) : void { if (val == _hls.audioTrack) return; _hls.audioTrack = val; if (!isNaN(_media_position)) { _hls.stream.seek(_media_position); } }; /** Mouse click handler. **/ private function _clickHandler(event : MouseEvent) : void { if (stage.displayState == StageDisplayState.FULL_SCREEN_INTERACTIVE || stage.displayState == StageDisplayState.FULL_SCREEN) { stage.displayState = StageDisplayState.NORMAL; } else { stage.displayState = StageDisplayState.FULL_SCREEN; } }; /** StageVideo detector. **/ private function _onStageVideoState(event : StageVideoAvailabilityEvent) : void { var available : Boolean = (event.availability == StageVideoAvailability.AVAILABLE); _hls = new HLS(); _hls.stage = stage; _hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE, _completeHandler); _hls.addEventListener(HLSEvent.ERROR, _errorHandler); _hls.addEventListener(HLSEvent.FRAGMENT_LOADED, _fragmentHandler); _hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestHandler); _hls.addEventListener(HLSEvent.MEDIA_TIME, _mediaTimeHandler); _hls.addEventListener(HLSEvent.PLAYBACK_STATE, _stateHandler); _hls.addEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler); _hls.addEventListener(HLSEvent.AUDIO_TRACKS_LIST_CHANGE, _audioTracksListChange); _hls.addEventListener(HLSEvent.AUDIO_TRACK_CHANGE, _audioTrackChange); if (available && stage.stageVideos.length > 0) { _stageVideo = stage.stageVideos[0]; _stageVideo.viewPort = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); _stageVideo.attachNetStream(_hls.stream); } else { _video = new Video(stage.stageWidth, stage.stageHeight); addChild(_video); _video.smoothing = true; _video.attachNetStream(_hls.stream); } stage.removeEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY, _onStageVideoState); var autoLoadUrl : String = root.loaderInfo.parameters.url as String; if (autoLoadUrl != null) { _autoLoad = true; _load(autoLoadUrl); } }; private function _onStageResize(event : Event) : void { stage.fullScreenSourceRect = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); _sheet.width = stage.stageWidth; _sheet.height = stage.stageHeight; _resize(); }; private function _resize() : void { var rect : Rectangle; rect = ScaleVideo.resizeRectangle(_videoWidth, _videoHeight, stage.stageWidth, stage.stageHeight); // resize video if (_video) { _video.width = rect.width; _video.height = rect.height; _video.x = rect.x; _video.y = rect.y; } else if (_stageVideo) { _stageVideo.viewPort = rect; } } } }
package org.mangui.chromeless { import flash.net.URLStream; import org.mangui.hls.model.Level; import org.mangui.hls.*; import org.mangui.hls.utils.*; import flash.display.*; import flash.events.*; import flash.external.ExternalInterface; import flash.geom.Rectangle; import flash.media.Video; import flash.media.SoundTransform; import flash.media.StageVideo; import flash.media.StageVideoAvailability; import flash.utils.setTimeout; // import com.sociodox.theminer.*; public class ChromelessPlayer extends Sprite { /** reference to the framework. **/ protected var _hls : HLS; /** Sheet to place on top of the video. **/ protected var _sheet : Sprite; /** Reference to the stage video element. **/ protected var _stageVideo : StageVideo = null; /** Reference to the video element. **/ protected var _video : Video = null; /** Video size **/ protected var _videoWidth : int = 0; protected var _videoHeight : int = 0; /** current media position */ protected var _media_position : Number; protected var _duration : Number; /** URL autoload feature */ protected var _autoLoad : Boolean = false; /** Initialization. **/ public function ChromelessPlayer() { // Set stage properties stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; stage.fullScreenSourceRect = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); stage.addEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY, _onStageVideoState); stage.addEventListener(Event.RESIZE, _onStageResize); // Draw sheet for catching clicks _sheet = new Sprite(); _sheet.graphics.beginFill(0x000000, 0); _sheet.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight); _sheet.addEventListener(MouseEvent.CLICK, _clickHandler); _sheet.buttonMode = true; addChild(_sheet); // Connect getters to JS. ExternalInterface.addCallback("getLevel", _getLevel); ExternalInterface.addCallback("getLevels", _getLevels); ExternalInterface.addCallback("getAutoLevel", _getAutoLevel); ExternalInterface.addCallback("getMetrics", _getMetrics); ExternalInterface.addCallback("getDuration", _getDuration); ExternalInterface.addCallback("getPosition", _getPosition); ExternalInterface.addCallback("getPlaybackState", _getPlaybackState); ExternalInterface.addCallback("getSeekState", _getSeekState); ExternalInterface.addCallback("getType", _getType); ExternalInterface.addCallback("getmaxBufferLength", _getmaxBufferLength); ExternalInterface.addCallback("getminBufferLength", _getminBufferLength); ExternalInterface.addCallback("getlowBufferLength", _getlowBufferLength); ExternalInterface.addCallback("getbufferLength", _getbufferLength); ExternalInterface.addCallback("getLogDebug", _getLogDebug); ExternalInterface.addCallback("getLogDebug2", _getLogDebug2); ExternalInterface.addCallback("getCapLeveltoStage", _getCapLeveltoStage); ExternalInterface.addCallback("getflushLiveURLCache", _getflushLiveURLCache); ExternalInterface.addCallback("getstartFromLevel", _getstartFromLevel); ExternalInterface.addCallback("getseekFromLowestLevel", _getseekFromLevel); ExternalInterface.addCallback("getJSURLStream", _getJSURLStream); ExternalInterface.addCallback("getPlayerVersion", _getPlayerVersion); ExternalInterface.addCallback("getAudioTrackList", _getAudioTrackList); ExternalInterface.addCallback("getAudioTrackId", _getAudioTrackId); // Connect calls to JS. ExternalInterface.addCallback("playerLoad", _load); ExternalInterface.addCallback("playerPlay", _play); ExternalInterface.addCallback("playerPause", _pause); ExternalInterface.addCallback("playerResume", _resume); ExternalInterface.addCallback("playerSeek", _seek); ExternalInterface.addCallback("playerStop", _stop); ExternalInterface.addCallback("playerVolume", _volume); ExternalInterface.addCallback("playerSetLevel", _setLevel); ExternalInterface.addCallback("playerSmoothSetLevel", _smoothSetLevel); ExternalInterface.addCallback("playerSetmaxBufferLength", _setmaxBufferLength); ExternalInterface.addCallback("playerSetminBufferLength", _setminBufferLength); ExternalInterface.addCallback("playerSetlowBufferLength", _setlowBufferLength); ExternalInterface.addCallback("playerSetflushLiveURLCache", _setflushLiveURLCache); ExternalInterface.addCallback("playerSetstartFromLevel", _setstartFromLevel); ExternalInterface.addCallback("playerSetseekFromLevel", _setseekFromLevel); ExternalInterface.addCallback("playerSetLogDebug", _setLogDebug); ExternalInterface.addCallback("playerSetLogDebug2", _setLogDebug2); ExternalInterface.addCallback("playerCapLeveltoStage", _setCapLeveltoStage); ExternalInterface.addCallback("playerSetAudioTrack", _setAudioTrack); ExternalInterface.addCallback("playerSetJSURLStream", _setJSURLStream); setTimeout(_pingJavascript, 50); }; /** Notify javascript the framework is ready. **/ protected function _pingJavascript() : void { ExternalInterface.call("onHLSReady", ExternalInterface.objectID); }; /** Forward events from the framework. **/ protected function _completeHandler(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onComplete"); } }; protected function _errorHandler(event : HLSEvent) : void { if (ExternalInterface.available) { var hlsError : HLSError = event.error; ExternalInterface.call("onError", hlsError.code, hlsError.url, hlsError.msg); } }; protected function _fragmentHandler(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onFragment", event.metrics.bandwidth, event.metrics.level, stage.stageWidth); } }; protected function _manifestHandler(event : HLSEvent) : void { _duration = event.levels[_hls.startlevel].duration; if (_autoLoad) { _play(); } if (ExternalInterface.available) { ExternalInterface.call("onManifest", _duration); } }; protected function _mediaTimeHandler(event : HLSEvent) : void { _duration = event.mediatime.duration; _media_position = event.mediatime.position; if (ExternalInterface.available) { ExternalInterface.call("onPosition", event.mediatime.position, event.mediatime.duration, event.mediatime.live_sliding,event.mediatime.buffer, event.mediatime.program_date); } var videoWidth : int = _video ? _video.videoWidth : _stageVideo.videoWidth; var videoHeight : int = _video ? _video.videoHeight : _stageVideo.videoHeight; if (videoWidth && videoHeight) { var changed : Boolean = _videoWidth != videoWidth || _videoHeight != videoHeight; if (changed) { _videoHeight = videoHeight; _videoWidth = videoWidth; _resize(); if (ExternalInterface.available) { ExternalInterface.call("onVideoSize", _videoWidth, _videoHeight); } } } }; protected function _stateHandler(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onState", event.state); } }; protected function _levelSwitchHandler(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onSwitch", event.level); } }; protected function _audioTracksListChange(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onAudioTracksListChange", _getAudioTrackList()); } } protected function _audioTrackChange(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onAudioTrackChange", event.audioTrack); } } /** Javascript getters. **/ protected function _getLevel() : int { return _hls.level; }; protected function _getLevels() : Vector.<Level> { return _hls.levels; }; protected function _getAutoLevel() : Boolean { return _hls.autolevel; }; protected function _getMetrics() : Object { return _hls.metrics; }; protected function _getDuration() : Number { return _duration; }; protected function _getPosition() : Number { return _hls.position; }; protected function _getPlaybackState() : String { return _hls.playbackState; }; protected function _getSeekState() : String { return _hls.seekState; }; protected function _getType() : String { return _hls.type; }; protected function _getbufferLength() : Number { return _hls.bufferLength; }; protected function _getmaxBufferLength() : Number { return HLSSettings.maxBufferLength; }; protected function _getminBufferLength() : Number { return HLSSettings.minBufferLength; }; protected function _getlowBufferLength() : Number { return HLSSettings.lowBufferLength; }; protected function _getflushLiveURLCache() : Boolean { return HLSSettings.flushLiveURLCache; }; protected function _getstartFromLevel() : int { return HLSSettings.startFromLevel; }; protected function _getseekFromLevel() : int { return HLSSettings.seekFromLevel; }; protected function _getLogDebug() : Boolean { return HLSSettings.logDebug; }; protected function _getLogDebug2() : Boolean { return HLSSettings.logDebug2; }; protected function _getCapLeveltoStage() : Boolean { return HLSSettings.capLevelToStage; }; protected function _getJSURLStream() : Boolean { return (_hls.URLstream is JSURLStream); }; protected function _getPlayerVersion() : Number { return 2; }; protected function _getAudioTrackList() : Array { var list : Array = []; var vec : Vector.<HLSAudioTrack> = _hls.audioTracks; for (var i : Object in vec) { list.push(vec[i]); } return list; }; protected function _getAudioTrackId() : int { return _hls.audioTrack; }; /** Javascript calls. **/ protected function _load(url : String) : void { _hls.load(url); }; protected function _play() : void { _hls.stream.play(); }; protected function _pause() : void { _hls.stream.pause(); }; protected function _resume() : void { _hls.stream.resume(); }; protected function _seek(position : Number) : void { _hls.stream.seek(position); }; protected function _stop() : void { _hls.stream.close(); }; protected function _volume(percent : Number) : void { _hls.stream.soundTransform = new SoundTransform(percent / 100); }; protected function _setLevel(level : int) : void { _smoothSetLevel(level); if (!isNaN(_media_position) && level != -1) { _hls.stream.seek(_media_position); } }; protected function _smoothSetLevel(level : int) : void { if (level != _hls.level) { _hls.level = level; } }; protected function _setmaxBufferLength(new_len : Number) : void { HLSSettings.maxBufferLength = new_len; }; protected function _setminBufferLength(new_len : Number) : void { HLSSettings.minBufferLength = new_len; }; protected function _setlowBufferLength(new_len : Number) : void { HLSSettings.lowBufferLength = new_len; }; protected function _setflushLiveURLCache(flushLiveURLCache : Boolean) : void { HLSSettings.flushLiveURLCache = flushLiveURLCache; }; protected function _setstartFromLevel(startFromLevel : int) : void { HLSSettings.startFromLevel = startFromLevel; }; protected function _setseekFromLevel(seekFromLevel : int) : void { HLSSettings.seekFromLevel = seekFromLevel; }; protected function _setLogDebug(debug : Boolean) : void { HLSSettings.logDebug = debug; }; protected function _setLogDebug2(debug2 : Boolean) : void { HLSSettings.logDebug2 = debug2; }; protected function _setCapLeveltoStage(value : Boolean) : void { HLSSettings.capLevelToStage = value; }; protected function _setJSURLStream(jsURLstream : Boolean) : void { if (jsURLstream) { _hls.URLstream = JSURLStream as Class; } else { _hls.URLstream = URLStream as Class; } }; protected function _setAudioTrack(val : int) : void { if (val == _hls.audioTrack) return; _hls.audioTrack = val; if (!isNaN(_media_position)) { _hls.stream.seek(_media_position); } }; /** Mouse click handler. **/ protected function _clickHandler(event : MouseEvent) : void { if (stage.displayState == StageDisplayState.FULL_SCREEN_INTERACTIVE || stage.displayState == StageDisplayState.FULL_SCREEN) { stage.displayState = StageDisplayState.NORMAL; } else { stage.displayState = StageDisplayState.FULL_SCREEN; } }; /** StageVideo detector. **/ protected function _onStageVideoState(event : StageVideoAvailabilityEvent) : void { var available : Boolean = (event.availability == StageVideoAvailability.AVAILABLE); _hls = new HLS(); _hls.stage = stage; _hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE, _completeHandler); _hls.addEventListener(HLSEvent.ERROR, _errorHandler); _hls.addEventListener(HLSEvent.FRAGMENT_LOADED, _fragmentHandler); _hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestHandler); _hls.addEventListener(HLSEvent.MEDIA_TIME, _mediaTimeHandler); _hls.addEventListener(HLSEvent.PLAYBACK_STATE, _stateHandler); _hls.addEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler); _hls.addEventListener(HLSEvent.AUDIO_TRACKS_LIST_CHANGE, _audioTracksListChange); _hls.addEventListener(HLSEvent.AUDIO_TRACK_CHANGE, _audioTrackChange); if (available && stage.stageVideos.length > 0) { _stageVideo = stage.stageVideos[0]; _stageVideo.viewPort = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); _stageVideo.attachNetStream(_hls.stream); } else { _video = new Video(stage.stageWidth, stage.stageHeight); addChild(_video); _video.smoothing = true; _video.attachNetStream(_hls.stream); } stage.removeEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY, _onStageVideoState); var autoLoadUrl : String = root.loaderInfo.parameters.url as String; if (autoLoadUrl != null) { _autoLoad = true; _load(autoLoadUrl); } }; protected function _onStageResize(event : Event) : void { stage.fullScreenSourceRect = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); _sheet.width = stage.stageWidth; _sheet.height = stage.stageHeight; _resize(); }; protected function _resize() : void { var rect : Rectangle; rect = ScaleVideo.resizeRectangle(_videoWidth, _videoHeight, stage.stageWidth, stage.stageHeight); // resize video if (_video) { _video.width = rect.width; _video.height = rect.height; _video.x = rect.x; _video.y = rect.y; } else if (_stageVideo) { _stageVideo.viewPort = rect; } } } }
transform ChromelessPlayer functions to protected
transform ChromelessPlayer functions to protected
ActionScript
mpl-2.0
Corey600/flashls,aevange/flashls,stevemayhew/flashls,codex-corp/flashls,dighan/flashls,aevange/flashls,fixedmachine/flashls,School-Improvement-Network/flashls,hola/flashls,ryanhefner/flashls,aevange/flashls,Peer5/flashls,suuhas/flashls,fixedmachine/flashls,thdtjsdn/flashls,neilrackett/flashls,neilrackett/flashls,loungelogic/flashls,jlacivita/flashls,Peer5/flashls,suuhas/flashls,aevange/flashls,thdtjsdn/flashls,tedconf/flashls,Peer5/flashls,vidible/vdb-flashls,Boxie5/flashls,vidible/vdb-flashls,NicolasSiver/flashls,tedconf/flashls,mangui/flashls,Boxie5/flashls,viktorot/flashls,jlacivita/flashls,Peer5/flashls,suuhas/flashls,clappr/flashls,JulianPena/flashls,viktorot/flashls,dighan/flashls,loungelogic/flashls,ryanhefner/flashls,suuhas/flashls,NicolasSiver/flashls,stevemayhew/flashls,stevemayhew/flashls,ryanhefner/flashls,hola/flashls,School-Improvement-Network/flashls,JulianPena/flashls,mangui/flashls,codex-corp/flashls,clappr/flashls,stevemayhew/flashls,Corey600/flashls,School-Improvement-Network/flashls,viktorot/flashls,ryanhefner/flashls
ac14bd46b61f820aa31fa0157c36fec9fa6371b6
net/saqoosha/pv3d/util/Slerper.as
net/saqoosha/pv3d/util/Slerper.as
package net.saqoosha.pv3d { import org.papervision3d.core.math.Quaternion; import org.papervision3d.objects.DisplayObject3D; public class Slerper { private var _target:DisplayObject3D; private var _start:Quaternion; private var _end:Quaternion; private var _current:Quaternion; private var _alpha:Number = 0; public function Slerper(target:DisplayObject3D, start:Quaternion = null, end:Quaternion = null) { this._target = target; this._start = start; this._end = end; this._current = this._start ? this._start.clone() : new Quaternion(); this._alpha = 0; } public function get target():DisplayObject3D { return this._target; } public function set target(value:DisplayObject3D):void { this._target = value; } public function get start():Quaternion { return this._start; } public function set start(value:Quaternion):void { this._start = value; } public function get end():Quaternion { return this._end; } public function set end(value:Quaternion):void { this._end = value; } public function get alpha():Number { return this._alpha } private static var tmp:Quaternion; public function set alpha(value:Number):void { this._alpha = value; if (this._alpha == 0.0) { tmp = this._start; } else if (this._alpha == 1.0) { tmp = this._end; } else { tmp = this._current; slerp(this._start, this._end, this._alpha, this._current); } this._target.transform.copy3x3(tmp.matrix); } private static var __angle:Number; private static var __scale:Number; private static var __invscale:Number; private static var __theta:Number; private static var __invsintheta:Number; public static function slerp( qa:Quaternion, qb:Quaternion, alpha:Number, out:Quaternion = null ):Quaternion { __angle = qa.w * qb.w + qa.x * qb.x + qa.y * qb.y + qa.z * qb.z if (__angle < 0.0) { qa.x *= -1.0; qa.y *= -1.0; qa.z *= -1.0; qa.w *= -1.0; __angle *= -1.0; } if ((__angle + 1.0) > Quaternion.EPSILON) // Take the shortest path { if ((1.0 - __angle) >= Quaternion.EPSILON) // spherical interpolation { __theta = Math.acos(__angle); __invsintheta = 1.0 / Math.sin(__theta); __scale = Math.sin(__theta * (1.0-alpha)) * __invsintheta; __invscale = Math.sin(__theta * alpha) * __invsintheta; } else // linear interploation { __scale = 1.0 - alpha; __invscale = alpha; } } else // long way to go... { qb.y = -qa.y; qb.x = qa.x; qb.w = -qa.w; qb.z = qa.z; __scale = Math.sin(Math.PI * (0.5 - alpha)); __invscale = Math.sin(Math.PI * alpha); } if (out) { out.x = __scale * qa.x + __invscale * qb.x; out.y = __scale * qa.y + __invscale * qb.y; out.z = __scale * qa.z + __invscale * qb.z; out.w = __scale * qa.w + __invscale * qb.w; } else { out = new Quaternion( __scale * qa.x + __invscale * qb.x, __scale * qa.y + __invscale * qb.y, __scale * qa.z + __invscale * qb.z, __scale * qa.w + __invscale * qb.w ); } return out; } } }
package net.saqoosha.pv3d.util { import org.papervision3d.core.math.Quaternion; import org.papervision3d.objects.DisplayObject3D; public class Slerper { private var _target:DisplayObject3D; private var _start:Quaternion; private var _end:Quaternion; private var _current:Quaternion; private var _alpha:Number = 0; public function Slerper(target:DisplayObject3D, start:Quaternion = null, end:Quaternion = null) { this._target = target; this._start = start; this._end = end; this._current = this._start ? this._start.clone() : new Quaternion(); this._alpha = 0; } public function get target():DisplayObject3D { return this._target; } public function set target(value:DisplayObject3D):void { this._target = value; } public function get start():Quaternion { return this._start; } public function set start(value:Quaternion):void { this._start = value; } public function get end():Quaternion { return this._end; } public function set end(value:Quaternion):void { this._end = value; } public function get alpha():Number { return this._alpha } private static var tmp:Quaternion; public function set alpha(value:Number):void { this._alpha = value; if (this._alpha == 0.0) { tmp = this._start; } else if (this._alpha == 1.0) { tmp = this._end; } else { tmp = this._current; slerp(this._start, this._end, this._alpha, this._current); } this._target.transform.copy3x3(tmp.matrix); } private static var __angle:Number; private static var __scale:Number; private static var __invscale:Number; private static var __theta:Number; private static var __invsintheta:Number; public static function slerp( qa:Quaternion, qb:Quaternion, alpha:Number, out:Quaternion = null ):Quaternion { __angle = qa.w * qb.w + qa.x * qb.x + qa.y * qb.y + qa.z * qb.z if (__angle < 0.0) { qa.x *= -1.0; qa.y *= -1.0; qa.z *= -1.0; qa.w *= -1.0; __angle *= -1.0; } if ((__angle + 1.0) > Quaternion.EPSILON) // Take the shortest path { if ((1.0 - __angle) >= Quaternion.EPSILON) // spherical interpolation { __theta = Math.acos(__angle); __invsintheta = 1.0 / Math.sin(__theta); __scale = Math.sin(__theta * (1.0-alpha)) * __invsintheta; __invscale = Math.sin(__theta * alpha) * __invsintheta; } else // linear interploation { __scale = 1.0 - alpha; __invscale = alpha; } } else // long way to go... { qb.y = -qa.y; qb.x = qa.x; qb.w = -qa.w; qb.z = qa.z; __scale = Math.sin(Math.PI * (0.5 - alpha)); __invscale = Math.sin(Math.PI * alpha); } if (out) { out.x = __scale * qa.x + __invscale * qb.x; out.y = __scale * qa.y + __invscale * qb.y; out.z = __scale * qa.z + __invscale * qb.z; out.w = __scale * qa.w + __invscale * qb.w; } else { out = new Quaternion( __scale * qa.x + __invscale * qb.x, __scale * qa.y + __invscale * qb.y, __scale * qa.z + __invscale * qb.z, __scale * qa.w + __invscale * qb.w ); } return out; } } }
fix package.
fix package.
ActionScript
bsd-3-clause
Saqoosha/SAQAS3
12a213e1d5c84733413941a724d9eda586fc07e8
exporter/src/main/as/flump/export/Atlas.as
exporter/src/main/as/flump/export/Atlas.as
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.display.Sprite; import flash.filesystem.File; import flump.SwfTexture; public class Atlas { // The empty border size around the right and bottom edges of each texture, to prevent bleeding public static const PADDING :int = 1; public var name :String; public var targetDevice :DeviceType; public function Atlas (name :String, targetDevice :DeviceType, w :int, h :int) { this.name = name; this.targetDevice = targetDevice; _root = new Node(0, 0, w, h); } // Try to place a texture in this atlas, return true if it fit public function place (texture :SwfTexture) :Boolean { var node :Node = _root.search(texture.w + PADDING, texture.h + PADDING); if (node == null) { return false; } node.texture = texture; return true; } public function get area () :int { return _root.bounds.width * _root.bounds.height; } public function get used () :int { var used :int = 0; _root.forEach(function (n :Node) :void { used += n.bounds.width * n.bounds.height; }); return used; } public function publish (dir :File) :void { var constructed :Sprite = new Sprite(); _root.forEach(function (node :Node) :void { var tex :SwfTexture = node.texture; var sprite :Sprite = new Sprite(); sprite.scaleX = sprite.scaleY = tex.scale; constructed.addChild(tex.holder); tex.holder.x = node.bounds.x; tex.holder.y = node.bounds.y; }); PngPublisher.publish(dir.resolvePath(name + targetDevice.extension + ".png"), _root.bounds.width, _root.bounds.height, constructed); } public function toJSON (_:*) :Object { var json :Object = { file: name + ".png", textures: [] }; _root.forEach(function (node :Node) :void { var tex :SwfTexture = node.texture; var textureJson :Object = { name: tex.symbol, offset: [ tex.offset.x, tex.offset.y ], rect: [ node.bounds.x, node.bounds.y, tex.w, tex.h ] }; if (tex.md5 != null) { textureJson.md5 = tex.md5; } json.textures.push(textureJson); }); return json; } public function toXML () :XML { var json :Object = toJSON(null); var xml :XML = <atlas file={json.file} />; for each (var tex :Object in json.textures) { var textureXml :XML = <texture name={tex.name} offset={tex.offset} rect={tex.rect} />; if (tex.md5 != null) { textureXml.@md5 = tex.md5; } xml.appendChild(textureXml); } return xml; } protected var _root :Node; } } import flash.geom.Rectangle; import flump.SwfTexture; // A node in a k-d tree class Node { // The bounds of this node (and its children) public var bounds :Rectangle; // The texture that is placed here, if any. Implies that this is a leaf node public var texture :SwfTexture; // This node's two children, if any public var left :Node; public var right :Node; public function Node (x :int, y :int, w :int, h :int) { bounds = new Rectangle(x, y, w, h); } // Find a free node in this tree big enough to fit an area, or null public function search (w :int, h :int) :Node { if (texture != null) { // There's already a texture here, terminate return null; } if (left != null && right != null) { // Try to fit it into this node's children var descendent :Node = left.search(w, h); if (descendent == null) { descendent = right.search(w, h); } return descendent; } else { if (bounds.width == w && bounds.height == h) { // This node is a perfect size, no need to subdivide return this; } if (bounds.width < w || bounds.height < h) { // This will never fit, terminate return null; } var dw :Number = bounds.width - w; var dh :Number = bounds.height - h; if (dw > dh) { left = new Node(bounds.x, bounds.y, w, bounds.height); right = new Node(bounds.x + w, bounds.y, dw, bounds.height); } else { left = new Node(bounds.x, bounds.y, bounds.width, h); right = new Node(bounds.x, bounds.y + h, bounds.width, dh); } return left.search(w, h); } } // Iterate over all nodes with textures in this tree public function forEach (fn :Function /* Node -> void */) :void { if (texture != null) { fn(this); } if (left != null && right != null) { left.forEach(fn); right.forEach(fn); } } }
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.display.Sprite; import flash.filesystem.File; import flump.SwfTexture; public class Atlas { // The empty border size around the right and bottom edges of each texture, to prevent bleeding public static const PADDING :int = 1; public var name :String; public var targetDevice :DeviceType; public function Atlas (name :String, targetDevice :DeviceType, w :int, h :int) { this.name = name; this.targetDevice = targetDevice; _root = new Node(0, 0, w, h); } // Try to place a texture in this atlas, return true if it fit public function place (texture :SwfTexture) :Boolean { var node :Node = _root.search(texture.w + PADDING, texture.h + PADDING); if (node == null) { return false; } node.texture = texture; return true; } public function get area () :int { return _root.bounds.width * _root.bounds.height; } public function get used () :int { var used :int = 0; _root.forEach(function (n :Node) :void { used += n.bounds.width * n.bounds.height; }); return used; } public function publish (dir :File) :void { var constructed :Sprite = new Sprite(); _root.forEach(function (node :Node) :void { var tex :SwfTexture = node.texture; var sprite :Sprite = new Sprite(); sprite.scaleX = sprite.scaleY = tex.scale; constructed.addChild(tex.holder); tex.holder.x = node.bounds.x; tex.holder.y = node.bounds.y; }); PngPublisher.publish(dir.resolvePath(name + targetDevice.extension + ".png"), _root.bounds.width, _root.bounds.height, constructed); } public function toJSON (_:*) :Object { var json :Object = { file: name + ".png", textures: [] }; _root.forEach(function (node :Node) :void { var tex :SwfTexture = node.texture; var textureJson :Object = { name: tex.symbol, rect: [ node.bounds.x, node.bounds.y, tex.w, tex.h ] }; if (tex.offset.x != 0 || tex.offset.y != 0) { textureJson.offset = [ tex.offset.x, tex.offset.y ]; } if (tex.md5 != null) { textureJson.md5 = tex.md5; } json.textures.push(textureJson); }); return json; } public function toXML () :XML { var json :Object = toJSON(null); var xml :XML = <atlas file={json.file} />; for each (var tex :Object in json.textures) { var textureXml :XML = <texture name={tex.name} rect={tex.rect} />; if (tex.offset != null) { textureXml.@offset = tex.offset; } if (tex.md5 != null) { textureXml.@md5 = tex.md5; } xml.appendChild(textureXml); } return xml; } protected var _root :Node; } } import flash.geom.Rectangle; import flump.SwfTexture; // A node in a k-d tree class Node { // The bounds of this node (and its children) public var bounds :Rectangle; // The texture that is placed here, if any. Implies that this is a leaf node public var texture :SwfTexture; // This node's two children, if any public var left :Node; public var right :Node; public function Node (x :int, y :int, w :int, h :int) { bounds = new Rectangle(x, y, w, h); } // Find a free node in this tree big enough to fit an area, or null public function search (w :int, h :int) :Node { if (texture != null) { // There's already a texture here, terminate return null; } if (left != null && right != null) { // Try to fit it into this node's children var descendent :Node = left.search(w, h); if (descendent == null) { descendent = right.search(w, h); } return descendent; } else { if (bounds.width == w && bounds.height == h) { // This node is a perfect size, no need to subdivide return this; } if (bounds.width < w || bounds.height < h) { // This will never fit, terminate return null; } var dw :Number = bounds.width - w; var dh :Number = bounds.height - h; if (dw > dh) { left = new Node(bounds.x, bounds.y, w, bounds.height); right = new Node(bounds.x + w, bounds.y, dw, bounds.height); } else { left = new Node(bounds.x, bounds.y, bounds.width, h); right = new Node(bounds.x, bounds.y + h, bounds.width, dh); } return left.search(w, h); } } // Iterate over all nodes with textures in this tree public function forEach (fn :Function /* Node -> void */) :void { if (texture != null) { fn(this); } if (left != null && right != null) { left.forEach(fn); right.forEach(fn); } } }
Make the texture offset optional.
Make the texture offset optional. @tconkling: This will need to be accounted for in Betwixt.
ActionScript
mit
mathieuanthoine/flump,mathieuanthoine/flump,mathieuanthoine/flump,funkypandagame/flump,funkypandagame/flump,tconkling/flump,tconkling/flump
2c2536aa94e353b74945c28d1bf067bafe8d4143
as3/com/netease/protobuf/stringToByteArray.as
as3/com/netease/protobuf/stringToByteArray.as
// vim: tabstop=4 shiftwidth=4 // Copyright (c) 2010 , NetEase.com,Inc. All rights reserved. // // Author: Yang Bo ([email protected]) // // Use, modification and distribution are subject to the "New BSD License" // as listed at <url: http://www.opensource.org/licenses/bsd-license.php >. package com.netease.protobuf { import flash.utils.ByteArray public function stringToByteArray(s:String):ByteArray { const ba:ByteArray = new ByteArray for (var i:uint = 0; i < s.length; ++i) { ba.writeByte(s.charCodeAt(i)) } return ba } }
// vim: tabstop=4 shiftwidth=4 // Copyright (c) 2010 , NetEase.com,Inc. All rights reserved. // // Author: Yang Bo ([email protected]) // // Use, modification and distribution are subject to the "New BSD License" // as listed at <url: http://www.opensource.org/licenses/bsd-license.php >. package com.netease.protobuf { import flash.utils.ByteArray public function stringToByteArray(s:String):ByteArray { const ba:ByteArray = new ByteArray ba.length = s.length for (var i:uint = 0; i < s.length; ++i) { ba[i] = s.charCodeAt(i) } return ba } }
初始化ByteArray时position为0
初始化ByteArray时position为0
ActionScript
bsd-2-clause
tconkling/protoc-gen-as3
ebd6644eac471beb608a1277da88496791129bf7
src/goplayer/SkinnedPlayerView.as
src/goplayer/SkinnedPlayerView.as
package goplayer { public class SkinnedPlayerView extends Component implements PlayerVideoUpdateListener, SkinBackend { private const missingSkinParts : Array = [] private var skin : Skin private var video : PlayerVideo private var player : Player public function SkinnedPlayerView (skin : Skin, video : PlayerVideo, player : Player) { this.skin = skin this.video = video this.player = player skin.backend = this addChild(video) addChild(skin.frontend) video.addUpdateListener(this) } public function handlePlayerVideoUpdated() : void { video.visible = !player.finished skin.update() } // ----------------------------------------------------- public function handleUserPlay() : void { if (player.started) player.paused = false else player.start() } public function handleUserPause() : void { player.paused = true } public function handleUserSeek(ratio : Number) : void { player.playheadRatio = ratio } public function handleUserMute() : void { player.mute() } public function handleUserUnmute() : void { player.unmute() } public function handleUserToggleFullscreen() : void { video.toggleFullscreen() } // ----------------------------------------------------- public function get skinWidth() : Number { return video.dimensions.width } public function get skinHeight() : Number { return video.dimensions.height } public function get skinScale() : Number { return video.fullscreenEnabled ? 2 : 1 } public function get streamLengthSeconds() : Number { return player.streamLength.seconds } public function get playheadRatio() : Number { return player.playheadRatio } public function get bufferRatio() : Number { return player.bufferRatio } public function get bufferFillRatio() : Number { return player.bufferFillRatio } public function get playing() : Boolean { return player.playing } public function get buffering() : Boolean { return player.buffering } public function get volume() : Number { return player.volume } // ----------------------------------------------------- public function handleSkinPartMissing(name : String) : void { if (missingSkinParts.indexOf(name) == -1) $handleSkinPartMissing(name) } private function $handleSkinPartMissing(name : String) : void { debug("Error: Skin part missing: " + name) missingSkinParts.push(name) } } }
package goplayer { import flash.display.Sprite import flash.events.Event import flash.events.MouseEvent import flash.utils.getTimer public class SkinnedPlayerView extends Component implements PlayerVideoUpdateListener, SkinBackend { private const IDLE_TIME_MS : uint = 2000 private const missingSkinParts : Array = [] private const skinContainer : Sprite = new Sprite private var skin : Skin private var video : PlayerVideo private var player : Player private var lastInteractionTime : uint = 0 public function SkinnedPlayerView (skin : Skin, video : PlayerVideo, player : Player) { this.skin = skin this.video = video this.player = player skin.backend = this addChild(video) skinContainer.addChild(skin.frontend) addChild(skinContainer) video.addUpdateListener(this) addEventListener(Event.ADDED_TO_STAGE, handleAddedToStage) } private function handleAddedToStage(event : Event) : void { stage.addEventListener(MouseEvent.MOUSE_MOVE, handleStageMouseMove) stage.addEventListener(Event.MOUSE_LEAVE, handleStageMouseLeave) } private function handleStageMouseMove(event : MouseEvent) : void { lastInteractionTime = getTimer() } private function handleStageMouseLeave(event : Event) : void { lastInteractionTime = 0 } public function handlePlayerVideoUpdated() : void { video.visible = !player.finished skinContainer.visible = !userIdle skin.update() } private function get userIdle() : Boolean { return getTimer() - lastInteractionTime > IDLE_TIME_MS } // ----------------------------------------------------- public function handleUserPlay() : void { if (player.started) player.paused = false else player.start() } public function handleUserPause() : void { player.paused = true } public function handleUserSeek(ratio : Number) : void { player.playheadRatio = ratio } public function handleUserMute() : void { player.mute() } public function handleUserUnmute() : void { player.unmute() } public function handleUserToggleFullscreen() : void { video.toggleFullscreen() } // ----------------------------------------------------- public function get skinWidth() : Number { return video.dimensions.width } public function get skinHeight() : Number { return video.dimensions.height } public function get skinScale() : Number { return video.fullscreenEnabled ? 2 : 1 } public function get streamLengthSeconds() : Number { return player.streamLength.seconds } public function get playheadRatio() : Number { return player.playheadRatio } public function get bufferRatio() : Number { return player.bufferRatio } public function get bufferFillRatio() : Number { return player.bufferFillRatio } public function get playing() : Boolean { return player.playing } public function get buffering() : Boolean { return player.buffering } public function get volume() : Number { return player.volume } // ----------------------------------------------------- public function handleSkinPartMissing(name : String) : void { if (missingSkinParts.indexOf(name) == -1) $handleSkinPartMissing(name) } private function $handleSkinPartMissing(name : String) : void { debug("Error: Skin part missing: " + name) missingSkinParts.push(name) } } }
Hide skin when user is idle.
Hide skin when user is idle.
ActionScript
mit
dbrock/goplayer,dbrock/goplayer
5acc2b767a6bb8afc7b4c222843153ff3c25e068
src/as/com/threerings/util/Integer.as
src/as/com/threerings/util/Integer.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 { /** * Equivalent to java.lang.Integer. */ // Unfortunately, I think this is necessary. // I was going to remove this class and just make the streaming stuff // autotranslate between int <--> java.lang.Integer and // Number <--> java.lang.Double. However, a Number object that refers // to an integer value is actually an int. Yes, it's totally fucked. public class Integer implements Equalable, Wrapped { public var value :int; public static function valueOf (val :int) :Integer { return new Integer(val); } public function Integer (value :int) { this.value = value; } // from Equalable public function equals (other :Object) :Boolean { return (other is Integer) && (value === (other as Integer).value); } // from Wrapped public function unwrap () :Object { return value; } /** * Compares to int values in an overflow safe manner. */ public static function compare (val1 :int, val2 :int) :int { return (val1 > val2) ? 1 : (val1 == val2 ? 0 : -1); } } }
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.util { /** * Equivalent to java.lang.Integer. */ // Unfortunately, I think this is necessary. // I was going to remove this class and just make the streaming stuff // autotranslate between int <--> java.lang.Integer and // Number <--> java.lang.Double. However, a Number object that refers // to an integer value is actually an int. Yes, it's totally fucked. public class Integer implements Equalable, Wrapped { public var value :int; public static function valueOf (val :int) :Integer { return new Integer(val); } public function Integer (value :int) { this.value = value; } // from Equalable public function equals (other :Object) :Boolean { return (other is Integer) && (value === (other as Integer).value); } // from Wrapped public function unwrap () :Object { return value; } // cannot use the override keyword on toString() because actionscript is stupid public function toString () :String { return value.toString(); } /** * Compares to int values in an overflow safe manner. */ public static function compare (val1 :int, val2 :int) :int { return (val1 > val2) ? 1 : (val1 == val2 ? 0 : -1); } } }
implement toString
implement toString git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4678 542714f4-19e9-0310-aa3c-eee0fc999fb1
ActionScript
lgpl-2.1
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
6893cbd358edb2c5144baeafefed1195807dbf4c
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) { _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 controller is already loading an asset.'); _currentState = STATE_PARSING; _progress.execute(this, 0.5); if (_parserOptions != null && _parserOptions.parser != null) { _parser = new (_parserOptions.parser)(_parserOptions); } 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; 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) { _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); } 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); } } }
Fix error message
Fix error message
ActionScript
mit
aerys/minko-as3
67623cb9acd9b0bbee7469407742f1f22c8c0eb9
skin-src/goplayer/StandardSkin.as
skin-src/goplayer/StandardSkin.as
package goplayer { import flash.display.DisplayObject import flash.display.InteractiveObject import flash.display.Sprite import flash.text.TextField public class StandardSkin extends AbstractStandardSkin { private var _seekBarWidth : Number override public function update() : void { super.update() setPosition(largePlayButton, dimensions.center) setPosition(bufferingIndicator, dimensions.center) setDimensions(largePlayButton, dimensions.halved.innerSquare) upperPanel.x = 0 upperPanel.y = 0 packLeft (upperPanelLeft, [upperPanelMiddle, setUpperPanelWidth], upperPanelRight) controlBar.x = 0 controlBar.y = dimensions.height packLeft (showPlayPauseButton ? playPausePart : null, beforeLeftTimePart, showElapsedTime ? leftTimePart : null, [seekBar, setSeekBarWidth], showTotalTime ? rightTimePart : null, afterRightTimePart, showVolumeControl ? volumePart : null, showFullscreenButton ? fullscreenPart : null) playPausePart.visible = showPlayPauseButton leftTimePart.visible = showElapsedTime seekBar.visible = showSeekBar rightTimePart.visible = showTotalTime volumePart.visible = showVolumeControl fullscreenPart.visible = showFullscreenButton } private function packLeft(... items : Array) : void { Packer.$packLeft(dimensions.width, items) } private function setUpperPanelWidth(value : Number) : void { upperPanelMiddleBackground.width = value titleField.width = value } private function setSeekBarWidth(value : Number) : void { _seekBarWidth = value } override protected function get seekBarWidth() : Number { return _seekBarWidth } override protected function get upperPanel() : Sprite { return lookup("chrome.upperPanel") } private function get upperPanelLeft() : Sprite { return lookup("chrome.upperPanel.left") } private function get upperPanelMiddle() : Sprite { return lookup("chrome.upperPanel.middle") } private function get upperPanelMiddleBackground() : Sprite { return lookup("chrome.upperPanel.middle.background") } private function get upperPanelRight() : Sprite { return lookup("chrome.upperPanel.right") } override protected function get largePlayButton() : InteractiveObject { return lookup("largePlayButton") } override protected function get bufferingIndicator() : InteractiveObject { return lookup("bufferingIndicator") } override protected function get chrome() : Sprite { return lookup("chrome") } override protected function get titleField() : TextField { return lookup("chrome.upperPanel.middle.titleField") } override protected function get controlBar() : Sprite { return lookup("chrome.controlBar") } private function get playPausePart() : DisplayObject { return lookup("chrome.controlBar.playPause") } override protected function get playButton() : DisplayObject { return lookup("chrome.controlBar.playPause.playButton") } override protected function get pauseButton() : DisplayObject { return lookup("chrome.controlBar.playPause.pauseButton") } private function get beforeLeftTimePart() : DisplayObject { return lookup("chrome.controlBar.beforeLeftTime") } private function get leftTimePart() : TextField { return lookup("chrome.controlBar.leftTime") } override protected function get leftTimeField() : TextField { return lookup("chrome.controlBar.leftTime.field") } override protected function get seekBar() : Sprite { return lookup("chrome.controlBar.seekBar") } override protected function get seekBarBackground() : DisplayObject { return lookup("chrome.controlBar.seekBar.background") } override protected function get seekBarBuffer() : DisplayObject { return lookup("chrome.controlBar.seekBar.buffer") } override protected function get seekBarPlayhead() : DisplayObject { return lookup("chrome.controlBar.seekBar.playhead") } override protected function get seekBarTooltip() : DisplayObject { return lookup("chrome.controlBar.seekBar.tooltip") } override protected function get seekBarTooltipField() : TextField { return lookup("chrome.controlBar.seekBar.tooltip.field") } private function get rightTimePart() : DisplayObject { return lookup("chrome.controlBar.rightTime") } override protected function get rightTimeField() : TextField { return lookup("chrome.controlBar.rightTime.field") } private function get afterRightTimePart() : DisplayObject { return lookup("chrome.controlBar.afterRightTime") } private function get volumePart() : DisplayObject { return lookup("chrome.controlBar.volume") } override protected function get muteButton() : DisplayObject { return lookup("chrome.controlBar.volume.muteButton") } override protected function get unmuteButton() : DisplayObject { return lookup("chrome.controlBar.volume.unmuteButton") } override protected function get volumeSlider() : Sprite { return lookup("chrome.controlBar.volume.slider") } override protected function get volumeSliderThumb() : DisplayObject { return lookup("chrome.controlBar.volume.slider.thumb") } override protected function get volumeSliderThumbGuide() : DisplayObject { return lookup("chrome.controlBar.volume.slider.thumbGuide") } override protected function get volumeSliderFill() : DisplayObject { return lookup("chrome.controlBar.volume.slider.fill") } private function get fullscreenPart() : DisplayObject { return lookup("chrome.controlBar.fullscreen") } override protected function get enableFullscreenButton() : DisplayObject { return lookup("chrome.controlBar.fullscreen.enableButton") } override protected function lookup(name : String) : * { return super.lookup("skinContent." + name) } } }
package goplayer { import flash.display.DisplayObject import flash.display.InteractiveObject import flash.display.Sprite import flash.text.TextField public class StandardSkin extends AbstractStandardSkin { private var _seekBarWidth : Number override public function update() : void { super.update() setPosition(largePlayButton, dimensions.center) setPosition(bufferingIndicator, dimensions.center) setDimensions(largePlayButton, dimensions.halved.innerSquare) upperPanel.x = 0 upperPanel.y = 0 packLeft (upperPanelLeft, [upperPanelMiddle, setUpperPanelWidth], upperPanelRight) controlBar.x = 0 controlBar.y = dimensions.height packLeft (showPlayPauseButton ? playPausePart : null, beforeLeftTimePart, showElapsedTime ? leftTimeBackgroundPart : null, afterLeftTimePart, [seekBar, setSeekBarWidth], beforeRightTimePart, showTotalTime ? rightTimeBackgroundPart : null, afterRightTimePart, showVolumeControl ? volumePart : null, showFullscreenButton ? fullscreenPart : null) leftTimeFieldPart.x = beforeLeftTimePart.x rightTimeFieldPart.x = beforeRightTimePart.x playPausePart.visible = showPlayPauseButton leftTimeBackgroundPart.visible = showElapsedTime leftTimeFieldPart.visible = showElapsedTime seekBar.visible = showSeekBar rightTimeBackgroundPart.visible = showTotalTime rightTimeFieldPart.visible = showTotalTime volumePart.visible = showVolumeControl fullscreenPart.visible = showFullscreenButton } private function packLeft(... items : Array) : void { Packer.$packLeft(dimensions.width, items) } private function setUpperPanelWidth(value : Number) : void { upperPanelMiddleBackground.width = value titleField.width = value } private function setSeekBarWidth(value : Number) : void { _seekBarWidth = value } override protected function get seekBarWidth() : Number { return _seekBarWidth } override protected function get upperPanel() : Sprite { return lookup("chrome.upperPanel") } private function get upperPanelLeft() : Sprite { return lookup("chrome.upperPanel.left") } private function get upperPanelMiddle() : Sprite { return lookup("chrome.upperPanel.middle") } private function get upperPanelMiddleBackground() : Sprite { return lookup("chrome.upperPanel.middle.background") } private function get upperPanelRight() : Sprite { return lookup("chrome.upperPanel.right") } override protected function get largePlayButton() : InteractiveObject { return lookup("largePlayButton") } override protected function get bufferingIndicator() : InteractiveObject { return lookup("bufferingIndicator") } override protected function get chrome() : Sprite { return lookup("chrome") } override protected function get titleField() : TextField { return lookup("chrome.upperPanel.middle.titleField") } override protected function get controlBar() : Sprite { return lookup("chrome.controlBar") } private function get playPausePart() : DisplayObject { return lookup("chrome.controlBar.playPause") } override protected function get playButton() : DisplayObject { return lookup("chrome.controlBar.playPause.playButton") } override protected function get pauseButton() : DisplayObject { return lookup("chrome.controlBar.playPause.pauseButton") } private function get beforeLeftTimePart() : DisplayObject { return lookup("chrome.controlBar.beforeLeftTime") } private function get leftTimeBackgroundPart() : DisplayObject { return lookup("chrome.controlBar.leftTimeBackground") } private function get leftTimeFieldPart() : DisplayObject { return lookup("chrome.controlBar.leftTime") } override protected function get leftTimeField() : TextField { return lookup("chrome.controlBar.leftTime.field") } private function get afterLeftTimePart() : DisplayObject { return lookup("chrome.controlBar.afterLeftTime") } override protected function get seekBar() : Sprite { return lookup("chrome.controlBar.seekBar") } override protected function get seekBarBackground() : DisplayObject { return lookup("chrome.controlBar.seekBar.background") } override protected function get seekBarBuffer() : DisplayObject { return lookup("chrome.controlBar.seekBar.buffer") } override protected function get seekBarPlayhead() : DisplayObject { return lookup("chrome.controlBar.seekBar.playhead") } override protected function get seekBarTooltip() : DisplayObject { return lookup("chrome.controlBar.seekBar.tooltip") } override protected function get seekBarTooltipField() : TextField { return lookup("chrome.controlBar.seekBar.tooltip.field") } private function get beforeRightTimePart() : DisplayObject { return lookup("chrome.controlBar.beforeRightTime") } private function get rightTimeBackgroundPart() : DisplayObject { return lookup("chrome.controlBar.rightTimeBackground") } private function get rightTimeFieldPart() : DisplayObject { return lookup("chrome.controlBar.rightTime") } override protected function get rightTimeField() : TextField { return lookup("chrome.controlBar.rightTime.field") } private function get afterRightTimePart() : DisplayObject { return lookup("chrome.controlBar.afterRightTime") } private function get volumePart() : DisplayObject { return lookup("chrome.controlBar.volume") } override protected function get muteButton() : DisplayObject { return lookup("chrome.controlBar.volume.muteButton") } override protected function get unmuteButton() : DisplayObject { return lookup("chrome.controlBar.volume.unmuteButton") } override protected function get volumeSlider() : Sprite { return lookup("chrome.controlBar.volume.slider") } override protected function get volumeSliderThumb() : DisplayObject { return lookup("chrome.controlBar.volume.slider.thumb") } override protected function get volumeSliderThumbGuide() : DisplayObject { return lookup("chrome.controlBar.volume.slider.thumbGuide") } override protected function get volumeSliderFill() : DisplayObject { return lookup("chrome.controlBar.volume.slider.fill") } private function get fullscreenPart() : DisplayObject { return lookup("chrome.controlBar.fullscreen") } override protected function get enableFullscreenButton() : DisplayObject { return lookup("chrome.controlBar.fullscreen.enableButton") } override protected function lookup(name : String) : * { return super.lookup("skinContent." + name) } } }
Split left/right time parts into several pieces.
Split left/right time parts into several pieces.
ActionScript
mit
dbrock/goplayer,dbrock/goplayer
7bdf53f95c3134671c12cbb3d015e43240e6b74b
HLSPlugin/src/com/kaltura/hls/m2ts/PESProcessor.as
HLSPlugin/src/com/kaltura/hls/m2ts/PESProcessor.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; import com.hurlant.util.Hex; CONFIG::LOGGING { import org.osmf.logging.Logger; import org.osmf.logging.Log; } /** * Process packetized elementary streams and extract NALUs and other data. */ public class PESProcessor { CONFIG::LOGGING { private static const logger:Logger = Log.getLogger("com.kaltura.hls.m2ts.PESProcessor"); } public var types:Object = {}; public var streams:Object = {}; public var lastVideoNALU:NALU = null; public var transcoder:FLVTranscoder = new FLVTranscoder(); public var headerSent:Boolean = false; public var pmtStreamId:int = -1; protected var pendingBuffers:Vector.<Object> = new Vector.<Object>(); protected var pendingLastConvertedIndex:int = 0; public function logStreams():void { CONFIG::LOGGING { logger.debug("----- PES state -----"); for(var k:* in streams) { logger.debug(" " + k + " has " + streams[k].buffer.length + " bytes, type=" + types[k]); } } } public function clear(clearAACConfig:Boolean = true):void { streams = {}; lastVideoNALU = null; transcoder.clear(clearAACConfig); } private function parseProgramAssociationTable(bytes:ByteArray, cursor:uint):Boolean { // Get the section length. var sectionLen:uint = ((bytes[cursor+2] & 0x03) << 8) | bytes[cursor+3]; // Check the section length for a single PMT. CONFIG::LOGGING { if (sectionLen > 13) { logger.debug("Saw multiple PMT entries in the PAT; blindly choosing first one."); } } // Grab the PMT ID. pmtStreamId = ((bytes[cursor+10] << 8) | bytes[cursor+11]) & 0x1FFF; CONFIG::LOGGING { logger.debug("Saw PMT ID of " + pmtStreamId); } return true; } private function parseProgramMapTable(bytes:ByteArray, cursor:uint):Boolean { var sectionLength:uint; var sectionLimit:uint; var programInfoLength:uint; var type:uint; var pid:uint; var esInfoLength:uint; var seenPIDsByClass:Array; var mediaClass:int; var hasAudio:Boolean = false, hasVideo:Boolean = false; // Set up types. types = []; seenPIDsByClass = []; seenPIDsByClass[MediaClass.VIDEO] = Infinity; seenPIDsByClass[MediaClass.AUDIO] = Infinity; // Process section length and limit. cursor++; sectionLength = ((bytes[cursor] & 0x0f) << 8) + bytes[cursor + 1]; cursor += 2; if(sectionLength + cursor > bytes.length) { CONFIG::LOGGING { logger.error("Not enough data to read. 1"); } return false; } // Skip a few things we don't care about: program number, RSV, version, CNI, section, last_section, pcr_cid sectionLimit = cursor + sectionLength; cursor += 7; // And get the program info length. programInfoLength = ((bytes[cursor] & 0x0f) << 8) + bytes[cursor + 1]; cursor += 2; // If not enough data to proceed, bail. if(programInfoLength + cursor > bytes.length) { CONFIG::LOGGING { logger.error("Not enough data to read. 2"); } return false; } cursor += programInfoLength; const CRC_SIZE:int = 4; while(cursor < sectionLimit - CRC_SIZE) { type = bytes[cursor++]; pid = ((bytes[cursor] & 0x1f) << 8) + bytes[cursor + 1]; cursor += 2; mediaClass = MediaClass.calculate(type); if(mediaClass == MediaClass.VIDEO) hasVideo = true if(mediaClass == MediaClass.AUDIO) hasAudio = true // For video & audio, select the lowest PID for each kind. if(mediaClass == MediaClass.OTHER || pid < seenPIDsByClass[mediaClass]) { // Clear a higher PID if present. if(mediaClass != MediaClass.OTHER && seenPIDsByClass[mediaClass] < Infinity) types[seenPIDsByClass[mediaClass]] = -1; types[pid] = type; seenPIDsByClass[mediaClass] = pid; } // Skip the esInfo data. esInfoLength = ((bytes[cursor] & 0x0f) << 8) + bytes[cursor + 1]; cursor += 2; cursor += esInfoLength; } // Cook out header to transcoder. //transcoder.writeHeader(hasAudio, hasVideo); headerSent = true; return true; } public function append(packet:PESPacket):Boolean { // logger.debug("saw packet of " + packet.buffer.length); var b:ByteArray = packet.buffer; b.position = 0; if(b.length < 8) { CONFIG::LOGGING { logger.error("Ignoring too short PES packet, length=" + b.length); } return true; } // Get the start code. var startCode:uint = b.readUnsignedInt(); if((startCode & 0xFFFFFF00) != 0x00000100) { // It could be a program association table. if((startCode & 0xFFFFFF00) == 0x0000b000) { parseProgramAssociationTable(b, 1); return true; } // It could be the program map table. if((startCode & 0xFFFFFC00) == 0x0002b000) { parseProgramMapTable(b, 1); return true; } var tmp:ByteArray = new ByteArray(); tmp.writeInt(startCode); CONFIG::LOGGING { logger.error("ES prefix was wrong, expected 00:00:01:xx but got " + Hex.fromArray(tmp, true)); } return true; } // Get the stream ID. var streamID:int = startCode & 0xFF; // Get the length. var packetLength:uint = b.readUnsignedShort(); if(packetLength) { if(b.length < packetLength ) { CONFIG::LOGGING { logger.warn("WARNING: parsePESPacket - not enough bytes, expecting " + packetLength + ", but have " + b.length); } return false; // not enough bytes in packet } } if(b.length < 9) { CONFIG::LOGGING { logger.warn("WARNING: parsePESPacket - too short to read header!"); } return false; } // Read the rest of the header. var cursor:uint = 6; var dataAlignment:Boolean = (b[cursor] & 0x04) != 0; cursor++; var ptsDts:uint = (b[cursor] & 0xc0) >> 6; cursor++; var pesHeaderDataLength:uint = b[cursor]; cursor++; //logger.debug(" PES align=" + dataAlignment + " ptsDts=" + ptsDts + " header=" + pesHeaderDataLength); var pts:Number = 0, dts:Number = 0; if(ptsDts & 0x02) { // has PTS at least if(cursor + 5 > b.length) return true; pts = b[cursor] & 0x0e; pts *= 128; pts += b[cursor + 1]; pts *= 256; pts += b[cursor + 2] & 0xfe; pts *= 128; pts += b[cursor + 3]; pts *= 256; pts += b[cursor + 4] & 0xfe; pts /= 2; if(ptsDts & 0x01) { // DTS too! if(cursor + 10 > b.length) return true; dts = b[cursor + 5] & 0x0e; dts *= 128; dts += b[cursor + 6]; dts *= 256; dts += b[cursor + 7] & 0xfe; dts *= 128; dts += b[cursor + 8]; dts *= 256; dts += b[cursor + 9] & 0xfe; dts /= 2; } else { //logger.debug("Filling in DTS") dts = pts; } } // Handle partially overflowed PTS/DTS values. if (pts < (1<<31) && dts > 3*(1<<31)) dts -= 1<<33; if (dts < (1<<31) && pts > 3*(1<<31)) pts -= 1<<33; packet.pts = pts; packet.dts = dts; //logger.debug(" PTS=" + pts/90000 + " DTS=" + dts/90000); cursor += pesHeaderDataLength; if(cursor > b.length) { CONFIG::LOGGING { logger.warn("WARNING: parsePESPacket - ran out of bytes"); } return true; } if(types[packet.packetID] == undefined) { CONFIG::LOGGING { logger.warn("WARNING: parsePESPacket - unknown type"); } return true; } var pes:PESPacketStream; if(streams[packet.packetID] == undefined) { if(dts < 0.0) { CONFIG::LOGGING { logger.warn("WARNING: parsePESPacket - invalid decode timestamp, skipping"); } return true; } pes = new PESPacketStream(); streams[packet.packetID] = pes; } else { pes = streams[packet.packetID]; } if(headerSent == false) { CONFIG::LOGGING { logger.warn("Skipping data that came before PMT"); } return true; } // Note the type at this moment in time. packet.type = types[packet.packetID]; packet.headerLength = cursor; // And process. if(MediaClass.calculate(types[packet.packetID]) == MediaClass.VIDEO) { var start:int = NALU.scan(b, cursor, true); if(start == -1 && lastVideoNALU) { CONFIG::LOGGING { logger.debug("Stuff entire " + (b.length - cursor) + " bytes into previous NALU."); } lastVideoNALU.buffer.position = lastVideoNALU.buffer.length; b.position = 0; lastVideoNALU.buffer.writeBytes(b, cursor, b.length - cursor); return true; } else if((start - cursor) > 0 && lastVideoNALU) { // Shove into previous buffer. CONFIG::LOGGING { logger.debug("Stuffing first " + (start - cursor) + " bytes into previous NALU."); } lastVideoNALU.buffer.position = lastVideoNALU.buffer.length; b.position = 0; lastVideoNALU.buffer.writeBytes(b, cursor, start - cursor); cursor = start; } // If it's identical timestamps, accumulate it into the current unit and keep going. if(lastVideoNALU && pts == lastVideoNALU.pts && dts == lastVideoNALU.dts) { CONFIG::LOGGING { logger.debug("Combining " + (start-cursor) + " bytes into previous NALU due to matching DTS/PTS."); } lastVideoNALU.buffer.position = lastVideoNALU.buffer.length; b.position = 0; lastVideoNALU.buffer.writeBytes(b, cursor, start - cursor); cursor = start; } else { // Submit previous data. if(lastVideoNALU) { pendingBuffers.push(lastVideoNALU.clone()); } // Update NALU state. lastVideoNALU = new NALU(); lastVideoNALU.buffer = new ByteArray(); lastVideoNALU.pts = pts; lastVideoNALU.dts = dts; lastVideoNALU.type = packet.type; lastVideoNALU.buffer.writeBytes(b, cursor); } } else if(types[packet.packetID] == 0x0F) { // It's an AAC stream. pendingBuffers.push(packet.clone()); } else if(types[packet.packetID] == 0x03 || types[packet.packetID] == 0x04) { // It's an MP3 stream. pendingBuffers.push(packet.clone()); } else { CONFIG::LOGGING { logger.warn("Unknown packet ID type " + types[packet.packetID] + ", ignoring (A)."); } } bufferPendingNalus(); return true; } /** * To avoid transcoding all content on flush, we buffer it into FLV * tags as we go. However, they remain undelivered until we can gather * final SPS/PPS information. This method is responsible for * incrementally buffering in the FLV transcoder as we go. */ public function bufferPendingNalus():void { // Iterate and buffer new NALUs. for(var i:int=pendingLastConvertedIndex; i<pendingBuffers.length; i++) { if(pendingBuffers[i] is NALU) { transcoder.convert(pendingBuffers[i] as NALU); } else if(pendingBuffers[i] is PESPacket) { var packet:PESPacket = pendingBuffers[i] as PESPacket; if(packet.type == 0x0F) { // It's an AAC stream. transcoder.convertAAC(packet); } else if(packet.type == 0x03 || packet.type == 0x04) { // It's an MP3 stream. Pass through directly. transcoder.convertMP3(packet); } else { CONFIG::LOGGING { logger.warn("Unknown packet ID type " + packet.type + ", ignoring (B)."); } } } } // Note the last item we converted so we can avoid duplicating work. pendingLastConvertedIndex = pendingBuffers.length; } public function processAllNalus():void { // Consume any unposted video NALUs. if(lastVideoNALU) { pendingBuffers.push(lastVideoNALU.clone()); lastVideoNALU = null; } // First walk all the video NALUs and get the correct SPS/PPS if(pendingBuffers.length == 0) return; // Then emit SPS/PPS transcoder.emitSPSPPSUnbuffered(); // Complete buffering and emit it all. bufferPendingNalus(); transcoder.emitBufferedTags(); // Don't forget to clear the pending list. pendingBuffers.length = 0; pendingLastConvertedIndex = 0; } } }
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; import com.hurlant.util.Hex; CONFIG::LOGGING { import org.osmf.logging.Logger; import org.osmf.logging.Log; } /** * Process packetized elementary streams and extract NALUs and other data. */ public class PESProcessor { CONFIG::LOGGING { private static const logger:Logger = Log.getLogger("com.kaltura.hls.m2ts.PESProcessor"); } public var types:Object = {}; public var streams:Object = {}; public var lastVideoNALU:NALU = null; public var transcoder:FLVTranscoder = new FLVTranscoder(); public var headerSent:Boolean = false; public var pmtStreamId:int = -1; protected var pendingBuffers:Vector.<Object> = new Vector.<Object>(); protected var pendingLastConvertedIndex:int = 0; public function logStreams():void { CONFIG::LOGGING { logger.debug("----- PES state -----"); for(var k:* in streams) { logger.debug(" " + k + " has " + streams[k].buffer.length + " bytes, type=" + types[k]); } } } public function clear(clearAACConfig:Boolean = true):void { streams = {}; lastVideoNALU = null; transcoder.clear(clearAACConfig); } private function parseProgramAssociationTable(bytes:ByteArray, cursor:uint):Boolean { // Get the section length. var sectionLen:uint = ((bytes[cursor+2] & 0x03) << 8) | bytes[cursor+3]; // Check the section length for a single PMT. CONFIG::LOGGING { if (sectionLen > 13) { logger.debug("Saw multiple PMT entries in the PAT; blindly choosing first one."); } } // Grab the PMT ID. pmtStreamId = ((bytes[cursor+10] << 8) | bytes[cursor+11]) & 0x1FFF; CONFIG::LOGGING { logger.debug("Saw PMT ID of " + pmtStreamId); } return true; } private function parseProgramMapTable(bytes:ByteArray, cursor:uint):Boolean { var sectionLength:uint; var sectionLimit:uint; var programInfoLength:uint; var type:uint; var pid:uint; var esInfoLength:uint; var seenPIDsByClass:Array; var mediaClass:int; var hasAudio:Boolean = false, hasVideo:Boolean = false; // Set up types. types = []; seenPIDsByClass = []; seenPIDsByClass[MediaClass.VIDEO] = Infinity; seenPIDsByClass[MediaClass.AUDIO] = Infinity; // Process section length and limit. cursor++; sectionLength = ((bytes[cursor] & 0x0f) << 8) + bytes[cursor + 1]; cursor += 2; if(sectionLength + cursor > bytes.length) { CONFIG::LOGGING { logger.error("Not enough data to read. 1"); } return false; } // Skip a few things we don't care about: program number, RSV, version, CNI, section, last_section, pcr_cid sectionLimit = cursor + sectionLength; cursor += 7; // And get the program info length. programInfoLength = ((bytes[cursor] & 0x0f) << 8) + bytes[cursor + 1]; cursor += 2; // If not enough data to proceed, bail. if(programInfoLength + cursor > bytes.length) { CONFIG::LOGGING { logger.error("Not enough data to read. 2"); } return false; } cursor += programInfoLength; const CRC_SIZE:int = 4; while(cursor < sectionLimit - CRC_SIZE) { type = bytes[cursor++]; pid = ((bytes[cursor] & 0x1f) << 8) + bytes[cursor + 1]; cursor += 2; mediaClass = MediaClass.calculate(type); if(mediaClass == MediaClass.VIDEO) hasVideo = true if(mediaClass == MediaClass.AUDIO) hasAudio = true // For video & audio, select the lowest PID for each kind. if(mediaClass == MediaClass.OTHER || pid < seenPIDsByClass[mediaClass]) { // Clear a higher PID if present. if(mediaClass != MediaClass.OTHER && seenPIDsByClass[mediaClass] < Infinity) types[seenPIDsByClass[mediaClass]] = -1; types[pid] = type; seenPIDsByClass[mediaClass] = pid; } // Skip the esInfo data. esInfoLength = ((bytes[cursor] & 0x0f) << 8) + bytes[cursor + 1]; cursor += 2; cursor += esInfoLength; } // Cook out header to transcoder. //transcoder.writeHeader(hasAudio, hasVideo); headerSent = true; return true; } public function append(packet:PESPacket):Boolean { // logger.debug("saw packet of " + packet.buffer.length); var b:ByteArray = packet.buffer; b.position = 0; if(b.length < 8) { CONFIG::LOGGING { logger.error("Ignoring too short PES packet, length=" + b.length); } return true; } // Get the start code. var startCode:uint = b.readUnsignedInt(); if((startCode & 0xFFFFFF00) != 0x00000100) { // It could be a program association table. if((startCode & 0xFFFFFF00) == 0x0000b000) { parseProgramAssociationTable(b, 1); return true; } // It could be the program map table. if((startCode & 0xFFFFFC00) == 0x0002b000) { parseProgramMapTable(b, 1); return true; } var tmp:ByteArray = new ByteArray(); tmp.writeInt(startCode); CONFIG::LOGGING { logger.error("ES prefix was wrong, expected 00:00:01:xx but got " + Hex.fromArray(tmp, true)); } return true; } // Get the stream ID. var streamID:int = startCode & 0xFF; // Get the length. var packetLength:uint = b.readUnsignedShort(); if(packetLength) { if(b.length < packetLength ) { CONFIG::LOGGING { logger.warn("WARNING: parsePESPacket - not enough bytes, expecting " + packetLength + ", but have " + b.length); } return false; // not enough bytes in packet } } if(b.length < 9) { CONFIG::LOGGING { logger.warn("WARNING: parsePESPacket - too short to read header!"); } return false; } // Read the rest of the header. var cursor:uint = 6; var dataAlignment:Boolean = (b[cursor] & 0x04) != 0; cursor++; var ptsDts:uint = (b[cursor] & 0xc0) >> 6; cursor++; var pesHeaderDataLength:uint = b[cursor]; cursor++; //logger.debug(" PES align=" + dataAlignment + " ptsDts=" + ptsDts + " header=" + pesHeaderDataLength); var pts:Number = 0, dts:Number = 0; if(ptsDts & 0x02) { // has PTS at least if(cursor + 5 > b.length) return true; pts = b[cursor] & 0x0e; pts *= 128; pts += b[cursor + 1]; pts *= 256; pts += b[cursor + 2] & 0xfe; pts *= 128; pts += b[cursor + 3]; pts *= 256; pts += b[cursor + 4] & 0xfe; pts /= 2; if(ptsDts & 0x01) { // DTS too! if(cursor + 10 > b.length) return true; dts = b[cursor + 5] & 0x0e; dts *= 128; dts += b[cursor + 6]; dts *= 256; dts += b[cursor + 7] & 0xfe; dts *= 128; dts += b[cursor + 8]; dts *= 256; dts += b[cursor + 9] & 0xfe; dts /= 2; } else { //logger.debug("Filling in DTS") dts = pts; } } // Handle partially overflowed PTS/DTS values. //if (pts < (1<<31) && dts > 3*(1<<31)) // dts -= 1<<33; //if (dts < (1<<31) && pts > 3*(1<<31)) // pts -= 1<<33; packet.pts = pts; packet.dts = dts; //logger.debug(" PTS=" + pts/90000 + " DTS=" + dts/90000); cursor += pesHeaderDataLength; if(cursor > b.length) { CONFIG::LOGGING { logger.warn("WARNING: parsePESPacket - ran out of bytes"); } return true; } if(types[packet.packetID] == undefined) { CONFIG::LOGGING { logger.warn("WARNING: parsePESPacket - unknown type"); } return true; } var pes:PESPacketStream; if(streams[packet.packetID] == undefined) { if(dts < 0.0) { CONFIG::LOGGING { logger.warn("WARNING: parsePESPacket - invalid decode timestamp, skipping"); } return true; } pes = new PESPacketStream(); streams[packet.packetID] = pes; } else { pes = streams[packet.packetID]; } if(headerSent == false) { CONFIG::LOGGING { logger.warn("Skipping data that came before PMT"); } return true; } // Note the type at this moment in time. packet.type = types[packet.packetID]; packet.headerLength = cursor; // And process. if(MediaClass.calculate(types[packet.packetID]) == MediaClass.VIDEO) { var start:int = NALU.scan(b, cursor, true); if(start == -1 && lastVideoNALU) { CONFIG::LOGGING { logger.debug("Stuff entire " + (b.length - cursor) + " bytes into previous NALU."); } lastVideoNALU.buffer.position = lastVideoNALU.buffer.length; b.position = 0; lastVideoNALU.buffer.writeBytes(b, cursor, b.length - cursor); return true; } else if((start - cursor) > 0 && lastVideoNALU) { // Shove into previous buffer. CONFIG::LOGGING { logger.debug("Stuffing first " + (start - cursor) + " bytes into previous NALU."); } lastVideoNALU.buffer.position = lastVideoNALU.buffer.length; b.position = 0; lastVideoNALU.buffer.writeBytes(b, cursor, start - cursor); cursor = start; } // If it's identical timestamps, accumulate it into the current unit and keep going. if(lastVideoNALU && pts == lastVideoNALU.pts && dts == lastVideoNALU.dts) { CONFIG::LOGGING { logger.debug("Combining " + (start-cursor) + " bytes into previous NALU due to matching DTS/PTS."); } lastVideoNALU.buffer.position = lastVideoNALU.buffer.length; b.position = 0; lastVideoNALU.buffer.writeBytes(b, cursor, start - cursor); cursor = start; } else { // Submit previous data. if(lastVideoNALU) { pendingBuffers.push(lastVideoNALU.clone()); } // Update NALU state. lastVideoNALU = new NALU(); lastVideoNALU.buffer = new ByteArray(); lastVideoNALU.pts = pts; lastVideoNALU.dts = dts; lastVideoNALU.type = packet.type; lastVideoNALU.buffer.writeBytes(b, cursor); } } else if(types[packet.packetID] == 0x0F) { // It's an AAC stream. pendingBuffers.push(packet.clone()); } else if(types[packet.packetID] == 0x03 || types[packet.packetID] == 0x04) { // It's an MP3 stream. pendingBuffers.push(packet.clone()); } else { CONFIG::LOGGING { logger.warn("Unknown packet ID type " + types[packet.packetID] + ", ignoring (A)."); } } bufferPendingNalus(); return true; } /** * To avoid transcoding all content on flush, we buffer it into FLV * tags as we go. However, they remain undelivered until we can gather * final SPS/PPS information. This method is responsible for * incrementally buffering in the FLV transcoder as we go. */ public function bufferPendingNalus():void { // Iterate and buffer new NALUs. for(var i:int=pendingLastConvertedIndex; i<pendingBuffers.length; i++) { if(pendingBuffers[i] is NALU) { transcoder.convert(pendingBuffers[i] as NALU); } else if(pendingBuffers[i] is PESPacket) { var packet:PESPacket = pendingBuffers[i] as PESPacket; if(packet.type == 0x0F) { // It's an AAC stream. transcoder.convertAAC(packet); } else if(packet.type == 0x03 || packet.type == 0x04) { // It's an MP3 stream. Pass through directly. transcoder.convertMP3(packet); } else { CONFIG::LOGGING { logger.warn("Unknown packet ID type " + packet.type + ", ignoring (B)."); } } } } // Note the last item we converted so we can avoid duplicating work. pendingLastConvertedIndex = pendingBuffers.length; } public function processAllNalus():void { // Consume any unposted video NALUs. if(lastVideoNALU) { pendingBuffers.push(lastVideoNALU.clone()); lastVideoNALU = null; } // First walk all the video NALUs and get the correct SPS/PPS if(pendingBuffers.length == 0) return; // Then emit SPS/PPS transcoder.emitSPSPPSUnbuffered(); // Complete buffering and emit it all. bufferPendingNalus(); transcoder.emitBufferedTags(); // Don't forget to clear the pending list. pendingBuffers.length = 0; pendingLastConvertedIndex = 0; } } }
rollback for pts/dts fix
rollback for pts/dts fix fix for live problem (fail to play several streams - QA and customer): https://kaltura.atlassian.net/browse/FEC-4080 - regression since 2.35.rc4 Original defect - https://kaltura.atlassian.net/browse/FEC-3720 Commented code didn’t fix the original defect, so right now it commented.
ActionScript
agpl-3.0
kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF
c8419cef81eb19934c01a95ec1a73d72679b0d6c
build-aux/urbi.as
build-aux/urbi.as
## -*- shell-script -*- ## urbi.as: This file is part of build-aux. ## Copyright (C) Gostai S.A.S., 2006-2008. ## ## This software is provided "as is" without warranty of any kind, ## either expressed or implied, including but not limited to the ## implied warranties of fitness for a particular purpose. ## ## See the LICENSE file for more information. ## For comments, bug reports and feedback: http://www.urbiforge.com ## m4_pattern_allow([^URBI_SERVER$]) m4_divert_text([URBI-INIT], [ # check_dir VARIABLE WITNESS # -------------------------- # Check that VARIABLE contains a directory name that contains WITNESS. check_dir () { local var=$[1] local witness=$[2] local dir eval "dir=\$$[1]" test x"$dir" != x || fatal "undefined variable: $var" shift test -e "$dir" || fatal "$var does not exist: $dir" "(pwd = $(pwd))" test -d "$dir" || fatal "$var is not a directory: $dir" "(pwd = $(pwd))" if test x"$witness" != x; then test -f "$dir/$witness" || fatal "$var does not contain $witness: $dir" "(pwd = $(pwd))" fi } # check_and_abs_dir VAR WITNESS # ----------------------------- # Check that $VAR/WITNESS exists, and set VAR to $(absolute $VAR). check_and_abs_dir () { local var=$[1] local witness=$[2] check_dir "$[@]" # Normalize the directory name, and as safety belts, run the same # tests on it. But save time if possible. So put in "$@" the dirs # to check, the last one being the actual result. AS_IF([! is_absolute "$val"], [local dir eval "dir=\$$[1]" dir=$(absolute "$val") check_dir "$dir" "$witness" eval "$var='$dir'" ]) } # find_srcdir WITNESS # ------------------- # Find the location of the src directory of the tests suite. # Make sure the value is correct by checking for the presence of WITNESS. find_srcdir () { # Guess srcdir if not defined. if test -z "$srcdir"; then # Try to compute it from $[0]. srcdir=$(dirname "$[0]") fi check_dir srcdir "$[1]" } # find_top_builddir [POSSIBILITIES] # --------------------------------- # Set/check top_builddir. # - $top_builddir if the user wants to define it, # - (dirname $0)/.. since that's where we are supposed to be # - ../.. for the common case where we're in tests/my-test.dir # - .. if we're in tests/ # - . if we're in top-builddir. find_top_builddir () { if test x"$top_builddir" = x; then if test $[#] = 0; then set $(dirname "$0")/.. ../.. .. . fi for d do if test -f "$d/config.status"; then top_builddir=$d break fi done fi check_dir top_builddir "config.status" } # find_urbi_server # ---------------- # Set URBI_SERVER to the location of urbi-server. find_urbi_server () { case $URBI_SERVER in ('') # If URBI_SERVER is not defined, try to find one. If we are in # $top_builddir/tests/TEST.dir, then look in $top_builddir/src. URBI_SERVER=$(find_prog "urbi-server" \ "$top_builddir/src${PATH_SEPARATOR}.") ;; (*[[\\/]]*) # A path, relative or absolute. Make it absolute. URBI_SERVER=$(absolute "$URBI_SERVER") ;; (*) # A simple name, most certainly urbi-server. # Find it in the PATH. local res res=$(find_prog "$URBI_SERVER") # If we can't find it, then ucore-pc was probably not installed. # Skip. test x"$res" != x || error 77 "cannot find $URBI_SERVER in $PATH" URBI_SERVER=$res ;; esac if test -z "$URBI_SERVER"; then fatal "cannot find urbi-server, please define URBI_SERVER" fi if test ! -f "$URBI_SERVER"; then fatal "cannot find urbi-server, please check \$URBI_SERVER: $URBI_SERVER" fi # Check its version. if ! run "Server version" "$URBI_SERVER" --version >&3; then fatal "cannot run $URBI_SERVER --version" fi } # spawn_urbi_server FLAGS # ----------------------- # Spawn an $URBI_SERVER in back-ground, registering it as the child "server". # Wait until the server.port file is created. Make it fatal if this does # not happen with 10s. # # Dies if the server does not create server.port for whatever reason. spawn_urbi_server () { rm -f server.port local flags="--port 0 --port-file server.port $*" local cmd="$(instrument "server.val") $URBI_SERVER $flags" echo "$cmd" >server.cmd $cmd </dev/null >server.out 2>server.err & children_register server # Wait for the port file to be completed: it must have one full line # (with \n to be sure it is complete). local t=0 local tmax=8 local dt=.5 # 0 if we stop, 1 to continue sleeping. local cont while children_alive server && { test ! -f server.port || test $(wc -l <server.port) = 0; }; do # test/expr don't like floating points. cont=$(echo "$t <= $tmax" | bc) case $cont in (1) sleep $dt t=$(echo "$t + $dt" | bc);; (0) fatal "$URBI_SERVER did not issue port in server.port in ${tmax}s";; esac done test -f server.port || fatal "$URBI_SERVER failed before creating server.por" } ])
## -*- shell-script -*- ## urbi.as: This file is part of build-aux. ## Copyright (C) Gostai S.A.S., 2006-2008. ## ## This software is provided "as is" without warranty of any kind, ## either expressed or implied, including but not limited to the ## implied warranties of fitness for a particular purpose. ## ## See the LICENSE file for more information. ## For comments, bug reports and feedback: http://www.urbiforge.com ## m4_pattern_allow([^URBI_SERVER$]) m4_divert_text([URBI-INIT], [ # check_dir VARIABLE WITNESS # -------------------------- # Check that VARIABLE contains a directory name that contains WITNESS. check_dir () { local var=$[1] local witness=$[2] local dir eval "dir=\$$[1]" test x"$dir" != x || fatal "undefined variable: $var" shift test -e "$dir" || fatal "$var does not exist: $dir" "(pwd = $(pwd))" test -d "$dir" || fatal "$var is not a directory: $dir" "(pwd = $(pwd))" if test x"$witness" != x; then test -f "$dir/$witness" || fatal "$var does not contain $witness: $dir" "(pwd = $(pwd))" fi } # check_and_abs_dir VAR WITNESS # ----------------------------- # Check that $VAR/WITNESS exists, and set VAR to $(absolute $VAR). check_and_abs_dir () { local var=$[1] local witness=$[2] check_dir "$[@]" # Normalize the directory name, and as safety belts, run the same # tests on it. But save time if possible. So put in "$@" the dirs # to check, the last one being the actual result. AS_IF([! is_absolute "$val"], [local dir eval "dir=\$$[1]" dir=$(absolute "$val") check_dir "$dir" "$witness" eval "$var='$dir'" ]) } # find_srcdir WITNESS # ------------------- # Find the location of the src directory of the tests suite. # Make sure the value is correct by checking for the presence of WITNESS. find_srcdir () { # Guess srcdir if not defined. if test -z "$srcdir"; then # Try to compute it from $[0]. srcdir=$(dirname "$[0]") fi check_dir srcdir "$[1]" } # find_top_builddir [POSSIBILITIES] # --------------------------------- # Set/check top_builddir. # - $top_builddir if the user wants to define it, # - (dirname $0)/.. since that's where we are supposed to be # - ../.. for the common case where we're in tests/my-test.dir # - .. if we're in tests/ # - . if we're in top-builddir. find_top_builddir () { if test x"$top_builddir" = x; then if test $[#] = 0; then set $(dirname "$0")/.. ../.. .. . fi for d do if test -f "$d/config.status"; then top_builddir=$d break fi done fi check_dir top_builddir "config.status" } # find_urbi_server # ---------------- # Set URBI_SERVER to the location of urbi-server. find_urbi_server () { case $URBI_SERVER in ('') # If URBI_SERVER is not defined, try to find one. If we are in # $top_builddir/tests/TEST.dir, then look in $top_builddir/src. URBI_SERVER=$(find_prog "urbi-server" \ "$top_builddir/src${PATH_SEPARATOR}.") ;; (*[[\\/]]*) # A path, relative or absolute. Make it absolute. URBI_SERVER=$(absolute "$URBI_SERVER") ;; (*) # A simple name, most certainly urbi-server. # Find it in the PATH. local res res=$(find_prog "$URBI_SERVER") # If we can't find it, then ucore-pc was probably not installed. # Skip. test x"$res" != x || error SKIP "cannot find $URBI_SERVER in $PATH" URBI_SERVER=$res ;; esac if test -z "$URBI_SERVER"; then fatal "cannot find urbi-server, please define URBI_SERVER" fi if test ! -f "$URBI_SERVER"; then fatal "cannot find urbi-server, please check \$URBI_SERVER: $URBI_SERVER" fi # Check its version. if ! run "Server version" "$URBI_SERVER" --version >&3; then fatal "cannot run $URBI_SERVER --version" fi } # spawn_urbi_server FLAGS # ----------------------- # Spawn an $URBI_SERVER in back-ground, registering it as the child "server". # Wait until the server.port file is created. Make it fatal if this does # not happen with 10s. # # Dies if the server does not create server.port for whatever reason. spawn_urbi_server () { rm -f server.port local flags="--port 0 --port-file server.port $*" local cmd="$(instrument "server.val") $URBI_SERVER $flags" echo "$cmd" >server.cmd $cmd </dev/null >server.out 2>server.err & children_register server # Wait for the port file to be completed: it must have one full line # (with \n to be sure it is complete). local t=0 local tmax=8 local dt=.5 # 0 if we stop, 1 to continue sleeping. local cont while children_alive server && { test ! -f server.port || test $(wc -l <server.port) = 0; }; do # test/expr don't like floating points. cont=$(echo "$t <= $tmax" | bc) case $cont in (1) sleep $dt t=$(echo "$t + $dt" | bc);; (0) fatal "$URBI_SERVER did not issue port in server.port in ${tmax}s";; esac done test -f server.port || fatal "$URBI_SERVER failed before creating server.por" } ])
Use the right exit status for SKIP.
Use the right exit status for SKIP. * build-aux/urbi.as (find_urbi_server): 77 is not SKIP.
ActionScript
bsd-3-clause
aldebaran/libport,aldebaran/libport,aldebaran/libport,aldebaran/libport,aldebaran/libport
b073ae84ae7049cdafc593d6a4c6e519046cbe34
WEB-INF/lps/lfc/kernel/swf9/LzHTTPLoader.as
WEB-INF/lps/lfc/kernel/swf9/LzHTTPLoader.as
/** * LzHTTPLoader.as * * @copyright Copyright 2007-2009 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic swf9 * @affects lzloader */ public class LzHTTPLoader { #passthrough (toplevel:true) { import flash.events.IEventDispatcher; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.net.URLLoader; import flash.net.URLLoaderDataFormat; import flash.net.URLRequest; import flash.net.URLRequestHeader; import flash.net.URLRequestMethod; }# static const GET_METHOD:String = "GET"; static const POST_METHOD:String = "POST"; static const PUT_METHOD:String = "PUT"; static const DELETE_METHOD:String = "DELETE"; // holds list of outstanding data requests, to handle timeouts static const activeRequests :Object = {}; static var loaderIDCounter :uint = 0; const owner:*; const __loaderid:uint; var __abort:Boolean = false; var __timeout:Boolean = false; var gstart:Number; var secure:Boolean; var options:Object; // Default infinite timeout var timeout:Number = Infinity; var requestheaders:Object; var requestmethod:String; var requesturl:String; var responseText:String; var responseXML:XML = null; // The URLLoader object var loader:URLLoader = null; var dataRequest:LzHTTPDataRequest = null; var baserequest:LzURL; var secureport:uint; public function LzHTTPLoader (owner:*, proxied:Boolean) { super(); this.owner = owner; this.options = {parsexml: true, serverproxyargs: null}; this.requestheaders = {}; this.requestmethod = LzHTTPLoader.GET_METHOD; this.__loaderid = LzHTTPLoader.loaderIDCounter++; } // Default callback handlers public var loadSuccess:Function = function (...data) :void { trace('loadSuccess callback not defined on', this); } public var loadError:Function = function (...data) :void { trace('loadError callback not defined on', this); }; public var loadTimeout:Function = function (...data) :void { trace('loadTimeout callback not defined on', this); }; /* Returns the response as a string */ public function getResponse () :String { return this.responseText; } /* Returns numeric status code (200, 404, 500, etc...) */ public function getResponseStatus () :int { // nyi - only available in IE, see doc: flash.events.HTTPStatusEvent#status return 0; } /* Returns an array of response headers */ public function getResponseHeaders () :Array { // There seems to be no way to get response headers in the flash.net URLLoader API // flash.events.HTTPStatusEvent docs say response headers are AIR-only return null; } public function getResponseHeader (key:String) :String { // There seems to be no way to get response headers in the flash.net URLLoader API trace('getResponseHeader not implemented in swf9'); return null; } /* @param Object obj: A hash table of headers for the HTTP request @access public */ public function setRequestHeaders (obj:Object) :void { this.requestheaders = obj; } /* @param String key: HTTP request header name @param String val: header value @access public */ public function setRequestHeader (key:String, val:String) :void { this.requestheaders[key] = val; } /* @public */ public function setOption (key:String, val:*) :void { this.options[key] = val; } /* @public */ public function getOption (key:String) :* { return this.options[key]; } /* @public */ public function setProxied (proxied:Boolean) :void { this.setOption('proxied', proxied); } /* @public */ public function setQueryParams (qparams:Object) :void { } /* @public */ public function setQueryString (qstring:String) :void { } /* If queueRequests is true, subsequent requests will made sequentially If queueRequests is false, subsequent requests will interrupt requests already in process */ public function setQueueing (queuing:Boolean) :void { this.setOption('queuing', queuing); // [todo hqm 2006-07] NYI } public function abort () :void { if (this.loader) { this.__abort = true; this.loader.close(); this.loader = null; this.removeTimeout(this); } } // headers can be a hashtable or null public function open (method:String, url:String, username:String = null, password:String = null) :void { if (this.loader) { if ($debug) { Debug.warn("pending request for id=%s", this.__loaderid); } this.abort(); } this.loader = new URLLoader(); this.loader.dataFormat = URLLoaderDataFormat.TEXT; this.responseText = null; this.responseXML = null; this.__abort = false; this.__timeout = false; this.requesturl = url; this.requestmethod = method; } public function send (content:String = null) :void { this.loadXMLDoc(/* method */ this.requestmethod, /* url */ this.requesturl, /* headers */ this.requestheaders, /* postbody */ content, /* ignorewhite */ true); } // @access public // @param String url: url, including query args // @param String reqtype: 'POST' or 'GET' // @param Object headers: hash table of HTTP request headers public function makeProxiedURL( proxyurl:String, url:String, httpmethod:String, lzt:String, headers:Object, postbody:String):String { var params:Object = { serverproxyargs: this.options.serverproxyargs, sendheaders: this.options.sendheaders, trimwhitespace: this.options.trimwhitespace, nsprefix: this.options.nsprefix, timeout: this.timeout, cache: this.options.cacheable, ccache: this.options.ccache, proxyurl: proxyurl, url: url, secure: this.secure, postbody: postbody, headers: headers, httpmethod: httpmethod, service: lzt }; return lz.Browser.makeProxiedURL(params); } public function setTimeout (timeout:Number) :void { this.timeout = timeout; // [todo hqm 2006-07] Should we have an API method for setting LzLoader timeout? } // Set up a pending timeout for a loader. public function setupTimeout (httploader:LzHTTPLoader, duration:Number) :void { var endtime:Number = (new Date()).getTime() + duration; var lid:uint = httploader.__loaderid; LzHTTPLoader.activeRequests[lid] = [httploader, endtime]; var callback:Function = function () :void { LzHTTPLoader.__LZcheckXMLHTTPTimeouts(lid); } var timeoutid:uint = LzTimeKernel.setTimeout(callback, duration); LzHTTPLoader.activeRequests[lid][2] = timeoutid; } // Remove a loader from the timeouts list. public function removeTimeout (httploader:LzHTTPLoader) :void { var lid:uint = httploader.__loaderid; //Debug.write("remove timeout for id=%s", lid); var reqarr:Array = LzHTTPLoader.activeRequests[lid]; if (reqarr && reqarr[0] === httploader) { LzTimeKernel.clearTimeout(reqarr[2]); delete LzHTTPLoader.activeRequests[lid]; } } // Check if any outstanding requests have timed out. static function __LZcheckXMLHTTPTimeouts (lid:uint) :void { var req:Array = LzHTTPLoader.activeRequests[lid]; if (req) { var now:Number = (new Date()).getTime(); var httploader:LzHTTPLoader = req[0]; var dstimeout:Number = req[1]; //Debug.write("diff %d", now - dstimeout); if (now >= dstimeout) { //Debug.write("timeout for %s", lid); delete LzHTTPLoader.activeRequests[lid]; httploader.__timeout = true; httploader.abort(); httploader.loadTimeout(httploader, null); } else { // if it hasn't timed out, add it back to the list for the future //Debug.write("recheck timeout"); var callback:Function = function () :void { LzHTTPLoader.__LZcheckXMLHTTPTimeouts(lid); } var timeoutid:uint = LzTimeKernel.setTimeout(callback, now - dstimeout); req[2] = timeoutid; } } } public function getElapsedTime () :Number { return ((new Date()).getTime() - this.gstart); } private function configureListeners(dispatcher:IEventDispatcher):void { dispatcher.addEventListener(Event.COMPLETE, completeHandler); dispatcher.addEventListener(Event.OPEN, openHandler); dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler); dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); } private function completeHandler(event:Event):void { // trace("completeHandler: " + event + ", target = " + event.target); if (event && event.target is URLLoader) { //trace("completeHandler: " , this, loader); //trace("completeHandler: bytesLoaded" , loader.bytesLoaded, 'bytesTotal', loader.bytesTotal); //trace('typeof data:', typeof(loader.data), loader.data.length, 'parsexml=', options.parsexml); if (this.loader == null) { // URLLoader was cleared, ignore complete event } else if (this.__timeout) { // request has timed out, ignore complete event } else if (this.__abort) { // request was cancelled, ignore complete event } else { removeTimeout(this); this.responseText = loader.data; loader = null; if (this.options['parsexml']) { var lzxdata:LzDataElement = null; // Parse data into flash native XML and then convert to LFC LzDataElement tree try { if (this.responseText != null) { // This is almost identical to LzXMLParser.parseXML() // except ignoreWhitespace comes from options XML.ignoreWhitespace = options.trimwhitespace; this.responseXML = XML(responseText); this.responseXML.normalize(); lzxdata = LzXMLTranslator.copyXML(this.responseXML, options.trimwhitespace, options.nsprefix); } } catch (err:Error) { trace("caught error parsing xml", err); loadError(this, null); return; } loadSuccess(this, lzxdata); } else { loadSuccess(this, this.responseText); } } } } private function openHandler(event:Event):void { trace("openHandler: " + event); } private function progressHandler(event:ProgressEvent):void { trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal); } private function securityErrorHandler(event:SecurityErrorEvent):void { trace("securityErrorHandler: " + event); removeTimeout(this); loader = null; loadError(this, null); } private function ioErrorHandler(event:IOErrorEvent):void { trace("ioErrorHandler: " + event); removeTimeout(this); loader = null; loadError(this, null); } // public // parseXML flag : if true, translate native XML tree into LzDataNode tree, // if false, don't attempt to translate the XML (if it exists) public function loadXMLDoc (method:String, url:String, headers:Object, postbody:String, ignorewhite:Boolean) :void { if (this.loader == null) { // TODO [hqm 2008-01] wonder if we should be throwing an // exception or returning some indication that the send // did not execute? XMLHttpRequest doesn't return // anything, but we could... or maybe at least a debugger // message? if ($debug) { Debug.warn("LzHTTPLoader.send, no request to send to, has open() been called?"); } return; } var secure:Boolean = (url.indexOf("https:") == 0); url = lz.Browser.toAbsoluteURL( url, secure ); configureListeners(this.loader); var request:URLRequest = new URLRequest(url); request.data = postbody; request.method = (method == LzHTTPLoader.GET_METHOD) ? URLRequestMethod.GET : URLRequestMethod.POST; //TODO: [20080916 anba] set content-type? //request.contentType = "application/x-www-form-urlencoded"; var hasContentType:Boolean = false; for (var k:String in headers) { request.requestHeaders.push(new URLRequestHeader(k, headers[k])); if (k.toLowerCase() == "content-type") { hasContentType = true; } } // If no content-type for POST was explicitly specified, // use "application/x-www-form-urlencoded" if ((method == "POST") && !hasContentType) { request.requestHeaders.push( new URLRequestHeader('Content-Type', 'application/x-www-form-urlencoded')); } try { this.gstart = (new Date()).getTime(); this.loader.load(request); // Set up the timeout if (isFinite(this.timeout)) { this.setupTimeout(this, this.timeout); } } catch (error) { // TODO [hqm 2008-01] make this send appropriate error event to listener, // and abort the load. trace("Unable to load requested document.", error); } } } /* Event Summary Defined By complete Dispatched after all the received data is decoded and placed in the data property of the URLLoader object. httpStatus Dispatched if a call to URLLoader.load() attempts to access data over HTTP and the current Flash Player environment is able to detect and return the status code for the request. URLLoader ioError Dispatched if a call to URLLoader.load() results in a fatal error that terminates the download. URLLoader open Dispatched when the download operation commences following a call to the URLLoader.load() method. URLLoader progress Dispatched when data is received as the download operation progresses. URLLoader securityError Dispatched if a call to URLLoader.load() attempts to load data from a server outside the security sandbox. URLLoader */
/** * LzHTTPLoader.as * * @copyright Copyright 2007-2010 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic swf9 * @affects lzloader */ public class LzHTTPLoader { #passthrough (toplevel:true) { import flash.events.IEventDispatcher; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.net.URLLoader; import flash.net.URLLoaderDataFormat; import flash.net.URLRequest; import flash.net.URLRequestHeader; import flash.net.URLRequestMethod; }# static const GET_METHOD:String = "GET"; static const POST_METHOD:String = "POST"; static const PUT_METHOD:String = "PUT"; static const DELETE_METHOD:String = "DELETE"; // holds list of outstanding data requests, to handle timeouts static const activeRequests :Object = {}; static var loaderIDCounter :uint = 0; const owner:*; const __loaderid:uint; var __abort:Boolean = false; var __timeout:Boolean = false; var gstart:Number; var secure:Boolean; var options:Object; // Default infinite timeout var timeout:Number = Infinity; var requestheaders:Object; var requestmethod:String; var requesturl:String; var responseText:String; var responseXML:XML = null; // The URLLoader object var loader:URLLoader = null; var dataRequest:LzHTTPDataRequest = null; var baserequest:LzURL; var secureport:uint; public function LzHTTPLoader (owner:*, proxied:Boolean) { super(); this.owner = owner; this.options = {parsexml: true, serverproxyargs: null}; this.requestheaders = {}; this.requestmethod = LzHTTPLoader.GET_METHOD; this.__loaderid = LzHTTPLoader.loaderIDCounter++; } // Default callback handlers public var loadSuccess:Function = function (...data) :void { trace('loadSuccess callback not defined on', this); } public var loadError:Function = function (...data) :void { trace('loadError callback not defined on', this); }; public var loadTimeout:Function = function (...data) :void { trace('loadTimeout callback not defined on', this); }; /* Returns the response as a string */ public function getResponse () :String { return this.responseText; } /* Returns numeric status code (200, 404, 500, etc...) */ public function getResponseStatus () :int { // nyi - only available in IE, see doc: flash.events.HTTPStatusEvent#status return 0; } /* Returns an array of response headers */ public function getResponseHeaders () :Array { // There seems to be no way to get response headers in the flash.net URLLoader API // flash.events.HTTPStatusEvent docs say response headers are AIR-only return null; } public function getResponseHeader (key:String) :String { // There seems to be no way to get response headers in the flash.net URLLoader API return null; } /* @param Object obj: A hash table of headers for the HTTP request @access public */ public function setRequestHeaders (obj:Object) :void { this.requestheaders = obj; } /* @param String key: HTTP request header name @param String val: header value @access public */ public function setRequestHeader (key:String, val:String) :void { this.requestheaders[key] = val; } /* @public */ public function setOption (key:String, val:*) :void { this.options[key] = val; } /* @public */ public function getOption (key:String) :* { return this.options[key]; } /* @public */ public function setProxied (proxied:Boolean) :void { this.setOption('proxied', proxied); } /* @public */ public function setQueryParams (qparams:Object) :void { } /* @public */ public function setQueryString (qstring:String) :void { } /* If queueRequests is true, subsequent requests will made sequentially If queueRequests is false, subsequent requests will interrupt requests already in process */ public function setQueueing (queuing:Boolean) :void { this.setOption('queuing', queuing); // [todo hqm 2006-07] NYI } public function abort () :void { if (this.loader) { this.__abort = true; this.loader.close(); this.loader = null; this.removeTimeout(this); } } // headers can be a hashtable or null public function open (method:String, url:String, username:String = null, password:String = null) :void { if (this.loader) { if ($debug) { Debug.warn("pending request for id=%s", this.__loaderid); } this.abort(); } this.loader = new URLLoader(); this.loader.dataFormat = URLLoaderDataFormat.TEXT; this.responseText = null; this.responseXML = null; this.__abort = false; this.__timeout = false; this.requesturl = url; this.requestmethod = method; } public function send (content:String = null) :void { this.loadXMLDoc(/* method */ this.requestmethod, /* url */ this.requesturl, /* headers */ this.requestheaders, /* postbody */ content, /* ignorewhite */ true); } // @access public // @param String url: url, including query args // @param String reqtype: 'POST' or 'GET' // @param Object headers: hash table of HTTP request headers public function makeProxiedURL( proxyurl:String, url:String, httpmethod:String, lzt:String, headers:Object, postbody:String):String { var params:Object = { serverproxyargs: this.options.serverproxyargs, sendheaders: this.options.sendheaders, trimwhitespace: this.options.trimwhitespace, nsprefix: this.options.nsprefix, timeout: this.timeout, cache: this.options.cacheable, ccache: this.options.ccache, proxyurl: proxyurl, url: url, secure: this.secure, postbody: postbody, headers: headers, httpmethod: httpmethod, service: lzt }; return lz.Browser.makeProxiedURL(params); } public function setTimeout (timeout:Number) :void { this.timeout = timeout; // [todo hqm 2006-07] Should we have an API method for setting LzLoader timeout? } // Set up a pending timeout for a loader. public function setupTimeout (httploader:LzHTTPLoader, duration:Number) :void { var endtime:Number = (new Date()).getTime() + duration; var lid:uint = httploader.__loaderid; LzHTTPLoader.activeRequests[lid] = [httploader, endtime]; var callback:Function = function () :void { LzHTTPLoader.__LZcheckXMLHTTPTimeouts(lid); } var timeoutid:uint = LzTimeKernel.setTimeout(callback, duration); LzHTTPLoader.activeRequests[lid][2] = timeoutid; } // Remove a loader from the timeouts list. public function removeTimeout (httploader:LzHTTPLoader) :void { var lid:uint = httploader.__loaderid; //Debug.write("remove timeout for id=%s", lid); var reqarr:Array = LzHTTPLoader.activeRequests[lid]; if (reqarr && reqarr[0] === httploader) { LzTimeKernel.clearTimeout(reqarr[2]); delete LzHTTPLoader.activeRequests[lid]; } } // Check if any outstanding requests have timed out. static function __LZcheckXMLHTTPTimeouts (lid:uint) :void { var req:Array = LzHTTPLoader.activeRequests[lid]; if (req) { var now:Number = (new Date()).getTime(); var httploader:LzHTTPLoader = req[0]; var dstimeout:Number = req[1]; //Debug.write("diff %d", now - dstimeout); if (now >= dstimeout) { //Debug.write("timeout for %s", lid); delete LzHTTPLoader.activeRequests[lid]; httploader.__timeout = true; httploader.abort(); httploader.loadTimeout(httploader, null); } else { // if it hasn't timed out, add it back to the list for the future //Debug.write("recheck timeout"); var callback:Function = function () :void { LzHTTPLoader.__LZcheckXMLHTTPTimeouts(lid); } var timeoutid:uint = LzTimeKernel.setTimeout(callback, now - dstimeout); req[2] = timeoutid; } } } public function getElapsedTime () :Number { return ((new Date()).getTime() - this.gstart); } private function configureListeners(dispatcher:IEventDispatcher):void { dispatcher.addEventListener(Event.COMPLETE, completeHandler); dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); } private function completeHandler(event:Event):void { // trace("completeHandler: " + event + ", target = " + event.target); if (event && event.target is URLLoader) { //trace("completeHandler: " , this, loader); //trace("completeHandler: bytesLoaded" , loader.bytesLoaded, 'bytesTotal', loader.bytesTotal); //trace('typeof data:', typeof(loader.data), loader.data.length, 'parsexml=', options.parsexml); if (this.loader == null) { // URLLoader was cleared, ignore complete event } else if (this.__timeout) { // request has timed out, ignore complete event } else if (this.__abort) { // request was cancelled, ignore complete event } else { removeTimeout(this); this.responseText = loader.data; loader = null; if (this.options['parsexml']) { var lzxdata:LzDataElement = null; // Parse data into flash native XML and then convert to LFC LzDataElement tree try { if (this.responseText != null) { // This is almost identical to LzXMLParser.parseXML() // except ignoreWhitespace comes from options XML.ignoreWhitespace = options.trimwhitespace; this.responseXML = XML(responseText); this.responseXML.normalize(); lzxdata = LzXMLTranslator.copyXML(this.responseXML, options.trimwhitespace, options.nsprefix); } } catch (err:Error) { loadError(this, null); return; } loadSuccess(this, lzxdata); } else { loadSuccess(this, this.responseText); } } } } private function securityErrorHandler(event:SecurityErrorEvent):void { removeTimeout(this); loader = null; loadError(this, null); } private function ioErrorHandler(event:IOErrorEvent):void { removeTimeout(this); loader = null; loadError(this, null); } // public // parseXML flag : if true, translate native XML tree into LzDataNode tree, // if false, don't attempt to translate the XML (if it exists) public function loadXMLDoc (method:String, url:String, headers:Object, postbody:String, ignorewhite:Boolean) :void { if (this.loader == null) { // TODO [hqm 2008-01] wonder if we should be throwing an // exception or returning some indication that the send // did not execute? XMLHttpRequest doesn't return // anything, but we could... or maybe at least a debugger // message? if ($debug) { Debug.warn("LzHTTPLoader.send, no request to send to, has open() been called?"); } return; } var secure:Boolean = (url.indexOf("https:") == 0); url = lz.Browser.toAbsoluteURL( url, secure ); configureListeners(this.loader); var request:URLRequest = new URLRequest(url); request.data = postbody; request.method = (method == LzHTTPLoader.GET_METHOD) ? URLRequestMethod.GET : URLRequestMethod.POST; //TODO: [20080916 anba] set content-type? //request.contentType = "application/x-www-form-urlencoded"; var hasContentType:Boolean = false; for (var k:String in headers) { request.requestHeaders.push(new URLRequestHeader(k, headers[k])); if (k.toLowerCase() == "content-type") { hasContentType = true; } } // If no content-type for POST was explicitly specified, // use "application/x-www-form-urlencoded" if ((method == "POST") && !hasContentType) { request.requestHeaders.push( new URLRequestHeader('Content-Type', 'application/x-www-form-urlencoded')); } try { this.gstart = (new Date()).getTime(); this.loader.load(request); // Set up the timeout if (isFinite(this.timeout)) { this.setupTimeout(this, this.timeout); } } catch (error:Error) { this.loader = null; this.loadError(this, null); } } }
Change 20100225-bargull-yMA by bargull@dell--p4--2-53 on 2010-02-25 00:16:01 in /home/Admin/src/svn/openlaszlo/trunk for http://svn.openlaszlo.org/openlaszlo/trunk
Change 20100225-bargull-yMA by bargull@dell--p4--2-53 on 2010-02-25 00:16:01 in /home/Admin/src/svn/openlaszlo/trunk for http://svn.openlaszlo.org/openlaszlo/trunk Summary: clear URLLoader if load fails New Features: Bugs Fixed: LPP-8789 (SWF9/10: Unhandled URLStream error) Technical Reviewer: henry QA Reviewer: (pending) Doc Reviewer: (pending) Documentation: Release Notes: Overview: Details: If an error was thrown when calling URLLoader#load() in loadXMLDoc(), the "loader" member wasn't set to null. This led to a bug because the next time open() was called, the abort() function was invoked since there was still a "loader". abort() calls URLLoader#close(), but you are only allowed to call this function if there is an open stream. Setting the "loader" to null in the catch bug fixes this bug. I've also added a call to loadError() to inform the user about the error. Additionally, I've removed the copied parts from the URLLoader docs (no longer necessary here), a few calls to trace() which were added initially to help implementing the data support for swf9. Tests: see bugreport git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@15813 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
ActionScript
epl-1.0
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
b470c89b6529d3acb4d8dce6a111a2b953ef91a4
src/aerys/minko/render/geometry/stream/iterator/VertexIterator.as
src/aerys/minko/render/geometry/stream/iterator/VertexIterator.as
package aerys.minko.render.geometry.stream.iterator { import aerys.minko.ns.minko_stream; import aerys.minko.render.geometry.stream.IVertexStream; import aerys.minko.render.geometry.stream.IndexStream; import aerys.minko.render.geometry.stream.format.VertexComponent; import aerys.minko.render.geometry.stream.format.VertexFormat; import flash.utils.Proxy; import flash.utils.flash_proxy; /** * VertexIterator allow per-vertex access on VertexStream objects. * * The class overrides the "[]" and "delete" operators and is iterable * using "for" and "for each" loops. It enable an higher level and easier * traversal and manipulation of the underlaying data stream while * minimizing the memory footprint. * * <pre> * public function printPositions(mesh : IMesh) : void * { * var vertices : VertexIterator = new VertexIterator(mesh.vertexStream); * * for each (var vertex : VertexReference in vertices) * trac e(vertex.x, vertex.y, vertex.z); * } * </pre> * * @author Jean-Marc Le Roux * */ public dynamic final class VertexIterator extends Proxy { use namespace minko_stream; private var _index : uint; private var _offset : uint; private var _singleReference : Boolean; private var _vertex : VertexReference; private var _vstream : IVertexStream; private var _istream : IndexStream; private var _propertyToStream : Object; public function get vertexStream() : IVertexStream { return _vstream; } public function get length() : int { return _istream ? _istream.length : _vstream.numVertices; } /** * Create a new VertexIterator instance. * * If the "singleReference" argument is true, only one VertexReference * will be created during a "for each" loop on the iterator. This * VertexReference will be updated at each iteration to provide * the data of the current vertex. Otherwise, a dedicated * VertexReference will be provided at each iteration. Using the * "single reference" mode is nicer on the memory footprint, but makes * it impossible to keep a VertexReference object and re-use it later * as it will be automatically updated at each iteration. * * @param vertexStream The VertexStream to use. * * @param indexStream The IndexStream to use. If none is * provided, the iterator will iterate on each vertex of the * VertexStream. Otherwise, the iterator will iterate * on vertices as provided by the indices in the IndexStream. * * @param shallow Whether to use the "single reference" mode. * * @return * */ public function VertexIterator(vertexStream : IVertexStream, indexStream : IndexStream = null, singleReference : Boolean = true) { super(); _vstream = vertexStream; _istream = indexStream; _singleReference = singleReference; initialize(); } private function initialize() : void { _propertyToStream = {}; var format : VertexFormat = _vstream.format; var numComponents : uint = format.numComponents; for (var componentIndex : uint = 0; componentIndex < numComponents; ++componentIndex) { var component : VertexComponent = format.getComponent(componentIndex); var numProperties : uint = component.numProperties; for (var propertyId : uint = 0; propertyId < numProperties; ++propertyId) { _propertyToStream[component.getProperty(propertyId)] = _vstream.getStreamByComponent( component ); } } } override flash_proxy function getProperty(name : *) : * { var index : int = int(name); if (_istream) index = _istream.get(index); var vertex : VertexReference = _vertex; if (_singleReference) { if (!_vertex) { _vertex = new VertexReference(_vstream, index); _vertex._propertyToStream = _propertyToStream; } else { _vertex.index = index; } vertex = _vertex; } else { vertex = new VertexReference(_vstream, index); vertex._propertyToStream = _propertyToStream; } return vertex; } override flash_proxy function setProperty(name : *, value : *) : void { var ref : VertexReference = flash_proxy::getProperty(int(name)); var obj : Object = Object(value); var format : VertexFormat = _vstream.format; var numComponents : uint = format.numComponents; for (var componentIndex : uint = 0; componentIndex < numComponents; ++componentIndex) { var component : VertexComponent = format.getComponent(componentIndex); var numProperties : uint = component.numProperties; for (var propertyId : uint = 0; propertyId < numProperties; ++propertyId) { var propertyName : String = component.getProperty(propertyId); ref[propertyName] = Number(obj[propertyName]); } } } override flash_proxy function deleteProperty(name : *) : Boolean { var index : int = int(name); if (_vstream.deleteVertex(index)) { if (index <= _index) ++_offset; return true; } return false; } override flash_proxy function hasProperty(name : *) : Boolean { var index : int = int(name); return _istream ? index < _istream.length : index < _vstream.numVertices; } override flash_proxy function nextNameIndex(index : int) : int { index -= _offset; _offset = 0; return _istream ? index < _istream.length ? index + 1 : 0 : index < _vstream.numVertices ? index + 1 : 0; } override flash_proxy function nextName(index : int) : String { return String(index - 1); } override flash_proxy function nextValue(index : int) : * { _index = index - 1; index = _istream ? _istream.get(_index) : _index; if (!_singleReference || !_vertex) { _vertex = new VertexReference(_vstream, index); _vertex._propertyToStream = _propertyToStream; } if (_singleReference) _vertex.index = -_offset + index; return _vertex; } } }
package aerys.minko.render.geometry.stream.iterator { import aerys.minko.ns.minko_stream; import aerys.minko.render.geometry.stream.IVertexStream; import aerys.minko.render.geometry.stream.IndexStream; import aerys.minko.render.geometry.stream.format.VertexComponent; import aerys.minko.render.geometry.stream.format.VertexFormat; import flash.utils.Proxy; import flash.utils.flash_proxy; /** * VertexIterator allow per-vertex access on VertexStream objects. * * The class overrides the "[]" and "delete" operators and is iterable * using "for" and "for each" loops. It enable an higher level and easier * traversal and manipulation of the underlaying data stream while * minimizing the memory footprint. * * <pre> * public function printPositions(mesh : IMesh) : void * { * var vertices : VertexIterator = new VertexIterator(mesh.vertexStream); * * for each (var vertex : VertexReference in vertices) * trac e(vertex.x, vertex.y, vertex.z); * } * </pre> * * @author Jean-Marc Le Roux * */ public dynamic final class VertexIterator extends Proxy { use namespace minko_stream; private var _index : uint; private var _offset : uint; private var _singleReference : Boolean; private var _vertex : VertexReference; private var _vstream : IVertexStream; private var _istream : IndexStream; private var _propertyToStream : Object; public function get vertexStream() : IVertexStream { return _vstream; } public function get length() : uint { return _istream ? _istream.length : _vstream.numVertices; } /** * Create a new VertexIterator instance. * * If the "singleReference" argument is true, only one VertexReference * will be created during a "for each" loop on the iterator. This * VertexReference will be updated at each iteration to provide * the data of the current vertex. Otherwise, a dedicated * VertexReference will be provided at each iteration. Using the * "single reference" mode is nicer on the memory footprint, but makes * it impossible to keep a VertexReference object and re-use it later * as it will be automatically updated at each iteration. * * @param vertexStream The VertexStream to use. * * @param indexStream The IndexStream to use. If none is * provided, the iterator will iterate on each vertex of the * VertexStream. Otherwise, the iterator will iterate * on vertices as provided by the indices in the IndexStream. * * @param shallow Whether to use the "single reference" mode. * * @return * */ public function VertexIterator(vertexStream : IVertexStream, indexStream : IndexStream = null, singleReference : Boolean = true) { super(); _vstream = vertexStream; _istream = indexStream; _singleReference = singleReference; initialize(); } private function initialize() : void { _propertyToStream = {}; var format : VertexFormat = _vstream.format; var numComponents : uint = format.numComponents; for (var componentIndex : uint = 0; componentIndex < numComponents; ++componentIndex) { var component : VertexComponent = format.getComponent(componentIndex); var numProperties : uint = component.numProperties; for (var propertyId : uint = 0; propertyId < numProperties; ++propertyId) { _propertyToStream[component.getProperty(propertyId)] = _vstream.getStreamByComponent( component ); } } } override flash_proxy function getProperty(name : *) : * { var index : int = int(name); if (_istream) index = _istream.get(index); var vertex : VertexReference = _vertex; if (_singleReference) { if (!_vertex) { _vertex = new VertexReference(_vstream, index); _vertex._propertyToStream = _propertyToStream; } else { _vertex.index = index; } vertex = _vertex; } else { vertex = new VertexReference(_vstream, index); vertex._propertyToStream = _propertyToStream; } return vertex; } override flash_proxy function setProperty(name : *, value : *) : void { var ref : VertexReference = flash_proxy::getProperty(int(name)); var obj : Object = Object(value); var format : VertexFormat = _vstream.format; var numComponents : uint = format.numComponents; for (var componentIndex : uint = 0; componentIndex < numComponents; ++componentIndex) { var component : VertexComponent = format.getComponent(componentIndex); var numProperties : uint = component.numProperties; for (var propertyId : uint = 0; propertyId < numProperties; ++propertyId) { var propertyName : String = component.getProperty(propertyId); ref[propertyName] = Number(obj[propertyName]); } } } override flash_proxy function deleteProperty(name : *) : Boolean { var index : int = int(name); if (_vstream.deleteVertex(index)) { if (index <= _index) ++_offset; return true; } return false; } override flash_proxy function hasProperty(name : *) : Boolean { var index : int = int(name); return _istream ? index < _istream.length : index < _vstream.numVertices; } override flash_proxy function nextNameIndex(index : int) : int { index -= _offset; _offset = 0; return _istream ? index < _istream.length ? index + 1 : 0 : index < _vstream.numVertices ? index + 1 : 0; } override flash_proxy function nextName(index : int) : String { return String(index - 1); } override flash_proxy function nextValue(index : int) : * { _index = index - 1; index = _istream ? _istream.get(_index) : _index; if (!_singleReference || !_vertex) { _vertex = new VertexReference(_vstream, index); _vertex._propertyToStream = _propertyToStream; } if (_singleReference) _vertex.index = -_offset + index; return _vertex; } } }
set VertexIterator.length type to uint
set VertexIterator.length type to uint
ActionScript
mit
aerys/minko-as3
dcaed98f85c63f3b5646f85d1938cbc5804d801e
HLSPlugin/src/com/kaltura/hls/manifest/HLSManifestEncryptionKey.as
HLSPlugin/src/com/kaltura/hls/manifest/HLSManifestEncryptionKey.as
package com.kaltura.hls.manifest { import com.hurlant.util.Hex; import com.kaltura.hls.crypto.FastAESKey; import flash.events.Event; import flash.events.EventDispatcher; import flash.net.URLLoader; import flash.net.URLLoaderDataFormat; import flash.net.URLRequest; import flash.utils.ByteArray; import flash.utils.Dictionary; import flash.utils.getTimer; CONFIG::LOGGING { import org.osmf.logging.Logger; import org.osmf.logging.Log; } /** * HLSManifestEncryptionKey is used to parse AES decryption key data from a m3u8 * manifest, load the specified key file into memory, and use the key data to decrypt * audio and video streams. It supports AES-128 encryption with #PKCS7 padding, and uses * explicitly passed in Initialization Vectors. */ public class HLSManifestEncryptionKey extends EventDispatcher { CONFIG::LOGGING { private static const logger:Logger = Log.getLogger("com.kaltura.hls.manifest.HLSManifestEncryptionKey"); } private static const LOADER_CACHE:Dictionary = new Dictionary(); private var _key:FastAESKey; public var usePadding:Boolean = false; public var iv:String = ""; public var url:String = ""; private var iv0 : uint; private var iv1 : uint; private var iv2 : uint; private var iv3 : uint; // Keep track of the segments this key applies to public var startSegmentId:uint = 0; public var endSegmentId:uint = uint.MAX_VALUE; private var _keyData:ByteArray; public var isLoading:Boolean = false; public function HLSManifestEncryptionKey() { } public function get isLoaded():Boolean { return _keyData != null; } public override function toString():String { return "[HLSManifestEncryptionKey start=" + startSegmentId +", end=" + endSegmentId + ", iv=" + iv + ", url=" + url + ", loaded=" + isLoaded + "]"; } public static function fromParams( params:String ):HLSManifestEncryptionKey { var result:HLSManifestEncryptionKey = new HLSManifestEncryptionKey(); var tokens:Array = KeyParamParser.parseParams( params ); var tokenCount:int = tokens.length; for ( var i:int = 0; i < tokenCount; i += 2 ) { var name:String = tokens[ i ]; var value:String = tokens[ i + 1 ]; switch ( name ) { case "URI" : result.url = value; break; case "IV" : result.iv = value; break; } } return result; } /** * Creates an initialization vector from the passed in uint ID, usually * a segment ID. */ public static function createIVFromID( id:uint ):ByteArray { var result:ByteArray = new ByteArray(); result.writeUnsignedInt( 0 ); result.writeUnsignedInt( 0 ); result.writeUnsignedInt( 0 ); result.writeUnsignedInt( id ); return result; } public static function clearLoaderCache():void { for ( var key:String in LOADER_CACHE ) delete LOADER_CACHE[ key ]; } /** * Decrypts a video or audio stream using AES-128 with the provided initialization vector. */ public function decrypt( data:ByteArray, iv:ByteArray ):ByteArray { //logger.debug("got " + data.length + " bytes"); if(data.length == 0) return data; var startTime:uint = getTimer(); _key = new FastAESKey(_keyData); iv.position = 0; iv0 = iv.readUnsignedInt(); iv1 = iv.readUnsignedInt(); iv2 = iv.readUnsignedInt(); iv3 = iv.readUnsignedInt(); data.position = 0; data = _decryptCBC(data,data.length); if ( usePadding ){ data = unpad( data ); } // logger.debug( "DECRYPTION OF " + data.length + " BYTES TOOK " + ( getTimer() - startTime ) + " MS" ); return data; } /* Cypher Block Chaining Decryption, refer to * http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher-block_chaining_ * for algorithm description */ private function _decryptCBC(crypt : ByteArray, len : uint) : ByteArray { var src : Vector.<uint> = new Vector.<uint>(4); var dst : Vector.<uint> = new Vector.<uint>(4); var decrypt : ByteArray = new ByteArray(); decrypt.length = len; for (var i : uint = 0; i < len / 16; i++) { // read src byte array src[0] = crypt.readUnsignedInt(); src[1] = crypt.readUnsignedInt(); src[2] = crypt.readUnsignedInt(); src[3] = crypt.readUnsignedInt(); // AES decrypt src vector into dst vector _key.decrypt128(src, dst); // CBC : write output = XOR(decrypted,IV) decrypt.writeUnsignedInt(dst[0] ^ iv0); decrypt.writeUnsignedInt(dst[1] ^ iv1); decrypt.writeUnsignedInt(dst[2] ^ iv2); decrypt.writeUnsignedInt(dst[3] ^ iv3); // CBC : next IV = (input) iv0 = src[0]; iv1 = src[1]; iv2 = src[2]; iv3 = src[3]; } return decrypt; } public function unpad(bytesToUnpad : ByteArray) : ByteArray { if ((bytesToUnpad.length % 16) != 0) { throw new Error("PKCS#5::unpad: ByteArray.length isn't a multiple of the blockSize"); return a; } const paddingValue:int = bytesToUnpad[bytesToUnpad.length - 1]; if (paddingValue > 15) { //Return early, since any values bigger than 15 aren't actually padding. return bytesTounpad; } var doUnpad:Boolean = true; for (var i:int = 0; i<paddingValue; i++) { var readValue:int = bytesToUnpad[bytesToUnpad.length - (1 + i)]; if (paddingValue != readValue) { doUnpad = false; //Break since we know we are not dealing with padding break; } } if(doUnpad) { //subtract paddingValue to remove the padding from the block bytesToUnpad.length -= paddingValue; } return bytesToUnpad; } public function retrieveStoredIV():ByteArray { CONFIG::LOGGING { logger.debug("IV of " + iv + " for " + url + ", key=" + Hex.fromArray(_keyData)); } return Hex.toArray( iv ); } private static function getLoader( url:String ):URLLoader { if ( LOADER_CACHE[ url ] != null ) return LOADER_CACHE[ url ] as URLLoader; var newLoader:URLLoader = new URLLoader(); newLoader.dataFormat = URLLoaderDataFormat.BINARY; newLoader.load( new URLRequest( url ) ); LOADER_CACHE[ url ] = newLoader; return newLoader; } public function load():void { isLoading = true; if ( isLoaded ) throw new Error( "Already loaded!" ); var loader:URLLoader = getLoader( url ); if ( loader.bytesTotal > 0 && loader.bytesLoaded == loader.bytesTotal ) onLoad(); else loader.addEventListener( Event.COMPLETE, onLoad ); } private function onLoad( e:Event = null ):void { isLoading = false; CONFIG::LOGGING { logger.debug("KEY LOADED! " + url); } var loader:URLLoader = getLoader( url ); _keyData = loader.data as ByteArray; loader.removeEventListener( Event.COMPLETE, onLoad ); dispatchEvent( new Event( Event.COMPLETE ) ); } } } class KeyParamParser { private static const STATE_PARSE_NAME:String = "ParseName"; private static const STATE_BEGIN_PARSE_VALUE:String = "BeginParseValue"; private static const STATE_PARSE_VALUE:String = "ParseValue"; public static function parseParams( paramString:String ):Array { var result:Array = []; var cursor:int = 0; var state:String = STATE_PARSE_NAME; var accum:String = ""; var usingQuotes:Boolean = false; while ( cursor < paramString.length ) { var char:String = paramString.charAt( cursor ); switch ( state ) { case STATE_PARSE_NAME: if ( char == '=' ) { result.push( accum ); accum = ""; state = STATE_BEGIN_PARSE_VALUE; } else accum += char; break; case STATE_BEGIN_PARSE_VALUE: if ( char == '"' ) usingQuotes = true; else accum += char; state = STATE_PARSE_VALUE; break; case STATE_PARSE_VALUE: if ( !usingQuotes && char == ',' ) { result.push( accum ); accum = ""; state = STATE_PARSE_NAME; break; } if ( usingQuotes && char == '"' ) { usingQuotes = false; break; } accum += char; break; } cursor++; if ( cursor == paramString.length ) result.push( accum ); } return result; } }
package com.kaltura.hls.manifest { import com.hurlant.util.Hex; import com.kaltura.hls.crypto.FastAESKey; import flash.events.Event; import flash.events.EventDispatcher; import flash.net.URLLoader; import flash.net.URLLoaderDataFormat; import flash.net.URLRequest; import flash.utils.ByteArray; import flash.utils.Dictionary; import flash.utils.getTimer; CONFIG::LOGGING { import org.osmf.logging.Logger; import org.osmf.logging.Log; } /** * HLSManifestEncryptionKey is used to parse AES decryption key data from a m3u8 * manifest, load the specified key file into memory, and use the key data to decrypt * audio and video streams. It supports AES-128 encryption with #PKCS7 padding, and uses * explicitly passed in Initialization Vectors. */ public class HLSManifestEncryptionKey extends EventDispatcher { CONFIG::LOGGING { private static const logger:Logger = Log.getLogger("com.kaltura.hls.manifest.HLSManifestEncryptionKey"); } private static const LOADER_CACHE:Dictionary = new Dictionary(); private var _key:FastAESKey; public var usePadding:Boolean = false; public var iv:String = ""; public var url:String = ""; private var iv0 : uint; private var iv1 : uint; private var iv2 : uint; private var iv3 : uint; // Keep track of the segments this key applies to public var startSegmentId:uint = 0; public var endSegmentId:uint = uint.MAX_VALUE; private var _keyData:ByteArray; public var isLoading:Boolean = false; public function HLSManifestEncryptionKey() { } public function get isLoaded():Boolean { return _keyData != null; } public override function toString():String { return "[HLSManifestEncryptionKey start=" + startSegmentId +", end=" + endSegmentId + ", iv=" + iv + ", url=" + url + ", loaded=" + isLoaded + "]"; } public static function fromParams( params:String ):HLSManifestEncryptionKey { var result:HLSManifestEncryptionKey = new HLSManifestEncryptionKey(); var tokens:Array = KeyParamParser.parseParams( params ); var tokenCount:int = tokens.length; for ( var i:int = 0; i < tokenCount; i += 2 ) { var name:String = tokens[ i ]; var value:String = tokens[ i + 1 ]; switch ( name ) { case "URI" : result.url = value; break; case "IV" : result.iv = value; break; } } return result; } /** * Creates an initialization vector from the passed in uint ID, usually * a segment ID. */ public static function createIVFromID( id:uint ):ByteArray { var result:ByteArray = new ByteArray(); result.writeUnsignedInt( 0 ); result.writeUnsignedInt( 0 ); result.writeUnsignedInt( 0 ); result.writeUnsignedInt( id ); return result; } public static function clearLoaderCache():void { for ( var key:String in LOADER_CACHE ) delete LOADER_CACHE[ key ]; } /** * Decrypts a video or audio stream using AES-128 with the provided initialization vector. */ public function decrypt( data:ByteArray, iv:ByteArray ):ByteArray { //logger.debug("got " + data.length + " bytes"); if(data.length == 0) return data; var startTime:uint = getTimer(); _key = new FastAESKey(_keyData); iv.position = 0; iv0 = iv.readUnsignedInt(); iv1 = iv.readUnsignedInt(); iv2 = iv.readUnsignedInt(); iv3 = iv.readUnsignedInt(); data.position = 0; data = _decryptCBC(data,data.length); if ( usePadding ){ data = unpad( data ); } // logger.debug( "DECRYPTION OF " + data.length + " BYTES TOOK " + ( getTimer() - startTime ) + " MS" ); return data; } /* Cypher Block Chaining Decryption, refer to * http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher-block_chaining_ * for algorithm description */ private function _decryptCBC(crypt : ByteArray, len : uint) : ByteArray { var src : Vector.<uint> = new Vector.<uint>(4); var dst : Vector.<uint> = new Vector.<uint>(4); var decrypt : ByteArray = new ByteArray(); decrypt.length = len; for (var i : uint = 0; i < len / 16; i++) { // read src byte array src[0] = crypt.readUnsignedInt(); src[1] = crypt.readUnsignedInt(); src[2] = crypt.readUnsignedInt(); src[3] = crypt.readUnsignedInt(); // AES decrypt src vector into dst vector _key.decrypt128(src, dst); // CBC : write output = XOR(decrypted,IV) decrypt.writeUnsignedInt(dst[0] ^ iv0); decrypt.writeUnsignedInt(dst[1] ^ iv1); decrypt.writeUnsignedInt(dst[2] ^ iv2); decrypt.writeUnsignedInt(dst[3] ^ iv3); // CBC : next IV = (input) iv0 = src[0]; iv1 = src[1]; iv2 = src[2]; iv3 = src[3]; } return decrypt; } public function unpad(bytesToUnpad : ByteArray) : ByteArray { if ((bytesToUnpad.length % 16) != 0) { throw new Error("PKCS#5::unpad: ByteArray.length isn't a multiple of the blockSize"); return a; } const paddingValue:int = bytesToUnpad[bytesToUnpad.length - 1]; if (paddingValue > 15) { //Return early, since any values bigger than 15 aren't actually padding. return bytesToUnpad; } var doUnpad:Boolean = true; for (var i:int = 0; i<paddingValue; i++) { var readValue:int = bytesToUnpad[bytesToUnpad.length - (1 + i)]; if (paddingValue != readValue) { doUnpad = false; //Break since we know we are not dealing with padding break; } } if(doUnpad) { //subtract paddingValue to remove the padding from the block bytesToUnpad.length -= paddingValue; } return bytesToUnpad; } public function retrieveStoredIV():ByteArray { CONFIG::LOGGING { logger.debug("IV of " + iv + " for " + url + ", key=" + Hex.fromArray(_keyData)); } return Hex.toArray( iv ); } private static function getLoader( url:String ):URLLoader { if ( LOADER_CACHE[ url ] != null ) return LOADER_CACHE[ url ] as URLLoader; var newLoader:URLLoader = new URLLoader(); newLoader.dataFormat = URLLoaderDataFormat.BINARY; newLoader.load( new URLRequest( url ) ); LOADER_CACHE[ url ] = newLoader; return newLoader; } public function load():void { isLoading = true; if ( isLoaded ) throw new Error( "Already loaded!" ); var loader:URLLoader = getLoader( url ); if ( loader.bytesTotal > 0 && loader.bytesLoaded == loader.bytesTotal ) onLoad(); else loader.addEventListener( Event.COMPLETE, onLoad ); } private function onLoad( e:Event = null ):void { isLoading = false; CONFIG::LOGGING { logger.debug("KEY LOADED! " + url); } var loader:URLLoader = getLoader( url ); _keyData = loader.data as ByteArray; loader.removeEventListener( Event.COMPLETE, onLoad ); dispatchEvent( new Event( Event.COMPLETE ) ); } } } class KeyParamParser { private static const STATE_PARSE_NAME:String = "ParseName"; private static const STATE_BEGIN_PARSE_VALUE:String = "BeginParseValue"; private static const STATE_PARSE_VALUE:String = "ParseValue"; public static function parseParams( paramString:String ):Array { var result:Array = []; var cursor:int = 0; var state:String = STATE_PARSE_NAME; var accum:String = ""; var usingQuotes:Boolean = false; while ( cursor < paramString.length ) { var char:String = paramString.charAt( cursor ); switch ( state ) { case STATE_PARSE_NAME: if ( char == '=' ) { result.push( accum ); accum = ""; state = STATE_BEGIN_PARSE_VALUE; } else accum += char; break; case STATE_BEGIN_PARSE_VALUE: if ( char == '"' ) usingQuotes = true; else accum += char; state = STATE_PARSE_VALUE; break; case STATE_PARSE_VALUE: if ( !usingQuotes && char == ',' ) { result.push( accum ); accum = ""; state = STATE_PARSE_NAME; break; } if ( usingQuotes && char == '"' ) { usingQuotes = false; break; } accum += char; break; } cursor++; if ( cursor == paramString.length ) result.push( accum ); } return result; } }
Update HLSManifestEncryptionKey.as
Update HLSManifestEncryptionKey.as Case correction.
ActionScript
agpl-3.0
kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF
ba642b8ed3bf62ca9d081f4459285e3be44508e8
WEB-INF/lps/lfc/kernel/swf9/LzMouseKernel.as
WEB-INF/lps/lfc/kernel/swf9/LzMouseKernel.as
/** * LzMouseKernel.as * * @copyright Copyright 2001-2009 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic AS2 */ // Receives mouse events from the runtime class LzMouseKernel { #passthrough (toplevel:true) { import flash.display.*; import flash.events.*; import flash.utils.*; import flash.ui.*; }# // sends mouse events to the callback static function __sendEvent(view, eventname) { if (__callback) __scope[__callback](eventname, view); //Debug.write('LzMouseKernel event', eventname); } static var __callback = null; static var __scope = null; static var __lastMouseDown = null; static var __mouseLeft:Boolean = false; static var __listeneradded:Boolean = false; /** * Shows or hides the hand cursor for all clickable views. */ static var showhandcursor:Boolean = true; static function setCallback (scope, funcname) { __scope = scope; __callback = funcname; if (__listeneradded == false) { /* TODO [hqm 2008-01] Do we want to do anything with other * events, like click? stage.addEventListener(MouseEvent.CLICK, reportClick); */ LFCApplication.stage.addEventListener(MouseEvent.MOUSE_MOVE, __mouseHandler); LFCApplication.stage.addEventListener(MouseEvent.MOUSE_UP, __mouseHandler); LFCApplication.stage.addEventListener(MouseEvent.MOUSE_DOWN, __mouseHandler); LFCApplication.stage.addEventListener(MouseEvent.MOUSE_WHEEL, __mouseWheelHandler); LFCApplication.stage.addEventListener(Event.MOUSE_LEAVE, __mouseLeavesHandler); __listeneradded = true; } } // Handles global mouse events static function __mouseHandler(event:MouseEvent):void { var eventname = 'on' + event.type.toLowerCase(); if (eventname == 'onmouseup' && __lastMouseDown != null) { // call mouseup on the sprite that got the last mouse down __lastMouseDown.__globalmouseup(event); __lastMouseDown = null; } else { if (__mouseLeft && event.buttonDown) { __mouseLeft = false; __mouseUpOutsideHandler(); } __sendEvent(null, eventname); } } // sends mouseup and calls __globalmouseup when the mouse goes up outside the app - see LPP-7724 static function __mouseUpOutsideHandler():void { if (__lastMouseDown != null) { var ev = new MouseEvent('mouseup'); __lastMouseDown.__globalmouseup(ev); __lastMouseDown = null; } } // handles MOUSE_LEAVE event static function __mouseLeavesHandler(event:Event):void { var eventname = 'on' + event.type.toLowerCase(); __mouseLeft = true; __sendEvent(null, eventname); } static function __mouseWheelHandler(event:MouseEvent):void { lz.Keys.__mousewheelEvent(event.delta); } /** * Shows or hides the hand cursor for all clickable views. * @param Boolean show: true shows the hand cursor for buttons, false hides it */ static function showHandCursor (show) { showhandcursor = show; } static var __amLocked:Boolean = false; static var cursorSprite:Sprite = null; static var globalCursorResource:String = null; static var lastCursorResource:String = null; /** * Sets the cursor to a resource * @param String what: The resource to use as the cursor. */ static function setCursorGlobal ( what:String ){ globalCursorResource = what; setCursorLocal(what); } static function setCursorLocal ( what:String ) { if ( __amLocked ) { return; } Mouse.hide(); cursorSprite.x = LFCApplication.stage.mouseX; cursorSprite.y = LFCApplication.stage.mouseY; LFCApplication.setChildIndex(cursorSprite, LFCApplication._sprite.numChildren-1); if (lastCursorResource != what) { if (cursorSprite.numChildren > 0) { cursorSprite.removeChildAt(0); } var resourceSprite = getCursorResource(what); cursorSprite.addChild( resourceSprite ); lastCursorResource = what; } // respond to mouse move events cursorSprite.startDrag(); LFCApplication.stage.addEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler); cursorSprite.visible = true; } static function mouseLeaveHandler(evt:Event):void { cursorSprite.visible = false; } static function getCursorResource (resource:String):Sprite { var resinfo = LzResourceLibrary[resource]; var assetclass; var frames = resinfo.frames; var asset:Sprite; // single frame resources get an entry in LzResourceLibrary which has // 'assetclass' pointing to the resource Class object. if (resinfo.assetclass is Class) { assetclass = resinfo.assetclass; } else { // Multiframe resources have an array of Class objects in frames[] assetclass = frames[0]; } if (! assetclass) return null; asset = new assetclass(); asset.scaleX = 1.0; asset.scaleY = 1.0; //Debug.write('cursor asset', asset); return asset; } /** * This function restores the default cursor if there is no locked cursor on * the screen. * * @access private */ static function restoreCursor ( ){ if ( __amLocked ) { return; } cursorSprite.stopDrag(); cursorSprite.visible = false; globalCursorResource = null; Mouse.show(); } /** Called by LzSprite to restore cursor to global value. */ static function restoreCursorLocal ( ){ if ( __amLocked ) { return; } if (globalCursorResource == null) { // Restore to system default pointer restoreCursor(); } else { // Restore to the last value set by setCursorGlobal setCursorLocal(globalCursorResource); } } /** * Prevents the cursor from being changed until unlock is called. * */ static function lock (){ __amLocked = true; } /** * Restores the default cursor. * */ static function unlock (){ __amLocked = false; restoreCursor(); } static function initCursor () { cursorSprite = new Sprite(); cursorSprite.mouseChildren = false; cursorSprite.mouseEnabled = false; // Add the cursor DisplayObject to the root sprite LFCApplication.addChild(cursorSprite); cursorSprite.x = -10000; cursorSprite.y = -10000; } }
/** * LzMouseKernel.as * * @copyright Copyright 2001-2009 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic AS2 */ // Receives mouse events from the runtime class LzMouseKernel { #passthrough (toplevel:true) { import flash.display.*; import flash.events.*; import flash.utils.*; import flash.ui.*; }# // sends mouse events to the callback static function __sendEvent(view, eventname) { if (__callback) __scope[__callback](eventname, view); //Debug.write('LzMouseKernel event', eventname); } static var __callback = null; static var __scope = null; static var __lastMouseDown = null; static var __mouseLeft:Boolean = false; static var __listeneradded:Boolean = false; /** * Shows or hides the hand cursor for all clickable views. */ static var showhandcursor:Boolean = true; static function setCallback (scope, funcname) { __scope = scope; __callback = funcname; if (__listeneradded == false) { /* TODO [hqm 2008-01] Do we want to do anything with other * events, like click? stage.addEventListener(MouseEvent.CLICK, reportClick); */ LFCApplication.stage.addEventListener(MouseEvent.MOUSE_MOVE, __mouseHandler); LFCApplication.stage.addEventListener(MouseEvent.MOUSE_UP, __mouseHandler); LFCApplication.stage.addEventListener(MouseEvent.MOUSE_DOWN, __mouseHandler); LFCApplication.stage.addEventListener(MouseEvent.MOUSE_WHEEL, __mouseWheelHandler); LFCApplication.stage.addEventListener(Event.MOUSE_LEAVE, __mouseLeaveHandler); __listeneradded = true; } } // Handles global mouse events static function __mouseHandler(event:MouseEvent):void { var eventname = 'on' + event.type.toLowerCase(); if (eventname == 'onmouseup' && __lastMouseDown != null) { // call mouseup on the sprite that got the last mouse down __lastMouseDown.__globalmouseup(event); __lastMouseDown = null; } else { if (__mouseLeft) { __mouseLeft = false; if (event.buttonDown) __mouseUpOutsideHandler(); } __sendEvent(null, eventname); } } // sends mouseup and calls __globalmouseup when the mouse goes up outside the app - see LPP-7724 static function __mouseUpOutsideHandler():void { if (__lastMouseDown != null) { var ev = new MouseEvent('mouseup'); __lastMouseDown.__globalmouseup(ev); __lastMouseDown = null; } } // handles MOUSE_LEAVE event static function __mouseLeaveHandler(event:Event = null):void { __mouseLeft = true; __sendEvent(null, 'onmouseleave'); } static function __mouseWheelHandler(event:MouseEvent):void { lz.Keys.__mousewheelEvent(event.delta); } /** * Shows or hides the hand cursor for all clickable views. * @param Boolean show: true shows the hand cursor for buttons, false hides it */ static function showHandCursor (show) { showhandcursor = show; } static var __amLocked:Boolean = false; static var cursorSprite:Sprite = null; static var globalCursorResource:String = null; static var lastCursorResource:String = null; /** * Sets the cursor to a resource * @param String what: The resource to use as the cursor. */ static function setCursorGlobal ( what:String ){ globalCursorResource = what; setCursorLocal(what); } static function setCursorLocal ( what:String ) { if ( __amLocked ) { return; } Mouse.hide(); cursorSprite.x = LFCApplication.stage.mouseX; cursorSprite.y = LFCApplication.stage.mouseY; LFCApplication.setChildIndex(cursorSprite, LFCApplication._sprite.numChildren-1); if (lastCursorResource != what) { if (cursorSprite.numChildren > 0) { cursorSprite.removeChildAt(0); } var resourceSprite = getCursorResource(what); cursorSprite.addChild( resourceSprite ); lastCursorResource = what; } // respond to mouse move events cursorSprite.startDrag(); LFCApplication.stage.addEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler); cursorSprite.visible = true; } static function mouseLeaveHandler(evt:Event):void { cursorSprite.visible = false; } static function getCursorResource (resource:String):Sprite { var resinfo = LzResourceLibrary[resource]; var assetclass; var frames = resinfo.frames; var asset:Sprite; // single frame resources get an entry in LzResourceLibrary which has // 'assetclass' pointing to the resource Class object. if (resinfo.assetclass is Class) { assetclass = resinfo.assetclass; } else { // Multiframe resources have an array of Class objects in frames[] assetclass = frames[0]; } if (! assetclass) return null; asset = new assetclass(); asset.scaleX = 1.0; asset.scaleY = 1.0; //Debug.write('cursor asset', asset); return asset; } /** * This function restores the default cursor if there is no locked cursor on * the screen. * * @access private */ static function restoreCursor ( ){ if ( __amLocked ) { return; } cursorSprite.stopDrag(); cursorSprite.visible = false; globalCursorResource = null; Mouse.show(); } /** Called by LzSprite to restore cursor to global value. */ static function restoreCursorLocal ( ){ if ( __amLocked ) { return; } if (globalCursorResource == null) { // Restore to system default pointer restoreCursor(); } else { // Restore to the last value set by setCursorGlobal setCursorLocal(globalCursorResource); } } /** * Prevents the cursor from being changed until unlock is called. * */ static function lock (){ __amLocked = true; } /** * Restores the default cursor. * */ static function unlock (){ __amLocked = false; restoreCursor(); } static function initCursor () { cursorSprite = new Sprite(); cursorSprite.mouseChildren = false; cursorSprite.mouseEnabled = false; // Add the cursor DisplayObject to the root sprite LFCApplication.addChild(cursorSprite); cursorSprite.x = -10000; cursorSprite.y = -10000; } }
Change 20090212-maxcarlson-9 by [email protected] on 2009-02-12 23:59:18 PST in /Users/maxcarlson/openlaszlo/trunk-clean for http://svn.openlaszlo.org/openlaszlo/trunk
Change 20090212-maxcarlson-9 by [email protected] on 2009-02-12 23:59:18 PST in /Users/maxcarlson/openlaszlo/trunk-clean for http://svn.openlaszlo.org/openlaszlo/trunk Summary: Improve mouseupoutside behavior outside windows Bugs Fixed: LPP-7724 - Mouse events behave wrong in opaque mode (FireFox) Technical Reviewer: hminsky QA Reviewer: promanik Details: Rename __mouseLeaveHandler -> __mouseLeaveHandler. Clear __mouseLeft if set, regardless of button state. Make argument to __mouseLeaveHandler() optional so it can be called from external JavaScript. Tests: See updated testcase at LPP-7724 - test app.lzx?lzr=swf9, em.html, emOp.html and emIf.html in firefox 3 windows and mac. git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@12851 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
ActionScript
epl-1.0
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
3bfb9677a5c247738a7469a2f63c8560a8ce181e
src/aerys/minko/type/stream/VertexStream.as
src/aerys/minko/type/stream/VertexStream.as
package aerys.minko.type.stream { import aerys.minko.ns.minko_stream; import aerys.minko.render.resource.VertexBuffer3DResource; import aerys.minko.type.IVersionable; import aerys.minko.type.stream.format.VertexComponent; import aerys.minko.type.stream.format.VertexComponentType; import aerys.minko.type.stream.format.VertexFormat; import flash.utils.ByteArray; import flash.utils.Dictionary; public class VertexStream implements IVersionable, IVertexStream { use namespace minko_stream; public static const DEFAULT_FORMAT : VertexFormat = VertexFormat.XYZ_UV; minko_stream var _data : Vector.<Number> = null; private var _dynamic : Boolean = false; private var _version : uint = 0; private var _format : VertexFormat = null; private var _resource : VertexBuffer3DResource = null; private var _length : uint = 0; private var _componentToStream : Dictionary = new Dictionary(true); public function get format() : VertexFormat { return _format; } public function get version() : uint { return _version; } public function get isDynamic() : Boolean { return _dynamic; } public function get resource() : VertexBuffer3DResource { return _resource; } public function get length() : uint { return _length; } protected function get data() : Vector.<Number> { return _data; } protected function set data(value : Vector.<Number>) : void { _data = value; invalidate(); } public function VertexStream(data : Vector.<Number> = null, format : VertexFormat = null, isDynamic : Boolean = false) { super(); initialize(data, format, isDynamic); } private function initialize(data : Vector.<Number> = null, format : VertexFormat = null, isDynamic : Boolean = false) : void { _resource = new VertexBuffer3DResource(this); _format = format || DEFAULT_FORMAT; if (data && data.length && data.length % _format.dwordsPerVertex) throw new Error("Incompatible vertex format: the data length does not match."); _data = data ? data.concat() : new Vector.<Number>(); _dynamic = isDynamic; invalidate(); } public function deleteVertexByIndex(index : uint) : Boolean { if (index > length) return false; _data.splice(index, _format.dwordsPerVertex); invalidate(); return true; } public function getSubStreamByComponent(vertexComponent : VertexComponent) : VertexStream { return _format.hasComponent(vertexComponent) ? this : null; } public function get(i : int) : Number { return _data[i]; } public function set(i : int, value : Number) : void { _data[i] = value; invalidate(); } public function push(data : Vector.<Number>) : void { var dataLength : int = data.length; if (dataLength % _format.dwordsPerVertex) throw new Error("Invalid data length."); for (var i : int = 0; i < dataLength; i++) _data.push(data[i]); invalidate(); } public function disposeLocalData() : void { if (length != resource.numVertices) throw new Error("Unable to dispose local data: " + "some vertices have not been uploaded."); _data = null; _dynamic = false; } protected function invalidate() : void { _length = _data.length / _format.dwordsPerVertex; ++_version; } minko_stream function invalidate() : void { protected::invalidate(); } public static function fromPositionsAndUVs(positions : Vector.<Number>, uvs : Vector.<Number> = null, isDynamic : Boolean = false) : VertexStream { var numVertices : int = positions.length / 3; var stride : int = uvs ? 5 : 3; var data : Vector.<Number> = new Vector.<Number>(numVertices * stride, true); for (var i : int = 0; i < numVertices; ++i) { var offset : int = i * stride; data[offset] = positions[int(i * 3)]; data[int(offset + 1)] = positions[int(i * 3 + 1)]; data[int(offset + 2)] = positions[int(i * 3 + 2)]; if (uvs) { data[int(offset + 3)] = uvs[int(i * 2)]; data[int(offset + 4)] = uvs[int(i * 2 + 1)]; } } return new VertexStream(data, uvs ? VertexFormat.XYZ_UV : VertexFormat.XYZ, isDynamic); } public static function extractSubStream(source : IVertexStream, vertexFormat : VertexFormat = null) : VertexStream { vertexFormat ||= source.format; var newVertexStreamData : Vector.<Number> = new Vector.<Number>(); var components : Vector.<VertexComponent> = vertexFormat.components; var numComponents : uint = components.length; var componentOffsets : Vector.<uint> = new Vector.<uint>(numComponents, true); var componentSizes : Vector.<uint> = new Vector.<uint>(numComponents, true); var componentDwordsPerVertex : Vector.<uint> = new Vector.<uint>(numComponents, true); var componentDatas : Vector.<Vector.<Number>> = new Vector.<Vector.<Number>>(numComponents, true); var totalVertices : int = 0; var totalIndices : int = 0; // cache get offsets, sizes, and buffers for each components for (var k : int = 0; k < numComponents; ++k) { var vertexComponent : VertexComponent = components[k]; var subVertexStream : VertexStream = source.getSubStreamByComponent(vertexComponent); var subvertexFormat : VertexFormat = subVertexStream.format; componentOffsets[k] = subvertexFormat.getOffsetForComponent(vertexComponent); componentDwordsPerVertex[k] = subvertexFormat.dwordsPerVertex; componentSizes[k] = vertexComponent.dwords; componentDatas[k] = subVertexStream._data; } // push vertex data into the new buffer. var numVertices : uint = source.length; for (var vertexId : uint = 0; vertexId < numVertices; ++vertexId) { for (var componentId : int = 0; componentId < numComponents; ++componentId) { var vertexData : Vector.<Number> = componentDatas[componentId]; var componentSize : uint = componentSizes[componentId]; var componentOffset : uint = componentOffsets[componentId] + vertexId * componentDwordsPerVertex[componentId]; var componentLimit : uint = componentSize + componentOffset; for (var n : int = componentOffset; n < componentLimit; ++n, ++totalVertices) newVertexStreamData[totalVertices] = vertexData[n]; } } // avoid copying data vectors var newVertexStream : VertexStream = new VertexStream(null, vertexFormat); newVertexStream.data = newVertexStreamData; return newVertexStream; } public static function concat(streams : Vector.<IVertexStream>) : VertexStream { var format : VertexFormat = streams[0].format; var numStreams : int = streams.length; for (var i : int = 0; i < numStreams; ++i) if (!streams[i].format.equals(format)) throw new Error("All vertex streams must have the same format."); // a bit expensive... but hey, it works :) var stream : VertexStream = extractSubStream(streams[0], format); for (i = 1; i < numStreams; ++i) stream.data = stream.data.concat(extractSubStream(streams[i], format).data); return stream; } public static function fromByteArray(bytes : ByteArray, count : int, formatIn : VertexFormat, formatOut : VertexFormat = null, isDynamic : Boolean = false, reader : Function = null, dwordSize : uint = 4) : VertexStream { formatOut ||= formatIn; reader ||= bytes.readFloat; var dataLength : int = 0; var data : Vector.<Number> = null; var stream : VertexStream = new VertexStream(null, formatOut, isDynamic); var start : int = bytes.position; var componentsOut : Vector.<VertexComponent> = formatOut.components; var numComponents : int = componentsOut.length; var nativeFormats : Vector.<int> = new Vector.<int>(numComponents, true); for (var k : int = 0; k < numComponents; k++) nativeFormats[k] = componentsOut[k].nativeFormat; data = new Vector.<Number>(formatOut.dwordsPerVertex * count, true); for (var vertexId : int = 0; vertexId < count; ++vertexId) { for (var componentId : int = 0; componentId < numComponents; ++componentId) { bytes.position = start + formatIn.dwordsPerVertex * vertexId * dwordSize + formatIn.getOffsetForComponent(componentsOut[componentId]) * dwordSize; switch (nativeFormats[componentId]) { case VertexComponentType.FLOAT_4 : data[int(dataLength++)] = reader(); case VertexComponentType.FLOAT_3 : data[int(dataLength++)] = reader(); case VertexComponentType.FLOAT_2 : data[int(dataLength++)] = reader(); case VertexComponentType.FLOAT_1 : data[int(dataLength++)] = reader(); break ; } } } // make sure the ByteArray position is at the end of the buffer bytes.position = start + formatIn.dwordsPerVertex * count * dwordSize; stream.data = data; return stream; } } }
package aerys.minko.type.stream { import aerys.minko.ns.minko_stream; import aerys.minko.render.resource.VertexBuffer3DResource; import aerys.minko.type.IVersionable; import aerys.minko.type.stream.format.VertexComponent; import aerys.minko.type.stream.format.VertexComponentType; import aerys.minko.type.stream.format.VertexFormat; import flash.utils.ByteArray; import flash.utils.Dictionary; public class VertexStream implements IVersionable, IVertexStream { use namespace minko_stream; public static const DEFAULT_FORMAT : VertexFormat = VertexFormat.XYZ_UV; minko_stream var _data : Vector.<Number> = null; private var _dynamic : Boolean = false; private var _version : uint = 0; private var _format : VertexFormat = null; private var _resource : VertexBuffer3DResource = null; private var _length : uint = 0; private var _componentToStream : Dictionary = new Dictionary(true); public function get format() : VertexFormat { return _format; } public function get version() : uint { return _version; } public function get isDynamic() : Boolean { return _dynamic; } public function get resource() : VertexBuffer3DResource { return _resource; } public function get length() : uint { return _length; } protected function get data() : Vector.<Number> { return _data; } protected function set data(value : Vector.<Number>) : void { _data = value; invalidate(); } public function VertexStream(data : Vector.<Number> = null, format : VertexFormat = null, isDynamic : Boolean = false) { super(); initialize(data, format, isDynamic); } private function initialize(data : Vector.<Number> = null, format : VertexFormat = null, isDynamic : Boolean = false) : void { _resource = new VertexBuffer3DResource(this); _format = format || DEFAULT_FORMAT; if (data && data.length && data.length % _format.dwordsPerVertex) throw new Error("Incompatible vertex format: the data length does not match."); _data = data ? data.concat() : new Vector.<Number>(); _dynamic = isDynamic; invalidate(); } public function deleteVertexByIndex(index : uint) : Boolean { if (index > length) return false; _data.splice(index, _format.dwordsPerVertex); invalidate(); return true; } public function getSubStreamByComponent(vertexComponent : VertexComponent) : VertexStream { return _format.hasComponent(vertexComponent) ? this : null; } public function get(i : int) : Number { return _data[i]; } public function set(i : int, value : Number) : void { _data[i] = value; invalidate(); } public function push(data : Vector.<Number>) : void { var dataLength : int = data.length; if (dataLength % _format.dwordsPerVertex) throw new Error("Invalid data length."); for (var i : int = 0; i < dataLength; i++) _data.push(data[i]); invalidate(); } public function disposeLocalData() : void { if (length != resource.numVertices) throw new Error("Unable to dispose local data: " + "some vertices have not been uploaded."); _data = null; _dynamic = false; } protected function invalidate() : void { _length = _data.length / _format.dwordsPerVertex; ++_version; } minko_stream function invalidate() : void { protected::invalidate(); } public static function fromPositionsAndUVs(positions : Vector.<Number>, uvs : Vector.<Number> = null, isDynamic : Boolean = false) : VertexStream { var numVertices : int = positions.length / 3; var stride : int = uvs ? 5 : 3; var data : Vector.<Number> = new Vector.<Number>(numVertices * stride, true); for (var i : int = 0; i < numVertices; ++i) { var offset : int = i * stride; data[offset] = positions[int(i * 3)]; data[int(offset + 1)] = positions[int(i * 3 + 1)]; data[int(offset + 2)] = positions[int(i * 3 + 2)]; if (uvs) { data[int(offset + 3)] = uvs[int(i * 2)]; data[int(offset + 4)] = uvs[int(i * 2 + 1)]; } } return new VertexStream(data, uvs ? VertexFormat.XYZ_UV : VertexFormat.XYZ, isDynamic); } public static function extractSubStream(source : IVertexStream, vertexFormat : VertexFormat = null) : VertexStream { vertexFormat ||= source.format; var newVertexStreamData : Vector.<Number> = new Vector.<Number>(); var components : Vector.<VertexComponent> = vertexFormat.components; var numComponents : uint = components.length; var componentOffsets : Vector.<uint> = new Vector.<uint>(numComponents, true); var componentSizes : Vector.<uint> = new Vector.<uint>(numComponents, true); var componentDwordsPerVertex : Vector.<uint> = new Vector.<uint>(numComponents, true); var componentDatas : Vector.<Vector.<Number>> = new Vector.<Vector.<Number>>(numComponents, true); var totalVertices : int = 0; var totalIndices : int = 0; // cache get offsets, sizes, and buffers for each components for (var k : int = 0; k < numComponents; ++k) { var vertexComponent : VertexComponent = components[k]; var subVertexStream : VertexStream = source.getSubStreamByComponent(vertexComponent); var subvertexFormat : VertexFormat = subVertexStream.format; componentOffsets[k] = subvertexFormat.getOffsetForComponent(vertexComponent); componentDwordsPerVertex[k] = subvertexFormat.dwordsPerVertex; componentSizes[k] = vertexComponent.dwords; componentDatas[k] = subVertexStream._data; } // push vertex data into the new buffer. var numVertices : uint = source.length; for (var vertexId : uint = 0; vertexId < numVertices; ++vertexId) { for (var componentId : int = 0; componentId < numComponents; ++componentId) { var vertexData : Vector.<Number> = componentDatas[componentId]; var componentSize : uint = componentSizes[componentId]; var componentOffset : uint = componentOffsets[componentId] + vertexId * componentDwordsPerVertex[componentId]; var componentLimit : uint = componentSize + componentOffset; for (var n : int = componentOffset; n < componentLimit; ++n, ++totalVertices) newVertexStreamData[totalVertices] = vertexData[n]; } } // avoid copying data vectors var newVertexStream : VertexStream = new VertexStream(null, vertexFormat); newVertexStream.data = newVertexStreamData; return newVertexStream; } public static function concat(streams : Vector.<IVertexStream>) : VertexStream { var format : VertexFormat = streams[0].format; var numStreams : int = streams.length; for (var i : int = 0; i < numStreams; ++i) if (!streams[i].format.equals(format)) throw new Error("All vertex streams must have the same format."); // a bit expensive... but hey, it works :) var stream : VertexStream = extractSubStream(streams[0], format); for (i = 1; i < numStreams; ++i) stream.data = stream.data.concat(extractSubStream(streams[i], format).data); return stream; } public static function fromByteArray(bytes : ByteArray, count : int, formatIn : VertexFormat, formatOut : VertexFormat = null, isDynamic : Boolean = false, functionReader : Dictionary = null, dwordSize : uint = 4) : VertexStream { formatOut ||= formatIn; var dataLength : int = 0; var data : Vector.<Number> = null; var stream : VertexStream = new VertexStream(null, formatOut, isDynamic); var start : int = bytes.position; var componentsOut : Vector.<VertexComponent> = formatOut.components; var numComponents : int = componentsOut.length; var nativeFormats : Vector.<int> = new Vector.<int>(numComponents, true); for (var k : int = 0; k < numComponents; k++) nativeFormats[k] = componentsOut[k].nativeFormat; data = new Vector.<Number>(formatOut.dwordsPerVertex * count, true); for (var vertexId : int = 0; vertexId < count; ++vertexId) { for (var componentId : int = 0; componentId < numComponents; ++componentId) { bytes.position = start + formatIn.dwordsPerVertex * vertexId * dwordSize + formatIn.getOffsetForComponent(componentsOut[componentId]) * dwordSize; var reader : Function = null; if (functionReader[componentsOut[componentId].nativeFormatString]) reader = functionReader[componentsOut[componentId].nativeFormatString]; else if (functionReader["defaut"]) reader = functionReader["defaut"]; else reader = bytes.readFloat; switch (nativeFormats[componentId]) { case VertexComponentType.FLOAT_4 : data[int(dataLength++)] = reader(); case VertexComponentType.FLOAT_3 : data[int(dataLength++)] = reader(); case VertexComponentType.FLOAT_2 : data[int(dataLength++)] = reader(); case VertexComponentType.FLOAT_1 : data[int(dataLength++)] = reader(); break ; } } } // make sure the ByteArray position is at the end of the buffer bytes.position = start + formatIn.dwordsPerVertex * count * dwordSize; stream.data = data; return stream; } } }
Read function feature
Read function feature M The reader function use to transform ByteArray into VertexStream is now a collection indexed by the components name
ActionScript
mit
aerys/minko-as3
d99921abe77c24805821926d37347be6d5745349
src/aerys/minko/type/loader/parser/ParserOptions.as
src/aerys/minko/type/loader/parser/ParserOptions.as
package aerys.minko.type.loader.parser { import aerys.minko.render.Effect; import aerys.minko.render.material.Material; import aerys.minko.scene.node.Mesh; import aerys.minko.type.animation.SkinningMethod; import aerys.minko.type.loader.ILoader; import aerys.minko.type.loader.SceneLoader; import aerys.minko.type.loader.TextureLoader; import flash.net.URLRequest; /** * ParserOptions objects provide properties and function references * to customize how a LoaderGroup object will load and interpret * content. * * @author Jean-Marc Le Roux * */ public final class ParserOptions { private var _dependencyLoaderFunction : Function; private var _loadSkin : Boolean; private var _skinningMethod : uint; private var _mipmapTextures : Boolean; private var _meshEffect : Effect; private var _material : Material; private var _vertexStreamUsage : uint; private var _indexStreamUsage : uint; private var _parser : Class; public function get skinningMethod() : uint { return _skinningMethod; } public function set skinningMethod(value : uint) : void { _skinningMethod = value; } public function get parser() : Class { return _parser; } public function set parser(value : Class) : void { _parser = value; } public function get indexStreamUsage() : uint { return _indexStreamUsage; } public function set indexStreamUsage(value : uint) : void { _indexStreamUsage = value; } public function get vertexStreamUsage() : uint { return _vertexStreamUsage; } public function set vertexStreamUsage(value : uint) : void { _vertexStreamUsage = value; } public function get material():Material { return _material; } public function set material(value:Material):void { _material = value; } public function get mipmapTextures() : Boolean { return _mipmapTextures; } public function set mipmapTextures(value : Boolean) : void { _mipmapTextures = value; } public function get dependencyLoaderFunction() : Function { return _dependencyLoaderFunction; } public function set dependencyLoaderFunction(value : Function) : void { _dependencyLoaderFunction = value; } public function get loadSkin() : Boolean { return _loadSkin; } public function set loadSkin(value : Boolean) : void { _loadSkin = value; } public function clone() : ParserOptions { return new ParserOptions( _dependencyLoaderFunction, _loadSkin, _skinningMethod, _mipmapTextures, _material, _vertexStreamUsage, _indexStreamUsage, _parser ); } public function ParserOptions(dependencyLoaderFunction : Function = null, loadSkin : Boolean = true, skinningMethod : uint = 2, mipmapTextures : Boolean = true, material : Material = null, vertexStreamUsage : uint = 0, indexStreamUsage : uint = 0, parser : Class = null) { _dependencyLoaderFunction = dependencyLoaderFunction || defaultDependencyLoaderFunction; _loadSkin = loadSkin; _skinningMethod = skinningMethod; _mipmapTextures = mipmapTextures; _material = _material || new Material(); _vertexStreamUsage = vertexStreamUsage; _indexStreamUsage = indexStreamUsage; _parser = parser; } private function defaultDependencyLoaderFunction(dependencyPath : String, isTexture : Boolean, options : ParserOptions) : ILoader { var loader : ILoader; if (isTexture) { loader = new TextureLoader(true); loader.load(new URLRequest(dependencyPath)); } else { loader = new SceneLoader(options); loader.load(new URLRequest(dependencyPath)); } return loader; } } }
package aerys.minko.type.loader.parser { import aerys.minko.render.Effect; import aerys.minko.render.material.Material; import aerys.minko.render.material.basic.BasicMaterial; import aerys.minko.scene.node.Mesh; import aerys.minko.type.animation.SkinningMethod; import aerys.minko.type.loader.ILoader; import aerys.minko.type.loader.SceneLoader; import aerys.minko.type.loader.TextureLoader; import flash.net.URLRequest; /** * ParserOptions objects provide properties and function references * to customize how a LoaderGroup object will load and interpret * content. * * @author Jean-Marc Le Roux * */ public final class ParserOptions { private var _dependencyLoaderFunction : Function; private var _loadSkin : Boolean; private var _skinningMethod : uint; private var _mipmapTextures : Boolean; private var _meshEffect : Effect; private var _material : Material; private var _vertexStreamUsage : uint; private var _indexStreamUsage : uint; private var _parser : Class; public function get skinningMethod() : uint { return _skinningMethod; } public function set skinningMethod(value : uint) : void { _skinningMethod = value; } public function get parser() : Class { return _parser; } public function set parser(value : Class) : void { _parser = value; } public function get indexStreamUsage() : uint { return _indexStreamUsage; } public function set indexStreamUsage(value : uint) : void { _indexStreamUsage = value; } public function get vertexStreamUsage() : uint { return _vertexStreamUsage; } public function set vertexStreamUsage(value : uint) : void { _vertexStreamUsage = value; } public function get material():Material { return _material; } public function set material(value:Material):void { _material = value; } public function get mipmapTextures() : Boolean { return _mipmapTextures; } public function set mipmapTextures(value : Boolean) : void { _mipmapTextures = value; } public function get dependencyLoaderFunction() : Function { return _dependencyLoaderFunction; } public function set dependencyLoaderFunction(value : Function) : void { _dependencyLoaderFunction = value; } public function get loadSkin() : Boolean { return _loadSkin; } public function set loadSkin(value : Boolean) : void { _loadSkin = value; } public function clone() : ParserOptions { return new ParserOptions( _dependencyLoaderFunction, _loadSkin, _skinningMethod, _mipmapTextures, _material, _vertexStreamUsage, _indexStreamUsage, _parser ); } public function ParserOptions(dependencyLoaderFunction : Function = null, loadSkin : Boolean = true, skinningMethod : uint = 2, mipmapTextures : Boolean = true, material : Material = null, vertexStreamUsage : uint = 0, indexStreamUsage : uint = 0, parser : Class = null) { _dependencyLoaderFunction = dependencyLoaderFunction || defaultDependencyLoaderFunction; _loadSkin = loadSkin; _skinningMethod = skinningMethod; _mipmapTextures = mipmapTextures; _material = _material || new BasicMaterial(); _vertexStreamUsage = vertexStreamUsage; _indexStreamUsage = indexStreamUsage; _parser = parser; } private function defaultDependencyLoaderFunction(dependencyPath : String, isTexture : Boolean, options : ParserOptions) : ILoader { var loader : ILoader; if (isTexture) { loader = new TextureLoader(true); loader.load(new URLRequest(dependencyPath)); } else { loader = new SceneLoader(options); loader.load(new URLRequest(dependencyPath)); } return loader; } } }
set default value of ParserOptions.material to be a BasicMaterial
set default value of ParserOptions.material to be a BasicMaterial
ActionScript
mit
aerys/minko-as3
429dccf94c8869b0fd5d6986bf94184c3859a071
src/skein/core/PropertySetter.as
src/skein/core/PropertySetter.as
/** * Created with IntelliJ IDEA. * User: mobitile * Date: 4/21/13 * Time: 1:37 PM * To change this template use File | Settings | File Templates. */ package skein.core { import skein.binding.core.BindingContext; import skein.binding.core.PropertyDestination; import skein.binding.core.Source; public class PropertySetter { public static function set(site:Object, property:String, value:Object):void { if (value is Source) { var ctx:BindingContext = new BindingContext(); ctx.bind(Source(value), new PropertyDestination(site, property)); } else { site[property] = value; } } } }
/** * Created with IntelliJ IDEA. * User: mobitile * Date: 4/21/13 * Time: 1:37 PM * To change this template use File | Settings | File Templates. */ package skein.core { import flash.utils.getDefinitionByName; public class PropertySetter { public static function set(site:Object, property:String, value:Object):void { var SourceClass:Class = getDefinitionByName("skein.binding.core::Source") as Class; var BindingContextClass:Class = getDefinitionByName("skein.binding.core::BindingContext") as Class; if (SourceClass && BindingContextClass && value is SourceClass) { BindingContextClass["bindProperty"](site, property, value); } else { site[property] = value; } } } }
Remove dependency on skein.binding
[core] Remove dependency on skein.binding
ActionScript
mit
skeinlib/skein
7a20094687987dc80c69f7c0928376c6af8a7cb5
dolly-framework/src/test/actionscript/dolly/utils/PropertyUtilTests.as
dolly-framework/src/test/actionscript/dolly/utils/PropertyUtilTests.as
package dolly.utils { import dolly.core.dolly_internal; import mx.collections.ArrayCollection; import mx.collections.ArrayList; use namespace dolly_internal; public class PropertyUtilTests { private var sourceObj:Object; private var targetObj:Object; [Before] public function before():void { sourceObj = {}; sourceObj.array = [0, 1, 2, 3, 4]; sourceObj.arrayList = new ArrayList([0, 1, 2, 3, 4]); sourceObj.arrayCollection = new ArrayCollection([0, 1, 2, 3, 4]); targetObj = {}; } [After] public function after():void { sourceObj = targetObj = null; } } }
package dolly.utils { import dolly.core.dolly_internal; import mx.collections.ArrayCollection; import mx.collections.ArrayList; import org.flexunit.assertThat; import org.flexunit.asserts.assertTrue; import org.hamcrest.collection.array; import org.hamcrest.collection.arrayWithSize; import org.hamcrest.collection.everyItem; import org.hamcrest.core.isA; import org.hamcrest.object.equalTo; use namespace dolly_internal; public class PropertyUtilTests { private var sourceObj:Object; private var targetObj:Object; [Before] public function before():void { sourceObj = {}; sourceObj.array = [0, 1, 2, 3, 4]; sourceObj.arrayList = new ArrayList([0, 1, 2, 3, 4]); sourceObj.arrayCollection = new ArrayCollection([0, 1, 2, 3, 4]); targetObj = {}; } [After] public function after():void { sourceObj = targetObj = null; } [Test] public function copyingOfArray():void { PropertyUtil.copyArray(targetObj, "array", sourceObj.array); assertThat(targetObj.array, arrayWithSize(5)); assertThat(targetObj.array, sourceObj.array); assertTrue(targetObj.array != sourceObj.array); assertThat(targetObj.array, everyItem(isA(Number))); assertThat(targetObj.array, array(equalTo(0), equalTo(1), equalTo(2), equalTo(3), equalTo(4))); } } }
Test for PropertyUtil.copyArray() method.
Test for PropertyUtil.copyArray() method.
ActionScript
mit
Yarovoy/dolly