package aerys.minko.render.shader.compiler.graph.visitors
{
	import aerys.minko.render.shader.compiler.graph.ShaderGraph;
	import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode;
	import aerys.minko.render.shader.compiler.graph.nodes.leaf.Attribute;
	import aerys.minko.render.shader.compiler.graph.nodes.leaf.BindableConstant;
	import aerys.minko.render.shader.compiler.graph.nodes.leaf.BindableSampler;
	import aerys.minko.render.shader.compiler.graph.nodes.leaf.Constant;
	import aerys.minko.render.shader.compiler.graph.nodes.leaf.Sampler;
	import aerys.minko.render.shader.compiler.graph.nodes.vertex.Extract;
	import aerys.minko.render.shader.compiler.graph.nodes.vertex.Instruction;
	import aerys.minko.render.shader.compiler.graph.nodes.vertex.Interpolate;
	import aerys.minko.render.shader.compiler.graph.nodes.vertex.Overwriter;
	import aerys.minko.render.shader.compiler.graph.nodes.vertex.VariadicExtract;
	import aerys.minko.render.shader.compiler.register.Components;

	import flash.utils.Dictionary;

	/**
	 * @private
	 * @author Romain Gilliotte
	 */
	public class AbstractVisitor
	{
		private var _visited		: Vector.<AbstractNode>;
		protected var _shaderGraph	: ShaderGraph;

		public function AbstractVisitor()
		{
			_visited	= new Vector.<AbstractNode>();
		}

		public function process(shaderGraph : ShaderGraph) : void
		{
			_shaderGraph = shaderGraph;

			start();

			visit(_shaderGraph.position, true);
			visit(_shaderGraph.color, false);
			for each (var kill : AbstractNode in _shaderGraph.kills)
				visit(kill, false);

			finish();
		}

		protected function start() : void
		{
		}

		protected function finish() : void
		{
			_visited.length	= 0;
			_shaderGraph	= null;
		}

		protected function visit(node : AbstractNode, isVertexShader : Boolean) : void
		{
			if (_visited.indexOf(node) == -1)
			{
				_visited.push(node);

				if (node is Extract || node is Instruction || node is Interpolate || node is Overwriter || node is VariadicExtract)
					visitTraversable(node, isVertexShader);
				else
					visitNonTraversable(node, isVertexShader);
			}
		}

		protected function visitArguments(node : AbstractNode, isVertexShader : Boolean) : void
		{
			var numArguments : uint = node.numArguments;

			for (var argumentId : uint = 0; argumentId < numArguments; ++argumentId)
				visit(node.getArgumentAt(argumentId), isVertexShader);
		}

		protected function replaceInParents(oldNode : AbstractNode, newNode : AbstractNode) : void
		{
			var numParents	: uint					= oldNode.numParents;
			var parents		: Vector.<AbstractNode> = new Vector.<AbstractNode>(numParents, true);
			var parentId	: uint;

			for (parentId = 0; parentId < numParents; ++parentId)
				parents[parentId] = oldNode.getParentAt(parentId);

			for (parentId = 0; parentId < numParents; ++parentId)
				parents[parentId].replaceArgument(oldNode, newNode);

			if (_shaderGraph.position === oldNode)
				_shaderGraph.position = newNode;

			if (_shaderGraph.color === oldNode)
				_shaderGraph.color = newNode;

			var kills		: Vector.<AbstractNode>	= _shaderGraph.kills;
			var numKills	: uint					= kills.length;

			for (var killId : uint = 0; killId < numKills; ++killId)
				if (kills[killId] === oldNode)
					kills[killId] = newNode;
		}

		protected function swizzleParents(node		: AbstractNode,
										  modifier	: uint) : void
		{
			var numParents		: uint			= node.numParents;
			var visitedParents	: Dictionary	= new Dictionary();

			for (var parentId : uint = 0; parentId < numParents; ++parentId)
			{
				var parent : AbstractNode = node.getParentAt(parentId);

				if (visitedParents[parent])
					continue;
				visitedParents[parent] = true;

				var numArgument	: uint	= parent.numArguments;

				// loop backward, because we are removing elements from the parents array
				for (var argumentId : int = numArgument - 1; argumentId >= 0; --argumentId)
					if (parent.getArgumentAt(argumentId) === node)
						parent.setComponentAt(argumentId,
							Components.applyCombination(modifier, parent.getComponentAt(argumentId))
						);
			}

			if (_shaderGraph.position == node)
				_shaderGraph.positionComponents = Components.applyCombination(modifier, _shaderGraph.positionComponents);

			if (_shaderGraph.color == node)
				_shaderGraph.colorComponents = Components.applyCombination(modifier, _shaderGraph.colorComponents);

			var kills			: Vector.<AbstractNode>	= _shaderGraph.kills;
			var killComponents	: Vector.<uint>			= _shaderGraph.killComponents;
			var numKills		: uint = kills.length;

			for (var killId : uint = 0; killId < numKills; ++killId)
				if (kills[killId] === node)
					killComponents[killId] = Components.applyCombination(modifier, killComponents[killId]);
		}

		protected function replaceInParentsAndSwizzle(oldNode	: AbstractNode,
													  newNode	: AbstractNode,
													  modifier	: uint) : void
		{

			swizzleParents(oldNode, modifier);
			replaceInParents(oldNode, newNode);
		}

		protected function visitTraversable(node : AbstractNode, isVertexShader : Boolean) : void
		{
			if (node is Extract)
				visitExtract(Extract(node), isVertexShader);
			else if (node is Instruction)
				visitInstruction(Instruction(node), isVertexShader);
			else if (node is Interpolate)
				visitInterpolate(Interpolate(node), isVertexShader);
			else if (node is Overwriter)
				visitOverwriter(Overwriter(node), isVertexShader);
			else if (node is VariadicExtract)
				visitVariadicExtract(VariadicExtract(node), isVertexShader);
		}

		protected function visitNonTraversable(node : AbstractNode, isVertexShader : Boolean) : void
		{
			if (node is Attribute)
				visitAttribute(Attribute(node), isVertexShader);
			else if (node is Constant)
				visitConstant(Constant(node), isVertexShader);
			else if (node is BindableConstant)
				visitBindableConstant(BindableConstant(node), isVertexShader);
			else if (node is Sampler)
				visitSampler(Sampler(node), isVertexShader);
			else if (node is BindableSampler)
				visitBindableSampler(BindableSampler(node), isVertexShader);
		}

		protected function visitAttribute(attribute			: Attribute,
										  isVertexShader	: Boolean) : void
		{
		}

		protected function visitConstant(constant		: Constant,
										 isVertexShader : Boolean) : void
		{
		}

		protected function visitBindableConstant(bindableConstant	: BindableConstant,
												 isVertexShader		: Boolean) : void
		{
		}

		protected function visitSampler(sampler			: Sampler,
										isVertexShader	: Boolean) : void
		{
		}

		protected function visitBindableSampler(bindableSampler	: BindableSampler,
												isVertexShader	: Boolean) : void
		{
		}

		protected function visitExtract(extract			: Extract,
										isVertexShader	: Boolean) : void
		{
		}

		protected function visitInstruction(instruction		: Instruction,
										    isVertexShader	: Boolean) : void
		{
		}

		protected function visitInterpolate(interpolate		: Interpolate,
											isVertexShader	: Boolean) : void
		{
		}

		protected function visitOverwriter(overwriter		: Overwriter,
										   isVertexShader	: Boolean) : void
		{
		}

		protected function visitVariadicExtract(variadicExtract : VariadicExtract,
												isVertexShader	: Boolean) : void
		{
		}
	}
}

fix coding style

fix coding style


package aerys.minko.scene.controller.mesh
{
	import aerys.minko.render.Viewport;
	import aerys.minko.render.resource.texture.TextureResource;
	import aerys.minko.scene.controller.EnterFrameController;
	import aerys.minko.scene.node.ISceneNode;
	import aerys.minko.scene.node.Mesh;
	import aerys.minko.scene.node.Scene;
	import aerys.minko.type.binding.DataProvider;

	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;

	/**
	 * The DynamicTextureController makes it possible to use Flash DisplayObjects
	 * as dynamic textures.
	 *
	 * <p>
	 * The DynamicTextureController listen for the Scene.enterFrame signal and
	 * update the specified texture property of the targeted Meshes by rasterizing
	 * the source Flash DisplayObject.
	 * </p>
	 *
	 * @author Jean-Marc Le Roux
	 *
	 */
	public final class DynamicTextureController extends EnterFrameController
	{
		private var _data					: DataProvider;

		private var _source					: DisplayObject;
		private var _framerate				: Number;
		private var _mipMapping				: Boolean;
		private var _propertyName			: String;
		private var _matrix					: Matrix;
		private var _forceBitmapDataClear	: Boolean;
		private var _bitmapData				: BitmapData;
		private var _texture				: TextureResource;

		private var _lastDraw	            : Number;

		/**
		 * Create a new DynamicTextureController.
		 *
		 * @param source The source DisplayObject to use as a dynamic texture.
		 * @param width The width of the dynamic texture.
		 * @param height The height of the dynamic texture.
		 * @param mipMapping Whether mip-mapping should be enabled or not. Default value is 'true'.
		 * @param framerate The frame rate of the dynamic texture. Default value is '30'.
		 * @param propertyName The name of the bindings property that should be set with the
		 * dynamic texture. Default value if 'diffuseMap'.
		 * @param matrix The Matrix object that shall be used when rasterizing the DisplayObject
		 * into the dynamic texture. Default value is 'null'.
		 *
		 */
		public function DynamicTextureController(source					: DisplayObject,
												 width					: Number,
												 height					: Number,
												 mipMapping				: Boolean	= true,
												 framerate				: Number	= 30.,
												 propertyName			: String	= 'diffuseMap',
												 matrix					: Matrix	= null,
												 forceBitmapDataClear	: Boolean	= false)
		{
			super();

			_source = source;
			_texture = new TextureResource(width, height);
			_framerate = framerate;
			_mipMapping = mipMapping;
			_propertyName = propertyName;
			_matrix = matrix;
			_forceBitmapDataClear = forceBitmapDataClear;

			_data = new DataProvider();
			_data.setProperty(propertyName, _texture);
		}

		public function get forceBitmapDataClear():Boolean
		{
			return _forceBitmapDataClear;
		}

		public function set forceBitmapDataClear(value:Boolean):void
		{
			_forceBitmapDataClear = value;
		}

		override protected function targetAddedHandler(ctrl		: EnterFrameController,
													   target	: ISceneNode) : void
		{
			super.targetAddedHandler(ctrl, target);

			if (target is Scene)
				(target as Scene).bindings.addProvider(_data);
			else if (target is Mesh)
				(target as Mesh).bindings.addProvider(_data);
			else
				throw new Error();
		}

		override protected function targetRemovedHandler(ctrl	: EnterFrameController,
														 target	: ISceneNode) : void
		{
			super.targetRemovedHandler(ctrl, target);

			if (target is Scene)
				(target as Scene).bindings.removeProvider(_data);
			else if (target is Mesh)
				(target as Mesh).bindings.removeProvider(_data);
		}

		override protected function sceneEnterFrameHandler(scene	: Scene,
														   viewport	: Viewport,
														   target	: BitmapData,
														   time		: Number) : void
		{
			if (!_lastDraw || time - _lastDraw > 1000. / _framerate)
			{
				_lastDraw = time;

				_bitmapData ||= new BitmapData(_source.width, _source.height);
				if (_forceBitmapDataClear)
					_bitmapData.fillRect(
                        new Rectangle(0, 0, _bitmapData.width, _bitmapData.height),
                        0
                    );

				_bitmapData.draw(_source, _matrix);

				_texture.setContentFromBitmapData(_bitmapData, _mipMapping);
			}
		}
	}
}

