package
{
  import flash.display.BlendMode;

  import org.flixel.*;

  // The main coordinator: part config list, part asset list.
  // Handles all of the character animations.
  // TODO, offload animation logic to PlayerDelegate interface.

  public class PlayState extends FlxState
  {
    // Tileset that works with AUTO mode (best for thin walls)
    [Embed(source='data/auto_tiles.png')]private static var auto_tiles:Class;
    // Tileset that works with OFF mode (do what you want mode)
    [Embed(source='data/empty_tiles.png')]private static var empty_tiles:Class;

    [Embed(source='data/player.png')]private static var player_img:Class;

    [Embed(source='data/bg-1.png')]private static var bg1_img:Class;
    [Embed(source='data/bg-2.png')]private static var bg2_img:Class;
    [Embed(source='data/bg-3.png')]private static var bg3_img:Class;
    [Embed(source='data/bg-4.png')]private static var bg4_img:Class;
    [Embed(source='data/bg-5.png')]private static var bg5_img:Class;
    [Embed(source='data/bg-6.png')]private static var bg6_img:Class;
    [Embed(source='data/bg-7.png')]private static var bg7_img:Class;
    [Embed(source='data/bg-8.png')]private static var bg8_img:Class;
    [Embed(source='data/bg-9.png')]private static var bg9_img:Class;
    [Embed(source='data/bg-10.png')]private static var bg10_img:Class;
    [Embed(source='data/bg-11.png')]private static var bg11_img:Class;
    [Embed(source='data/bg-12.png')]private static var bg12_img:Class;

    // The dynamically generated and extended FlxTilemap.
    private var platform:Platform;
    // Ledge controls, in tiles.

    // The extend FlxSprite.
    private const PLAYER_WIDTH:uint = 72;
    private const PLAYER_HEIGHT:uint = 72;
    private var player:Player;

    // The background with parallax.
    private var bg:Background;

    // Some game switches.
    private var fallChecking:Boolean;

    // Flixel Methods
    // --------------
    override public function create():void
    {
      // Globals.
      FlxG.framerate = 30;
      FlxG.flashFramerate = 30;
      fallChecking = false;

      // Start our setup chain.
      setupPlatform();

      // For now, we add things in order to get correct layering.
      // TODO - offload to draw method?
      add(bg);
      add(platform);
      add(player);
    }
    override public function update():void
    {
      // Start our update chain.
      updatePlatform();

      super.update();
    }
    override public function draw():void
    {
      super.draw();
    }

    // Setup Routines
    // --------------
    // Since the observer pattern is too slow, we'll just name our functions to be like hooks.
    // The platform is the first thing that gets set up.
    private function setupPlatform():void
    {
      // Load our scenery.
      bg = new Background();
      bg.bounds.x = 0;
      bg.bounds.y = 0;
      bg.parallax_factor = 1; // Our bg is part "foreground".
      bg.parallax_buffer = 1.7;
      bg.addImage(bg12_img);
      bg.addImage(bg11_img);
      bg.addImage(bg10_img);
      bg.addImage(bg9_img);
      bg.addImage(bg8_img);
      bg.addImage(bg7_img);
      bg.addImage(bg6_img);
      bg.addImage(bg5_img);
      bg.addImage(bg4_img);
      bg.addImage(bg3_img);
      bg.addImage(bg2_img);
      bg.addImage(bg1_img);
      bg.layout();

      // Creates a new tilemap with no arguments.
      platform = new Platform();

      // Customize our tile generation.
      platform.tileWidth = 32;
      platform.tileHeight = 32;
      platform.minLedgeSize = 3;
      platform.maxLedgeSize = 6;
      platform.minLedgeSpacing = new FlxPoint(4, 2);
      platform.maxLedgeSpacing = new FlxPoint(8, 4);
      platform.ledgeThickness = 2;

      // Set the bounds based on the background.
      // TODO - Account for parallax.
      platform.bounds = new FlxRect(bg.bounds.x, bg.bounds.y, bg.bounds.width, bg.bounds.height);

      // Make our platform.
      platform.makeMap(auto_tiles);

      setupPlatformAfter();
    }
    // Hooks.
    private function setupPlatformAfter():void
    {
      // Draw player at the bottom.
      var start:FlxPoint = new FlxPoint();
      var floorHeight:Number = PLAYER_HEIGHT;
      start.x = (FlxG.width - PLAYER_HEIGHT) / 2;
      start.y = platform.height - (PLAYER_HEIGHT + floorHeight);
//      start.x = 0;
//      start.y = 0;
      setupPlayer(start);

      // Move until we don't overlap.
      while (platform.overlaps(player))
      {
        if (player.x <= 0)
        {
          player.x = FlxG.width;
        }
        player.x -= platform.tileWidth;
      }

      setupPlatformAndPlayerAfter();
    }
    private function setupPlatformAndPlayerAfter():void
    {
      setupCamera();
    }
    // Hooked routines.
    private function setupPlayer(start:FlxPoint):void
    {
      // Find start position for player.

      player = new Player(start.x, start.y);
      player.loadGraphic(player_img, true, true, 72);

      // Bounding box tweaks.
      player.height = player.frameWidth / 2;
      player.offset.y = player.frameWidth - player.height;
      player.tailOffset.x = 35;
      player.headOffset.x = 10;
      player.width = player.frameWidth - player.tailOffset.x;
      player.face(FlxObject.RIGHT);

      // Basic player physics.
      player.drag.x = 1000; // friction
      player.acceleration.y = 500; // gravity
      player.maxVelocity.x = 200;
      player.maxVelocity.y = 1500;

      // Player jump physics.
      player.jumpVelocity.y = -420;

      // Animations.
      // Make sure to add end transitions, otherwise the last frame is skipped if framerate is low.
      player.addAnimation('still',[17], 12);
      player.addAnimation('idle', [], 12, false);
      player.addAnimation('run',  [0,1,2,3,4,5,6,7,8,9,10,11], 24);
      player.addAnimation('stop', [12,13,14,15,16,17], 24, false);
      player.addAnimation('start',[17,16,15,14,13,12], 24, false);
      player.addAnimation('jump', [18,19,20,21,22,23,24,25,26,27,28,29,30,31], 24, false);
      player.addAnimation('fall', [31]);
      player.addAnimation('land', [32,33,18,17], 12, false);
    }
    private function setupCamera():void
    {
      FlxG.camera.follow(player);
      platform.follow();
    }

    // Update Routines
    // ---------------
    private function updatePlatform():void
    {
      updatePlatformAfter();
    }
    // Hooks.
    private function updatePlatformAfter():void
    {
      // Tilemaps can be collided just like any other FlxObject, and flixel
      // automatically collides each individual tile with the object.
      FlxG.collide(player, platform);

      wrapToStage(player);
      updatePlayer();

      updatePlatformAndPlayerAfter();
    }
    private function updatePlatformAndPlayerAfter():void
    {
      updateCamera(player.justFell());
    }
    // Hooked routines.
    private function updatePlayer():void
    {
      player.moveWithInput();

      if (player.willJump) // We only need to play the jump animation once.
      {
        player.play('jump');
      }
      else if (player.justFell())
      {
        player.play('land');
      }
      else if (!player.rising && player.finished)
      {
        if (player.falling)
        {
          player.play('fall');
        }
        else if (player.willStop)
        {
          player.play('stop');
        }
        else if (player.velocity.x == 0 ||
          (player.x == 0 || player.x >= (platform.width - player.width))
        )
        {
          player.play('still');
        }
        else if (player.willStart)
        {
          player.play('start');
          player.willStart = false; // TODO - Hack.
        }
        else
        {
          player.play('run');
        }
      }
    }
    private function updateCamera(playerJustFell:Boolean):void
    {
      if (fallChecking && playerJustFell)
      {
        FlxG.camera.shake(
          0.01,
          0.1, null, true,
          FlxCamera.SHAKE_VERTICAL_ONLY
        );
      }
    }

    // Helpers
    // -------
    private function wrapToStage(obj:FlxSprite):void
    {
      obj.x = FlxU.bound(obj.x, 0, (platform.width - obj.width));
      obj.y = FlxU.bound(obj.y, 0, (platform.height - obj.height));
    }
  }
}