package aerys.minko.scene.controller.mesh
{
	import aerys.minko.render.Viewport;
	import aerys.minko.render.resource.texture.TextureResource;
	import aerys.minko.scene.controller.EnterFrameController;
	import aerys.minko.scene.node.ISceneNode;
	import aerys.minko.scene.node.Mesh;
	import aerys.minko.scene.node.Scene;
	import aerys.minko.type.binding.DataProvider;

	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;

	/**
	 * The DynamicTextureController makes it possible to use Flash DisplayObjects
	 * as dynamic textures.
	 *
	 * <p>
	 * The DynamicTextureController listen for the Scene.enterFrame signal and
	 * update the specified texture property of the targeted Meshes by rasterizing
	 * the source Flash DisplayObject.
	 * </p>
	 *
	 * @author Jean-Marc Le Roux
	 *
	 */
	public final class DynamicTextureController extends EnterFrameController
	{
		private var _data					: DataProvider;

		private var _source					: Object;
		private var _framerate				: Number;
		private var _mipMapping				: Boolean;
		private var _propertyName			: String;
		private var _matrix					: Matrix;
		private var _forceBitmapDataClear	: Boolean;
		private var _tmpBitmapData			: BitmapData;
		private var _texture				: TextureResource;

		private var _lastDraw	            : Number;

		/**
		 * Create a new DynamicTextureController.
		 *
		 * @param source The source (BitmapData or DisplayObject) to use as a dynamic texture.
		 * @param mipMapping Whether mip-mapping should be enabled or not. Default value is 'true'.
		 * @param framerate The frame rate of the dynamic texture. Default value is '30'.
		 * @param propertyName The name of the bindings property that should be set with the
		 * dynamic texture. Default value if 'diffuseMap'.
		 * @param matrix The Matrix object that shall be used when rasterizing the DisplayObject
		 * into the dynamic texture. Default value is 'null'.
		 *
		 */
		public function DynamicTextureController(source					: Object,
												 mipMapping				: Boolean	= true,
												 framerate				: Number	= 30.,
												 propertyName			: String	= 'diffuseMap',
												 matrix					: Matrix	= null,
												 forceBitmapDataClear	: Boolean	= false)
		{
			super();

			if (!(source is DisplayObject) && !(source is BitmapData))
				throw new Error("Invalid argument: source must be of type DisplayObject or BitmapData.");

			_source = source;
			_texture = new TextureResource();
			_framerate = framerate;
			_mipMapping = mipMapping;
			_propertyName = propertyName;
			_matrix = matrix;
			_forceBitmapDataClear = forceBitmapDataClear;

			_data = new DataProvider();
			_data.setProperty(propertyName, _texture);
		}

		public function get forceBitmapDataClear():Boolean
		{
			return _forceBitmapDataClear;
		}

		public function set forceBitmapDataClear(value:Boolean):void
		{
			_forceBitmapDataClear = value;
		}

		override protected function targetAddedHandler(ctrl		: EnterFrameController,
													   target	: ISceneNode) : void
		{
			super.targetAddedHandler(ctrl, target);

			if (target is Scene)
				(target as Scene).bindings.addProvider(_data);
			else if (target is Mesh)
				(target as Mesh).bindings.addProvider(_data);
			else
				throw new Error();
		}

		override protected function targetRemovedHandler(ctrl	: EnterFrameController,
														 target	: ISceneNode) : void
		{
			super.targetRemovedHandler(ctrl, target);

			if (target is Scene)
				(target as Scene).bindings.removeProvider(_data);
			else if (target is Mesh)
				(target as Mesh).bindings.removeProvider(_data);
		}

		override protected function sceneEnterFrameHandler(scene	: Scene,
														   viewport	: Viewport,
														   target	: BitmapData,
														   time		: Number) : void
		{
			if (!_lastDraw || time - _lastDraw > 1000. / _framerate)
			{
				_lastDraw = time;

				if (_source is DisplayObject)
				    updateFromDisplayObject();
				else
					updateFromBitmapData();
			}
		}

		private function updateFromDisplayObject() : void
		{
			var sourceDisplayObject : DisplayObject = _source as DisplayObject;

			refreshTempBitmapData();

			_tmpBitmapData.draw(sourceDisplayObject, _matrix);
			_texture.setContentFromBitmapData(_tmpBitmapData, _mipMapping);
		}

		private function updateFromBitmapData() : void
		{
			if (_matrix)
			{
				refreshTempBitmapData();

				_tmpBitmapData.draw(_source as BitmapData, _matrix);
				_texture.setContentFromBitmapData(_tmpBitmapData, _mipMapping);
			}

			_texture.setContentFromBitmapData(_source as BitmapData, _mipMapping);
		}

		private function refreshTempBitmapData() : void
		{
			if (!_tmpBitmapData)
				_tmpBitmapData = new BitmapData(_source.width, _source.height);
			else if (_forceBitmapDataClear)
				_tmpBitmapData.fillRect(
					new Rectangle(0, 0, _tmpBitmapData.width, _tmpBitmapData.height),
					0
				);
		}
	}
}

add support for BitmapData as a source for DynamicTextureController


/**
 *  GODPAPER Confidential,Copyright 2012. All rights reserved.
 *
 *  Permission is hereby granted, free of charge, to any person obtaining
 *  a copy of this software and associated documentation files (the "Software"),
 *  to deal in the Software without restriction, including without limitation
 *  the rights to use, copy, modify, merge, publish, distribute, sub-license,
 *  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
{
	//--------------------------------------------------------------------------
	//
	//  Imports
	//
	//--------------------------------------------------------------------------
	import com.godpaper.as3.configs.LoggerConfig;
	import com.godpaper.as3.utils.LogUtil;
	import com.godpaper.mqtt.as3.core.MQTTEvent;
	import com.godpaper.mqtt.as3.impl.MQTTSocket;
	import com.godpaper.mqtt.as3.utils.UIDUtil;

	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.system.Security;
	import flash.utils.ByteArray;
	import flash.utils.Endian;

	import mx.logging.ILogger;
	import mx.logging.LogEventLevel;

	/**
	 * Pure Action Script 3 that implements the MQTT (Message Queue Telemetry Transport) protocol, a lightweight protocol for publish/subscribe messaging. </br>
	 * AS3 socket is a mechanism used to send data over a network (e.g. the Internet), it is the combination of an IP address and a port. </br>
	 * @see https://github.com/yangboz/as3MQTT
	 * @see https://github.com/yangboz/as3MQTT/wiki
	 * @see https://github.com/yangboz/as3Logger
	 *
	 * @author yangboz
	 * @langVersion 3.0
	 * @playerVersion 11.2+
	 * @airVersion 3.2+
	 * Created Nov 20, 2012 10:19:53 AM
	 */
	public class MQTTClient_AS3 extends Sprite
	{
		//--------------------------------------------------------------------------
		//
		//  Variables
		//
		//--------------------------------------------------------------------------
		private var mqttSocket:MQTTSocket;
		//----------------------------------
		//  CONSTANTS
		//----------------------------------
		//Notice: You need to define a cross domain policy file at your remote server root document, or have a policy file server on the target.
		private static const MY_HOST:String="16.157.65.23"; //You'd better change it to your private ip address! //test.mosquitto.org//16.157.65.23(Ubuntu)//15.185.106.72(hp cs instance)
		private static const MY_PORT:Number=1883; //Socket port.
		//as3Logger
//		LoggerConfig.filters = ["MQTTClient_AS3"];
		LoggerConfig.filters = ["com.godpaper.mqtt.as3.impl.*"];
		LoggerConfig.level = LogEventLevel.DEBUG;
		private static const LOG:ILogger = LogUtil.getLogger(MQTTClient_AS3);

		//--------------------------------------------------------------------------
		//
		//  Public properties
		//
		//--------------------------------------------------------------------------

		//--------------------------------------------------------------------------
		//
		//  Protected properties
		//
		//--------------------------------------------------------------------------

		//--------------------------------------------------------------------------
		//
		//  Constructor
		//
		//--------------------------------------------------------------------------
		public function MQTTClient_AS3()
		{
//			Creating a Socket
			this.mqttSocket=new MQTTSocket(MY_HOST, MY_PORT);
			//Notice: You need to define a cross domain policy file at your remote server root document, or have a policy file server on the target.
			Security.allowDomain("*");
//			Security.loadPolicyFile("http://www.lookbackon.com/crossdomain.xml");
			//event listeners
			mqttSocket.addEventListener(MQTTEvent.CONNECT, onConnect); //dispatched when the connection is established
			mqttSocket.addEventListener(MQTTEvent.CLOSE, onClose); //dispatched when the connection is closed
			mqttSocket.addEventListener(MQTTEvent.ERROR, onError); //dispatched when an error occurs
			mqttSocket.addEventListener(MQTTEvent.MESSGE, onMessage); //dispatched when socket can be read
			//try to connect
			mqttSocket.connect();
		}

		//--------------------------------------------------------------------------
		//
		//  Public methods
		//
		//--------------------------------------------------------------------------

		//--------------------------------------------------------------------------
		//
		//  Protected methods
		//
		//--------------------------------------------------------------------------

		//--------------------------------------------------------------------------
		//
		//  Private methods
		//
		//--------------------------------------------------------------------------
		//
		private function onConnect(event:MQTTEvent):void
		{
			LOG.info("MQTT connect: {0}",event.message);
		}

		//
		private function onClose(event:MQTTEvent):void
		{
			LOG.info("MQTT close: {0}",event.message);
		}

		//
		private function onError(event:MQTTEvent):void
		{
			LOG.info("MQTT Error: {0}",event.message);
		}

		//
		private function onMessage(event:MQTTEvent):void
		{
			LOG.info("MQTT message: {0}",event.message);
		}

	}

}