package
{
  import flash.display.BlendMode;

  import org.flixel.*;

  // The main coordinator: part config list, part asset list.
  // Handles all of the character animations.
  // TODO, offload animation logic to PlayerDelegate interface.

  public class PlayState extends FlxState
  {
    // Tileset that works with AUTO mode (best for thin walls)
    [Embed(source='data/auto_tiles.png')]private static var auto_tiles:Class;
    // Tileset that works with OFF mode (do what you want mode)
    [Embed(source='data/empty_tiles.png')]private static var empty_tiles:Class;

    [Embed(source='data/player.png')]private static var player_img:Class;

    [Embed(source='data/bg-1.png')]private static var bg1_img:Class;
    [Embed(source='data/bg-2.png')]private static var bg2_img:Class;
    [Embed(source='data/bg-3.png')]private static var bg3_img:Class;
    [Embed(source='data/bg-4.png')]private static var bg4_img:Class;
    [Embed(source='data/bg-5.png')]private static var bg5_img:Class;
    [Embed(source='data/bg-6.png')]private static var bg6_img:Class;
    [Embed(source='data/bg-7.png')]private static var bg7_img:Class;
    [Embed(source='data/bg-8.png')]private static var bg8_img:Class;
    [Embed(source='data/bg-9.png')]private static var bg9_img:Class;
    [Embed(source='data/bg-10.png')]private static var bg10_img:Class;
    [Embed(source='data/bg-11.png')]private static var bg11_img:Class;
    [Embed(source='data/bg-12.png')]private static var bg12_img:Class;

    // The dynamically generated and extended FlxTilemap.
    private var platform:Platform;
    // Ledge controls, in tiles.

    // The extend FlxSprite.
    private const PLAYER_WIDTH:uint = 72;
    private const PLAYER_HEIGHT:uint = 72;
    private var player:Player;

    // The background with parallax.
    private var bg:Background;

    // Some game switches.
    private var fallChecking:Boolean;

    // Flixel Methods
    // --------------
    override public function create():void
    {
      FlxG.mouse.hide();

      // Globals.
      FlxG.framerate = 30;
      FlxG.flashFramerate = 30;
      fallChecking = false;

      // Start our setup chain.
      setupPlatform();

      // For now, we add things in order to get correct layering.
      // TODO - offload to draw method?
      add(bg);
      add(platform);
      add(player);
    }
    override public function update():void
    {
      // Start our update chain.
      updatePlatform();

      super.update();
    }
    override public function draw():void
    {
      super.draw();
    }

    // Setup Routines
    // --------------
    // Since the observer pattern is too slow, we'll just name our functions to be like hooks.
    // The platform is the first thing that gets set up.
    private function setupPlatform():void
    {
      // Load our scenery.
      bg = new Background();
      bg.bounds.x = 0;
      bg.bounds.y = 0;
      bg.parallax_factor = 1; // Our bg is part "foreground".
      bg.parallax_buffer = 1.7;
      bg.addImage(bg12_img);
      bg.addImage(bg11_img);
      bg.addImage(bg10_img);
      bg.addImage(bg9_img);
      bg.addImage(bg8_img);
      bg.addImage(bg7_img);
      bg.addImage(bg6_img);
      bg.addImage(bg5_img);
      bg.addImage(bg4_img);
      bg.addImage(bg3_img);
      bg.addImage(bg2_img);
      bg.addImage(bg1_img);
      bg.layout();

      // Creates a new tilemap with no arguments.
      platform = new Platform();

      // Customize our tile generation.
      platform.tileWidth = 32;
      platform.tileHeight = 32;
      platform.minLedgeSize = 3;
      platform.maxLedgeSize = 6;
      platform.minLedgeSpacing = new FlxPoint(4, 2);
      platform.maxLedgeSpacing = new FlxPoint(8, 4);
      platform.ledgeThickness = 2;

      // Set the bounds based on the background.
      // TODO - Account for parallax.
      platform.bounds = new FlxRect(bg.bounds.x, bg.bounds.y, bg.bounds.width, bg.bounds.height);

      // Make our platform.
      platform.makeMap(auto_tiles);

      setupPlatformAfter();
    }
    // Hooks.
    private function setupPlatformAfter():void
    {
      // Draw player at the bottom.
      var start:FlxPoint = new FlxPoint();
      var floorHeight:Number = PLAYER_HEIGHT;
      start.x = (FlxG.width - PLAYER_HEIGHT) / 2;
      start.y = platform.height - (PLAYER_HEIGHT + floorHeight);
//      start.x = 0;
//      start.y = 0;
      setupPlayer(start);

      // Move until we don't overlap.
      while (platform.overlaps(player))
      {
        if (player.x <= 0)
        {
          player.x = FlxG.width;
        }
        player.x -= platform.tileWidth;
      }

      setupPlatformAndPlayerAfter();
    }
    private function setupPlatformAndPlayerAfter():void
    {
      setupCamera();
    }
    // Hooked routines.
    private function setupPlayer(start:FlxPoint):void
    {
      // Find start position for player.

      player = new Player(start.x, start.y);
      player.loadGraphic(player_img, true, true, 72);

      // Bounding box tweaks.
      player.height = player.frameWidth / 2;
      player.offset.y = player.frameWidth - player.height;
      player.tailOffset.x = 35;
      player.headOffset.x = 10;
      player.width = player.frameWidth - player.tailOffset.x;
      player.face(FlxObject.RIGHT);

      // Basic player physics.
      player.drag.x = 1000; // friction
      player.acceleration.y = 500; // gravity
      player.maxVelocity.x = 200;
      player.maxVelocity.y = 1500;

      // Player jump physics.
      player.jumpVelocity.y = -420;

      // Animations.
      // Make sure to add end transitions, otherwise the last frame is skipped if framerate is low.
      player.addAnimation('still',[17], 12);
      player.addAnimation('idle', [], 12, false);
      player.addAnimation('run',  [0,1,2,3,4,5,6,7,8,9,10,11], 24);
      player.addAnimation('stop', [12,13,14,15,16,17], 24, false);
      player.addAnimation('start',[17,16,15,14,13,12], 24, false);
      player.addAnimation('jump', [18,19,20,21,22,23,24,25,26,27,28,29,30,31], 24, false);
      player.addAnimation('fall', [31]);
      player.addAnimation('land', [32,33,18,17], 12, false);
    }
    private function setupCamera():void
    {
      FlxG.camera.follow(player);
      platform.follow();
    }

    // Update Routines
    // ---------------
    private function updatePlatform():void
    {
      updatePlatformAfter();
    }
    // Hooks.
    private function updatePlatformAfter():void
    {
      // Tilemaps can be collided just like any other FlxObject, and flixel
      // automatically collides each individual tile with the object.
      FlxG.collide(player, platform);

      wrapToStage(player);
      updatePlayer();

      updatePlatformAndPlayerAfter();
    }
    private function updatePlatformAndPlayerAfter():void
    {
      updateCamera(player.justFell());
    }
    // Hooked routines.
    private function updatePlayer():void
    {
      player.moveWithInput();

      if (player.willJump) // We only need to play the jump animation once.
      {
        player.play('jump');
      }
      else if (player.justFell())
      {
        player.play('land');
      }
      else if (!player.rising && player.finished)
      {
        if (player.falling)
        {
          player.play('fall');
        }
        else if (player.willStop)
        {
          player.play('stop');
        }
        else if (player.velocity.x == 0 ||
          (player.x == 0 || player.x >= (platform.width - player.width))
        )
        {
          player.play('still');
        }
        else if (player.willStart)
        {
          player.play('start');
          player.willStart = false; // TODO - Hack.
        }
        else
        {
          player.play('run');
        }
      }
    }
    private function updateCamera(playerJustFell:Boolean):void
    {
      if (fallChecking && playerJustFell)
      {
        FlxG.camera.shake(
          0.01,
          0.1, null, true,
          FlxCamera.SHAKE_VERTICAL_ONLY
        );
      }
    }

    // Helpers
    // -------
    private function wrapToStage(obj:FlxSprite):void
    {
      obj.x = FlxU.bound(obj.x, 0, (platform.width - obj.width));
      obj.y = FlxU.bound(obj.y, 0, (platform.height - obj.height));
    }
  }
}

Hide cursor on play state.

Hide cursor on play state.


package com.kaltura.hls.m2ts
{
	import com.kaltura.hls.HLSDVRTimeTrait;
	import com.kaltura.hls.HLSDVRTrait;
	import com.kaltura.hls.HLSMetadataNamespaces;

	import flash.net.NetConnection;
	import flash.net.NetStream;
	import flash.events.NetStatusEvent;

	import org.osmf.events.DVRStreamInfoEvent;
	import org.osmf.media.MediaResourceBase;
	import org.osmf.media.URLResource;
	import org.osmf.metadata.Metadata;
	import org.osmf.metadata.MetadataNamespaces;
	import org.osmf.net.NetStreamLoadTrait;
	import org.osmf.net.NetStreamCodes;
	import org.osmf.net.httpstreaming.HLSHTTPNetStream;
	import org.osmf.net.httpstreaming.HTTPStreamingFactory;
	import org.osmf.net.httpstreaming.HTTPStreamingNetLoader;
	import org.osmf.net.httpstreaming.dvr.DVRInfo;
	import org.osmf.traits.LoadState;

	import org.osmf.net.NetStreamSwitchManagerBase
	import org.osmf.net.metrics.BandwidthMetric;
	import org.osmf.net.DynamicStreamingResource;
	import org.osmf.net.httpstreaming.DefaultHTTPStreamingSwitchManager;

	import org.osmf.net.metrics.MetricType;
	import org.osmf.net.rules.BandwidthRule;

	/**
	 * Factory to identify and process MPEG2 TS via OSMF.
	 */
	public class M2TSNetLoader extends HTTPStreamingNetLoader
	{
		private var netStream:HLSHTTPNetStream;

		override public function canHandleResource( resource:MediaResourceBase ):Boolean
		{
			var metadata:Object = resource.getMetadataValue( HLSMetadataNamespaces.PLAYABLE_RESOURCE_METADATA );

			if ( metadata != null && metadata == true )
				return true;

			return false;
		}

		override protected function createNetStream(connection:NetConnection, resource:URLResource):NetStream
		{
			var factory:HTTPStreamingFactory = new M2TSStreamingFactory();
			var httpNetStream:HLSHTTPNetStream = new HLSHTTPNetStream(connection, factory, resource);
			return httpNetStream;
		}

		override protected function createNetStreamSwitchManager(connection:NetConnection, netStream:NetStream, dsResource:DynamicStreamingResource):NetStreamSwitchManagerBase
		{
			var switcher:DefaultHTTPStreamingSwitchManager = super.createNetStreamSwitchManager(connection, netStream, dsResource) as DefaultHTTPStreamingSwitchManager;

			// Since our segments are large, switch rapidly.

			// First, try to bias the bandwidth metric itself.
			var weights:Vector.<Number> = new Vector.<Number>;
			weights.push(1.0);
			weights.push(0.0);
			weights.push(0.0);
			var bw:BandwidthMetric = switcher.metricRepository.getMetric(MetricType.BANDWIDTH, weights) as BandwidthMetric;
			trace("Tried to override BandwidthMetric to N=1, and N=" + bw.weights.length);

			// Second, bias the bandwidthrule.
			for(var i:int=0; i<switcher.normalRules.length; i++)
			{
				var bwr:BandwidthRule = switcher.normalRules[i] as BandwidthRule;
				if(!bwr)
					continue;

				bwr.weights.length = 3;
				bwr.weights[0] = 1.0;
				bwr.weights[1] = 0.0;
				bwr.weights[2] = 0.0;

				trace("Adjusted BandwidthRule");
			}

			return switcher;
		}

		override protected function processFinishLoading(loadTrait:NetStreamLoadTrait):void
		{
			// Set up DVR state updating.
			var resource:URLResource = loadTrait.resource as URLResource;

			if (!dvrMetadataPresent(resource))
			{
				updateLoadTrait(loadTrait, LoadState.READY);
				return;
			}

			netStream = loadTrait.netStream as HLSHTTPNetStream;
			netStream.addEventListener(DVRStreamInfoEvent.DVRSTREAMINFO, onDVRStreamInfo);
			netStream.DVRGetStreamInfo(null);
			function onDVRStreamInfo(event:DVRStreamInfoEvent):void
			{
				netStream.removeEventListener(DVRStreamInfoEvent.DVRSTREAMINFO, onDVRStreamInfo);

				loadTrait.setTrait(new HLSDVRTrait(loadTrait.connection, netStream, event.info as DVRInfo));
				loadTrait.setTrait(new HLSDVRTimeTrait(loadTrait.connection, netStream, event.info as DVRInfo));
				updateLoadTrait(loadTrait, LoadState.READY);
			}
		}

		private function dvrMetadataPresent(resource:URLResource):Boolean
		{
			var metadata:Metadata = resource.getMetadataValue(MetadataNamespaces.DVR_METADATA) as Metadata;

			return (metadata != null);
		}
	}
}

package com.kaltura.hls.m2ts
{
	import com.kaltura.hls.HLSDVRTimeTrait;
	import com.kaltura.hls.HLSDVRTrait;
	import com.kaltura.hls.HLSMetadataNamespaces;

	import flash.net.NetConnection;
	import flash.net.NetStream;
	import flash.events.NetStatusEvent;

	import org.osmf.events.DVRStreamInfoEvent;
	import org.osmf.media.MediaResourceBase;
	import org.osmf.media.URLResource;
	import org.osmf.metadata.Metadata;
	import org.osmf.metadata.MetadataNamespaces;
	import org.osmf.net.NetStreamLoadTrait;
	import org.osmf.net.NetStreamCodes;
	import org.osmf.net.httpstreaming.HLSHTTPNetStream;
	import org.osmf.net.httpstreaming.HTTPStreamingFactory;
	import org.osmf.net.httpstreaming.HTTPStreamingNetLoader;
	import org.osmf.net.httpstreaming.dvr.DVRInfo;
	import org.osmf.traits.LoadState;

	import org.osmf.net.NetStreamSwitchManagerBase
	import org.osmf.net.metrics.BandwidthMetric;
	import org.osmf.net.DynamicStreamingResource;
	import org.osmf.net.httpstreaming.DefaultHTTPStreamingSwitchManager;

	import org.osmf.net.metrics.MetricType;
	import org.osmf.net.rules.BandwidthRule;

	/**
	 * Factory to identify and process MPEG2 TS via OSMF.
	 */
	public class M2TSNetLoader extends HTTPStreamingNetLoader
	{
		private var netStream:HLSHTTPNetStream;

		override public function canHandleResource( resource:MediaResourceBase ):Boolean
		{
			var metadata:Object = resource.getMetadataValue( HLSMetadataNamespaces.PLAYABLE_RESOURCE_METADATA );

			if ( metadata != null && metadata == true )
				return true;

			return false;
		}

		override protected function createNetStream(connection:NetConnection, resource:URLResource):NetStream
		{
			var factory:HTTPStreamingFactory = new M2TSStreamingFactory();
			var httpNetStream:HLSHTTPNetStream = new HLSHTTPNetStream(connection, factory, resource);
			return httpNetStream;
		}

		override protected function createNetStreamSwitchManager(connection:NetConnection, netStream:NetStream, dsResource:DynamicStreamingResource):NetStreamSwitchManagerBase
		{
			var switcher:DefaultHTTPStreamingSwitchManager = super.createNetStreamSwitchManager(connection, netStream, dsResource) as DefaultHTTPStreamingSwitchManager;

			// Since our segments are large, switch rapidly.

			// First, try to bias the bandwidth metric itself.
			var weights:Vector.<Number> = new Vector.<Number>;
			weights.push(1.0);
			weights.push(0.0);
			weights.push(0.0);
			var bw:BandwidthMetric = switcher.metricRepository.getMetric(MetricType.BANDWIDTH, weights) as BandwidthMetric;
			trace("Tried to override BandwidthMetric to N=1, and N=" + bw.weights.length);

			// Second, bias the bandwidthrule.
			for(var i:int=0; i<switcher.normalRules.length; i++)
			{
				var bwr:BandwidthRule = switcher.normalRules[i] as BandwidthRule;
				if(!bwr)
					continue;

				bwr.weights.length = 3;
				bwr.weights[0] = 1.0;
				bwr.weights[1] = 0.0;
				bwr.weights[2] = 0.0;

				trace("Adjusted BandwidthRule");
			}

			// Third, adjust the switch logic to be less restrictive.
			switcher.maxReliabilityRecordSize = 3;
			switcher.maxUpSwitchLimit = -1;
			switcher.maxDownSwitchLimit = -1;

			return switcher;
		}

		override protected function processFinishLoading(loadTrait:NetStreamLoadTrait):void
		{
			// Set up DVR state updating.
			var resource:URLResource = loadTrait.resource as URLResource;

			if (!dvrMetadataPresent(resource))
			{
				updateLoadTrait(loadTrait, LoadState.READY);
				return;
			}

			netStream = loadTrait.netStream as HLSHTTPNetStream;
			netStream.addEventListener(DVRStreamInfoEvent.DVRSTREAMINFO, onDVRStreamInfo);
			netStream.DVRGetStreamInfo(null);
			function onDVRStreamInfo(event:DVRStreamInfoEvent):void
			{
				netStream.removeEventListener(DVRStreamInfoEvent.DVRSTREAMINFO, onDVRStreamInfo);

				loadTrait.setTrait(new HLSDVRTrait(loadTrait.connection, netStream, event.info as DVRInfo));
				loadTrait.setTrait(new HLSDVRTimeTrait(loadTrait.connection, netStream, event.info as DVRInfo));
				updateLoadTrait(loadTrait, LoadState.READY);
			}
		}

		private function dvrMetadataPresent(resource:URLResource):Boolean
		{
			var metadata:Metadata = resource.getMetadataValue(MetadataNamespaces.DVR_METADATA) as Metadata;

			return (metadata != null);
		}
	}
}

Tweak switching logic settings.

Tweak switching logic settings.


#if __SWF_VERSION__ == 5
// create a _global object, since it doesn't have one, these are ver 6 values
_global = new_empty_object ();
_global.ASSetNative = ASSetNative;
_global.ASSetNativeAccessor = ASSetNativeAccessor;
_global.ASSetPropFlags = ASSetPropFlags;
_global.ASconstructor = ASconstructor;
_global.ASnative = ASnative;
_global.Accessibility = Accessibility;
_global.Array = Array;
_global.AsBroadcaster = AsBroadcaster;
_global.AsSetupError = AsSetupError;
_global.Boolean = Boolean;
_global.Button = Button;
_global.Camera = Camera;
_global.Color = Color;
_global.ContextMenu = ContextMenu;
_global.ContextMenuItem = ContextMenuItem;
_global.Date = Date;
_global.Error = Error;
_global.Function = Function;
_global.Infinity = Infinity;
_global.Key = Key;
_global.LoadVars = LoadVars;
_global.LocalConnection = LocalConnection;
_global.Math = Math;
_global.Microphone = Microphone;
_global.Mouse = Mouse;
_global.MovieClip = MovieClip;
_global.MovieClipLoader = MovieClipLoader;
_global.NaN = NaN;
_global.NetConnection = NetConnection;
_global.NetStream = NetStream;
_global.Number = Number;
_global.Object = Object;
_global.PrintJob = PrintJob;
_global.RemoteLSOUsage = RemoteLSOUsage;
_global.Selection = Selection;
_global.SharedObject = SharedObject;
_global.Sound = Sound;
_global.Stage = Stage;
_global.String = String;
_global.System = System;
_global.TextField = TextField;
_global.TextFormat = TextFormat;
_global.TextSnapshot = TextSnapshot;
_global.Video = Video;
_global.XML = XML;
_global.XMLNode = XMLNode;
_global.XMLSocket = XMLSocket;
_global.clearInterval = clearInterval;
_global.clearTimeout = clearTimeout;
_global.enableDebugConsole = enableDebugConsole;
_global.escape = escape;
_global.flash = flash;
_global.isFinite = isFinite;
_global.isNaN = isNaN;
_global.o = o;
_global.parseFloat = parseFloat;
_global.parseInt = parseInt;
_global.setInterval = setInterval;
_global.setTimeout = setTimeout;
_global.showRedrawRegions = showRedrawRegions;
_global.textRenderer = textRenderer;
_global.trace = trace;
_global.unescape = unescape;
_global.updateAfterEvent = updateAfterEvent;
#endif

function new_empty_object () {
  var hash = new Object ();
  ASSetPropFlags (hash, null, 0, 7);
  for (var prop in hash) {
    hash[prop] = "to-be-deleted";
    delete hash[prop];
  }
  return hash;
}

function hasOwnProperty_inner (o, prop)
{
  if (o.hasOwnProperty != undefined)
    return o.hasOwnProperty (prop);

  o.hasOwnProperty = ASnative (101, 5);
  var result = o.hasOwnProperty (prop);
  delete o.hasOwnProperty;
  return result;
}

function hasOwnProperty (o, prop)
{
  var result = hasOwnProperty_inner (o, prop);
#if __SWF_VERSION__ != 6
  if (result == false) {
    ASSetPropFlags (o, prop, 0, 256);
    result = hasOwnProperty_inner (o, prop);
    if (result)
      ASSetPropFlags (o, prop, 256);
  }
#endif
  return result;
}

function new_info () {
  return new_empty_object ();
}

function set_info (info, prop, id, value) {
  info[prop + "_-_" + id] = value;
}

function get_info (info, prop, id) {
  return info[prop + "_-_" + id];
}

function is_blaclisted (o, prop)
{
  if (prop == "mySecretId" || prop == "globalSecretId")
    return true;

  if (o == _global.Camera && prop == "names")
    return true;

  if (o == _global.Microphone && prop == "names")
    return true;

  return false;
}

function trace_properties_recurse (o, prefix, identifier, level)
{
  // to collect info about different properties
  var info = new_info ();

  // calculate indentation
  var indentation = "";
  for (var j = 0; j < level; j++) {
    indentation = indentation + "  ";
  }

  // mark the ones that are not hidden
  for (var prop in o)
  {
    // only get the ones that are not only in the __proto__
    if (is_blaclisted (o, prop) == false) {
      if (hasOwnProperty (o, prop) == true)
	set_info (info, prop, "hidden", false);
    }
  }

  // unhide everything
  ASSetPropFlags (o, null, 0, 1);

  var all = new Array ();
  var hidden = new Array ();
  for (var prop in o)
  {
    // only get the ones that are not only in the __proto__
    if (is_blaclisted (o, prop) == false) {
      if (hasOwnProperty (o, prop) == true) {
	all.push (prop);
	if (get_info (info, prop, "hidden") != false) {
	  set_info (info, prop, "hidden", true);
	  hidden.push (prop);
	}
      }
    }
  }
  all.sort ();

  // hide the ones that were already hidden
  ASSetPropFlags (o, hidden, 1, 0);

  if (all.length == 0) {
    trace (indentation + "no children");
    return nextSecretId;
  }

#if __SWF_VERSION__ != 6
  for (var i = 0; i < all.length; i++)
  {
    var prop = all[i];

    // try changing value
    if (!hasOwnProperty_inner(o, prop) && hasOwnProperty(o, prop))
    {
      set_info (info, prop, "not6", true);
    }
    else
    {
      set_info (info, prop, "not6", false);
    }
  }
#endif

  for (var i = 0; i < all.length; i++)
  {
    var prop = all[i];

    if (typeof (o[prop]) == "undefined") {
      ASSetPropFlags (o, prop, 0, 5248);
      if (typeof (o[prop]) != "undefined") {
	set_info (info, prop, "newer", true);
	// don't set the flags back
      } else {
	set_info (info, prop, "newer", false);
      }
    } else {
      set_info (info, prop, "newer", false);
    }
  }

  for (var i = 0; i < all.length; i++)
  {
    var prop = all[i];

    // try changing value
    var old = o[prop];
    var val = "hello " + o[prop];
    o[prop] = val;
    if (o[prop] != val)
    {
      set_info (info, prop, "constant", true);

      // try changing value after removing constant propflag
      ASSetPropFlags (o, prop, 0, 4);
      o[prop] = val;
      if (o[prop] != val) {
	set_info (info, prop, "superconstant", true);
      } else {
	set_info (info, prop, "superconstant", false);
	o[prop] = old;
      }
      ASSetPropFlags (o, prop, 4);
    }
    else
    {
      set_info (info, prop, "constant", false);
      set_info (info, prop, "superconstant", false);
      o[prop] = old;
    }
  }

  for (var i = 0; i < all.length; i++)
  {
    var prop = all[i];

    // remove constant flag
    ASSetPropFlags (o, prop, 0, 4);

    // try deleting
    var old = o[prop];
    delete o[prop];
    if (hasOwnProperty (o, prop))
    {
      set_info (info, prop, "permanent", true);
    }
    else
    {
      set_info (info, prop, "permanent", false);
      o[prop] = old;
    }

    // put constant flag back, if it was set
    if (get_info (info, prop, "constant") == true)
      ASSetPropFlags (o, prop, 4);
  }

  for (var i = 0; i < all.length; i++) {
    var prop = all[i];

    // format propflags
    var flags = "";
    if (get_info (info, prop, "hidden") == true) {
      flags += "h";
    }
    if (get_info (info, prop, "superpermanent") == true) {
      flags += "P";
    } else if (get_info (info, prop, "permanent") == true) {
      flags += "p";
    }
    if (get_info (info, prop, "superconstant") == true) {
      flags += "C";
    } else if (get_info (info, prop, "constant") == true) {
      flags += "c";
    }
    if (get_info (info, prop, "not6") == true) {
      flags += "6";
    }
    if (get_info (info, prop, "newer") == true) {
      flags += "n";
    }
    if (flags != "")
      flags = " (" + flags + ")";

    var value = "";
    // add value depending on the type
    if (typeof (o[prop]) == "number" || typeof (o[prop]) == "boolean") {
      value += " : " + o[prop];
    } else if (typeof (o[prop]) == "string") {
      value += " : \"" + o[prop] + "\"";
    }

    // recurse if it's object or function and this is the place it has been
    // named after
    if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function")
    {
      if (prefix + (prefix != "" ? "." : "") + identifier + "." + prop ==
	  o[prop]["mySecretId"])
      {
	trace (indentation + prop + flags + " = " + typeof (o[prop]));
	trace_properties_recurse (o[prop], prefix + (prefix != "" ? "." : "") +
	    identifier, prop, level + 1);
      }
      else
      {
	trace (indentation + prop + flags + " = " + o[prop]["mySecretId"]);
      }
    }
    else
    {
      trace (indentation + prop + flags + " = " + typeof (o[prop]) + value);
    }
  }
}

function generate_names (o, prefix, identifier)
{
  // mark the ones that are not hidden
  var nothidden = new Array ();
  for (var prop in o) {
    nothidden.push (prop);
  }

  // unhide everything
  ASSetPropFlags (o, null, 0, 1);

  var all = new Array ();
  for (var prop in o)
  {
    if (is_blaclisted (o, prop) == false) {
      // only get the ones that are not only in the __proto__
      if (hasOwnProperty (o, prop) == true) {
	all.push (prop);
      }
    }
  }
  all.sort ();

  // hide the ones that were already hidden
  ASSetPropFlags (o, null, 1, 0);
  ASSetPropFlags (o, nothidden, 0, 1);

  for (var i = 0; i < all.length; i++) {
    var newer = false;
    var prop = all[i];

    if (typeof (o[prop]) == "undefined") {
      ASSetPropFlags (o, prop, 0, 5248);
      if (typeof (o[prop]) != "undefined")
	newer = true;
    }

    if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function") {
      if (hasOwnProperty (o[prop], "mySecretId")) {
	all[i] = null; // don't recurse to it again
      } else {
	o[prop]["mySecretId"] = prefix + (prefix != "" ? "." : "") +
	  identifier + "." + prop;
      }
    }

    if (newer == true)
      ASSetPropFlags (o, prop, 5248);
  }

  for (var i = 0; i < all.length; i++) {
    var prop = all[i];

    if (prop != null) {
      var newer = false;

      if (typeof (o[prop]) == "undefined") {
	ASSetPropFlags (o, prop, 0, 5248);
	if (typeof (o[prop]) != "undefined")
	  newer = true;
      }

      if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function")
	generate_names (o[prop], prefix + (prefix != "" ? "." : "") +
	    identifier, prop);

      if (newer == true)
	ASSetPropFlags (o, prop, 5248);
    }
  }
}