/**
 *  GODPAPER Confidential,Copyright 2012. All rights reserved.
 *
 *  Permission is hereby granted, free of charge, to any person obtaining
 *  a copy of this software and associated documentation files (the "Software"),
 *  to deal in the Software without restriction, including without limitation
 *  the rights to use, copy, modify, merge, publish, distribute, sub-license,
 *  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
{
	//--------------------------------------------------------------------------
	//
	//  Imports
	//
	//--------------------------------------------------------------------------
	import com.godpaper.as3.configs.LoggerConfig;
	import com.godpaper.as3.utils.LogUtil;
	import com.godpaper.mqtt.as3.core.MQTTEvent;
	import com.godpaper.mqtt.as3.impl.MQTTSocket;

	import flash.display.Sprite;
	import flash.system.Security;

	import mx.logging.ILogger;
	import mx.logging.LogEventLevel;

	/**
	 * Pure Action Script 3 that implements the MQTT (Message Queue Telemetry Transport) protocol, a lightweight protocol for publish/subscribe messaging. </br>
	 * AS3 socket is a mechanism used to send data over a network (e.g. the Internet), it is the combination of an IP address and a port. </br>
	 * @see https://github.com/yangboz/as3MQTT
	 * @see https://github.com/yangboz/as3MQTT/wiki
	 * @see https://github.com/yangboz/as3Logger
	 *
	 * @author yangboz
	 * @langVersion 3.0
	 * @playerVersion 11.2+
	 * @airVersion 3.2+
	 * Created Nov 20, 2012 10:19:53 AM
	 */
	public class MQTTClient_AS3 extends Sprite
	{
		//--------------------------------------------------------------------------
		//
		//  Variables
		//
		//--------------------------------------------------------------------------
		private var mqttSocket:MQTTSocket;
		//----------------------------------
		//  CONSTANTS
		//----------------------------------
		//Notice: You need to define a cross domain policy file at your remote server root document, or have a policy file server on the target.
		private static const MY_HOST:String="test.mosquitto.org"; //You'd better change it to your private ip address! //test.mosquitto.org//16.157.65.23(Ubuntu)//15.185.106.72(hp cs instance)
		private static const MY_PORT:Number=1883; //Socket port.
		//as3Logger
//		LoggerConfig.filters = ["MQTTClient_AS3"];
		LoggerConfig.filters = ["com.godpaper.mqtt.as3.impl.*"];
		LoggerConfig.level = LogEventLevel.DEBUG;
		private static const LOG:ILogger = LogUtil.getLogger(MQTTClient_AS3);

		//--------------------------------------------------------------------------
		//
		//  Public properties
		//
		//--------------------------------------------------------------------------

		//--------------------------------------------------------------------------
		//
		//  Protected properties
		//
		//--------------------------------------------------------------------------

		//--------------------------------------------------------------------------
		//
		//  Constructor
		//
		//--------------------------------------------------------------------------
		public function MQTTClient_AS3()
		{
//			Creating a Socket
			this.mqttSocket=new MQTTSocket(MY_HOST, MY_PORT);
			//Notice: You need to define a cross domain policy file at your remote server root document, or have a policy file server on the target.
			Security.allowDomain("*");
//			Security.loadPolicyFile("http://www.lookbackon.com/crossdomain.xml");
			//event listeners
			mqttSocket.addEventListener(MQTTEvent.CONNECT, onConnect); //dispatched when the connection is established
			mqttSocket.addEventListener(MQTTEvent.CLOSE, onClose); //dispatched when the connection is closed
			mqttSocket.addEventListener(MQTTEvent.ERROR, onError); //dispatched when an error occurs
			mqttSocket.addEventListener(MQTTEvent.MESSGE, onMessage); //dispatched when socket can be read
			//try to connect
			mqttSocket.connect();
		}

		//--------------------------------------------------------------------------
		//
		//  Public methods
		//
		//--------------------------------------------------------------------------

		//--------------------------------------------------------------------------
		//
		//  Protected methods
		//
		//--------------------------------------------------------------------------

		//--------------------------------------------------------------------------
		//
		//  Private methods
		//
		//--------------------------------------------------------------------------
		//
		private function onConnect(event:MQTTEvent):void
		{
			LOG.info("MQTT connect: {0}",event.message);
		}

		//
		private function onClose(event:MQTTEvent):void
		{
			LOG.info("MQTT close: {0}",event.message);
		}

		//
		private function onError(event:MQTTEvent):void
		{
			LOG.info("MQTT Error: {0}",event.message);
		}

		//
		private function onMessage(event:MQTTEvent):void
		{
			LOG.info("MQTT message: {0}",event.message);
		}

	}

}

remove useless import

remove useless import


package aerys.minko.scene.controller
{
	import aerys.minko.render.Viewport;
	import aerys.minko.scene.node.Group;
	import aerys.minko.scene.node.ISceneNode;
	import aerys.minko.scene.node.Scene;
	import aerys.minko.type.Signal;
	import aerys.minko.type.animation.TimeLabel;
	import aerys.minko.type.animation.timeline.ITimeline;

	import flash.display.BitmapData;
	import flash.utils.getTimer;

	/**
	 * The AnimationController uses timelines to animate properties of scene nodes.
	 *
	 * @author Jean-Marc Le Roux
	 *
	 */
	public class AnimationController extends EnterFrameController
	{
		private var _timelines		: Vector.<ITimeline>;
		private var _isPlaying		: Boolean;
		private var _updateOneTime	: Boolean;

		private var _loopBeginTime	: int;
		private var _loopEndTime	: int;
		private var _looping		: Boolean;
		private var _currentTime	: int;
		private var _totalTime		: int;

		private var _timeFunction	: Function;
		private var _labels			: Vector.<TimeLabel>;

		private var _lastTime		: Number;

		private var _looped			: Signal;
		private var _started		: Signal;
		private var _stopped		: Signal;

		public function get timeFunction() : Function
		{
			return _timeFunction;
		}

		public function set timeFunction(value : Function) : void
		{
			_timeFunction = value;
		}

		public function get labels() : Vector.<TimeLabel>
		{
			return _labels;
		}

		public function get numTimelines() : uint
		{
			return _timelines.length;
		}

		public function get started() : Signal
		{
			return _started;
		}

		public function get stopped() : Signal
		{
			return _stopped;
		}

		public function get looped() : Signal
		{
			return _looped;
		}

		public function get totalTime() : int
		{
			return _totalTime;
		}

		public function get looping() : Boolean
		{
			return _looping;
		}
		public function set looping(value : Boolean) : void
		{
			_looping = value;
		}

		public function get isPlaying() : Boolean
		{
			return _isPlaying;
		}
		public function set isPlaying(value : Boolean) : void
		{
			_isPlaying = value;
		}

		public function get currentTime() : int
		{
			return _currentTime;
		}

		public function AnimationController(timelines 	: Vector.<ITimeline>,
											loop		: Boolean	= true)
		{
			super();

			initialize(timelines, loop);
		}

		private function initialize(timelines 	: Vector.<ITimeline>,
									loop		: Boolean) : void
		{
			_timelines = timelines.slice();
			_looping = loop;
			_labels = new <TimeLabel>[];
			_looped	= new Signal('AnimationController.looped');
			_started = new Signal('AnimationController.started');
			_stopped = new Signal('AnimationController.stopped');

			var numTimelines : uint = _timelines.length;

			for (var timelineId : uint = 0; timelineId < numTimelines; ++timelineId)
				if (_totalTime < _timelines[timelineId].duration)
					_totalTime = _timelines[timelineId].duration;

			setPlaybackWindow(0, _totalTime);
			seek(0).play();
		}

		override public function clone() : AbstractController
		{
			return new AnimationController(_timelines.slice());
		}

		public function cloneTimelines() : void
		{
			var numTimelines	: uint	= _timelines.length;

			for (var timelineId : uint = 0; timelineId < numTimelines; ++timelineId)
				_timelines[timelineId] = (_timelines[timelineId] as ITimeline).clone();
		}

		public function getTimeline(index : uint = 0) : ITimeline
		{
			return _timelines[index];
		}

		public function seek(time : Object) : AnimationController
		{
			var timeValue : uint = getAnimationTime(time);

			if (timeValue < _loopBeginTime || timeValue > _loopEndTime)
				throw new Error('Time value is outside of playback window. To reset playback window, call resetPlaybackWindow.');

			_currentTime = timeValue;

			return this;
		}

		public function play() : AnimationController
		{
			_isPlaying = true;
			_lastTime = _timeFunction != null ? _timeFunction(getTimer()) : getTimer();
			_started.execute(this);

			return this;
		}

		public function stop() : AnimationController
		{
			_isPlaying = false;
			_updateOneTime 	= true;
			_lastTime = _timeFunction != null ? _timeFunction(getTimer()) : getTimer();
			_stopped.execute(this);

			return this;
		}

		public function setPlaybackWindow(beginTime	: Object = null,
										  endTime	: Object = null) : AnimationController
		{
			_loopBeginTime	= beginTime != null ? getAnimationTime(beginTime) : 0;
			_loopEndTime	= endTime != null ? getAnimationTime(endTime) : _totalTime;

			if (_currentTime < _loopBeginTime || _currentTime > _loopEndTime)
				_currentTime = _loopBeginTime;

			return this;
		}

		public function resetPlaybackWindow() : AnimationController
		{
			setPlaybackWindow();

			return this;
		}

		private function getAnimationTime(time : Object) : uint
		{
			var timeValue : uint;

			if (time is uint || time is int || time is Number)
			{
				timeValue = uint(time);
			}
			else if (time is String)
			{
				var labelCount : uint = _labels.length;

				for (var labelId : uint = 0; labelId < labelCount; ++labelId)
					if (_labels[labelId].name == time)
						timeValue = _labels[labelId].time;
			}
			else
			{
				throw new Error('Invalid argument type: time must be Number or String');
			}

			return timeValue;
		}

		override protected function sceneEnterFrameHandler(scene	: Scene,
														   viewport	: Viewport,
														   target	: BitmapData,
														   time		: Number) : void
		{
			if (updateOnTime(time))
			{
				_updateOneTime = false;

				for (var j : uint = 0; j < numTargets; ++j)
				{
					var ctrlTarget		: ISceneNode	= getTarget(j);
					var numTimelines 	: int 			= _timelines.length;
					var group			: Group			= target as Group;

					if (ctrlTarget.root != scene)
						continue ;

					for (var i : int = 0; i < numTimelines; ++i)
					{
						var timeline : ITimeline = _timelines[i] as ITimeline;

						timeline.updateAt(
							_currentTime % (timeline.duration + 1),
							ctrlTarget
						);
					}
				}
			}
		}

		private function updateOnTime(time : Number) : Boolean
		{
			if (_isPlaying || _updateOneTime)
			{
				if (_timeFunction != null)
					time = _timeFunction(time);

				var deltaT 			: Number = time - _lastTime;
				var lastCurrentTime : Number = _currentTime;

				if (_isPlaying)
				{
					_currentTime = _loopBeginTime
						+ (_currentTime + deltaT - _loopBeginTime)
						% (_loopEndTime - _loopBeginTime);
				}

				if ((deltaT > 0 && lastCurrentTime > _currentTime)
					|| (deltaT < 0 && (lastCurrentTime < _currentTime || _currentTime * lastCurrentTime < 0)))
				{
					if (_looping)
						_looped.execute(this);
					else
					{
						_currentTime = deltaT > 0 ? _totalTime : 0;
						stop();

						return true;
					}
				}
			}

			_lastTime = time;

			return _isPlaying || _updateOneTime;
		}
	}
}