function trace_properties (o, prefix, identifier)
{
  _global["mySecretId"] = "_global";
  _global.Object["mySecretId"] = "_global.Object";
  _global.Function["mySecretId"] = "_global.Function";
  _global.Function.prototype["mySecretId"] = "_global.Function.prototype";
  _global.XMLNode["mySecretId"] = "_global.XMLNode";
  generate_names (_global.Object, "_global", "Object");
  generate_names (_global.Function, "_global", "Function");
  generate_names (_global.Function.prototype, "_global", "Function.prototype");
  generate_names (_global.XMLNode, "_global", "XMLNode");
  generate_names (_global, "", "_global");

  if (typeof (o) == "object" || typeof (o) == "function")
  {
    if (!o.hasOwnProperty ("mySecretId")) {
      o["mySecretId"] = prefix + (prefix != "" ? "." : "") + identifier;
      generate_names (o, prefix, identifier);
    }

    if (prefix + (prefix != "" ? "." : "") + identifier == o["mySecretId"])
    {
      trace (prefix + (prefix != "" ? "." : "") + identifier + " = " +
	  typeof (o));
    }
    else
    {
      trace (prefix + (prefix != "" ? "." : "") + identifier + " = " +
	  o["mySecretId"]);
    }
    trace_properties_recurse (o, prefix, identifier, 1);
  }
  else
  {
    var value = "";
    if (typeof (o) == "number" || typeof (o) == "boolean") {
      value += " : " + o;
    } else if (typeof (o) == "string") {
      value += " : \"" + o + "\"";
    }
    trace (prefix + (prefix != "" ? "." : "") + identifier + " = " +
	typeof (o) + value);
  }
}

#if __SWF_VERSION__ == 5
// create a _global object, since it doesn't have one, these are ver 6 values
_global = new_empty_object ();
_global.ASSetNative = ASSetNative;
_global.ASSetNativeAccessor = ASSetNativeAccessor;
_global.ASSetPropFlags = ASSetPropFlags;
_global.ASconstructor = ASconstructor;
_global.ASnative = ASnative;
_global.Accessibility = Accessibility;
_global.Array = Array;
_global.AsBroadcaster = AsBroadcaster;
_global.AsSetupError = AsSetupError;
_global.Boolean = Boolean;
_global.Button = Button;
_global.Camera = Camera;
_global.Color = Color;
_global.ContextMenu = ContextMenu;
_global.ContextMenuItem = ContextMenuItem;
_global.Date = Date;
_global.Error = Error;
_global.Function = Function;
_global.Infinity = Infinity;
_global.Key = Key;
_global.LoadVars = LoadVars;
_global.LocalConnection = LocalConnection;
_global.Math = Math;
_global.Microphone = Microphone;
_global.Mouse = Mouse;
_global.MovieClip = MovieClip;
_global.MovieClipLoader = MovieClipLoader;
_global.NaN = NaN;
_global.NetConnection = NetConnection;
_global.NetStream = NetStream;
_global.Number = Number;
_global.Object = Object;
_global.PrintJob = PrintJob;
_global.RemoteLSOUsage = RemoteLSOUsage;
_global.Selection = Selection;
_global.SharedObject = SharedObject;
_global.Sound = Sound;
_global.Stage = Stage;
_global.String = String;
_global.System = System;
_global.TextField = TextField;
_global.TextFormat = TextFormat;
_global.TextSnapshot = TextSnapshot;
_global.Video = Video;
_global.XML = XML;
_global.XMLNode = XMLNode;
_global.XMLSocket = XMLSocket;
_global.clearInterval = clearInterval;
_global.clearTimeout = clearTimeout;
_global.enableDebugConsole = enableDebugConsole;
_global.escape = escape;
_global.flash = flash;
_global.isFinite = isFinite;
_global.isNaN = isNaN;
_global.o = o;
_global.parseFloat = parseFloat;
_global.parseInt = parseInt;
_global.setInterval = setInterval;
_global.setTimeout = setTimeout;
_global.showRedrawRegions = showRedrawRegions;
_global.textRenderer = textRenderer;
_global.trace = trace;
_global.unescape = unescape;
_global.updateAfterEvent = updateAfterEvent;
#endif

function new_empty_object () {
  var hash = new Object ();
  ASSetPropFlags (hash, null, 0, 7);
  for (var prop in hash) {
    hash[prop] = "to-be-deleted";
    delete hash[prop];
  }
  return hash;
}

function hasOwnProperty_inner (o, prop)
{
  if (o.hasOwnProperty != undefined)
    return o.hasOwnProperty (prop);

  o.hasOwnProperty = ASnative (101, 5);
  var result = o.hasOwnProperty (prop);
  delete o.hasOwnProperty;
  return result;
}

function hasOwnProperty (o, prop)
{
  var result = hasOwnProperty_inner (o, prop);
#if __SWF_VERSION__ != 6
  if (result == false) {
    ASSetPropFlags (o, prop, 0, 256);
    result = hasOwnProperty_inner (o, prop);
    if (result)
      ASSetPropFlags (o, prop, 256);
  }
#endif
  return result;
}

function new_info () {
  return new_empty_object ();
}

function set_info (info, prop, id, value) {
  info[prop + "_-_" + id] = value;
}

function get_info (info, prop, id) {
  return info[prop + "_-_" + id];
}

function is_blaclisted (o, prop)
{
  if (prop == "mySecretId" || prop == "globalSecretId")
    return true;

  if (o == _global.Camera && prop == "names")
    return true;

  if (o == _global.Microphone && prop == "names")
    return true;

  return false;
}

function trace_properties_recurse (o, prefix, identifier, level)
{
  // to collect info about different properties
  var info = new_info ();

  // calculate indentation
  var indentation = "";
  for (var j = 0; j < level; j++) {
    indentation = indentation + "  ";
  }

  // mark the ones that are not hidden
  for (var prop in o)
  {
    // only get the ones that are not only in the __proto__
    if (is_blaclisted (o, prop) == false) {
      if (hasOwnProperty (o, prop) == true)
	set_info (info, prop, "hidden", false);
    }
  }

  // unhide everything
  ASSetPropFlags (o, null, 0, 1);

  var all = new Array ();
  var hidden = new Array ();
  for (var prop in o)
  {
    // only get the ones that are not only in the __proto__
    if (is_blaclisted (o, prop) == false) {
      if (hasOwnProperty (o, prop) == true) {
	all.push (prop);
	if (get_info (info, prop, "hidden") != false) {
	  set_info (info, prop, "hidden", true);
	  hidden.push (prop);
	}
      }
    }
  }
  all.sort ();

  // hide the ones that were already hidden
  ASSetPropFlags (o, hidden, 1, 0);

  if (all.length == 0) {
    trace (indentation + "no children");
    return nextSecretId;
  }

#if __SWF_VERSION__ != 6
  for (var i = 0; i < all.length; i++)
  {
    var prop = all[i];

    // try changing value
    if (!hasOwnProperty_inner(o, prop) && hasOwnProperty(o, prop))
    {
      set_info (info, prop, "not6", true);
    }
    else
    {
      set_info (info, prop, "not6", false);
    }
  }
#endif

  for (var i = 0; i < all.length; i++)
  {
    var prop = all[i];

    if (typeof (o[prop]) == "undefined") {
      ASSetPropFlags (o, prop, 0, 5248);
      if (typeof (o[prop]) != "undefined") {
	set_info (info, prop, "newer", true);
	// don't set the flags back
      } else {
	set_info (info, prop, "newer", false);
      }
    } else {
      set_info (info, prop, "newer", false);
    }
  }

  for (var i = 0; i < all.length; i++)
  {
    var prop = all[i];

    // try changing value
    var old = o[prop];
    var val = "hello " + o[prop];
    o[prop] = val;
    if (o[prop] != val)
    {
      set_info (info, prop, "constant", true);

      // try changing value after removing constant propflag
      ASSetPropFlags (o, prop, 0, 4);
      o[prop] = val;
      if (o[prop] != val) {
	set_info (info, prop, "superconstant", true);
      } else {
	set_info (info, prop, "superconstant", false);
	o[prop] = old;
      }
      ASSetPropFlags (o, prop, 4);
    }
    else
    {
      set_info (info, prop, "constant", false);
      set_info (info, prop, "superconstant", false);
      o[prop] = old;
    }
  }

  for (var i = 0; i < all.length; i++)
  {
    var prop = all[i];

    // remove constant flag
    ASSetPropFlags (o, prop, 0, 4);

    // try deleting
    var old = o[prop];
    delete o[prop];
    if (hasOwnProperty (o, prop))
    {
      set_info (info, prop, "permanent", true);
    }
    else
    {
      set_info (info, prop, "permanent", false);
      o[prop] = old;
    }

    // put constant flag back, if it was set
    if (get_info (info, prop, "constant") == true)
      ASSetPropFlags (o, prop, 4);
  }

  for (var i = 0; i < all.length; i++) {
    var prop = all[i];

    // format propflags
    var flags = "";
    if (get_info (info, prop, "hidden") == true) {
      flags += "h";
    }
    if (get_info (info, prop, "superpermanent") == true) {
      flags += "P";
    } else if (get_info (info, prop, "permanent") == true) {
      flags += "p";
    }
    if (get_info (info, prop, "superconstant") == true) {
      flags += "C";
    } else if (get_info (info, prop, "constant") == true) {
      flags += "c";
    }
    if (get_info (info, prop, "not6") == true) {
      flags += "6";
    }
    if (get_info (info, prop, "newer") == true) {
      flags += "n";
    }
    if (flags != "")
      flags = " (" + flags + ")";

    var value = "";
    // add value depending on the type
    if (typeof (o[prop]) == "number" || typeof (o[prop]) == "boolean") {
      value += " : " + o[prop];
    } else if (typeof (o[prop]) == "string") {
      value += " : \"" + o[prop] + "\"";
    }

    // recurse if it's object or function and this is the place it has been
    // named after
    if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function")
    {
      if (prefix + (prefix != "" ? "." : "") + identifier + "." + prop ==
	  o[prop]["mySecretId"])
      {
	trace (indentation + prop + flags + " = " + typeof (o[prop]));
	trace_properties_recurse (o[prop], prefix + (prefix != "" ? "." : "") +
	    identifier, prop, level + 1);
      }
      else
      {
	trace (indentation + prop + flags + " = " + o[prop]["mySecretId"]);
      }
    }
    else
    {
      trace (indentation + prop + flags + " = " + typeof (o[prop]) + value);
    }
  }
}

function generate_names (o, prefix, identifier)
{
  // mark the ones that are not hidden
  var nothidden = new Array ();
  for (var prop in o) {
    nothidden.push (prop);
  }

  // unhide everything
  ASSetPropFlags (o, null, 0, 1);

  var all = new Array ();
  for (var prop in o)
  {
    if (is_blaclisted (o, prop) == false) {
      // only get the ones that are not only in the __proto__
      if (hasOwnProperty (o, prop) == true) {
	all.push (prop);
      }
    }
  }
  all.sort ();

  // hide the ones that were already hidden
  ASSetPropFlags (o, null, 1, 0);
  ASSetPropFlags (o, nothidden, 0, 1);

  for (var i = 0; i < all.length; i++) {
    var newer = false;
    var prop = all[i];

    if (typeof (o[prop]) == "undefined") {
      ASSetPropFlags (o, prop, 0, 5248);
      if (typeof (o[prop]) != "undefined")
	newer = true;
    }

    if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function") {
      if (hasOwnProperty (o[prop], "mySecretId")) {
	all[i] = null; // don't recurse to it again
      } else {
	o[prop]["mySecretId"] = prefix + (prefix != "" ? "." : "") +
	  identifier + "." + prop;
      }
    }

    if (newer == true)
      ASSetPropFlags (o, prop, 5248);
  }

  for (var i = 0; i < all.length; i++) {
    var prop = all[i];

    if (prop != null) {
      var newer = false;

      if (typeof (o[prop]) == "undefined") {
	ASSetPropFlags (o, prop, 0, 5248);
	if (typeof (o[prop]) != "undefined")
	  newer = true;
      }

      if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function")
	generate_names (o[prop], prefix + (prefix != "" ? "." : "") +
	    identifier, prop);

      if (newer == true)
	ASSetPropFlags (o, prop, 5248);
    }
  }
}

function trace_properties (o, prefix, identifier)
{
  _global["mySecretId"] = "_global";
  _global.Object["mySecretId"] = "_global.Object";
  _global.Function["mySecretId"] = "_global.Function";
  _global.Function.prototype["mySecretId"] = "_global.Function.prototype";
  _global.XMLNode["mySecretId"] = "_global.XMLNode";
  _global.flash.text.TextRenderer["mySecretId"] = "_global.flash.text.TextRenderer";
  generate_names (_global.Object, "_global", "Object");
  generate_names (_global.Function, "_global", "Function");
  generate_names (_global.Function.prototype, "_global", "Function.prototype");
  generate_names (_global.XMLNode, "_global", "XMLNode");
  generate_names (_global.flash.text.TextRenderer, "_global.flash.text", "TextRenderer");
  generate_names (_global, "", "_global");

  if (typeof (o) == "object" || typeof (o) == "function")
  {
    if (!o.hasOwnProperty ("mySecretId")) {
      o["mySecretId"] = prefix + (prefix != "" ? "." : "") + identifier;
      generate_names (o, prefix, identifier);
    }

    if (prefix + (prefix != "" ? "." : "") + identifier == o["mySecretId"])
    {
      trace (prefix + (prefix != "" ? "." : "") + identifier + " = " +
	  typeof (o));
    }
    else
    {
      trace (prefix + (prefix != "" ? "." : "") + identifier + " = " +
	  o["mySecretId"]);
    }
    trace_properties_recurse (o, prefix, identifier, 1);
  }
  else
  {
    var value = "";
    if (typeof (o) == "number" || typeof (o) == "boolean") {
      value += " : " + o;
    } else if (typeof (o) == "string") {
      value += " : \"" + o + "\"";
    }
    trace (prefix + (prefix != "" ? "." : "") + identifier + " = " +
	typeof (o) + value);
  }
}

Add special case to trace_properties.as for _global.flash.text.TextRenderer

Now flash.text.TextRenderer gets priority in naming over textRenderer


/**
 * User: booster
 * Date: 18/12/13
 * Time: 11:29
 */
package starling.shaders {
import com.barliesque.agal.EasierAGAL;
import com.barliesque.agal.IComponent;
import com.barliesque.agal.IRegister;
import com.barliesque.agal.TextureFlag;
import com.barliesque.shaders.macro.Utils;

import flash.display3D.Context3D;
import flash.display3D.Context3DProgramType;

public class FastGaussianBlurShader extends EasierAGAL implements ITextureShader {
    public static const HORIZONTAL:String   = "horizontal";
    public static const VERTICAL:String     = "vertical";

    private static const DEFAULT_FIRST_PASS_STRENGTH:Number                 = 1.25;
    private static const DEFAULT_STRENGTH_INCREASE_PER_PASS_RATIO:Number    = 3.0;

    private static var _verticalOffsets:Vector.<Number>     = new <Number>[0.0, 1.3846153846, 0.0, 3.2307692308];
    private static var _horizontalOffsets:Vector.<Number>   = new <Number>[1.3846153846, 0.0, 3.2307692308, 0.0];

    private var _type:String                    = HORIZONTAL;
    private var _pass:int                       = 0;
    private var _strength:Number                = Number.NaN;
    private var _firstPassStrength:Number       = DEFAULT_FIRST_PASS_STRENGTH;
    private var _strengthIncreaseRatio:Number   = DEFAULT_STRENGTH_INCREASE_PER_PASS_RATIO;
    private var _pixelWidth:Number              = Number.NaN;
    private var _pixelHeight:Number             = Number.NaN;
    private var _paramsDirty:Boolean            = true;
    private var _strengthsDirty:Boolean         = true;

    private var _strengths:Vector.<Number>      = new <Number>[];
    private var _offsets:Vector.<Number>        = new <Number>[0, 0, 0, 0];
    private var _uv:Vector.<Number>             = new <Number>[0, 1, 0, 1];
    private var _weights:Vector.<Number>        = new <Number>[0.2270270270, 0.3162162162, 0.0702702703, 0];

    public function get type():String { return _type; }
    public function set type(value:String):void {
        if(value == _type)
            return;

        _type = value;
        _paramsDirty = true;
    }

    public function get strength():Number { return _strength; }
    public function set strength(value:Number):void {
        if(value == _strength)
            return;

        _strength = value;
        _paramsDirty = true;
        _strengthsDirty = true;
    }

    public function get firstPassStrength():Number { return _firstPassStrength; }
    public function set firstPassStrength(value:Number):void {
        if(_firstPassStrength == value)
            return;

        _firstPassStrength = value;
        _paramsDirty = true;
        _strengthsDirty = true;
    }

    public function get strengthIncreaseRatio():Number { return _strengthIncreaseRatio; }
    public function set strengthIncreaseRatio(value:Number):void {
        if(_strengthIncreaseRatio == value)
            return;

        _strengthIncreaseRatio = value;
        _paramsDirty = true;
        _strengthsDirty = true;
    }

    public function get pass():int { return _pass; }
    public function set pass(value:int):void {
        if(value == _pass)
            return;

        _pass = value;
        _paramsDirty = true;
    }

    public function get pixelWidth():Number { return _pixelWidth; }
    public function set pixelWidth(value:Number):void {
        if(value == _pixelWidth)
            return;

        _pixelWidth = value;
        _paramsDirty = true;
    }

    public function get pixelHeight():Number { return _pixelHeight; }
    public function set pixelHeight(value:Number):void {
        if(value == _pixelHeight)
            return;

        _pixelHeight = value;
        _paramsDirty = true;
    }

    public function get passesNeeded():int {
        if(_strengthsDirty)
            updateStrengths();

        return _strengths.length;
    }

    public function get minU():Number { return _uv[0]; }
    public function set minU(value:Number):void { _uv[0] = value; }

    public function get maxU():Number { return _uv[1]; }
    public function set maxU(value:Number):void { _uv[1] = value; }

    public function get minV():Number { return _uv[2]; }
    public function set minV(value:Number):void { _uv[2] = value; }

    public function get maxV():Number { return _uv[3]; }
    public function set maxV(value:Number):void { _uv[3] = value; }

    public function activate(context:Context3D):void {
        if(_strengthsDirty)
            updateStrengths();

        if(_paramsDirty)
            updateParameters();

        context.setProgramConstantsFromVector(Context3DProgramType.VERTEX,   4, _offsets);
        context.setProgramConstantsFromVector(Context3DProgramType.FRAGMENT, 0, _weights);
        context.setProgramConstantsFromVector(Context3DProgramType.FRAGMENT, 1, _uv);
    }

    public function deactivate(context:Context3D):void {
    }

    override protected function _vertexShader():void {
        comment("Apply a 4x4 matrix to transform vertices to clip-space");
        multiply4x4(OUTPUT, ATTRIBUTE[0], CONST[0]);

        comment("Pass uv coordinates to fragment shader");
        move(VARYING[0], ATTRIBUTE[1]);

        comment("pass 4 additional UVs for sampling neighbours, in order: -2, -1, +1, +2 pixels away");
        subtract(VARYING[1], ATTRIBUTE[1], CONST[4].zw);
        subtract(VARYING[2], ATTRIBUTE[1], CONST[4].xy);
        add(VARYING[3], ATTRIBUTE[1], CONST[4].xy);
        add(VARYING[4], ATTRIBUTE[1], CONST[4].zw);
    }

    override protected function _fragmentShader():void {
        var uvCenter:IRegister      = VARYING[0];
        var uvMinusTwo:IRegister    = VARYING[1];
        var uvMinusOne:IRegister    = VARYING[2];
        var uvPlusOne:IRegister     = VARYING[3];
        var uvPlusTwo:IRegister     = VARYING[4];
        var uv:IRegister            = TEMP[7];
        var weightCenter:IComponent = CONST[0].x;
        var weightOne:IComponent    = CONST[0].y;
        var weightTwo:IComponent    = CONST[0].z;
        var minU:IComponent         = CONST[1].x;
        var maxU:IComponent         = CONST[1].y;
        var minV:IComponent         = CONST[1].z;
        var maxV:IComponent         = CONST[1].w;
        var colorCenter:IRegister   = TEMP[0];
        var colorMinusTwo:IRegister = TEMP[1];
        var colorMinusOne:IRegister = TEMP[2];
        var colorPlusOne:IRegister  = TEMP[3];
        var colorPlusTwo:IRegister  = TEMP[4];
        var outputColor:IRegister   = TEMP[5];
        var textureFlags:Array      = [TextureFlag.TYPE_2D, TextureFlag.MODE_CLAMP, TextureFlag.FILTER_LINEAR, TextureFlag.MIP_NO];

        sampleTexture(colorCenter, uvCenter, SAMPLER[0], textureFlags);
        multiply(outputColor, colorCenter, weightCenter);

        move(uv, uvMinusTwo);
        Utils.clamp(uv.x, uv.x, minU, maxU);
        Utils.clamp(uv.y, uv.y, minV, maxV);
        sampleTexture(colorMinusTwo, uv, SAMPLER[0], textureFlags);
        multiply(colorMinusTwo, colorMinusTwo, weightTwo);
        add(outputColor, outputColor, colorMinusTwo);

        move(uv, uvMinusOne);
        Utils.clamp(uv.x, uv.x, minU, maxU);
        Utils.clamp(uv.y, uv.y, minV, maxV);
        sampleTexture(colorMinusOne, uv, SAMPLER[0], textureFlags);
        multiply(colorMinusOne, colorMinusOne, weightOne);
        add(outputColor, outputColor, colorMinusOne);

        move(uv, uvPlusOne);
        Utils.clamp(uv.x, uv.x, minU, maxU);
        Utils.clamp(uv.y, uv.y, minV, maxV);
        sampleTexture(colorPlusOne, uv, SAMPLER[0], textureFlags);
        multiply(colorPlusOne, colorPlusOne, weightOne);
        add(outputColor, outputColor, colorPlusOne);

        move(uv, uvPlusTwo);
        Utils.clamp(uv.x, uv.x, minU, maxU);
        Utils.clamp(uv.y, uv.y, minV, maxV);
        sampleTexture(colorPlusTwo, uv, SAMPLER[0], textureFlags);
        multiply(colorPlusTwo, colorPlusTwo, weightTwo);
        add(outputColor, outputColor, colorPlusTwo);

        move(OUTPUT, outputColor);
    }

    private function updateParameters():void {
        // algorithm described here:
        // http://rastergrid.com/blog/2010/09/efficient-gaussian-blur-with-linear-sampling/
        //
        // To run in constrained mode, we can only make 5 texture lookups in the fragment
        // shader. By making use of linear texture sampling, we can produce similar output
        // to what would be 9 lookups.

        _paramsDirty = false;

        var multiplier:Number, str:Number = _strengths[_pass];
        var i:int, count:int = 4;

        trace("str: " + str);

        if(type == HORIZONTAL) {
            multiplier = _pixelWidth * str;

            for(i = 0; i < count; i++)
                _offsets[i] = _horizontalOffsets[i] * multiplier;
        }
        else {
            multiplier = _pixelHeight * str;

            for(i = 0; i < count; i++)
                _offsets[i] = _verticalOffsets[i] * multiplier;
        }
    }

    private function updateStrengths():void {
        _strengthsDirty = false;

        _strengths.length   = 0;
        var str:Number      = Math.min(_firstPassStrength, _strength);
        var sum:Number      = 0;

        while(sum + str < _strength) {
            _strengths[_strengths.length] = str;
            sum += str;
            str *= _strengthIncreaseRatio;
        }

        var diff:Number = _strength - sum;

        if(diff > 0 || _strengths.length == 0)
            _strengths[_strengths.length] = diff;

        _strengths.sort(function (a:Number, b:Number):Number { return b - a; });

        trace("strengths: [" + _strengths + "], total: " + _strength);
    }
}
}