package aerys.minko.scene.controller
{
	import aerys.minko.render.Viewport;
	import aerys.minko.scene.node.Group;
	import aerys.minko.scene.node.ISceneNode;
	import aerys.minko.scene.node.Scene;
	import aerys.minko.type.Signal;
	import aerys.minko.type.animation.TimeLabel;
	import aerys.minko.type.animation.timeline.ITimeline;

	import flash.display.BitmapData;
	import flash.utils.getTimer;

	/**
	 * The AnimationController uses timelines to animate properties of scene nodes.
	 *
	 * @author Jean-Marc Le Roux
	 *
	 */
	public class AnimationController extends EnterFrameController
	{
		private var _timelines		: Vector.<ITimeline>;
		private var _isPlaying		: Boolean;
		private var _updateOneTime	: Boolean;

		private var _loopBeginTime	: int;
		private var _loopEndTime	: int;
		private var _looping		: Boolean;
		private var _currentTime	: int;
		private var _totalTime		: int;

		private var _timeFunction	: Function;
		private var _labels			: Vector.<TimeLabel>;

		private var _lastTime		: Number;

		private var _looped			: Signal;
		private var _started		: Signal;
		private var _stopped		: Signal;

		public function get timeFunction() : Function
		{
			return _timeFunction;
		}

		public function set timeFunction(value : Function) : void
		{
			_timeFunction = value;
		}

		public function get labels() : Vector.<TimeLabel>
		{
			return _labels;
		}

		public function get numTimelines() : uint
		{
			return _timelines.length;
		}

		public function get started() : Signal
		{
			return _started;
		}

		public function get stopped() : Signal
		{
			return _stopped;
		}

		public function get looped() : Signal
		{
			return _looped;
		}

		public function get totalTime() : int
		{
			return _totalTime;
		}

		public function get looping() : Boolean
		{
			return _looping;
		}
		public function set looping(value : Boolean) : void
		{
			_looping = value;
		}

		public function get isPlaying() : Boolean
		{
			return _isPlaying;
		}
		public function set isPlaying(value : Boolean) : void
		{
			_isPlaying = value;
		}

		public function get currentTime() : int
		{
			return _currentTime;
		}

		public function AnimationController(timelines 	: Vector.<ITimeline>,
											loop		: Boolean	= true)
		{
			super();

			initialize(timelines, loop);
		}

		private function initialize(timelines 	: Vector.<ITimeline>,
									loop		: Boolean) : void
		{
			_timelines = timelines.slice();
			_looping = loop;
			_labels = new <TimeLabel>[];
			_looped	= new Signal('AnimationController.looped');
			_started = new Signal('AnimationController.started');
			_stopped = new Signal('AnimationController.stopped');

			var numTimelines : uint = _timelines.length;

			for (var timelineId : uint = 0; timelineId < numTimelines; ++timelineId)
				if (_totalTime < _timelines[timelineId].duration)
					_totalTime = _timelines[timelineId].duration;

			setPlaybackWindow(0, _totalTime);
			seek(0).play();
		}

		override public function clone() : AbstractController
		{
			return new AnimationController(_timelines.slice());
		}

		public function cloneTimelines() : void
		{
			var numTimelines	: uint	= _timelines.length;

			for (var timelineId : uint = 0; timelineId < numTimelines; ++timelineId)
				_timelines[timelineId] = (_timelines[timelineId] as ITimeline).clone();
		}

		public function getTimeline(index : uint = 0) : ITimeline
		{
			return _timelines[index];
		}

		public function seek(time : Object) : AnimationController
		{
			var timeValue : uint = getAnimationTime(time);

			if (timeValue < _loopBeginTime || timeValue > _loopEndTime)
				throw new Error(
                    'Time value is outside of playback window. '
                    +'To reset playback window, call resetPlaybackWindow.'
                );

			_currentTime = timeValue;

			return this;
		}

		public function play() : AnimationController
		{
			_isPlaying = true;
			_lastTime = _timeFunction != null ? _timeFunction(getTimer()) : getTimer();
			_started.execute(this);

			return this;
		}

		public function stop() : AnimationController
		{
			_isPlaying = false;
			_updateOneTime 	= true;
			_lastTime = _timeFunction != null ? _timeFunction(getTimer()) : getTimer();
			_stopped.execute(this);

			return this;
		}

		public function setPlaybackWindow(beginTime	: Object = null,
										  endTime	: Object = null) : AnimationController
		{
			_loopBeginTime	= beginTime != null ? getAnimationTime(beginTime) : 0;
			_loopEndTime	= endTime != null ? getAnimationTime(endTime) : _totalTime;

			if (_currentTime < _loopBeginTime || _currentTime > _loopEndTime)
				_currentTime = _loopBeginTime;

			return this;
		}

		public function resetPlaybackWindow() : AnimationController
		{
			setPlaybackWindow();

			return this;
		}

		private function getAnimationTime(time : Object) : uint
		{
			var timeValue : uint;

			if (time is uint || time is int || time is Number)
			{
				timeValue = uint(time);
			}
			else if (time is String)
			{
				var labelCount : uint = _labels.length;

				for (var labelId : uint = 0; labelId < labelCount; ++labelId)
					if (_labels[labelId].name == time)
						timeValue = _labels[labelId].time;
			}
			else
			{
				throw new Error('Invalid argument type: time must be Number or String');
			}

			return timeValue;
		}

		override protected function sceneEnterFrameHandler(scene	: Scene,
														   viewport	: Viewport,
														   target	: BitmapData,
														   time		: Number) : void
		{
			if (updateOnTime(time))
			{
				_updateOneTime = false;

				for (var j : uint = 0; j < numTargets; ++j)
				{
					var ctrlTarget		: ISceneNode	= getTarget(j);
					var numTimelines 	: int 			= _timelines.length;
					var group			: Group			= target as Group;

					if (ctrlTarget.root != scene)
						continue ;

					for (var i : int = 0; i < numTimelines; ++i)
					{
						var timeline : ITimeline = _timelines[i] as ITimeline;

						timeline.updateAt(
							_currentTime % (timeline.duration + 1),
							ctrlTarget
						);
					}
				}
			}
		}

		private function updateOnTime(time : Number) : Boolean
		{
			if (_isPlaying || _updateOneTime)
			{
				if (_timeFunction != null)
					time = _timeFunction(time);

				var deltaT 			: Number = time - _lastTime;
				var lastCurrentTime : Number = _currentTime;

				if (_isPlaying)
				{
					_currentTime = _loopBeginTime
						+ (_currentTime + deltaT - _loopBeginTime)
						% (_loopEndTime - _loopBeginTime);
				}

				if ((deltaT > 0 && lastCurrentTime > _currentTime)
					|| (deltaT < 0 && (lastCurrentTime < _currentTime
                        || _currentTime * lastCurrentTime < 0)))
				{
					if (_looping)
						_looped.execute(this);
					else
					{
						_currentTime = deltaT > 0 ? _totalTime : 0;
						stop();

						return true;
					}
				}
			}

			_lastTime = time;

			return _isPlaying || _updateOneTime;
		}
	}
}

fix coding style

fix coding style


package gov.nih.nci.cbiit.casas.components
{
	import learnmath.mathml.components.MathMLEditor;

	import mx.core.IUIComponent;

	public class FormulaEditor extends MathMLEditor
	{
		public function FormulaEditor()
		{
//			this.setConfiguration("disableOpen", "false");
//decompile MathMLEditor
//decompile EditorApp to enable Save/Open functionalities
			super();
//			super.mainPannel.name= "what NCI Center for Biomedical Informatics & Information Technology - Scientific Algorithm Service";
		}
	}
}