/**
 * User: booster
 * Date: 18/12/13
 * Time: 11:29
 */
package starling.shaders {
import com.barliesque.agal.EasierAGAL;
import com.barliesque.agal.IComponent;
import com.barliesque.agal.IRegister;
import com.barliesque.agal.TextureFlag;
import com.barliesque.shaders.macro.Utils;

import flash.display3D.Context3D;
import flash.display3D.Context3DProgramType;

public class FastGaussianBlurShader extends EasierAGAL implements ITextureShader {
    public static const HORIZONTAL:String   = "horizontal";
    public static const VERTICAL:String     = "vertical";

    private static const DEFAULT_FIRST_PASS_STRENGTH:Number                 = 1.25;
    private static const DEFAULT_STRENGTH_INCREASE_PER_PASS_RATIO:Number    = 3.0;

    private static var _verticalOffsets:Vector.<Number>     = new <Number>[0.0, 1.3846153846, 0.0, 3.2307692308];
    private static var _horizontalOffsets:Vector.<Number>   = new <Number>[1.3846153846, 0.0, 3.2307692308, 0.0];

    private var _type:String                    = HORIZONTAL;
    private var _pass:int                       = 0;
    private var _strength:Number                = Number.NaN;
    private var _firstPassStrength:Number       = DEFAULT_FIRST_PASS_STRENGTH;
    private var _strengthIncreaseRatio:Number   = DEFAULT_STRENGTH_INCREASE_PER_PASS_RATIO;
    private var _pixelWidth:Number              = Number.NaN;
    private var _pixelHeight:Number             = Number.NaN;
    private var _paramsDirty:Boolean            = true;
    private var _strengthsDirty:Boolean         = true;

    private var _strengths:Vector.<Number>      = new <Number>[];
    private var _offsets:Vector.<Number>        = new <Number>[0, 0, 0, 0];
    private var _uv:Vector.<Number>             = new <Number>[0, 1, 0, 1];
    private var _weights:Vector.<Number>        = new <Number>[0.2270270270, 0.3162162162, 0.0702702703, 0];

    public function get type():String { return _type; }
    public function set type(value:String):void {
        if(value == _type)
            return;

        _type = value;
        _paramsDirty = true;
    }

    public function get strength():Number { return _strength; }
    public function set strength(value:Number):void {
        if(value == _strength)
            return;

        _strength = value;
        _paramsDirty = true;
        _strengthsDirty = true;
    }

    public function get firstPassStrength():Number { return _firstPassStrength; }
    public function set firstPassStrength(value:Number):void {
        if(_firstPassStrength == value)
            return;

        _firstPassStrength = value;
        _paramsDirty = true;
        _strengthsDirty = true;
    }

    public function get strengthIncreaseRatio():Number { return _strengthIncreaseRatio; }
    public function set strengthIncreaseRatio(value:Number):void {
        if(_strengthIncreaseRatio == value)
            return;

        _strengthIncreaseRatio = value;
        _paramsDirty = true;
        _strengthsDirty = true;
    }

    public function get pass():int { return _pass; }
    public function set pass(value:int):void {
        if(value == _pass)
            return;

        _pass = value;
        _paramsDirty = true;
    }

    public function get pixelWidth():Number { return _pixelWidth; }
    public function set pixelWidth(value:Number):void {
        if(value == _pixelWidth)
            return;

        _pixelWidth = value;
        _paramsDirty = true;
    }

    public function get pixelHeight():Number { return _pixelHeight; }
    public function set pixelHeight(value:Number):void {
        if(value == _pixelHeight)
            return;

        _pixelHeight = value;
        _paramsDirty = true;
    }

    public function get passesNeeded():int {
        if(_strengthsDirty)
            updateStrengths();

        return _strengths.length;
    }

    public function get minU():Number { return _uv[0]; }
    public function set minU(value:Number):void { _uv[0] = value; }

    public function get maxU():Number { return _uv[1]; }
    public function set maxU(value:Number):void { _uv[1] = value; }

    public function get minV():Number { return _uv[2]; }
    public function set minV(value:Number):void { _uv[2] = value; }

    public function get maxV():Number { return _uv[3]; }
    public function set maxV(value:Number):void { _uv[3] = value; }

    public function activate(context:Context3D):void {
        if(_strengthsDirty)
            updateStrengths();

        if(_paramsDirty)
            updateParameters();

        context.setProgramConstantsFromVector(Context3DProgramType.VERTEX,   4, _offsets);
        context.setProgramConstantsFromVector(Context3DProgramType.FRAGMENT, 0, _weights);
        context.setProgramConstantsFromVector(Context3DProgramType.FRAGMENT, 1, _uv);
    }

    public function deactivate(context:Context3D):void {
    }

    override protected function _vertexShader():void {
        comment("Apply a 4x4 matrix to transform vertices to clip-space");
        multiply4x4(OUTPUT, ATTRIBUTE[0], CONST[0]);

        comment("Pass uv coordinates to fragment shader");
        move(VARYING[0], ATTRIBUTE[1]);

        comment("pass 4 additional UVs for sampling neighbours, in order: -2, -1, +1, +2 pixels away");
        subtract(VARYING[1], ATTRIBUTE[1], CONST[4].zw);
        subtract(VARYING[2], ATTRIBUTE[1], CONST[4].xy);
        add(VARYING[3], ATTRIBUTE[1], CONST[4].xy);
        add(VARYING[4], ATTRIBUTE[1], CONST[4].zw);
    }

    override protected function _fragmentShader():void {
        var uvCenter:IRegister      = VARYING[0];
        var uvMinusTwo:IRegister    = VARYING[1];
        var uvMinusOne:IRegister    = VARYING[2];
        var uvPlusOne:IRegister     = VARYING[3];
        var uvPlusTwo:IRegister     = VARYING[4];
        var uv:IRegister            = TEMP[7];
        var weightCenter:IComponent = CONST[0].x;
        var weightOne:IComponent    = CONST[0].y;
        var weightTwo:IComponent    = CONST[0].z;
        var minU:IComponent         = CONST[1].x;
        var maxU:IComponent         = CONST[1].y;
        var minV:IComponent         = CONST[1].z;
        var maxV:IComponent         = CONST[1].w;
        var colorCenter:IRegister   = TEMP[0];
        var colorMinusTwo:IRegister = TEMP[1];
        var colorMinusOne:IRegister = TEMP[2];
        var colorPlusOne:IRegister  = TEMP[3];
        var colorPlusTwo:IRegister  = TEMP[4];
        var outputColor:IRegister   = TEMP[5];
        var textureFlags:Array      = [TextureFlag.TYPE_2D, TextureFlag.MODE_CLAMP, TextureFlag.FILTER_LINEAR, TextureFlag.MIP_NO];

        sampleTexture(colorCenter, uvCenter, SAMPLER[0], textureFlags);
        multiply(outputColor, colorCenter, weightCenter);

        move(uv, uvMinusTwo);
        Utils.clamp(uv.x, uv.x, minU, maxU);
        Utils.clamp(uv.y, uv.y, minV, maxV);
        sampleTexture(colorMinusTwo, uv, SAMPLER[0], textureFlags);
        multiply(colorMinusTwo, colorMinusTwo, weightTwo);
        add(outputColor, outputColor, colorMinusTwo);

        move(uv, uvMinusOne);
        Utils.clamp(uv.x, uv.x, minU, maxU);
        Utils.clamp(uv.y, uv.y, minV, maxV);
        sampleTexture(colorMinusOne, uv, SAMPLER[0], textureFlags);
        multiply(colorMinusOne, colorMinusOne, weightOne);
        add(outputColor, outputColor, colorMinusOne);

        move(uv, uvPlusOne);
        Utils.clamp(uv.x, uv.x, minU, maxU);
        Utils.clamp(uv.y, uv.y, minV, maxV);
        sampleTexture(colorPlusOne, uv, SAMPLER[0], textureFlags);
        multiply(colorPlusOne, colorPlusOne, weightOne);
        add(outputColor, outputColor, colorPlusOne);

        move(uv, uvPlusTwo);
        Utils.clamp(uv.x, uv.x, minU, maxU);
        Utils.clamp(uv.y, uv.y, minV, maxV);
        sampleTexture(colorPlusTwo, uv, SAMPLER[0], textureFlags);
        multiply(colorPlusTwo, colorPlusTwo, weightTwo);
        add(outputColor, outputColor, colorPlusTwo);

        move(OUTPUT, outputColor);
    }

    private function updateParameters():void {
        // algorithm described here:
        // http://rastergrid.com/blog/2010/09/efficient-gaussian-blur-with-linear-sampling/
        //
        // To run in constrained mode, we can only make 5 texture lookups in the fragment
        // shader. By making use of linear texture sampling, we can produce similar output
        // to what would be 9 lookups.

        _paramsDirty = false;

        var multiplier:Number, str:Number = _strengths[_pass];
        var i:int, count:int = 4;

        if(type == HORIZONTAL) {
            multiplier = _pixelWidth * str;

            for(i = 0; i < count; i++)
                _offsets[i] = _horizontalOffsets[i] * multiplier;
        }
        else {
            multiplier = _pixelHeight * str;

            for(i = 0; i < count; i++)
                _offsets[i] = _verticalOffsets[i] * multiplier;
        }

        //trace("str: " + str);
    }

    private function updateStrengths():void {
        _strengthsDirty = false;

        _strengths.length   = 0;
        var str:Number      = Math.min(_firstPassStrength, _strength);
        var sum:Number      = 0;

        while(sum + str < _strength) {
            _strengths[_strengths.length] = str;
            sum += str;
            str *= _strengthIncreaseRatio;
        }

        var diff:Number = _strength - sum;

        if(diff > 0 || _strengths.length == 0)
            _strengths[_strengths.length] = diff;

        _strengths.sort(function (a:Number, b:Number):Number { return b - a; });

        //trace("strengths: [" + _strengths + "], total: " + _strength);
    }
}
}

Debug messages removed

Debug messages removed


package dolly.data {

public class PropertyLevelCopyableClass {

	[Copyable]
	public static var staticProperty1:String = "Value of first-level static property 1.";

	public static var staticProperty2:String = "Value of first-level static property 2.";

	[Cloneable]
	private var _writableField1:String = "Value of first-level writable field.";

	[Cloneable]
	public var property1:String = "Value of first-level public property 1.";

	public var property2:String = "Value of first-level public property 2.";

	public function PropertyLevelCopyableClass() {
	}

	[Copyable]
	public function get writableField1():String {
		return _writableField1;
	}

	public function set writableField1(value:String):void {
		_writableField1 = value;
	}

	[Copyable]
	public function get readOnlyField1():String {
		return "Value of first-level read-only field.";
	}
}
}

package dolly.data {

public class PropertyLevelCopyableClass {

	[Copyable]
	public static var staticProperty1:String = "Value of first-level static property 1.";

	public static var staticProperty2:String = "Value of first-level static property 2.";

	[Copyable]
	private var _writableField1:String = "Value of first-level writable field.";

	[Copyable]
	public var property1:String = "Value of first-level public property 1.";

	public var property2:String = "Value of first-level public property 2.";

	public function PropertyLevelCopyableClass() {
	}

	[Copyable]
	public function get writableField1():String {
		return _writableField1;
	}

	public function set writableField1(value:String):void {
		_writableField1 = value;
	}

	[Copyable]
	public function get readOnlyField1():String {
		return "Value of first-level read-only field.";
	}
}
}

Fix stupid mistake with metadata names.

Fix stupid mistake with metadata names.


// vim: tabstop=4 shiftwidth=4

// Copyright (c) 2011 , Yang Bo All rights reserved.
//
// Author: Yang Bo (pop.atry@gmail.com)
//
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
package com.netease.protobuf {
	import flash.errors.IllegalOperationError
	import flash.utils.getDefinitionByName;
	import flash.utils.IDataInput
	/**
	 * @private
	 */
	public class BaseFieldDescriptor implements IFieldDescriptor {
		public var fullName:String
		protected var _name:String
		public final function get name():String {
			return _name
		}
		protected var tag:uint
		public final function get tagNumber():uint {
			return tag >>> 7
		}
		public function get type():Class {
			throw new IllegalOperationError("Not Implemented!")
		}
		public function readSingleField(input:IDataInput):* {
			throw new IllegalOperationError("Not Implemented!")
		}
		public function writeSingleField(output:WritingBuffer, value:*):void {
			throw new IllegalOperationError("Not Implemented!")
		}
		public function write(destination:WritingBuffer, source:Message):void {
			throw new IllegalOperationError("Not Implemented!")
		}
		private static const ACTIONSCRIPT_KEYWORDS:Object = {
			"as" : true,		"break" : true,		"case" : true,
			"catch" : true,		"class" : true,		"const" : true,
			"continue" : true,	"default" : true,	"delete" : true,
			"do" : true,		"else" : true,		"extends" : true,
			"false" : true,		"finally" : true,	"for" : true,
			"function" : true,	"if" : true,		"implements" : true,
			"import" : true,	"in" : true,		"instanceof" : true,
			"interface" : true,	"internal" : true,	"is" : true,
			"native" : true,	"new" : true,		"null" : true,
			"package" : true,	"private" : true,	"protected" : true,
			"public" : true,	"return" : true,	"super" : true,
			"switch" : true,	"this" : true,		"throw" : true,
			"to" : true,		"true" : true,		"try" : true,
			"typeof" : true,	"use" : true,		"var" : true,
			"void" : true,		"while" : true,		"with" : true
		}

		public function toString():String {
			return name
		}

		internal static function getExtensionByName(
				name:String):BaseFieldDescriptor {
			const fieldPosition:int = name.lastIndexOf('/')
			if (fieldPosition == -1) {
				return BaseFieldDescriptor(getDefinitionByName(name))
			} else {
				return getDefinitionByName(name.substring(0, fieldPosition))[
						name.substring(fieldPosition + 1)]
			}
		}
	}

}
function regexToUpperCase(matched:String, index:int, whole:String):String {
	return matched.charAt(1).toUpperCase()
}

// vim: tabstop=4 shiftwidth=4

// Copyright (c) 2011 , Yang Bo All rights reserved.
//
// Author: Yang Bo (pop.atry@gmail.com)
//
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
package com.netease.protobuf {
	import flash.errors.IllegalOperationError
	import flash.utils.getDefinitionByName;
	import flash.utils.IDataInput
	/**
	 * @private
	 */
	public class BaseFieldDescriptor implements IFieldDescriptor {
		public var fullName:String
		protected var _name:String
		public final function get name():String {
			return _name
		}
		protected var tag:uint
		public final function get tagNumber():uint {
			return tag >>> 3
		}
		public function get type():Class {
			throw new IllegalOperationError("Not Implemented!")
		}
		public function readSingleField(input:IDataInput):* {
			throw new IllegalOperationError("Not Implemented!")
		}
		public function writeSingleField(output:WritingBuffer, value:*):void {
			throw new IllegalOperationError("Not Implemented!")
		}
		public function write(destination:WritingBuffer, source:Message):void {
			throw new IllegalOperationError("Not Implemented!")
		}
		private static const ACTIONSCRIPT_KEYWORDS:Object = {
			"as" : true,		"break" : true,		"case" : true,
			"catch" : true,		"class" : true,		"const" : true,
			"continue" : true,	"default" : true,	"delete" : true,
			"do" : true,		"else" : true,		"extends" : true,
			"false" : true,		"finally" : true,	"for" : true,
			"function" : true,	"if" : true,		"implements" : true,
			"import" : true,	"in" : true,		"instanceof" : true,
			"interface" : true,	"internal" : true,	"is" : true,
			"native" : true,	"new" : true,		"null" : true,
			"package" : true,	"private" : true,	"protected" : true,
			"public" : true,	"return" : true,	"super" : true,
			"switch" : true,	"this" : true,		"throw" : true,
			"to" : true,		"true" : true,		"try" : true,
			"typeof" : true,	"use" : true,		"var" : true,
			"void" : true,		"while" : true,		"with" : true
		}

		public function toString():String {
			return name
		}

		internal static function getExtensionByName(
				name:String):BaseFieldDescriptor {
			const fieldPosition:int = name.lastIndexOf('/')
			if (fieldPosition == -1) {
				return BaseFieldDescriptor(getDefinitionByName(name))
			} else {
				return getDefinitionByName(name.substring(0, fieldPosition))[
						name.substring(fieldPosition + 1)]
			}
		}
	}

}
function regexToUpperCase(matched:String, index:int, whole:String):String {
	return matched.charAt(1).toUpperCase()
}

修复bug：tagID应该右移3位


package com.kemsky.support
{
    /**
     * Faster alternative to isNaN()
     * @private
     */
    public function isNaNFast(target:*):Boolean
    {
        return !(target <= 0) && !(target > 0);
    }

}

package com.kemsky.support
{
    /**
     * Faster alternative to isNaN()
     * Useless in fact, function call is more expensive than isNaN
     * @private
     */
    public function isNaNFast(target:*):Boolean
    {
        return !(target <= 0) && !(target > 0);
    }

}

replace isNaN

replace isNaN


package
{
	import flash.display.Graphics;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.TimerEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.utils.Timer;
	import flash.utils.getTimer;

	/**
	 * ...
	 * @author lizhi
	 */
	public class TestKLine extends Sprite
	{
		private var datas:Array = [];
		private var kline:Sprite = new Sprite;
		private var labelTF:TextField = new TextField;
		private var ox:Number = 80;
		private var ox2:Number = 200;
		private var oy:Number = 30;
		public function TestKLine()
		{
			CONFIG::js_only{
			SpriteFlexjs.autoSize = true;
			}
			stage.loaderInfo.parameters;
			labelTF.defaultTextFormat=new TextFormat("Courier New",24);
			labelTF.background = true;
			labelTF.backgroundColor = 0xdb5f4a;
			labelTF.textColor = 0xffffff;
			labelTF.autoSize = "left";
			stage.addEventListener(Event.RESIZE, resize);
			var loader:URLLoader = new URLLoader;
			loader.addEventListener(Event.COMPLETE, loader_complete_all);
			loader.addEventListener(IOErrorEvent.IO_ERROR, loader_ioError);
			loader.load(new URLRequest("http://121.43.100.114:9095/getAllMobilePrice.do?pcode=XTAG100G&v="+Math.random()));
			addChild(kline);
			kline.y = oy;
			//update();
		}

		private function loader_ioError(e:IOErrorEvent):void
		{
			trace(e);
			loader_complete_all(null);
		}

		private function timer_timer(e:TimerEvent):void
		{
			var loader:URLLoader = new URLLoader;
			loader.addEventListener(Event.COMPLETE, loader_complete);
			loader.load(new URLRequest("http://121.43.100.114:9095/getNewMobilePrice.do?pcode=XTAG100G&v="+Math.random()));
			//todo del
			//addData(10*Math.random());
			//update();
		}
		private function loader_complete_all(e:Event):void
		{
			if(e)
			var loader:URLLoader = e.currentTarget as URLLoader;
			if (loader){
				var obj:Object = JSON.parse(loader.data + "");
				for each(var o:Object in obj["content"]){
					var d:Number = o["price"];
					addData(d);
				}
				update();
			}
			var timer:Timer = new Timer(5000);
			timer.addEventListener(TimerEvent.TIMER, timer_timer);
			timer.start();
		}
		private function loader_complete(e:Event):void
		{
			var loader:URLLoader = e.currentTarget as URLLoader;
			var obj:Object = JSON.parse(loader.data+"");
			var d:Number = obj["content"]["price"];
			addData(d);
			update();
		}

		private function addData(data:Number):void{
			datas.unshift(data);
			if (datas.length > 120){
				datas.length = 120;
			}
		}

		private function resize(e:Event):void
		{
			update();
		}

		private function update():void{
			var min:Number = 1000;
			var max:Number =-1000;
			for each(var d:Number in datas){
				if (d<min){
					min = d;
				}
				if (d > max){
					max = d;
				}
			}

			var w:Number = stage.stageWidth;
			var w2:Number = (w - ox2) / 120;

			kline.removeChildren();
			kline.graphics.clear();
			kline.graphics.lineStyle(0,0x555555);
			//trace(min, max);
			var s:Number = 0.05;
			while (true){
				var minV:Number = Math.floor(min / s);// * s;
				var maxV:Number = Math.ceil(max / s);// * s;
				var numline:int = maxV - minV;
				if (numline < 4){
					for (; numline < 3;numline++ ){
						if ((numline%2)==0){
							minV -= 1;
						}else{
							maxV += 1;
						}
					}

					var h:Number =  (stage.stageHeight - 2 * oy) / numline;
					for (var i:int = 0; i <= numline; i++ ){
						var y:Number = getY(minV + i, minV, maxV, s, h);
						drawDashLine(kline.graphics, 0, y, w-ox, y,2);
						var tf:TextField = new TextField;
						tf.defaultTextFormat=new TextFormat("Courier New",24);
						tf.autoSize = "left";
						kline.addChild(tf);
						tf.text = ""+((minV + i)*s).toFixed(2);
						tf.y = y-tf.height/2;
						tf.x = w-ox;
					}
					break;
				}
				s += .5;
			}
			kline.graphics.lineStyle(0, 0xdb5f4a);
			for (i = 0; i < datas.length; i++ ){
				d = datas[i];
				y = getY(d/s, minV, maxV, s, h);
				var x:Number = w - i * w2-ox2;
				if(i==0){
					kline.graphics.moveTo(x + ox2-ox, y);
					kline.addChild(labelTF);
					labelTF.y = y - labelTF.height / 2;
					labelTF.x = w - ox;
					labelTF.text = d.toFixed(2) + "";
				}
				kline.graphics.lineTo(x, y);
				if (x < 0){
					break;
				}
			}
		}

		private function getY(v:Number, min:Number, max:Number,s:Number,h:Number):Number{
			return (max - v)  * h;
		}

		private function drawDashLine(ctx:Graphics, x1:Number, y1:Number, x2:Number, y2:Number, dashLen:Number=5):void
		{
			var xpos:Number = x2 - x1;//得到横向的高度;
			var ypos:Number = y2 - y1; //得到纵向的高度;
			var numDashes:Number = Math.floor(Math.sqrt(xpos * xpos + ypos * ypos) / dashLen);
			//利用正切获取斜边的长度除以虚线长度，得到要分为多少段;
			for (var i:int = 0; i < numDashes; i++)
			{
				if (i % 2 === 0)
				{
					ctx.moveTo(x1 + (xpos / numDashes) * i, y1 + (ypos / numDashes) * i);
						//有了横向宽度和多少段，得出每一段是多长，起点 + 每段长度 * i = 要绘制的起点；
				}
				else
				{
					ctx.lineTo(x1 + (xpos / numDashes) * i, y1 + (ypos / numDashes) * i);
				}
			}
		}

	}

}