package gov.nih.nci.cbiit.casas.components
{

	import fl.core.UIComponent;

	import flash.display.MovieClip;
	import flash.events.KeyboardEvent;
	import flash.utils.Timer;

	import learnmath.mathml.components.MathMLEditor;
	import learnmath.mathml.formula.Constants;
	import learnmath.windows.ConfigManager;

	import mx.controls.Alert;
	import mx.core.IUIComponent;

	import flash.events.TimerEvent;

	public class FormulaEditor extends MathMLEditor
	{
		public function FormulaEditor()
		{
			//duplicate MathMLEditor Constructor
			ConfigManager.urlFonts="./";
			Constants.setUrlFonts("./");
//			ConfigManager.setConfig("disableSave","false");
//			ConfigManager.setConfig("disableOpen","false");
			ConfigManager.disableOpen=new Boolean(false);
			ConfigManager.disableSave=new Boolean(false);
			addEventListener(KeyboardEvent.KEY_DOWN, processKey);
//			mainPannel.name= "NCI Center for Biomedical Informatics & Information Technology - Scientific Algorithm Service";
//			mainPannel.draw();
			return;
		}

//		override protected function createChildren():void
//		{
//			Alert.show("before created by super", mainPannel+"");
//			super.createChildren();
//			Alert.show("created by super", mainPannel+"");
//			mainPannel=null;
//			while (this.numChildren>0)
//			{
//				this.removeChildAt(0);
//			}
//			var _loc_1:*=new MovieClip();
//			var editorW:Number=800;
//			var editorH:Number=500;
//
//			mainPannel = new FormulaPanel(_loc_1, 0,0,editorW, editorH, returnFocus);
//			mainPannel.draw();
//			mainPannel.setMathML("..xx");
//			Alert.show(mainPannel+"", mainPannel.getMathML());
//			var _loc_2:*=new UIComponent();
//			addChild(_loc_2);
//
//			var _loc_3:*=new Timer(100,1);
//			_loc_3.addEventListenr(TimerEvent.TIMER, redrawEditor);
//			_loc_3.start();
//			return;
//		}

		//override private method
		private function redrawEditor(event:TimerEvent):void
		{
			mainPannel.draw();
			if (focusManager!=null)
			{
				focusManager.setFocus(this);
			}
			return;
		}
	}

}

clean version using FMathML FormulaEditor

SVN-Revision: 3125