package
{
	import flash.display.Graphics;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.TimerEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.utils.Timer;
	import flash.utils.getTimer;

	/**
	 * ...
	 * @author lizhi
	 */
	public class TestKLine extends Sprite
	{
		private var datas:Array = [];
		private var kline:Sprite = new Sprite;
		private var labelTF:TextField = new TextField;
		private var ox:Number = 80;
		private var ox2:Number = 200;
		private var oy:Number = 30;
		public function TestKLine()
		{
			CONFIG::js_only{
			SpriteFlexjs.autoSize = true;
			}
			stage.loaderInfo.parameters;
			labelTF.defaultTextFormat=new TextFormat("Courier New",24);
			labelTF.background = true;
			labelTF.backgroundColor = 0xdb5f4a;
			labelTF.textColor = 0xffffff;
			labelTF.autoSize = "left";
			stage.addEventListener(Event.RESIZE, resize);
			var loader:URLLoader = new URLLoader;
			loader.addEventListener(Event.COMPLETE, loader_complete_all);
			loader.addEventListener(IOErrorEvent.IO_ERROR, loader_ioError);
			loader.load(new URLRequest("http://121.43.100.114:9095/getAllMobilePrice.do?pcode=XTAG100G&v="+Math.random()));
			addChild(kline);
			kline.y = oy;
			//update();
		}

		private function loader_ioError(e:IOErrorEvent):void
		{
			trace(e);
			loader_complete_all(null);
		}

		private function timer_timer(e:TimerEvent):void
		{
			var loader:URLLoader = new URLLoader;
			loader.addEventListener(Event.COMPLETE, loader_complete);
			loader.load(new URLRequest("http://121.43.100.114:9095/getNewMobilePrice.do?pcode=XTAG100G&v="+Math.random()));
			//todo del
			//addData(10*Math.random());
			//update();
		}
		private function loader_complete_all(e:Event):void
		{
			if(e)
			var loader:URLLoader = e.currentTarget as URLLoader;
			if (loader){
				var obj:Object = JSON.parse(loader.data + "");
				for each(var o:Object in obj["content"]){
					var d:Number = o["price"];
					addData(d);
				}
				update();
			}
			var timer:Timer = new Timer(5000);
			timer.addEventListener(TimerEvent.TIMER, timer_timer);
			timer.start();
		}
		private function loader_complete(e:Event):void
		{
			var loader:URLLoader = e.currentTarget as URLLoader;
			var obj:Object = JSON.parse(loader.data+"");
			var d:Number = obj["content"]["price"];
			addData(d);
			update();
		}

		private function addData(data:Number):void{
			datas.unshift(data);
			if (datas.length > 120){
				datas.length = 120;
			}
		}

		private function resize(e:Event):void
		{
			update();
		}

		private function update():void{
			var min:Number = 1000;
			var max:Number =-1000;
			for each(var d:Number in datas){
				if (d<min){
					min = d;
				}
				if (d > max){
					max = d;
				}
			}

			var w:Number = stage.stageWidth;
			var w2:Number = (w - ox2) / 120;

			kline.removeChildren();
			kline.graphics.clear();
			kline.graphics.lineStyle(0,0x555555);
			//trace(min, max);
			var s:Number = 0.05;
			while (true){
				var minV:Number = Math.floor(min / s);// * s;
				var maxV:Number = Math.ceil(max / s);// * s;
				var numline:int = maxV - minV;
				if (numline < 4){
					for (; numline < 3;numline++ ){
						if ((numline%2)==0){
							minV -= 1;
						}else{
							maxV += 1;
						}
					}

					var h:Number =  int((stage.stageHeight - 2 * oy) / numline);
					for (var i:int = 0; i <= numline; i++ ){
						var y:Number = getY(minV + i, minV, maxV, s, h);
						drawDashLine(kline.graphics, 0, y, w-ox, y,2);
						var tf:TextField = new TextField;
						tf.defaultTextFormat=new TextFormat("Courier New",24);
						tf.autoSize = "left";
						kline.addChild(tf);
						tf.text = ""+((minV + i)*s).toFixed(2);
						tf.y = y-tf.height/2;
						tf.x = w-ox;
					}
					break;
				}
				s += .5;
			}
			kline.graphics.lineStyle(0, 0xdb5f4a);
			for (i = 0; i < datas.length; i++ ){
				d = datas[i];
				y = getY(d/s, minV, maxV, s, h);
				var x:Number = w - i * w2-ox2;
				if(i==0){
					kline.graphics.moveTo(x + ox2-ox, y);
					kline.addChild(labelTF);
					labelTF.y = y - labelTF.height / 2;
					labelTF.x = w - ox;
					labelTF.text = d.toFixed(2) + "";
				}
				kline.graphics.lineTo(x, y);
				if (x < 0){
					break;
				}
			}
		}

		private function getY(v:Number, min:Number, max:Number,s:Number,h:Number):Number{
			return Math.round((max - v)  * h)+.5;
		}

		private function drawDashLine(ctx:Graphics, x1:Number, y1:Number, x2:Number, y2:Number, dashLen:Number=5):void
		{
			var xpos:Number = x2 - x1;//得到横向的高度;
			var ypos:Number = y2 - y1; //得到纵向的高度;
			var numDashes:Number = Math.floor(Math.sqrt(xpos * xpos + ypos * ypos) / dashLen);
			//利用正切获取斜边的长度除以虚线长度，得到要分为多少段;
			for (var i:int = 0; i < numDashes; i++)
			{
				if (i % 2 === 0)
				{
					ctx.moveTo(x1 + (xpos / numDashes) * i, y1 + (ypos / numDashes) * i);
						//有了横向宽度和多少段，得出每一段是多长，起点 + 每段长度 * i = 要绘制的起点；
				}
				else
				{
					ctx.lineTo(x1 + (xpos / numDashes) * i, y1 + (ypos / numDashes) * i);
				}
			}
		}

	}

}

test kline update

test kline update


/* Vivified
 * Copyright (C) 2007 Benjamin Otte <otte@gnome.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA  02110-1301  USA
 */

/*** general objects ***/

Wrap = function () {};
Wrap.prototype = {};
Wrap.prototype.toString = Native.wrap_toString;

Frame = function () extends Wrap {};
Frame.prototype = new Wrap ();
Frame.prototype.addProperty ("code", Native.frame_code_get, null);
Frame.prototype.addProperty ("name", Native.frame_name_get, null);
Frame.prototype.addProperty ("next", Native.frame_next_get, null);

/*** breakpoints ***/

Breakpoint = function () extends Native.Breakpoint {
  super ();
  Breakpoint.list.push (this);
};
Breakpoint.list = new Array ();
Breakpoint.prototype.addProperty ("active", Native.breakpoint_active_get, Native.breakpoint_active_set);

/*** information about the player ***/

Player = {};
Player.addProperty ("frame", Native.player_frame_get, null);

/*** commands available for debugging ***/

Commands = new Object ();
Commands.print = Native.print;
Commands.error = Native.error;
Commands.r = Native.run;
Commands.run = Native.run;
Commands.halt = Native.stop;
Commands.stop = Native.stop;
Commands.s = Native.step;
Commands.step = Native.step;
Commands.reset = Native.reset;
Commands.restart = function () {
  Commands.reset ();
  Commands.run ();
};
Commands.quit = Native.quit;
/* can't use "break" as a function name, it's a keyword in JS */
Commands.add = function (name) {
  if (name == undefined) {
    Commands.error ("add command requires a function name");
    return undefined;
  }
  var ret = new Breakpoint ();
  ret.onStartFrame = function (frame) {
    if (frame.name != name)
      return false;

    Commands.print ("Breakpoint: function " + name + " called");
    Commands.print ("  " + frame);
    return true;
  };
  ret.toString = function () {
    return "function call " + name;
  };
};
Commands.list = function () {
  var a = Breakpoint.list;
  var i;
  for (i = 0; i < a.length; i++) {
    Commands.print (i + ": " + a[i]);
  }
};
Commands.del = function (id) {
  var a = Breakpoint.list;
  if (id == undefined) {
    while (a[0])
      Commands.del (0);
  }
  var b = a[id];
  a.splice (id, 1);
  b.active = false;
};
Commands.delete = Commands.del;

/* Vivified
 * Copyright (C) 2007 Benjamin Otte <otte@gnome.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA  02110-1301  USA
 */

/*** general objects ***/

Wrap = function () {};
Wrap.prototype = {};
Wrap.prototype.toString = Native.wrap_toString;

Frame = function () extends Wrap {};
Frame.prototype = new Wrap ();
Frame.prototype.addProperty ("code", Native.frame_code_get, null);
Frame.prototype.addProperty ("name", Native.frame_name_get, null);
Frame.prototype.addProperty ("next", Native.frame_next_get, null);

/*** breakpoints ***/

Breakpoint = function () extends Native.Breakpoint {
  super ();
  Breakpoint.list.push (this);
};
Breakpoint.list = new Array ();
Breakpoint.prototype.addProperty ("active", Native.breakpoint_active_get, Native.breakpoint_active_set);

/*** information about the player ***/

Player = {};
Player.addProperty ("frame", Native.player_frame_get, null);

/*** commands available for debugging ***/

Commands = new Object ();
Commands.print = Native.print;
Commands.error = Native.error;
Commands.r = Native.run;
Commands.run = Native.run;
Commands.halt = Native.stop;
Commands.stop = Native.stop;
Commands.s = Native.step;
Commands.step = Native.step;
Commands.reset = Native.reset;
Commands.restart = function () {
  Commands.reset ();
  Commands.run ();
};
Commands.quit = Native.quit;
/* can't use "break" as a function name, it's a keyword in JS */
Commands.add = function (name) {
  if (name == undefined) {
    Commands.error ("add command requires a function name");
    return undefined;
  }
  var ret = new Breakpoint ();
  ret.onStartFrame = function (frame) {
    if (frame.name != name)
      return false;

    Commands.print ("Breakpoint: function " + name + " called");
    Commands.print ("  " + frame);
    return true;
  };
  ret.toString = function () {
    return "function call " + name;
  };
  return ret;
};
Commands.list = function () {
  var a = Breakpoint.list;
  var i;
  for (i = 0; i < a.length; i++) {
    Commands.print (i + ": " + a[i]);
  }
};
Commands.del = function (id) {
  var a = Breakpoint.list;
  if (id == undefined) {
    while (a[0])
      Commands.del (0);
  }
  var b = a[id];
  a.splice (id, 1);
  b.active = false;
};
Commands.delete = Commands.del;

return the breakpoint that was added from Commands.add()


package com.threerings.util {

import flash.net.URLRequest;
//import flash.net.navigateToURL; // function import

public class NetUtil
{
    /**
     * Convenience method to load a web page in the browser window without
     * having to worry about SecurityErrors in various conditions.
     *
     * @return true if the url was unable to be loaded.
     */
    public static function navigateToURL (
            url :String, preferSameWindowOrTab :Boolean = true) :Boolean
    {
        var ureq :URLRequest = new URLRequest(url);
        if (preferSameWindowOrTab) {
            try {
                flash.net.navigateToURL(ureq, "_self");
                return true;
            } catch (err :SecurityError) {
                // ignore; fall back to using a blank window, below...
            }
        }

        // open in a blank window
        try {
            flash.net.navigateToURL(ureq);
            return true;
        } catch (err :SecurityError) {
            Log.getLog(NetUtil).warning(
                "Unable to navigate to URL [e=" + err + "].");
        }

        return false; // failure!
    }
}
}

package com.threerings.util {

import flash.net.URLRequest;
//import flash.net.navigateToURL; // function import

public class NetUtil
{
    /**
     * Convenience method to load a web page in the browser window without
     * having to worry about SecurityErrors in various conditions.
     *
     * @return true if the url was able to be loaded.
     */
    public static function navigateToURL (
            url :String, preferSameWindowOrTab :Boolean = true) :Boolean
    {
        var ureq :URLRequest = new URLRequest(url);
        if (preferSameWindowOrTab) {
            try {
                flash.net.navigateToURL(ureq, "_self");
                return true;
            } catch (err :SecurityError) {
                // ignore; fall back to using a blank window, below...
            }
        }

        // open in a blank window
        try {
            flash.net.navigateToURL(ureq);
            return true;
        } catch (err :SecurityError) {
            Log.getLog(NetUtil).warning(
                "Unable to navigate to URL [e=" + err + "].");
        }

        return false; // failure!
    }
}
}

fix comment to reflect reality

fix comment to reflect reality

git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4590 542714f4-19e9-0310-aa3c-eee0fc999fb1