package stdio {
  import flash.display.*
  import flash.events.*
  import flash.utils.*
  import flash.net.*

  public class StandardProcess implements Process {
    private const buffered_stdin: BufferedStream = new BufferedStream
    private const stdin_socket: SocketStream = new SocketStream
    private const readline_socket: SocketStream = new SocketStream

    private const stdout_socket: SocketStream = new SocketStream
    private const stderr_socket: SocketStream = new SocketStream

    private var _env: Object
    private var _prompt: String = "> "

    public function StandardProcess(env: Object) {
      _env = env
    }

    public function initialize(callback: Function): void {
      if (available) {
        connect(callback)
      } else {
        callback()
      }
    }

    public function get available(): Boolean {
      return env["stdio.enabled"]
    }

    private function get http_url(): String {
      return env["stdio.http"]
    }

    private function get interactive(): Boolean {
      return env["stdio.interactive"] === "true"
    }

    private function connect(callback: Function): void {
      stdin_socket.onopen = onopen
      readline_socket.onopen = onopen
      stdout_socket.onopen = onopen
      stderr_socket.onopen = onopen

      var n: int = 0

      function onopen(): void {
        if (++n === 3) {
          callback()
        }
      }

      stdin_socket.ondata = buffered_stdin.write
      stdin_socket.onclose = buffered_stdin.close
      readline_socket.ondata = buffered_stdin.write
      readline_socket.onclose = buffered_stdin.close

      const stdin_port: int = get_int("stdio.in")
      const readline_port: int = get_int("stdio.readline")

      if (interactive) {
        readline_socket.connect("localhost", readline_port)
      } else {
        stdin_socket.connect("localhost", stdin_port)
      }

      const stdout_port: int = get_int("stdio.out")
      const stderr_port: int = get_int("stdio.err")

      stdout_socket.connect("localhost", stdout_port)
      stderr_socket.connect("localhost", stderr_port)

      function get_int(name: String): int {
        return parseInt(env[name])
      }
    }

    //----------------------------------------------------------------

    public function get env(): * {
      return _env
    }

    public function get argv(): Array {
      if (env["stdio.argv"] === "") {
        return []
      } else {
        return env["stdio.argv"].split(" ").map(
          function (argument: String, ...rest: Array): String {
            return decodeURIComponent(argument)
          }
        )
      }
    }

    public function puts(value: *): void {
      if (available) {
        if (interactive) {
          readline_socket.puts("!" + value)
        } else {
          stdout.puts(value)
        }
      } else {
        debug.show("puts: " + value)
      }
    }

    public function warn(value: *): void {
      if (available) {
        stderr.puts(value)
      } else {
        debug.show("warn: " + value)
      }
    }

    public function die(value: *): void {
      if (available) {
        warn(value); exit(-1)
      } else {
        throw new Error("fatal error: " + String(value))
      }
    }

    public function style(styles: String, string: String): String {
      const codes: Object = {
        none: 0, bold: 1, italic: 3, underline: 4, inverse: 7,
        black: 30, red: 31, green: 32, yellow: 33, blue: 34,
        magenta: 35, cyan: 36, white: 37, gray: 90, grey: 90
      }

      if (styles === "") {
        return string
      } else {
        return styles.split(/\s+/).map(
          function (style: String, ...rest: Array): String {
            if (style in codes) {
              return escape_sequence(codes[style])
            } else {
              throw new Error("style not supported: " + style)
            }
          }
        ).join("") + string + escape_sequence(0)
      }

      function escape_sequence(code: int): String {
        return "\x1b[" + code + "m"
      }
    }

    public function gets(callback: Function): void {
      if (available) {
        if (interactive) {
          readline_socket.puts("?" + _prompt)
        }

        stdin.gets(callback)
      } else {
        callback(null)
      }
    }

    public function set prompt(value: String): void {
      _prompt = value
    }

    public function get stdin(): InputStream {
      return buffered_stdin
    }

    public function get stdout(): OutputStream {
      return stdout_socket
    }

    public function get stderr(): OutputStream {
      return stderr_socket
    }

    public function handle(error: *): void {
      if (error is UncaughtErrorEvent) {
        UncaughtErrorEvent(error).preventDefault()
        handle(UncaughtErrorEvent(error).error)
        exit(-1)
      } else if (error is Error) {
        // Important: Avoid the `Error(x)` casting syntax.
        http_post("/error", (error as Error).getStackTrace())
      } else if (error is ErrorEvent) {
        const event: ErrorEvent = ErrorEvent(error)

        http_post("/error", (
          getQualifiedClassName(event) + ": " + event.text
            + " [event.target: " + event.target + "]"
        ))
      } else {
        http_post("/error", String(error))
      }
    }

    private function shell_quote(word: String): String {
      if (/^[-=.,\w]+$/.test(word)) {
        return word
      } else {
        return "'" + word.replace(/'/g, "'\\''") + "'"
      }
    }

    public function exec(
      command: *,
      callback: Function,
      errback: Function = null
    ): void {
      if (available) {
        var stdin: String = ""

        if ("command" in command && "stdin" in command) {
          stdin = command.stdin
          command = command.command
        }

        if (command is String) {
          command = ["sh", "-c", command]
        }

        const url: String = "/exec?" + command.map(
          function (word: String, ...rest: Array): String {
            return encodeURIComponent(word)
          }
        ).join("&")

        http_post(url, stdin, function (data: String): void {
          const result: XML = new XML(data)
          const status: int = result.@status
          const stdout: String = result.stdout.text()
          const stderr: String = result.stderr.text()

          if (status === 0) {
            if (callback.length === 1) {
              callback(stdout)
            } else {
              callback(stdout, stderr)
            }
          } else if (errback === null) {
            warn(stderr)
          } else if (errback.length === 1) {
            errback(new Error(stderr))
          } else if (errback.length === 2) {
            errback(status, stderr)
          } else {
            errback(status, stderr, stdout)
          }
        })
      } else {
        throw new Error("cannot execute command: process not available")
      }
    }

    public function exit(status: int = 0): void {
      if (available) {
        when_ready(function (): void {
          http_post("/exit", String(status))
        })
      } else {
        throw new Error("cannot exit: process not available")
      }
    }

    //----------------------------------------------------------------

    private var n_pending_requests: int = 0
    private var ready_callbacks: Array = []

    private function when_ready(callback: Function): void {
      if (n_pending_requests === 0) {
        callback()
      } else {
        ready_callbacks.push(callback)
      }
    }

    private function handle_ready(): void {
      for each (var callback: Function in ready_callbacks) {
        callback()
      }

      ready_callbacks = []
    }

    private function http_post(
      path: String, content: String, callback: Function = null
    ): void {
      const request: URLRequest = new URLRequest(http_url + path)

      request.method = "POST"
      request.data = content

      const loader: URLLoader = new URLLoader

      ++n_pending_requests

      loader.addEventListener(
        Event.COMPLETE,
        function (event: Event): void {
          if (callback !== null) {
            callback(loader.data)
          }

          if (--n_pending_requests === 0) {
            handle_ready()
          }
        }
      )

      loader.load(request)
    }
  }
}

package stdio {
  import flash.display.*
  import flash.events.*
  import flash.utils.*
  import flash.net.*

  public class StandardProcess implements Process {
    private const buffered_stdin: BufferedStream = new BufferedStream
    private const stdin_socket: SocketStream = new SocketStream
    private const readline_socket: SocketStream = new SocketStream

    private const stdout_socket: SocketStream = new SocketStream
    private const stderr_socket: SocketStream = new SocketStream

    private var _env: Object
    private var _prompt: String = "> "

    public function StandardProcess(env: Object) {
      _env = env
    }

    public function initialize(callback: Function): void {
      if (available) {
        connect(callback)
      } else {
        callback()
      }
    }

    public function get available(): Boolean {
      return env["stdio.enabled"]
    }

    private function get http_url(): String {
      return env["stdio.http"]
    }

    private function get interactive(): Boolean {
      return env["stdio.interactive"] === "true"
    }

    private function connect(callback: Function): void {
      stdin_socket.onopen = onopen
      readline_socket.onopen = onopen
      stdout_socket.onopen = onopen
      stderr_socket.onopen = onopen

      var n: int = 0

      function onopen(): void {
        if (++n === 3) {
          callback()
        }
      }

      stdin_socket.ondata = buffered_stdin.write
      stdin_socket.onclose = buffered_stdin.close
      readline_socket.ondata = buffered_stdin.write
      readline_socket.onclose = buffered_stdin.close

      const stdin_port: int = get_int("stdio.in")
      const readline_port: int = get_int("stdio.readline")

      if (interactive) {
        readline_socket.connect("localhost", readline_port)
      } else {
        stdin_socket.connect("localhost", stdin_port)
      }

      const stdout_port: int = get_int("stdio.out")
      const stderr_port: int = get_int("stdio.err")

      stdout_socket.connect("localhost", stdout_port)
      stderr_socket.connect("localhost", stderr_port)

      function get_int(name: String): int {
        return parseInt(env[name])
      }
    }

    //----------------------------------------------------------------

    public function get env(): * {
      return _env
    }

    public function get argv(): Array {
      if (!env["stdio.argv"]) {
        return []
      } else {
        return env["stdio.argv"].split(" ").map(
          function (argument: String, ...rest: Array): String {
            return decodeURIComponent(argument)
          }
        )
      }
    }

    public function puts(value: *): void {
      if (available) {
        if (interactive) {
          readline_socket.puts("!" + value)
        } else {
          stdout.puts(value)
        }
      } else {
        debug.show("puts: " + value)
      }
    }

    public function warn(value: *): void {
      if (available) {
        stderr.puts(value)
      } else {
        debug.show("warn: " + value)
      }
    }

    public function die(value: *): void {
      if (available) {
        warn(value); exit(-1)
      } else {
        throw new Error("fatal error: " + String(value))
      }
    }

    public function style(styles: String, string: String): String {
      const codes: Object = {
        none: 0, bold: 1, italic: 3, underline: 4, inverse: 7,
        black: 30, red: 31, green: 32, yellow: 33, blue: 34,
        magenta: 35, cyan: 36, white: 37, gray: 90, grey: 90
      }

      if (styles === "") {
        return string
      } else {
        return styles.split(/\s+/).map(
          function (style: String, ...rest: Array): String {
            if (style in codes) {
              return escape_sequence(codes[style])
            } else {
              throw new Error("style not supported: " + style)
            }
          }
        ).join("") + string + escape_sequence(0)
      }

      function escape_sequence(code: int): String {
        return "\x1b[" + code + "m"
      }
    }

    public function gets(callback: Function): void {
      if (available) {
        if (interactive) {
          readline_socket.puts("?" + _prompt)
        }

        stdin.gets(callback)
      } else {
        callback(null)
      }
    }

    public function set prompt(value: String): void {
      _prompt = value
    }

    public function get stdin(): InputStream {
      return buffered_stdin
    }

    public function get stdout(): OutputStream {
      return stdout_socket
    }

    public function get stderr(): OutputStream {
      return stderr_socket
    }

    public function handle(error: *): void {
      if (error is UncaughtErrorEvent) {
        UncaughtErrorEvent(error).preventDefault()
        handle(UncaughtErrorEvent(error).error)
        exit(-1)
      } else if (error is Error) {
        // Important: Avoid the `Error(x)` casting syntax.
        http_post("/error", (error as Error).getStackTrace())
      } else if (error is ErrorEvent) {
        const event: ErrorEvent = ErrorEvent(error)

        http_post("/error", (
          getQualifiedClassName(event) + ": " + event.text
            + " [event.target: " + event.target + "]"
        ))
      } else {
        http_post("/error", String(error))
      }
    }

    private function shell_quote(word: String): String {
      if (/^[-=.,\w]+$/.test(word)) {
        return word
      } else {
        return "'" + word.replace(/'/g, "'\\''") + "'"
      }
    }

    public function exec(
      command: *,
      callback: Function,
      errback: Function = null
    ): void {
      if (available) {
        var stdin: String = ""

        if ("command" in command && "stdin" in command) {
          stdin = command.stdin
          command = command.command
        }

        if (command is String) {
          command = ["sh", "-c", command]
        }

        const url: String = "/exec?" + command.map(
          function (word: String, ...rest: Array): String {
            return encodeURIComponent(word)
          }
        ).join("&")

        http_post(url, stdin, function (data: String): void {
          const result: XML = new XML(data)
          const status: int = result.@status
          const stdout: String = result.stdout.text()
          const stderr: String = result.stderr.text()

          if (status === 0) {
            if (callback.length === 1) {
              callback(stdout)
            } else {
              callback(stdout, stderr)
            }
          } else if (errback === null) {
            warn(stderr)
          } else if (errback.length === 1) {
            errback(new Error(stderr))
          } else if (errback.length === 2) {
            errback(status, stderr)
          } else {
            errback(status, stderr, stdout)
          }
        })
      } else {
        throw new Error("cannot execute command: process not available")
      }
    }

    public function exit(status: int = 0): void {
      if (available) {
        when_ready(function (): void {
          http_post("/exit", String(status))
        })
      } else {
        throw new Error("cannot exit: process not available")
      }
    }

    //----------------------------------------------------------------

    private var n_pending_requests: int = 0
    private var ready_callbacks: Array = []

    private function when_ready(callback: Function): void {
      if (n_pending_requests === 0) {
        callback()
      } else {
        ready_callbacks.push(callback)
      }
    }

    private function handle_ready(): void {
      for each (var callback: Function in ready_callbacks) {
        callback()
      }

      ready_callbacks = []
    }

    private function http_post(
      path: String, content: String, callback: Function = null
    ): void {
      const request: URLRequest = new URLRequest(http_url + path)

      request.method = "POST"
      request.data = content

      const loader: URLLoader = new URLLoader

      ++n_pending_requests

      loader.addEventListener(
        Event.COMPLETE,
        function (event: Event): void {
          if (callback !== null) {
            callback(loader.data)
          }

          if (--n_pending_requests === 0) {
            handle_ready()
          }
        }
      )

      loader.load(request)
    }
  }
}

Fix null pointer exception for process.argv sans run-swf.


package krewdemo.actor.feature_test {

    import flash.display.Stage;
    import flash.geom.Rectangle;

    import starling.display.DisplayObject;
    import starling.display.Image;
    import starling.display.QuadBatch;
    import starling.display.Sprite;
    import starling.textures.Texture;
    import starling.textures.TextureSmoothing;

    import nape.geom.Vec2;
    import nape.geom.GeomPoly;
    import nape.geom.GeomPolyList;
    import nape.phys.Body;
    import nape.phys.BodyType;
    import nape.phys.Material;
    import nape.shape.Circle;
    import nape.shape.Polygon;
    import nape.shape.Shape;
    import nape.space.Space;
    import nape.util.BitmapDebug;
    import nape.util.Debug;

    import nape.callbacks.CbEvent;
    import nape.callbacks.CbType;
    import nape.callbacks.InteractionCallback;
    import nape.callbacks.InteractionListener;
    import nape.callbacks.InteractionType;

    import krewfw.NativeStageAccessor;
    import krewfw.builtin_actor.ui.SimpleVirtualJoystick;
    import krewfw.core.KrewActor;
    import krewfw.utils.starling.TileMapHelper;

    import krewdemo.GameEvent;
    import krewdemo.scene.PlatformerTestScene1;

    //------------------------------------------------------------
    public class PlatformerTester1 extends KrewActor {

        private const _debugMode:Boolean = false;

        protected var _physicsSpace:Space;
        protected var _gravity:Number = 900;

        protected var _tileMapDisplays:Array = [];
        private   var _clouds:Sprite;

        protected var _hero:Body;

        protected var _velocityX:Number = 0;
        protected var _velocityY:Number = 0;

        private var _interactionListener:InteractionListener;
        private var _wallCbType:CbType = new CbType();
        private var _heroCbType:CbType = new CbType();

        private var _jumpLife:int = 2;

        private var _isSceneEnding:Boolean = false;
        private var _debugDraw:Debug;

        //------------------------------------------------------------
        public override function init():void {
            var gravity:Vec2 = Vec2.weak(0, _gravity);
            _physicsSpace = new Space(gravity);

            _clouds = _makeClouds();
            addChild(_clouds);

            for (var i:int=0;  i < 2;  ++i) {
                _tileMapDisplays[i] = _makeMapDisplay("view_" + (i + 1));
                _tileMapDisplays[i].scaleX = 1.0;
                _tileMapDisplays[i].scaleY = 1.0;
                addChild(_tileMapDisplays[i]);
            }

            _initWallCollision("collision_1", 0.0);
            _initWallCollision("collision_bound", 4.0);
            _initHero();
            _initDebugDraw();

            _interactionListener = new InteractionListener(
                CbEvent.BEGIN, InteractionType.COLLISION,
                _heroCbType, _wallCbType, _onHeroToWall
            );

            _hero.cbTypes.add(_heroCbType);
            _physicsSpace.listeners.add(_interactionListener);

            listen(SimpleVirtualJoystick.UPDATE_JOYSTICK, _onUpdateJoystick);
            listen(GameEvent.TRIGGER_JUMP, _onTriggerJump);
        }

        protected override function onDispose():void {
            _physicsSpace.bodies.foreach(function(body:Body):void {
                _removePhysicsBody(body);
            });
            _physicsSpace.bodies.clear();

            _physicsSpace.clear();
            _physicsSpace = null;

            if (_debugDraw) {
                _debugDraw.clear();
                NativeStageAccessor.stage.removeChild(_debugDraw.display);
                _debugDraw = null;
            }

            removeChild(_clouds);
            _clouds = null;
        }

        private function _removePhysicsBody(body:Body):void {
            _physicsSpace.bodies.remove(body);

            var image:Image = body.userData.displayObj;
            if (image) {
                removeChild(image);
                image.texture.dispose();
                image.dispose();
            }

            body.shapes.foreach(function(shape:Shape):void {
                shape.body = null;
                shape = null;
            });
            body.shapes.clear();
            body.space = null;
            body = null;
        }

        private function _initHero():void {
            var physX:Number  = 240;
            var physY:Number  = 160;
            var imageX:Number = 240;
            var imageY:Number = 160;
            var size:Number   = 32 * 0.94;

            // nape physics body
            var body:Body = new Body(BodyType.DYNAMIC);
            var shape:Polygon = new Polygon(Polygon.box(size * 0.9, size * 0.9, true));
            shape.material.elasticity      = 0.0;
            shape.material.dynamicFriction = 0.0;
            shape.material.staticFriction  = 0.0;
            shape.material.density         = 4.0;
            shape.material.rollingFriction = 1.0;
            body.shapes.add(shape);
            body.position.setxy(physX, physY);
            body.allowRotation = false;
            _physicsSpace.bodies.add(body);

            // starling display
            var image:Image = getImage('rectangle_taro');
            addImage(image, size, size, imageX, imageY);
            body.userData.displayObj = image;

            _hero = body;
        }

        //----------------------------------------------------------------------
        // load level-map view
        //----------------------------------------------------------------------

        private function _makeMapDisplay(layerName:String):QuadBatch {
            var levelInfo:Object = getObject("level_1");
            var quadBatch:QuadBatch  = new QuadBatch();

            for each (var el:Object in levelInfo.layers[layerName].elements) {
                var image:Image = getImage(el.name);

                var textureRect:Rectangle = image.texture.frame;
                image.pivotX = (textureRect.width  * 0.5);
                image.pivotY = (textureRect.height * 0.5);

                image.x        = el.x;
                image.y        = el.y;
                image.width    = el.width;
                image.height   = el.height;
                image.rotation = krew.deg2rad(el.rotation);

                quadBatch.addImage(image);
            }

            return quadBatch;
        }

        private function _makeClouds():Sprite {
            var sprite:Sprite = new Sprite();

            krew.times(16, function():void {
                var image:Image = getImage("cloud_1");

                image.x = krew.rand(-300, 480 + 300);
                image.y = krew.rand(-200, 320 + 200);

                var scale:Number = krew.rand(0.4, 1.0);
                image.scaleX = scale;
                image.scaleY = scale;

                sprite.addChild(image);
            });

            return sprite;
        }

        //----------------------------------------------------------------------
        // load collision
        //----------------------------------------------------------------------

        private function _initWallCollision(layerName:String, elasticity:Number=0):void {
            var levelInfo:Object = getObject("level_1");

            for each (var vertices:Array in levelInfo.layers[layerName].polygons) {
                _makeCollisionBody(vertices, elasticity);
            }
        }

        private function _makeCollisionBody(vertices:Array, elasticity:Number=0):void {
            var vecList:Array = [];
            for each (var vertex:Object in vertices) {
                vecList.push(Vec2.get(vertex.x, vertex.y));
            }

            var geomPolySrc:GeomPoly = new GeomPoly(vecList);
            var geomPolyList:GeomPolyList = geomPolySrc.convexDecomposition();

            geomPolyList.foreach(function(geomPoly:GeomPoly):void {
                _addConvexCollision(geomPoly, elasticity);
            });
        }

        private function _addConvexCollision(geomPoly:GeomPoly, elasticity:Number=0):void {
            var body:Body = new Body(BodyType.STATIC);
            var shape:Polygon = new Polygon(geomPoly);
            shape.material.elasticity = elasticity;  // これ 2.0 とかにすればジャンプ床できる

            body.shapes.add(shape);
            _physicsSpace.bodies.add(body);

            body.cbTypes.add(_wallCbType);
        }

        //----------------------------------------------------------------------
        // landing detection
        //----------------------------------------------------------------------

        private function _onHeroToWall(cb:InteractionCallback):void {
            var hero:Body = cb.int1.castBody;
            var wall:Body = cb.int2.castBody;

            // ToDo: 着地判定をちゃんとやる
            _onHeroLanding();

            // if (hero.position.y < wall.position.y - wall.userData.height/2) {
            //     _onHeroLanding();
            // }
        }

        private function _onHeroLanding():void {
            _jumpLife = 2;
        }

        //----------------------------------------------------------------------
        // update handlers
        //----------------------------------------------------------------------

        protected function _onUpdateJoystick(args:Object):void {
            _velocityX = args.velocityX * 300;
        }

        private function _onTriggerJump(args:Object):void {
            if (_jumpLife == 0) { return; }

            --_jumpLife;
            _hero.velocity.y = -430;
        }

        public override function onUpdate(passedTime:Number):void {
            // physics
            _hero.velocity.x = _velocityX;
            if (_hero.velocity.y > 2000) { _hero.velocity.y = 2000; }

            _physicsSpace.step(passedTime);

            // view
            var cloudDepth:Number = 0.2;
            _clouds.x = 240 - (_hero.position.x * cloudDepth);
            _clouds.y = 160 - (_hero.position.y * cloudDepth);

            for (var i:int=0;  i < _tileMapDisplays.length;  ++i) {
                _tileMapDisplays[i].x = 240 - _hero.position.x;
                _tileMapDisplays[i].y = 160 - _hero.position.y;
            }

            var heroImage:Image = _hero.userData.displayObj;
            heroImage.rotation = _hero.rotation;

            _onUpdatePhysicsDebugDraw();

            // out of world border
            _checkExitWorld();
        }

        private function _checkExitWorld():void {
            if (_isSceneEnding) { return; }

            if (_hero.position.y > 1000) {
                _isSceneEnding = true;
                sendMessage(GameEvent.NEXT_SCENE, {nextScene: new PlatformerTestScene1});
            }
        }

        //----------------------------------------------------------------------
        // nape debug display
        //----------------------------------------------------------------------

        private function _initDebugDraw():void {
            if (!_debugMode) { return; }

            var stage:Stage = NativeStageAccessor.stage;
            _debugDraw = new BitmapDebug(stage.stageWidth, stage.stageHeight, stage.color);

            var scale:Number = stage.stageWidth / 480;
            _debugDraw.display.scaleX = scale;
            _debugDraw.display.scaleY = scale;
            _debugDraw.display.alpha  = 0.5;

            stage.addChild(_debugDraw.display);
        }

        private function _onUpdatePhysicsDebugDraw():void {
            if (!_debugDraw) { return; }

            var scale:Number = NativeStageAccessor.stage.stageWidth / 480;
            _debugDraw.display.x = (240 - _hero.position.x) * scale;
            _debugDraw.display.y = (160 - _hero.position.y) * scale;

            _debugDraw.clear();
            _debugDraw.draw(_physicsSpace);
            _debugDraw.flush();
        }

    }
}

package krewdemo.actor.feature_test {

    import flash.display.Stage;
    import flash.geom.Rectangle;

    import starling.display.DisplayObject;
    import starling.display.Image;
    import starling.display.QuadBatch;
    import starling.display.Sprite;
    import starling.textures.Texture;
    import starling.textures.TextureSmoothing;

    import nape.geom.Vec2;
    import nape.geom.GeomPoly;
    import nape.geom.GeomPolyList;
    import nape.phys.Body;
    import nape.phys.BodyType;
    import nape.phys.Material;
    import nape.shape.Circle;
    import nape.shape.Polygon;
    import nape.shape.Shape;
    import nape.space.Space;
    import nape.util.BitmapDebug;
    import nape.util.Debug;

    import nape.callbacks.CbEvent;
    import nape.callbacks.CbType;
    import nape.callbacks.InteractionCallback;
    import nape.callbacks.InteractionListener;
    import nape.callbacks.InteractionType;

    import krewfw.NativeStageAccessor;
    import krewfw.builtin_actor.ui.SimpleVirtualJoystick;
    import krewfw.core.KrewActor;
    import krewfw.utils.starling.TileMapHelper;

    import krewdemo.GameEvent;
    import krewdemo.scene.PlatformerTestScene1;

    //------------------------------------------------------------
    public class PlatformerTester1 extends KrewActor {

        private const _debugMode:Boolean = false;

        protected var _physicsSpace:Space;
        protected var _gravity:Number = 900;
        private   var _mapScale:Number = 0.5;

        protected var _tileMapDisplays:Array = [];
        private   var _clouds:Sprite;

        protected var _hero:Body;

        protected var _velocityX:Number = 0;
        protected var _velocityY:Number = 0;

        private var _interactionListener:InteractionListener;
        private var _wallCbType:CbType = new CbType();
        private var _heroCbType:CbType = new CbType();

        private var _jumpLife:int = 2;

        private var _isSceneEnding:Boolean = false;
        private var _debugDraw:Debug;

        //------------------------------------------------------------
        public override function init():void {
            var gravity:Vec2 = Vec2.weak(0, _gravity);
            _physicsSpace = new Space(gravity);

            _clouds = _makeClouds();
            addChild(_clouds);

            for (var i:int=0;  i < 2;  ++i) {
                _tileMapDisplays[i] = _makeMapDisplay("view_" + (i + 1));
                _tileMapDisplays[i].scaleX = _mapScale;
                _tileMapDisplays[i].scaleY = _mapScale;
                addChild(_tileMapDisplays[i]);
            }

            _initWallCollision("collision_1", 0.0);
            _initWallCollision("collision_bound", 4.0);
            _initHero();
            _initDebugDraw();

            _interactionListener = new InteractionListener(
                CbEvent.BEGIN, InteractionType.COLLISION,
                _heroCbType, _wallCbType, _onHeroToWall
            );

            _hero.cbTypes.add(_heroCbType);
            _physicsSpace.listeners.add(_interactionListener);

            listen(SimpleVirtualJoystick.UPDATE_JOYSTICK, _onUpdateJoystick);
            listen(GameEvent.TRIGGER_JUMP, _onTriggerJump);
        }

        protected override function onDispose():void {
            _physicsSpace.bodies.foreach(function(body:Body):void {
                _removePhysicsBody(body);
            });
            _physicsSpace.bodies.clear();

            _physicsSpace.clear();
            _physicsSpace = null;

            if (_debugDraw) {
                _debugDraw.clear();
                NativeStageAccessor.stage.removeChild(_debugDraw.display);
                _debugDraw = null;
            }

            removeChild(_clouds);
            _clouds = null;
        }

        private function _removePhysicsBody(body:Body):void {
            _physicsSpace.bodies.remove(body);

            var image:Image = body.userData.displayObj;
            if (image) {
                removeChild(image);
                image.texture.dispose();
                image.dispose();
            }

            body.shapes.foreach(function(shape:Shape):void {
                shape.body = null;
                shape = null;
            });
            body.shapes.clear();
            body.space = null;
            body = null;
        }

        private function _initHero():void {
            var physX:Number  = 240;
            var physY:Number  = 160;
            var imageX:Number = 240;
            var imageY:Number = 160;
            var size:Number   = 32 * 0.94;

            // nape physics body
            var body:Body = new Body(BodyType.DYNAMIC);
            var shape:Polygon = new Polygon(Polygon.box(size * 0.9, size * 0.9, true));
            shape.material.elasticity      = 0.0;
            shape.material.dynamicFriction = 0.0;
            shape.material.staticFriction  = 0.0;
            shape.material.density         = 4.0;
            shape.material.rollingFriction = 1.0;
            body.shapes.add(shape);
            body.position.setxy(physX, physY);
            body.allowRotation = false;
            _physicsSpace.bodies.add(body);

            // starling display
            var image:Image = getImage('rectangle_taro');
            addImage(image, size * _mapScale, size * _mapScale, imageX, imageY);

            _hero = body;
            _hero.userData.displayObj = image;
        }

        //----------------------------------------------------------------------
        // load level-map view
        //----------------------------------------------------------------------

        private function _makeMapDisplay(layerName:String):QuadBatch {
            var levelInfo:Object = getObject("level_1");
            var quadBatch:QuadBatch  = new QuadBatch();

            for each (var el:Object in levelInfo.layers[layerName].elements) {
                var image:Image = getImage(el.name);

                var textureRect:Rectangle = image.texture.frame;
                image.pivotX = (textureRect.width  * 0.5);
                image.pivotY = (textureRect.height * 0.5);

                image.x        = el.x;
                image.y        = el.y;
                image.width    = el.width;
                image.height   = el.height;
                image.rotation = krew.deg2rad(el.rotation);

                quadBatch.addImage(image);
            }

            return quadBatch;
        }

        private function _makeClouds():Sprite {
            var sprite:Sprite = new Sprite();

            krew.times(16, function():void {
                var image:Image = getImage("cloud_1");

                image.x = krew.rand(-300, 480 + 300);
                image.y = krew.rand(-200, 320 + 200);

                var scale:Number = krew.rand(0.4, 1.0);
                image.scaleX = scale;
                image.scaleY = scale;

                sprite.addChild(image);
            });

            return sprite;
        }

        //----------------------------------------------------------------------
        // load collision
        //----------------------------------------------------------------------

        private function _initWallCollision(layerName:String, elasticity:Number=0):void {
            var levelInfo:Object = getObject("level_1");

            for each (var vertices:Array in levelInfo.layers[layerName].polygons) {
                _makeCollisionBody(vertices, elasticity);
            }
        }

        private function _makeCollisionBody(vertices:Array, elasticity:Number=0):void {
            var vecList:Array = [];
            for each (var vertex:Object in vertices) {
                vecList.push(Vec2.get(vertex.x, vertex.y));
            }

            var geomPolySrc:GeomPoly = new GeomPoly(vecList);
            var geomPolyList:GeomPolyList = geomPolySrc.convexDecomposition();

            geomPolyList.foreach(function(geomPoly:GeomPoly):void {
                _addConvexCollision(geomPoly, elasticity);
            });
        }

        private function _addConvexCollision(geomPoly:GeomPoly, elasticity:Number=0):void {
            var body:Body = new Body(BodyType.STATIC);
            var shape:Polygon = new Polygon(geomPoly);
            shape.material.elasticity = elasticity;  // これ 2.0 とかにすればジャンプ床できる

            body.shapes.add(shape);
            _physicsSpace.bodies.add(body);

            body.cbTypes.add(_wallCbType);
        }

        //----------------------------------------------------------------------
        // landing detection
        //----------------------------------------------------------------------

        private function _onHeroToWall(cb:InteractionCallback):void {
            var hero:Body = cb.int1.castBody;
            var wall:Body = cb.int2.castBody;

            // ToDo: 着地判定をちゃんとやる
            _onHeroLanding();

            // if (hero.position.y < wall.position.y - wall.userData.height/2) {
            //     _onHeroLanding();
            // }
        }

        private function _onHeroLanding():void {
            _jumpLife = 2;
        }

        //----------------------------------------------------------------------
        // update handlers
        //----------------------------------------------------------------------

        protected function _onUpdateJoystick(args:Object):void {
            _velocityX = args.velocityX * 300;

            if (Math.abs(args.velocityY) > 0.5) {
                _updateMapScale(args.velocityY * 0.01);
            }
        }

        private function _updateMapScale(zoom:Number):void {
            _mapScale += zoom;

            for (var i:int=0;  i < 2;  ++i) {
                _tileMapDisplays[i].scaleX = _mapScale;
                _tileMapDisplays[i].scaleY = _mapScale;
            }

            var heroSize:Number = 32 * 0.94 * _mapScale;
            _hero.userData.displayObj.width  = heroSize;
            _hero.userData.displayObj.height = heroSize;

            _updateView();
        }

        private function _onTriggerJump(args:Object):void {
            if (_jumpLife == 0) { return; }

            --_jumpLife;
            _hero.velocity.y = -430;
        }

        public override function onUpdate(passedTime:Number):void {
            // physics
            _hero.velocity.x = _velocityX;
            if (_hero.velocity.y > 2000) { _hero.velocity.y = 2000; }

            _physicsSpace.step(passedTime);

            // view
            _updateView();

            _onUpdatePhysicsDebugDraw();

            // out of world border
            _checkExitWorld();
        }

        private function _updateView():void {
            var cloudDepth:Number = 0.2;
            _clouds.x = 240 - (_hero.position.x * cloudDepth);
            _clouds.y = 160 - (_hero.position.y * cloudDepth);

            for (var i:int=0;  i < _tileMapDisplays.length;  ++i) {
                _tileMapDisplays[i].x = 240 - (_hero.position.x * _mapScale);
                _tileMapDisplays[i].y = 160 - (_hero.position.y * _mapScale);
            }

            var heroImage:Image = _hero.userData.displayObj;
            heroImage.rotation = _hero.rotation;
        }

        private function _checkExitWorld():void {
            if (_isSceneEnding) { return; }

            if (_hero.position.y > 1000) {
                _isSceneEnding = true;
                sendMessage(GameEvent.NEXT_SCENE, {nextScene: new PlatformerTestScene1});
            }
        }

        //----------------------------------------------------------------------
        // nape debug display
        //----------------------------------------------------------------------

        private function _initDebugDraw():void {
            if (!_debugMode) { return; }

            var stage:Stage = NativeStageAccessor.stage;
            _debugDraw = new BitmapDebug(stage.stageWidth, stage.stageHeight, stage.color);

            var scale:Number = stage.stageWidth / 480;
            _debugDraw.display.scaleX = scale;
            _debugDraw.display.scaleY = scale;
            _debugDraw.display.alpha  = 0.5;

            stage.addChild(_debugDraw.display);
        }

        private function _onUpdatePhysicsDebugDraw():void {
            if (!_debugDraw) { return; }

            var scale:Number = NativeStageAccessor.stage.stageWidth / 480;
            _debugDraw.display.x = (240 - _hero.position.x) * scale;
            _debugDraw.display.y = (160 - _hero.position.y) * scale;

            _debugDraw.clear();
            _debugDraw.draw(_physicsSpace);
            _debugDraw.flush();
        }

    }
}

Modify lab.

Modify lab.


package aerys.minko.render.material.phong.multipass
{
    import aerys.minko.render.RenderTarget;
    import aerys.minko.render.material.basic.BasicShader;
    import aerys.minko.render.resource.texture.ITextureResource;
    import aerys.minko.render.shader.SFloat;
    import aerys.minko.render.shader.ShaderSettings;
    import aerys.minko.render.shader.part.phong.PhongShaderPart;
    import aerys.minko.type.enum.Blending;
    import aerys.minko.type.enum.BlendingDestination;
    import aerys.minko.type.enum.BlendingSource;
    import aerys.minko.type.enum.DepthTest;

    public class PhongEmissiveShader extends BasicShader
    {
        private var _lightAccumulator   : ITextureResource;

        private var _screenPos          : SFloat;

        public function PhongEmissiveShader(lightAccumulator    : ITextureResource,
                                            renderTarget        : RenderTarget  = null,
                                            priority            : Number        = 0.0)
        {
            super(renderTarget, priority);

            _lightAccumulator = lightAccumulator;
        }

        override protected function initializeSettings(settings : ShaderSettings) : void
        {
            super.initializeSettings(settings);

            if (!_lightAccumulator)
            {
                settings.blending = BlendingDestination.SOURCE_COLOR | BlendingSource.ZERO;
                settings.depthTest = DepthTest.LESS | DepthTest.EQUAL;
            }
        }

        override protected function getVertexPosition() : SFloat
        {
            return _screenPos = super.getVertexPosition();
        }

        override protected function getPixelColor() : SFloat
        {
            var diffuse : SFloat = super.getPixelColor();

            if (_lightAccumulator)
            {
                var uv : SFloat = interpolate(_screenPos);

                uv = divide(uv.xy, uv.w);
                uv = multiply(add(float2(uv.x, negate(uv.y)), 1), .5);

                var lighting : SFloat = sampleTexture(getTexture(_lightAccumulator), uv);

                diffuse = float4(multiply(diffuse.rgb, lighting.rgb), diffuse.a);
            }

            return diffuse;
        }
    }
}

package aerys.minko.render.material.phong.multipass
{
    import aerys.minko.render.RenderTarget;
    import aerys.minko.render.material.basic.BasicShader;
    import aerys.minko.render.resource.texture.ITextureResource;
    import aerys.minko.render.shader.SFloat;
    import aerys.minko.render.shader.ShaderSettings;
    import aerys.minko.type.enum.BlendingDestination;
    import aerys.minko.type.enum.BlendingSource;
    import aerys.minko.type.enum.DepthTest;

    public class PhongEmissiveShader extends BasicShader
    {
        private var _lightAccumulator   : ITextureResource;

        private var _screenPos          : SFloat;

        public function PhongEmissiveShader(lightAccumulator    : ITextureResource,
                                            renderTarget        : RenderTarget  = null,
                                            priority            : Number        = 0.0)
        {
            super(renderTarget, priority);

            _lightAccumulator = lightAccumulator;
        }

        override protected function initializeSettings(settings : ShaderSettings) : void
        {
            super.initializeSettings(settings);

            if (!_lightAccumulator)
            {
                settings.blending = BlendingDestination.SOURCE_COLOR | BlendingSource.ZERO;
                settings.depthTest = DepthTest.LESS | DepthTest.EQUAL;
            }
        }

        override protected function getVertexPosition() : SFloat
        {
            return _screenPos = super.getVertexPosition();
        }

        override protected function getPixelColor() : SFloat
        {
            var diffuse : SFloat = super.getPixelColor();

            if (_lightAccumulator)
            {
                var uv : SFloat = interpolate(_screenPos);

                uv = divide(uv.xy, uv.w);
                uv = multiply(add(float2(uv.x, negate(uv.y)), 1), .5);

                var lighting : SFloat = sampleTexture(getTexture(_lightAccumulator), uv);

                diffuse = float4(multiply(diffuse.rgb, lighting.rgb), diffuse.a);
            }

            return diffuse;
        }
    }
}

remove useless import

remove useless import