<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>www.makeyourflashgame.com</title>
	<atom:link href="http://blog.makeyourflashgame.com/feed" rel="self" type="application/rss+xml" />
	<link>http://blog.makeyourflashgame.com</link>
	<description>where creative people can create flash games together...</description>
	<lastBuildDate>Fri, 27 Aug 2010 07:40:06 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Generate PBE source code (as3)  for animation preview</title>
		<link>http://blog.makeyourflashgame.com/479/generate-pbe-source-code-as3-for-animation-preview.html</link>
		<comments>http://blog.makeyourflashgame.com/479/generate-pbe-source-code-as3-for-animation-preview.html#comments</comments>
		<pubDate>Mon, 23 Aug 2010 21:24:25 +0000</pubDate>
		<dc:creator>mas</dc:creator>
				<category><![CDATA[makeyourflashgame.com]]></category>
		<category><![CDATA[PBEngine]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[website]]></category>

		<guid isPermaLink="false">http://blog.makeyourflashgame.com/?p=479</guid>
		<description><![CDATA[To make the life of an actionscript developer , that works with the open source Push Button Flash Game Engine, just a little better, makeyourflashgame.com now offers PBE source code generation.
]]></description>
			<content:encoded><![CDATA[<p>To make the life of an actionscript developer , that works with the open source Push Button Flash Game Engine, just a little better, makeyourflashgame.com now offers <b> PBE source code generation </b>.</p>
<p>At this time only source code for the workspace Animation preview can be generated, but we will expand this when more content can be created.</p>
<p>To generate the content of an animation,<strong> go to the animation section </strong>in your makeyourflashgame.com workspace.</p>
<p><strong><span style="color: #ff5522;">!IMPORTANT</span></strong> <strong>Workspace</strong> is still in BETA, so <strong>be sure to <a href="http://community.makeyourflashgame.com/viewtopic.php?f=33&amp;t=45">join the beta program</a></strong>.</p>
<p><a href="http://content.makeyourflashgame.com/images/screenshots/generate-pbe-code/s-1.png"><img class="aligncenter" title="Animations workspace" src="http://content.makeyourflashgame.com/images/screenshots/generate-pbe-code/s-1.png" alt="Animations workspace" width="550" height="300" /></a></p>
<p>When you edit your animation you will find an button [<strong>Generate source code</strong>] in your animation&#8217;s settings.</p>
<p><a href="http://content.makeyourflashgame.com/images/screenshots/generate-pbe-code/s-2.png"><img class="aligncenter" title="Edit animation" src="http://content.makeyourflashgame.com/images/screenshots/generate-pbe-code/s-2.png" alt="Edit animation" width="550" height="300" /></a></p>
<p>When you choose to <b>generate the Push Button Engine source code </b> you can first specify some generation settings</p>
<p><a href="http://content.makeyourflashgame.com/images/screenshots/generate-pbe-code/s-3.png"><img title="Generation settings" src="http://content.makeyourflashgame.com/images/screenshots/generate-pbe-code/s-3.png" alt="Generation settings" width="550" height="300" /></a></p>
<ul>
<li><strong>Application<br />
</strong>Application class name for the generated PBE source code.</li>
<li><strong>Resources (embed or load)</strong><br />
Source is generated that will embed the resources (using ResourceBundle) or will load the resources dynamicly (using BulkLoaderResourceProvider ) .</li>
<li><strong>Resource location<br />
</strong>You can specify what is the path/uri to the resources.</li>
<li><strong>Mouse control<br />
</strong>When set to true the source is generated that lets your animation rotate (normal sprite sheet animation) or change direction (directional sprite sheet animation).<br />
The mouse SpriteRenderer is a dynamicly (in-memory) generated image and provided using its own &#8211; IResourceProvider &#8211; class</li>
<li><strong>Status</strong><br />
When set to true , source for a status label is generated</li>
</ul>
<p>Just press [<b>Generate</b>] and you have your code!</p>
<p><a href="http://content.makeyourflashgame.com/images/screenshots/generate-pbe-code/s-4.png"><img title="Generated PBE code" src="http://content.makeyourflashgame.com/images/screenshots/generate-pbe-code/s-4.png" alt="Generated PBE code" width="550" height="300" /></a></p>
<p>When the source display box is scrolled in top position you will find some controls that let you copy the source to clipboard. It will than be easy to create a new application file in you favorite  actionscript IDE ( Flashbuilder would be my choice ).</p>
<p>Needless to say that <b>you should</b> have some knowledge from PBE and <b>have the PBE source installed in your development environment</b>. The resources should be put there by yourself (if embedded) or on a downloadable position in case of synamic loading, as well.</p>
<p>The generated source code from the animation example from this post looks like this :</p>
<pre class="brush: as3;">
// ------------------------------------------------------------------
// http://www.makeyourglashgame.com
// Generated by user [mas] on August 23, 2010, 3:31 pm
// Animation 'walking blue man'
// ------------------------------------------------------------------
package
{

	import com.pblabs.engine.PBE;
	import com.pblabs.rendering2D.ui.SceneView;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.filters.DropShadowFilter;
	import flash.text.TextField;
	import flash.ui.Mouse;

	[SWF(width="136", height="148", framerate="60")]
	public class Application extends Sprite
	{
		// ------------------------------------------------------------------
		// public methods
		// ------------------------------------------------------------------
		public function Application()
		{
			super();
			// initialize the application
			initApplication();
			// create resources
			new Resources(createEntities);
		}
		// ------------------------------------------------------------------
		// private methods
		// ------------------------------------------------------------------
		private function initApplication():void
		{
			// create background bitmap
			var bmd:BitmapData = new BitmapData(136,148,false,0);
			this.addChild(new Bitmap(bmd));

			// initialize game engine
			initEngine();

			// add status text field
			tfStatus = new TextField();
			tfStatus.x = 2; tfStatus.y = 2; tfStatus.width = width-4;
			tfStatus.height = 20;
			tfStatus.text="";
			tfStatus.textColor = 0xffffff;
			tfStatus.filters = [ new DropShadowFilter(0,45,0,1,2,2,8) ];
			this.addChild(tfStatus);

			Mouse.hide();
		}
		private function initEngine():void
		{
			// Start up Push Button Engine
			if (!PBE.started)
				PBE.startup(this);
			// Set up a simple PBE scene
			PBE.initializeScene(new SceneView());
		}
		private function createEntities():void
		{
			// create spritesheet (SpriteSheetComponent) for this animation
			new SpriteSheet("walking blue man",
				{
					cols : 15,
					rows : 8,
					frameCount : 120,
					directionsPerFrame : 8,
					filename : "assets/_myfg_spritesheet_245.png"
				});
			// create the animating sprite (SpriteRenderer) for this animation
			animation = new AnimatingSprite("walking blue man",
				{
					duration : 1,
					animationType : "L",
					frameCount : 120,
					loop : true,
					directionsPerFrame : 8,
					startDirection : "D",
					directionRotation : "CL",
					spriteSheet : "walking blue man"
				});
 			// create mouse cursor
			new RotatingMouseCursor(mouseHandler);
		}
		private function mouseHandler(event:MouseEvent):void
		{
			animation.mouseHandler(event);
			tfStatus.text = "Direction  = "+animation.direction;
		}
		// ------------------------------------------------------------------
		// private and protected variables
		// ------------------------------------------------------------------
		private var animation:AnimatingSprite;
		private var tfStatus:TextField;
	}
}

// ------------------------------------------------------------------------
// Internal classes
// ------------------------------------------------------------------------

import com.pblabs.animation.Tween;
import com.pblabs.engine.PBE;
import com.pblabs.engine.entity.EntityComponent;
import com.pblabs.engine.entity.IEntity;
import com.pblabs.engine.entity.PropertyReference;
import com.pblabs.engine.resource.ImageResource;
import com.pblabs.engine.resource.Resource;
import com.pblabs.engine.resource.ResourceBundle;
import com.pblabs.engine.resource.provider.IResourceProvider;
import com.pblabs.rendering2D.DisplayObjectRenderer;
import com.pblabs.rendering2D.SpriteRenderer;
import com.pblabs.rendering2D.SpriteSheetRenderer;
import com.pblabs.rendering2D.spritesheet.CellCountDivider;
import com.pblabs.rendering2D.spritesheet.SpriteSheetComponent;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.filters.DropShadowFilter;
import flash.geom.Point;

class Resources extends ResourceBundle
{
	[Embed(source="assets/_myfg_spritesheet_245.png")]
	public var res1:Class;

	public function Resources(callWhenReady:Function)
	{
		super();
		callWhenReady();
	}
}
class SpriteSheet extends SpriteSheetComponent
{
	// ------------------------------------------------------------------
	// public methods
	// ------------------------------------------------------------------
	public function SpriteSheet(name:String , props:Object)
	{
		super();

		this.props = props;

		// By assigning the imageFilename attribute, the image will be automaticly loaded
		imageFilename = props.filename;		

		// Create a CellCountDivider to specify the number of columns and rows of our spritesheet
		var spriteSheetDivider:CellCountDivider = new CellCountDivider();
		spriteSheetDivider.xCount = props.cols;
		spriteSheetDivider.yCount = props.rows;

		// Hook up the SpriteSheetDivider
		divider = spriteSheetDivider;
		frameCount = props.frameCount;

		// if this spritesheet has multiple direction information the number of directions has to be set
		if (props.directionsPerFrame!=null)
		  directionsPerFrame = props.directionsPerFrame;		

		// add this spritesheet to the spritesheet repository
		SpriteSheet.add(this, name);
	}
	public static function lookup(name:String):SpriteSheet
	{
		entity = PBE.lookupEntity("spritesheets");
		if (entity != null)
			return (entity.lookupComponentByName(name) as SpriteSheet);
		else
			return null;
	}
	// ------------------------------------------------------------------
	// private methods
	// ------------------------------------------------------------------
	private static function add(spritesheet:SpriteSheet, name:String):void
	{
		entity = PBE.lookupEntity("spritesheets");
		if (entity == null)
		{
			entity = PBE.allocateEntity();
			entity.initialize("spritesheets");
		}
		entity.addComponent( spritesheet, name );
	}

	// ------------------------------------------------------------------
	// private and protected attributes
	// ------------------------------------------------------------------
	private static var entity:IEntity;
	private var props:Object;
}
class DirectionComponent extends EntityComponent
{
	public function get direction():Number
	{
		return _direction;
	}

	public function set direction(value:Number):void
	{
		_direction = value;
	}

	public function screenToDirection(screenPoint:Point):void
	{
		// transform screen mouse coordinates to world coordinates
		var worldPoint:Point = PBE.scene.transformScreenToWorld(screenPoint);
		// calculate the angle between the mouse world coordinates and the horizontal axes
		var rotationAngle:Number = Math.round((Math.atan2( worldPoint.y - render.y, worldPoint.x - render.x) * 180 ) / Math.PI);
		// display status label
		switch(orientation)
		{
			case "U":
				rotationAngle+=90;
				break;
			case "D":
				rotationAngle-=90;
				break
			case "L":
				rotationAngle+=180;
				break
		}
		if (rotation == "CC")
			rotationAngle*=-1;
		while (rotationAngle < 0) rotationAngle+=360;
		direction = rotationAngle;
	}

	public function DirectionComponent(render:DisplayObjectRenderer, orientation:String, rotation:String)
	{
		this.orientation = orientation;
		this.rotation = rotation;
		this.render = render;
		super();
	}

	private var _direction:Number = 0;
	private var orientation:String;
	private var rotation:String;
	private var render:DisplayObjectRenderer;
}
class AnimatingSprite extends Object
{
	// ------------------------------------------------------------------
	// public methods
	// ------------------------------------------------------------------
	public function AnimatingSprite(name:String , props:Object)
	{
		this.props = props;

		entity = PBE.allocateEntity();
		entity.initialize(name);

		// Create a sprite render component to display our animation
		render = new SpriteSheetRenderer();

		// assign the scene so this animatied sprite will we drawn.
		render.scene = PBE.scene;

		// Assign the spritesheet to the sprite
		if (props.spriteSheet is String)
			render.spriteSheet = SpriteSheet.lookup(props.spriteSheet);
		else
			render.spriteSheet = props.spriteSheet;

		render.alpha = 0;
		render.rotation = 0;

		render.directionReference = new PropertyReference("@direction.direction");
		entity.addComponent( directionComponent = new DirectionComponent(render, props.startDirection, props.directionRotation), "direction" );
		var target:Number = (props.frameCount/props.directionsPerFrame)-0.001;

		// Add our render component to the Animated Sprite Entity
		entity.addComponent( render, "render" );

		// create tween for the spriteIndex animation
		new Tween(entity,"@render.spriteIndex",props.duration,0,target,null,null,0,
			(props.animationType == "P")?true:false,(props.loop)?-1:1);						

		// tween render alpha from 0 to 1 so we can avoid strange positioning effects when PBE is initializing.
		new Tween(entity,render,0.1,
			{ alpha : 0 }, { alpha : 1 },null,null,0.05);
	}

	public function get rotation():Number
	{
		return render.rotation;
	}

	public function set rotation(value:Number):void
	{
		render.rotation = value;
	}

	public function get direction():Number
	{
		if (directionComponent!=null)
			return directionComponent.direction;
		return 0;
	}

	public function set direction(value:Number):void
	{
		if (directionComponent!=null)
			directionComponent.direction = value;
	}		

	public function mouseHandler(event:MouseEvent):void
	{
		if (event.buttonDown)
		{

			directionComponent.screenToDirection(new  Point(event.stageX,event.stageY));
		}
	}	

	// ------------------------------------------------------------------
	// private and protected attributes
	// ------------------------------------------------------------------
	private var entity:IEntity;
	private var render:SpriteSheetRenderer;
	private var props:Object;
	private var directionComponent:DirectionComponent;
}
class RotatingMouseCursor extends Object implements IResourceProvider
{
	// ------------------------------------------------------------------
	// public methods
	// ------------------------------------------------------------------
	public function RotatingMouseCursor(customMouseHandler:Function = null)
	{
		// register this class as an resource provider
		PBE.resourceManager.registerResourceProvider(this);
		this.customMouseHandler = customMouseHandler;

		// create mouse cursor entity
		entity = PBE.allocateEntity();
		entity.initialize("mouseCursor");

		// create the PBE resource
		mouseResource = new ImageResource();
		mouseResource.initialize(createBitmap());

		// create spriteRenderer component for the mousecursor
		createRenderer();

		PBE.mainStage.addEventListener(Event.MOUSE_LEAVE, mouseLeave);
		PBE.mainStage.addEventListener(MouseEvent.MOUSE_MOVE, mouseHandler);
	}

	public function isResourceKnown(uri:String, type:Class):Boolean
	{
		if (uri == "mouseCursor" &#038;&#038; type==ImageResource)
			return true;
		return false;
	}

	/**
	 * This method is called when the ResourceManager requests a known
	 * resource from a ResourceProvider
	 */
	public function getResource(uri:String, type:Class, forceReload:Boolean = false):Resource
	{
		if (uri == "mouseCursor" &#038;&#038; type==ImageResource)
			return mouseResource;
		return null;
	}

	// ------------------------------------------------------------------
	// private methods
	// ------------------------------------------------------------------
	private function createBitmap():Bitmap
	{
		// create mouse pointer bitmap
		var bitmapData:BitmapData = new BitmapData(17,19,true,0);
		var sy:int = 3;
		var ey:int = 15;
		for (var x:int = 3; x&lt;15; x++)
		{
			for (var y:int = sy; y&lt;ey; y++)
			{
				bitmapData.setPixel32(x,y,0xffffffff);
			}
			sy+=1; ey-=1;
		}
		bitmapData.applyFilter(bitmapData,bitmapData.rect,new Point(0,0),
			new DropShadowFilter(0,45,0,1,2,2,8));
		return new Bitmap(bitmapData);
	}

	private function createRenderer():void
	{
		render = new SpriteRenderer();
		render.scene = PBE.scene;
		render.fileName = "mouseCursor";
		render.alpha = 0;
		entity.addComponent(render,"render");
	}

	private function mouseLeave(event:Event):void
	{
		render.alpha = 0;
	}

	private function mouseHandler(event:MouseEvent):void
	{
		if (render.alpha==0) render.alpha = 1;
		// transform screen mouse coordinates to world coordinates
		var worldPoint:Point = PBE.scene.transformScreenToWorld(new  Point(event.stageX,event.stageY));
		// calculate the angle between the mouse world coordinates and the horizontal axes
		var rotationAngle:Number;
		if (centerObject==null)
			rotationAngle = Math.round((Math.atan2( worldPoint.y, worldPoint.x) * 180 ) / Math.PI);
		else
		  	rotationAngle = Math.round((Math.atan2( worldPoint.y - centerObject.y, worldPoint.x - centerObject.x) * 180 ) / Math.PI);

		render.rotation = rotationAngle;
		render.position = worldPoint; 

		if (customMouseHandler!=null) customMouseHandler(event);
	}

	// ------------------------------------------------------------------
	// private and protected attributes
	// ------------------------------------------------------------------
	private var mouseResource:ImageResource;
	private var entity:IEntity;
	private var render:SpriteRenderer;
	private var centerObject:DisplayObjectRenderer = null;
	private var customMouseHandler:Function = null;
}
</pre>
<p><strong><span style="color: #ff5522;">!IMPORTANT</span></strong> <strong>Workspace</strong> is still in BETA, so <strong>be sure to <a href="http://community.makeyourflashgame.com/viewtopic.php?f=33&amp;t=45">join the beta program</a></strong>.</p>
<p>Did you know that using the makeyourflashgame.com website you can easily <b>create an animation's spritesheet from a number of frames</b>? Read it in <a href="http://blog.makeyourflashgame.com/465/generate-a-sprite-sheet-from-single-frames-using-makeyourflashgame-com.html"> this post</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.makeyourflashgame.com/479/generate-pbe-source-code-as3-for-animation-preview.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Create a sprite sheet from single frames</title>
		<link>http://blog.makeyourflashgame.com/465/generate-a-sprite-sheet-from-single-frames.html</link>
		<comments>http://blog.makeyourflashgame.com/465/generate-a-sprite-sheet-from-single-frames.html#comments</comments>
		<pubDate>Mon, 23 Aug 2010 14:25:34 +0000</pubDate>
		<dc:creator>mas</dc:creator>
				<category><![CDATA[makeyourflashgame.com]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[website]]></category>

		<guid isPermaLink="false">http://blog.makeyourflashgame.com/?p=465</guid>
		<description><![CDATA[Have you 3D generated, or drawn, lots of single frame images? Are you wondering how the #$?%# you can create a nice sprite sheet with those images? You don't need to seek any further ... you have found the solution now ...]]></description>
			<content:encoded><![CDATA[<p>Have you 3D generated, or drawn, lots of single frame images? Are you wondering how the #$?%# you can create a nice sprite sheet with those images?</p>
<p>The only usefull (windows) tool I could find on the net is <b>SpriteStrip Composer</b>, a .NET application (<a href="http://dl.qj.net/xbox-360/homebrew-application/xna-sitestrip-composer-tool.html">download it here</a>) developed by a member for the XNA framework. I does some good work but, when you want to specify the column count you want to set for your sprite sheet, you will be dissapointed.</p>
<p>So .. seeking an online tool ? Well &#8230; seek no further &#8230;</p>
<p>Makeyourflashgame.com just finished <b>a tool that can merge a range of single frames into a single spritesheet</b>. That spritesheet can be used in your games and with engines like for example the open source Push Button Flash game engine.</p>
<p><b><span style="color:#ff5522">!IMPORTANT</span></b> <b>Workspace</b> is still in BETA, so <b>be sure to <a href="http://community.makeyourflashgame.com/viewtopic.php?f=33&#038;t=45">join the beta program</a></b>.</p>
<p>You will find this tool in your makeyourflashgame.com workspace under &#8216;sprite sheets&#8217; and it is called [<b>create new sprite sheet</b>].</p>
<p><a href="http://content.makeyourflashgame.com/images/screenshots/create-spritesheet/s-1.png"><img alt="Create sprite sheet in workspace" src="http://content.makeyourflashgame.com/images/screenshots/create-spritesheet/s-1.png" title="Create sprite sheet in workspace" class="aligncenter" width="550" height="300" /></a></p>
<p>After clicking the [<b>create new sprite sheet</b>] button, you can select multiple frame images for upload. In the example , I am creating a &#8216;multi-directional&#8217; sprite sheet out of 120 frames. The frames were rendered using the open source 3D program <a href="http://www.blender.org">Blender 2.5</a></p>
<p><a href="http://content.makeyourflashgame.com/images/screenshots/create-spritesheet/s-2.png"><img alt="Select frames to upload" src="http://content.makeyourflashgame.com/images/screenshots/create-spritesheet/s-2.png" title="Select frames to upload" class="aligncenter" width="550" height="300" /></a></p>
<p>After all files are uploaded to the makeyourflashgame.com website, you can <b>input some sprite sheet data</b>, like name, visibility and , very important, the number of columns your spritesheet should have. In my case 15, because I have a 15 frame animation with 8 directions ( 15 x 8 cells ).</p>
<p><a href="http://content.makeyourflashgame.com/images/screenshots/create-spritesheet/s-3.png"><img alt="Input sprite data" src="http://content.makeyourflashgame.com/images/screenshots/create-spritesheet/s-3.png" title="Input sprite data" class="aligncenter" width="550" height="300" /></a></p>
<p>Pressing the [<b>Create</b>] button will <b>start the merging process</b>.</p>
<p><a href="http://content.makeyourflashgame.com/images/screenshots/create-spritesheet/s-4.png"><img alt="Merging frames" src="http://content.makeyourflashgame.com/images/screenshots/create-spritesheet/s-4.png" title="Merging frames" class="aligncenter" width="550" height="300" /></a></p>
<p>After the merging is finished <b>you have your sprite sheet all made up</b> in your makeyourflashgame.com workspace.</p>
<p><a href="http://content.makeyourflashgame.com/images/screenshots/create-spritesheet/s-5.png"><img alt="Sprite sheet settings" src="http://content.makeyourflashgame.com/images/screenshots/create-spritesheet/s-5.png" title="Sprite sheet settings" class="aligncenter" width="550" height="300" /></a></p>
<p>Just set the animation type, click the [</b>Edit animation</b>] button and <b>your directional animation is ready to take off</b>. You can control the direction by using your mouse while the left mouse button is pressed.</p>
<p><a href="http://content.makeyourflashgame.com/images/screenshots/create-spritesheet/s-6.png"><img alt="Animation settings" src="http://content.makeyourflashgame.com/images/screenshots/create-spritesheet/s-6.png" title="Animation settings" class="aligncenter" width="550" height="300" /></a></p>
<p>And if you would be a PBE actionscript developer, you could even save some time and <b>generate the PBE source code for this animation</b>. You can see how that works in <a href="http://blog.makeyourflashgame.com/479/generate-pbe-source-code-as3-for-animation-preview.html">this post</a>.</p>
<p><b><span style="color:#ff5522">!IMPORTANT</span></b> <b>Workspace</b> is still in BETA, so <b>be sure to <a href="http://community.makeyourflashgame.com/viewtopic.php?f=33&#038;t=45">join the beta program</a></b>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.makeyourflashgame.com/465/generate-a-sprite-sheet-from-single-frames.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PushButton BitmapData modifiers explained.</title>
		<link>http://blog.makeyourflashgame.com/442/pushbutton-bitmapdata-modifiers-explained.html</link>
		<comments>http://blog.makeyourflashgame.com/442/pushbutton-bitmapdata-modifiers-explained.html#comments</comments>
		<pubDate>Thu, 22 Jul 2010 13:19:50 +0000</pubDate>
		<dc:creator>mas</dc:creator>
				<category><![CDATA[makeyourflashgame.com]]></category>
		<category><![CDATA[PBEngine]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://blog.makeyourflashgame.com/?p=442</guid>
		<description><![CDATA[Recently BitmapData modifiers were added to the PushButton Flash Game Engine. With this technique you can apply all kinds of BitmapData modification, like reflection, blur, glow and many more,  on Sprite and Spritesheet renderers, on SpriteContainers and even on the entire scene.]]></description>
			<content:encoded><![CDATA[<p>Recently <strong>BitmapData modifiers were added to the PushButton Flash Game Engine</strong>. With this technique you can apply all kinds of BitmapData modification on Sprite and Spritesheet renderers, on SpriteContainers and even on the entire scene ( if you use a BitmapDataScene that is..). </p>
<p>Modifiers for <strong>effects like Bloom, Glow , Blur, Colorize, Reflection are provided with the engine</strong>, but one can easily create your own. Even modifiers that perform animating modification, like a pulsating glow for example, are possible.</p>
<p><a href="http://www.makeyourflashgame.com/content?co=/tutorials/pbe&#038;tu=animatedSprite07" target="sample" >See working sample</a></p>
<p>Download tutorial code <a href="http://content.makeyourflashgame.com/pbe/tutorials/AnimatedSprite07.rar">here</a></p>
<p>Code uses <a href="http://www.minimalcomps.com/" target="min" >minimal components</a>, so import <a href="http://code.google.com/p/minimalcomps/downloads/list" target="swc">the swc</a> into your project.</p>
<p>You also need to put the <a href="http://content.makeyourflashgame.com/pbe/tutorials/pbe.png" target="image">PBE logo image</a> and the <a href="http://content.makeyourflashgame.com/pbe/tutorials/star-green.png" target="image">animating star spritesheet</a> into the same folder as your compiled swf, for the sample to work.</p>
<h2>Why would we need modifiers</h2>
<p>Answer is simple &#8230;<strong> Graphics that are modified by the engine don&#8217;t need to be created and loaded as a resource</strong>. If you would have a game with animating enemies that look the same, but having a different color, you could load one enemy animation resource and create multiple colorized modified SpriteContainer or SpriteSheet objects. You would be decreasing your loading time and only need to create one resource when designing the graphics of your game.</p>
<p>Image that you have to create/render a reflection resource for each frame in all your animations and sprites. TORTURE!! NO NEED &#8230; <strong>there is a ReflectionModifier that turns an image in its reflection</strong>.</p>
<p>In addition, <strong>some effects can be real time</strong> so you can switch on-off specific modifiers at your convienience. To set a BlurModifier when an object is moving fast, could render a nice effect. Or <strong>maybe you would want to set your entire scene to grayScale</strong> when someone completes a level and you show the level score, just assign a GrayscaleModifier to the (PBE.scene as BitmapDataScene) and your done.</p>
<h2>How do modifiers work</h2>
<p>When you create a game using the open source PushButton flash game engine, <strong>all images and animations you use consist of BitmapData objects</strong>. These objects are loaded and maintained by the Engine and contain raw bitmap data. <strong>BitmapData is pixel color and transparency (ARGB) information about an image</strong>.</p>
<p>A modifier is a class that will modify the bitmap data of an image.<br />
There are two types of modification :</p>
<p>- <strong>REAL-TIME</strong><br />
This modification is applied on each render pass. This type of modification is active when you are applying modifiers to a SpriteSheetRenderer or BitmapDataScene object. </p>
<p>- <strong>PRE-RENDERED</strong><br />
This modification is applied when the modifiers are assigned. The image data is stored in modified state. This type of modification is active when you are applying modifiers to a SpriteRenderer object or SpriteContainer subclass, like SpriteSheetComponent or SWFSpriteSheetComponent.</p>
<p>The classes mentioned above all have a <strong>modifiers:Array attribute</strong>. By assigning an array of one or multiple modifers to this attribute , you will activate the provided modifiers. </p>
<p>example : turn your scene into grayscale (only with BitmapDataScene)</p>
<pre class="brush: as3;">
(PBE.scene as BitmapDataScene).modifiers = [ new GrayscaleModifier() ];
</pre>
<p>example : apply a red colorization on a sprite</p>
<pre class="brush: as3;">
var render:SpriteRenderer = new SpriteRenderer();
render.modifiers = [ new ColorizeModifier([0.5,0.5,0.5,0,0],[0.5,0,0,0,0],[0.5,0,0,0,0],[0,0,0,1,0])];
</pre>
<p>example : apply a pulsating glow colorization on an animating sprite</p>
<pre class="brush: as3;">
var render:SpriteSheetRenderer = new SpriteSheetRenderer();
render.modifiers = [ new SizeModifier(150,150),
   new PulsatingGlowModifier( new GlowModifier(0xcc0000,.65,5,5,3,3),
   new GlowModifier(0xff2200,.9,8,8,6,10))];
</pre>
<p>Changing the assigned modifiers array has no effect, only when assigning a new Array it will show changes, a bit the same as the filters array you use with the Sprite Class.</p>
<pre class="brush: as3;">
// wrong
render.modifiers.push(GrayscaleModifier());

// wrong
render.modifiers[render.modifiers.length] = GrayscaleModifier();

// right
render.modifiers = render.modifiers.concat(GrayscaleModifier());
</pre>
<p>You can have multiple modifiers that will be applied in the modifiers Array&#8217;s order. </p>
<p>So, for example &#8230;. you have a nice cut-out sprite animation that you would want to apply a glow to. Because you have made such a solid sprite, having no overhead spacing pixels in your loaded image, only applying a GlowModifier would render a clipped glow. This because glow radiates outwards and therefor out off your Sprite&#8217;s boundaries. </p>
<p>Solution &#8230; RESIZE. To achieve a nice glow on a sprite or animation one should first size-up the image by using the SizeModifier (creating more render area for the glow) and after that apply the GlowModifier.</p>
<p>Set size to 100&#215;100 pixels and apply red glow.</p>
<pre class="brush: as3;">
render.modifiers = [ SizeModifier(100,100) , GlowModifier(0xff0000) ];
</pre>
<p>One could even finish with applying another SizeModifier to downscale the glowing Sprite.</p>
<h2>Create your own modifier</h2>
<p>We are gonna make a ColorBlockModifier that replaces the image with a block (rectangle) of a specific color.</p>
<p>To create a new modifier we subclass from the Modifier Class<br />
[com.pbe.rendering2D.modifier]. </p>
<pre class="brush: as3;">
public class ColorBlockModifier extends Modifier
{
  ...
}
</pre>
<p>In the modifier constructor you can provide parameters that you can use when you are modifying. In this case the color of the block we are creating.</p>
<pre class="brush: as3;">
public var color:uint = 0xff000000;

public function ColorBlockModifier(color:uint=0xff000000)
{
	this.color = color;
	super();
}
</pre>
<p>Now we only need to override the modify function that will handle the modification:</p>
<pre class="brush: as3;">
public override function modify(data:BitmapData, index:int=0, count:int=1):BitmapData
{
..
}
</pre>
<p><strong>data</strong>:BitmapData<br />
image BitmapData object</p>
<p><strong>index</strong>:int=0<br />
frame index when using modifier in combination with SpriteContainer subclass or SpriteSheetRenderer</p>
<p><strong>count</strong>:int=1<br />
frame count using modifier in combination with SpriteContainer subclass or SpriteSheetRenderer</p>
<p>You can use index and count attributes when you want to create an animating modification. A pulsating Glow for example. In the modify function we alter en return the image data:BitmapData object.</p>
<p>The entire modifier code should look something like this:</p>
<pre class="brush: as3;">

	public class ColorBlockModifier extends Modifier
	{
		public var color:uint = 0xff000000;

		public function ColorBlockModifier(color:uint=0xff000000)
		{
			this.color = color;
			super();
		}

		public override function modify(data:BitmapData, index:int=0, count:int=1):BitmapData
		{
			data.lock();

			for (var y:int = 0; y&lt;data.height;  y++)
			{
					for (var x:int=0; x&lt;data.width; x++)
						data.setPixel32(x,y,color);
			}

			data.unlock();
			return data;
		}

	}
</pre>
<p><a href="http://www.makeyourflashgame.com/content?co=/tutorials/pbe&#038;tu=animatedSprite07" target="sample" >See working sample</a></p>
<p>Download tutorial code <a href="http://content.makeyourflashgame.com/pbe/tutorials/AnimatedSprite07.rar">here</a></p>
<p>Code uses <a href="http://www.minimalcomps.com/" target="min" >minimal components</a>, so import <a href="http://code.google.com/p/minimalcomps/downloads/list" target="swc">the swc</a> into your project.</p>
<p>You also need to put the <a href="http://content.makeyourflashgame.com/pbe/tutorials/pbe.png" target="image">PBE logo image</a> and the <a href="http://content.makeyourflashgame.com/pbe/tutorials/star-green.png" target="image">animating star spritesheet</a> into the same folder as your compiled swf, for the sample to work.</p>
<p>As you have seen, <strong>modifiers are easy to use and easy to create</strong>. So use them well &#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.makeyourflashgame.com/442/pushbutton-bitmapdata-modifiers-explained.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Creating a scrolling bitmap component for the PushButton Engine</title>
		<link>http://blog.makeyourflashgame.com/424/creating-a-scrolling-bitmap-component-for-the-pushbutton-engine.html</link>
		<comments>http://blog.makeyourflashgame.com/424/creating-a-scrolling-bitmap-component-for-the-pushbutton-engine.html#comments</comments>
		<pubDate>Mon, 10 May 2010 19:36:02 +0000</pubDate>
		<dc:creator>mas</dc:creator>
				<category><![CDATA[makeyourflashgame.com]]></category>
		<category><![CDATA[PBEngine]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://blog.makeyourflashgame.com/?p=424</guid>
		<description><![CDATA[In this article, I will show how you can create a ScrollingBitmapRenderer component for the PushButton Game Engine. You can even create paralax scrolling backgrounds or overlays with this component.]]></description>
			<content:encoded><![CDATA[<p>In this article, I will show how you can create a PBE <b>ScrollingBitmapRenderer</b> component. </p>
<p><a href="http://www.makeyourflashgame.com/content?co=/tutorials/pbe&#038;tu=animatedSprite04">See example of this tutorial in action</a></p>
<p>Download <a href="http://content.makeyourflashgame.com/pbe/tutorials/AnimatedSprite04.rar" _target="_blank">the AS3 code from this article</a> (rar)</p>
<p>With this <b>PBE render component</b> (that extends the PBE BitmapRenderer component) you will be able to render an image of a specific with and height that will be filled with a bitmap you provide. </p>
<p>This render component exposes <b>2 attributes</b> for scrolling purposes:</p>
<p><b>scroll:Point</b><br />
With this point you can specify the <b>scrolling offset</b> for the scrolling bitmap, where scroll.x will be the horizontal scrolling value and the scroll.y will be the verical scrolling value.</p>
<p><b>scrollSpeed:Point</b><br />
With this point you can specify the <b>scrolling speed ( pixels/second )</b> for the scrolling bitmap, where scrollSpeed.x will be the horizontal scrolling speed and scrollSpeed.y will be the vertical scrolling speed.<br />
The scrolling speed will automaticly adjust the scrolling offset.</p>
<p>By using multiple ScrollingBitmapRenderer components in different scene render layers with different scrolling speeds, you will even be able to create a nice <b>paralax scrolling effect</b>. This will be demonstrated in the provided sample.</p>
<h2>The ScrollingBitmapRenderer Component Class</h2>
<p>First we create a component class that extends the PBE <b>BitmapRender</b> class. By extending the BitmapRenderer things like drawing and positioning are already handled by the PushButton Engine. We get a bitmapData attribute that we can assign or draw onto that gives us control of what is displayed.</p>
<pre class="brush: as3;">
	public class ScrollingBitmapRenderer extends BitmapRenderer
	{
	}
</pre>
<p>In this component&#8217;s constructor we will create and prepare mutilple bitmapData objects. The bitmapData for the scrolling bitmap, the bitmapData for clearing and the bitmapData that will contain all display data and will be used to copy pixels from, onto the scrolling bitmap.</p>
<pre class="brush: as3;">
		public function ScrollingBitmapRenderer(bitmap:Bitmap, width:int, height:int)
		{
			// call inherited constructor
			super();
			// store bitmap that will be used to fill the scrolling bitmap
			this.srcBitmap = bitmap;
			// create a bitmapdata object for the scrolling bitmap
			this.bitmapData =  new BitmapData(width,height);
			// determine how many times the bitmap has to be drawn horizontal and vertical
			// to fill the scrolling bitmap.
			// We add an aditional so that we have enough display to scroll in any direction
			var cx:int = Math.ceil(width/srcBitmap.width)+1;
			var cy:int = Math.ceil(height/srcBitmap.height)+1;
			// the scrollrect variable will be used to draw a specific area to the scrolling bitmap
			scrollRect = new Rectangle(0,0,width,height);
			// create a bitmapData object for clearing purposes
			emptyBitmapData = new BitmapData(width,height, true, 0);
			// create a bitmapData object that will contain all display info that will
			// be used when copying pixels to the scrolling bitmap
			scrollBitmapData = new BitmapData(cx*srcBitmap.width, cy*srcBitmap.height, true, 0x000000);
			for (var ix:int = 0; ix&lt;cx; ix++)
				for (var iy:int = 0; iy&lt;cy; iy++)
				{
					scrollBitmapData.copyPixels(srcBitmap.bitmapData,srcBitmap.bitmapData.rect, new Point(ix*srcBitmap.width,iy*srcBitmap.height));
				}
		}
</pre>
<p>Because the extended BitmapRenderer is in fact a DisplayObjectRenderer that extends the PBE AnimatedComponent we have a onFrame event that we can override and use to adjust the scrolling offset using the scrollSpeed. We can also copyPixel the right display data onto the scrolling bitmap so it will be displayed in the PushButton Game Engine.</p>
<pre class="brush: as3;">
		public override function onFrame(deltaTime:Number):void
		{
			// call onFrame of the extended BitmapRenderer
			super.onFrame(deltaTime);
			// adjust scroll offset using the scrollSpeed
			scroll.x += scrollSpeed.x * deltaTime;
			scroll.y += scrollSpeed.y * deltaTime;
			// determine the right drawing rectangle area of the bitmapData object with all display info
			// for the copyPixel command
			// determine x offset of rectangle draw area
			var dx:int = scroll.x - (Math.floor(scroll.x/srcBitmap.width)*srcBitmap.width);
			scrollRect.x = dx;
			// determine y offset of rectangle draw area
			var dy:int = (scroll.y) - (Math.floor((scroll.y)/srcBitmap.height)*srcBitmap.height);
			scrollRect.y = dy;
			// lock the bitmapData object so no changes will be displayed until it is unlocked
			bitmapData.lock();
			// clear the bitmapData using a emptyBitmapData copy
			bitmapData.copyPixels(emptyBitmapData, emptyBitmapData.rect, new Point(0,0), null, null, false);
			// draw the right area of the bitmapData object with all display info onto the scrolling bitmap
			bitmapData.copyPixels(scrollBitmapData, scrollRect, new Point(0,0), null, null, true);
			// unlock the bitmapData object so it can be displayed
			bitmapData.unlock();
		}
</pre>
<h2>Using the ScrollingBitmapRenderer Component in a sample</h2>
<p>To create a scrolling bitmap we just allocate a PBE Entity and add a ScrollingBitmaspRenderer component to it.</p>
<pre class="brush: as3;">
			// Allocate an entity for a scrolling bitmap
			var bm:IEntity = PBE.allocateEntity();
			// Register the entity with PBE
			bm.initialize("bm_front");
			// Create a bitmap render component to display our animation
			var bmRender:ScrollingBitmapRenderer = new ScrollingBitmapRenderer(logo.image,PBE.scene.sceneView.width,PBE.scene.sceneView.height);
			// assign the scene so this animatied sprite will we drawn.
			bmRender.scene = PBE.scene;
			// position this bitmap so that it will fill the entire PBE scene
			bmRender.x = -1*(PBE.scene.sceneView.width/2);
			bmRender.y = -1*(PBE.scene.sceneView.height/2);
			// set the layer of this renderer so it will render on top
			bmRender.layerIndex = 10;
			// set the scroll speed of this renderer
			bmRender.scrollSpeed.x = 100;
</pre>
<p><a href="http://www.makeyourflashgame.com/content?co=/tutorials/pbe&#038;tu=animatedSprite04">See example of this tutorial in action</a></p>
<p>Download <a href="http://content.makeyourflashgame.com/pbe/tutorials/AnimatedSprite04.rar" _target="_blank">the AS3 code from this article</a> (rar)</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.makeyourflashgame.com/424/creating-a-scrolling-bitmap-component-for-the-pushbutton-engine.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Single Logon implemented</title>
		<link>http://blog.makeyourflashgame.com/395/single-logon-implemented.html</link>
		<comments>http://blog.makeyourflashgame.com/395/single-logon-implemented.html#comments</comments>
		<pubDate>Wed, 11 Nov 2009 13:54:20 +0000</pubDate>
		<dc:creator>mas</dc:creator>
				<category><![CDATA[makeyourflashgame.com]]></category>
		<category><![CDATA[Game Development]]></category>
		<category><![CDATA[website]]></category>

		<guid isPermaLink="false">http://blog.makeyourflashgame.com/?p=395</guid>
		<description><![CDATA[Today I finished implementing the single logon system. It wasn't an easy task but while learning some additional PHP techniques I managed to do it.
]]></description>
			<content:encoded><![CDATA[<p>Today <strong>I finished implementing the single logon </strong>system. It wasn&#8217;t an easy task but while learning some additional PHP techniques I managed to do it.</p>
<p>Because the makeyourflashgame website consists of <strong>5 subdomains </strong>www, blog, community, base, content, and <strong>the community part is a PHPBB3 forum </strong>that has its own logon system, I had a real headbreaker in getting this to work.</p>
<p>however&#8230;.</p>
<p>To learn how easy it is to create <strong>PHP sessions and cookies that span multiple sub domains </strong>sent me into a state of euforia. It launched me straight into the right direction. </p>
<p>I use the PHPBB forum as leading for userid/passwords. I added some additional scripts to PHPBB and integrated my own code in some PHPBB base script files <img src="http://community.makeyourflashgame.com/images/smilies/devil.png"> .</p>
<p>If someone authenticates using the header fields in any sub-domain, a little flash app is used to do a secure call (URLRequest) to a user validation script within the PHPBB domain. PHPBB will log in and cookies/sessions are set. I integrated my code into PHPBB so if someone loggs in the normal PHPBB way the right cookies and session data is set as well and the person is logged into the sub-domains as well.</p>
<p>I tested it on IE8, Firefox, Chrome and Safari (for windows)</p>
<p><strong>now for some code &#8230;.</strong><br />
I am not gonna reveal to much of my own code but if someone wants to know how to create a cookie that spans multiple domains&#8230; with .makeyourflashgame.com as an example&#8230;</p>
<pre class="brush: as3;">
public function setCookie($cookie, $value)
{
   $expire = $this->si->addTime(52,"w");
   setcookie($cookie,$value,$expire,"/",".makeyourflashgame.com");
}

public function clearCookie($cookie)
{
   $expire = $this->si->addTime(-1,"w");
   setcookie($cookie,null,$expire,"/",".makeyourflashgame.com");
}
</pre>
<p>and to create cross subdomain session state (on the same machine) you need to set the <strong>session.cookie_domain</strong> before starting the session</p>
<pre class="brush: as3;">
// set session cookie domain to main domain so the session will be available in all subdomains
$pos = strpos($_SERVER['SERVER_NAME'],".");
$server_name = $_SERVER['SERVER_NAME'];
ini_set('session.cookie_domain',substr($server_name,$pos,strlen($server_name)-$pos));
// start domain wide session
session_start();
</pre>
<p>If this website should become a success and the subdomains have to be split up into different servers, I will have to use create some other way to manage session data across multiple servers. Will probably be putting this data into a MySQL Database and use a cross domain session id cookie to access this data.</p>
<p>Next is &#8230;.  <strong>user workspace management system.</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.makeyourflashgame.com/395/single-logon-implemented.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Integrating Flint particles with the Pushbutton Engine</title>
		<link>http://blog.makeyourflashgame.com/375/integrating-flint-particles-with-the-pushbutton-engine.html</link>
		<comments>http://blog.makeyourflashgame.com/375/integrating-flint-particles-with-the-pushbutton-engine.html#comments</comments>
		<pubDate>Wed, 04 Nov 2009 14:03:45 +0000</pubDate>
		<dc:creator>mas</dc:creator>
				<category><![CDATA[makeyourflashgame.com]]></category>
		<category><![CDATA[PBEngine]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://blog.makeyourflashgame.com/?p=375</guid>
		<description><![CDATA[This article explains how to integrate AS3 the Flint particle engine with the Open Source PushButton Flash Game Engine.]]></description>
			<content:encoded><![CDATA[<p>This article explains how to <b>integrate AS3 the Flint particle engine with the Open Source PushButton Flash Game Engine</b>.</p>
<p>Download <a href="http://content.makeyourflashgame.com/pbe/tutorials/flinttest-code.rar" _target="_blank">the AS3 code from this article</a> (rar)</p>
<p><a href="http://www.makeyourflashgame.com/content?co=/tutorials/pbe&#038;tu=flinttest">See example of this tutorial in action</a></p>
<p>The <a href="http://flintparticles.org/" target="_blank" >Flint particle engine</a> is <b>THE actionscript 3.0 open source particle engine</b> available on the net. It lets you create all kinds of particle effects like smoke, fire, explosions , trails and more.</p>
<p>Because it would be very nice to have this available in the PushButton Engine I gave it a go&#8230;.</p>
<p>The Flint system uses <b>particle emitters</b> that can be configured and that produce particles with specific behaviour that <b>render to a specific render class</b>. Flint has several render classes like <b>BitmapRenderer, BitmapLineRenderer, DisplayObjectRenderer, PixelRenderer and VectorLineRenderer</b>. </p>
<p>Because <b>I am no Flint specialist</b> I can not really tell the difference between all these renderers but the process of integration will probably be the same for all.</p>
<p>In this article I used the Flint example <b>examples\examples2D\FireAndSmoke\PureAS3</b>. In this example a Flint BitmapRenderer class is created with 2 emitters (fire/smoke). </p>
<p>The Flint BitmapRenderer is a subclassed Sprite class that holds a Bitmap and on this Bitmap particles are being rendered using this Bitmap&#8217;s BitmapData object. Because the <b>PBE DisplayObjectRenderer is be able to render sprites</b> , it shouldn&#8217;t be very problematic to wrap this in a PBE renderer class, .</p>
<p><b><span style="color:red">! Important note</span></b>. Both Flint and PBE have a BitmapRenderer and DisplayObjectRenderer class, so to combine these in your source files, be sure to use the <b>full namespace </b> when you refer to a specific class.</p>
<h2>Step 1 &#8211; Creating a FlintBitmapRenderer Class for PBE</h2>
<p>The first thing we will do is to create a <b>base FlintBitmapRenderer class</b> that we can subclass in the future to create specific particle render classes.</p>
<p>Because I want to do this the easy way, and the Flint BitmapRenderer class is essentially a Sprite, I will <b>subclass the DisplayObjectRenderer class</b> to get to a FlintBitmapRenderer class.</p>
<pre class="brush: as3;">
public class FlintBitmapRenderer extends DisplayObjectRenderer
{
	     ...
}
</pre>
<p>I need to <b>store the Flint BitmapRenderer class and the Flint emitters</b>.</p>
<pre class="brush: as3;">
  private   var _renderer:BitmapRenderer;
  protected var emitters:Array = new Array();
</pre>
<p>It would be nice to have an attribute to <b>access the Flint sprite</b> so we can set filters etc.</p>
<pre class="brush: as3;">
public function get sprite():Sprite
{
    return _renderer as Sprite;
}
</pre>
<p>Because the Flint BitmapRenderer class takes width and height as constructor parameters we get these from our constructor. </p>
<p>In the constructor an function addEmitters is called. <b>The function addEmitters() must be overridden</b> by the derrived class and will add the emitters to the emitters:Array</p>
<p>When the emitters are added to the Flint BitmapRenderer, we <b>set the renderer as the displayObject of our PBE DisplayObjectRenderer</b>.</p>
<pre class="brush: as3;">
public function FlintBitmapRenderer(width:int, height:int)
{
  super();

  // create the bitmap renderer object
  _renderer = new BitmapRenderer( new Rectangle( 0, 0, width, height ) );

  // add emitters to the emitters:Array
  addEmitters();

  for (var e:int=0; e < emitters.length; e++)
    _renderer.addEmitter( emitters[e] );

  this.displayObject = _renderer;
}
</pre>
<h2>Step 2 - Creating a subclass for the FireAndSmoke</h2>
<p>To create a PBE FireSmokeRenderer class we can <b>subclass the FlintBitmapRenderer class</b> and add the emitters.</p>
<p>We create a <b>canvas 250 pixels wide and 300 pixels high</b> using the function super(250,300); in our constructor.</p>
<p>The emitters  : Fire() and  Smoke() are taken from the Flint example, sources are in the <a href="http://content.makeyourflashgame.com/pbe/tutorials/flinttest-code.rar" _target="_blank">code download</a> from this article. The emitters are added to the emitters:Array in the <b>overridden function addEmitters()</b>.</p>
<pre class="brush: as3;">
	public class FireSmokeRenderer extends FlintBitmapRenderer
	{
		private var smoke:Emitter2D;
		private var fire:Emitter2D;

		public function FireSmokeRenderer()
		{
			// create a 250 x 300 particle canvas
			super(250,300);
		}

		protected override function addEmitters():void
		{
			emitters.push(smoke = new Smoke());
			smoke.x = 125;
			smoke.y = 290;
			smoke.start();

			emitters.push(fire = new Fire());
			fire.x = 125;
			fire.y = 290;
			fire.start();
		}
	}
</pre>
<h2>Step 3 - Adding the FireSmokeRenderer to the scene</h2>
<p>To add this to a PBE scene we have to create an PBE entity, add a SimpleSpatial component and the FireSmokeRenderer component.</p>
<p>We set the layerIndex of the render component to 1 so the rotating <a href="http://content.makeyourflashgame.com/pbe/tutorials/star-green.png" _target="_blank">green star sprite</a> will always be behind the smoke.</p>
<pre class="brush: as3;">
	    private function createFlintEntity():void
	    {
	       // Allocate an entity for our animated sprite
	       var flint:IEntity = allocateEntity();
	       // Register the entity with PBE
	       flint.initialize("flint");

	       var spatial:SimpleSpatialComponent = new SimpleSpatialComponent();
	       spatial.position.x = -125;
	       spatial.position.y = -150;

	       flint.addComponent(spatial,"spatial");

	       flintRender = new FireSmokeRenderer();
	       flintRender.scene = PBE.getScene();
	       flintRender.layerIndex = 1;
	       flintRender.positionProperty = new PropertyReference("@spatial.position");
	       flint.addComponent(flintRender,"render");

	    }
</pre>
<p>To add a nice color changing glow effect I created an onFrame event handler on the PBE.mainStage that will rotate glow colors for the FireSmokeRenderer.sprite glow filter.</p>
<pre class="brush: as3;">
	    private var glowColor:uint = 0x000000;
	    private var nextColor:uint = 0x000000;
	    private var lastTimer:int = 0;
	    private function onFrame(event:Event):void
	    {
	    	var elapsed:int = getTimer()-lastTimer;
	    	if (elapsed>2000)
	    	{
	    		// change color each second
	    		glowColor = nextColor;

	    		nextColor =
	    		   (Math.random()*0xff)*0x010000+
	    		   (Math.random()*0xff)*0x000100+
	    		   (Math.random()*0xff)*0x000001;

	    		lastTimer = getTimer();
	    		elapsed = 0;
	    	}
	    	flintRender.sprite.filters = [new GlowFilter(Color.interpolateColor(glowColor,nextColor,elapsed/2000))];
	    }
</pre>
<p>Download <a href="http://content.makeyourflashgame.com/pbe/tutorials/flinttest-code.rar" _target="_blank">the AS3 code from this article</a> (rar)</p>
<p><a href="http://www.makeyourflashgame.com/content?co=/tutorials/pbe&#038;tu=flinttest">See example of this tutorial in action</a></p>
<p>To run the sample you need to put the <a href="http://content.makeyourflashgame.com/pbe/tutorials/star-green.png" _target="_blank">green star sprite</a>  into the folder where the compiled swf is located.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.makeyourflashgame.com/375/integrating-flint-particles-with-the-pushbutton-engine.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PBE Rendering2D revision 538+</title>
		<link>http://blog.makeyourflashgame.com/351/pbe-rendering2d-revision-538.html</link>
		<comments>http://blog.makeyourflashgame.com/351/pbe-rendering2d-revision-538.html#comments</comments>
		<pubDate>Thu, 22 Oct 2009 12:24:43 +0000</pubDate>
		<dc:creator>mas</dc:creator>
				<category><![CDATA[makeyourflashgame.com]]></category>
		<category><![CDATA[PBEngine]]></category>

		<guid isPermaLink="false">http://blog.makeyourflashgame.com/?p=351</guid>
		<description><![CDATA[This post will show how to use the recoded rendering2D as of rivision 538 of the PushButton Game Engine.]]></description>
			<content:encoded><![CDATA[<p>As of revision 538, the <strong>rendering2D engine is recoded </strong>to give better performance, smoother animations and basicly make life of us developers easier when we want to put our graphics onto the screen using the PushButton Game Engine.</p>
<h2>The changes in a nutshell</h2>
<ul>
<li>The Scene2DComponent class has been replaced by the <b>DisplayObjectScene</b> class.</li>
<p></p>
<li>The Scene2DBitmapDataComponent class has been replaced by the<br /> <b>BitmapDataScene</b> class.</li>
<p></p>
<li>The basic rendering is done using the <b>DisplayObjectRenderer</b> class that has a scene property</li>
<p></p>
<li>The DisplayObjectRenderer has <b>multiple properties that can be used to influence the drawing without linking it to a spatial
<p></b></p>
<ul>
<li><b>position</b> can be used to set the X/Y scene (screen) coordinates of the object (! not world coordinates)</li>
<li><b>scale</b> can be used to resize the object ( 1 = 100% )</li>
<li><b>rotation</b> can be used to rotate the object ( in degrees )</li>
<li><b>alpha</b> can be used to set the object&#8217;s transparancy</li>
<li><b>layerIndex</b> can be used to set the object&#8217;s layer</li>
<li><b>zIndex</b> can be used to set the object&#8217;s depth within the layer</li>
<li><b>registrationPoint</b> indicates the pivot point of this object. With the SpriteRenderer for example the center of the image is used as the registrationPoint so the sprite is centered upon its position and will rotate around its center.</li>
</ul>
<p>
</li>
<li>Each of those DisplayObjectRenderer properties has a corresponding<br /> <b>{property}Property of the PropertyReference type</b><br />we have a positionProperty, scaleProperty, rotationProperty, alphaProperty, layerIndexProperty, zIndexProperty and a registrationPointProperty.<br />For example , a SimpleSpatialComponent can be used to move or rotate the object using the positionProperty and rotationProperty.</li>
<p></p>
<li>If the positionProperty is used and the scene attribute of the renderer is set, the <b>referenced coordinates are treated as worldcoordinates</b> and will be transformed to the scene.</li>
<p></p>
<li>There is a <b>SpriteSheetRenderer</b> class that can be used to draw spritesheet animations</li>
<p></p>
<li>There is a <b>SpriteRenderer</b> class that can be used to draw a sprite on screen</li>
<p></p>
<li>The static <b>Global</b> class has been <b>renamed to PBE</b> ( com.pblabs.engine.PBE ).</li>
<p></p>
<li>There is a <b>PBE.initializeScene</b> function to quickly setup your scene.</li>
<p></p>
<li><b>Find the scene</b> you created with PBE.initializeScene using <b>PBE.getScene()</b></li>
<p></p>
<li><b>Find the spatialManager</b> you created with PBE.initializeScene using <b>PBE.getSpatialManager()</b></li>
<p>
</ul>
<p><b>I have recoded the examples from the earlier posts.</b></p>
<h2>Recoding : Create an animated spritesheet</h2>
<p>Original post : <a href="http://blog.makeyourflashgame.com/81/animated-sprite-with-spritesheet-pushbutton-engine.html">Create an animated spritesheet</a></p>
<p><a href="http://content.makeyourflashgame.com/pbe/tutorials/animatedSprite01-538.rar">Download the 538+ code</a> for AnimatedSprite01</p>
<p><a href="http://content.makeyourflashgame.com/pbe/tutorials/animatedSprite02-538.rar">Download the 538+ code</a> and <a href="http://content.makeyourflashgame.com/pbe/tutorials/Levels-AnimatedSprite02-538.rar">download the resources</a> for AnimatedSprite02</p>
<p><a href="http://www.makeyourflashgame.com/content?co=/tutorials/pbe&#038;tu=AnimatedSprite01">see working sample</a></p>
<h2>Recoding : The PBEngine Scene2D BitmapData Component</h2>
<p>Original post : <a href="http://blog.makeyourflashgame.com/163/the-pbengine-scene2dbitmapdatacomponent.html" >The PBEngine Scene2D BitmapData Component</a></p>
<p><a href="http://content.makeyourflashgame.com/pbe/tutorials/animatedSprite03-code-538.rar">Download the 538+ code</a> and <a href="http://content.makeyourflashgame.com/pbe/tutorials/AnimatedSprite03-resources-538.rar">download the resources</a> for AnimatedSprite03</p>
<p><a href="http://www.makeyourflashgame.com/content?co=/tutorials/pbe&#038;tu=AnimatedSprite03">see working sample</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.makeyourflashgame.com/351/pbe-rendering2d-revision-538.html/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>To make a game in flash &#8211; part V &#8211;  Asteroids</title>
		<link>http://blog.makeyourflashgame.com/338/to-make-a-game-in-flash-part-v-asteroids.html</link>
		<comments>http://blog.makeyourflashgame.com/338/to-make-a-game-in-flash-part-v-asteroids.html#comments</comments>
		<pubDate>Thu, 08 Oct 2009 13:49:26 +0000</pubDate>
		<dc:creator>mas</dc:creator>
				<category><![CDATA[makeyourflashgame.com]]></category>
		<category><![CDATA[Blender]]></category>
		<category><![CDATA[Game Development]]></category>

		<guid isPermaLink="false">http://blog.makeyourflashgame.com/?p=338</guid>
		<description><![CDATA[I added some asteroids to shoot at. When hit by the canon's shockwave they explode into smaller ones that each get a random heading. ]]></description>
			<content:encoded><![CDATA[<p>I added some asteroids to shoot at. When hit by the canon&#8217;s shockwave they explode into smaller ones that each get a random heading. </p>
<p>When the asteroids get really small, they just vanish. When asteroids move out of the main (circle) view they vanish as well.</p>
<p>In the working sample, when you have destroyed all asteroids, the level is cleared and one proceeds to the next level. The higher the level, the more asteroids at the beginning of the level. Sometimes you even get a nice additional &#8216;bonus&#8217; weapon.<br />
( pssssttt .. the + key to add one still works  )</p>
<p><a href="http://www.makeyourflashgame.com/content?co=/spacecoredefender/work&#038;wo=03">You can see the work in progress here</a> </p>
<p>I created 3 different asteroid animations (143 frames) using blender.</p>
<h2>Asteroid 1</h2>
<p><img style="width:100%;" src="http://content.makeyourflashgame.com/spacecoredefender/asteroid-1-96.png"></p>
<h2>Asteroid 2</h2>
<p><img style="width:100%;" src="http://content.makeyourflashgame.com/spacecoredefender/asteroid-2-96.png"></p>
<h2>Asteroid 3</h2>
<p><img style="width:100%;" src="http://content.makeyourflashgame.com/spacecoredefender/asteroid-3-96.png"><br />
( everyone may use these sprite sheets  <img src='http://blog.makeyourflashgame.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  )</p>
<p>You can find the blenderfiles for these asteroids <a href="http://content.makeyourflashgame.com/spacecoredefender/blender-asteroid.rar">here</a></p>
<p><a href="http://www.makeyourflashgame.com/content?co=/spacecoredefender/work&#038;wo=03">You can see the work in progress here</a> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.makeyourflashgame.com/338/to-make-a-game-in-flash-part-v-asteroids.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using the BulkLoaderResource Provider with PBE</title>
		<link>http://blog.makeyourflashgame.com/316/using-the-bulkloaderresourceprovider-with-pbe.html</link>
		<comments>http://blog.makeyourflashgame.com/316/using-the-bulkloaderresourceprovider-with-pbe.html#comments</comments>
		<pubDate>Thu, 24 Sep 2009 18:58:32 +0000</pubDate>
		<dc:creator>mas</dc:creator>
				<category><![CDATA[makeyourflashgame.com]]></category>
		<category><![CDATA[PBEngine]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://blog.makeyourflashgame.com/?p=316</guid>
		<description><![CDATA[This tutorial will explain how the BulkLoaderResourceProvider is implemented and how it can be used and/or subclassed to load your resources in multiple phases.]]></description>
			<content:encoded><![CDATA[<p>This tutorial will explain how you can use the BulkLoaderResourceProvider to dynamicly load the resources in your game in multiple phases.</p>
<p><a href="http://www.makeyourflashgame.com/content?co=/tutorials/pbe&#038;tu=loadresources&#038;w=700&#038;h=300">See this tutorial in action</a><br />
<a href="http://content.makeyourflashgame.com/pbe/tutorials/loadresources-src.rar" target="_blank" >Download the sources of this tutorial</a><br />
<a href="http://content.makeyourflashgame.com/pbe/tutorials/loadresources.rar" target="_blank" >Download the flash + assets of this tutorial</a></p>
<h2>1. The BulkLoaderResourceProvider Class</h2>
<p>The BulkLoaderResourceProvider is <strong>subclassed from ResourceProviderBase</strong>. </p>
<p>The constructor takes 2 parameters and will auto-register with the ResourceManager.<br />
<strong>name:String </strong>- this is the name of the BulkLoader object that is created for this BulkLoaderResourceProvider.<br />
<strong>numConnections:int = 12 </strong>- number of connections the BulkLoader object will use.</p>
<p>The BulkLoaderResourceProvider has a <strong>phase</strong> property that tells you the current loading phase. The loading phase always <strong>starts with 1</strong> and increments after all resources of that phase have been loaded and as long as the phase has resources to be loaded.</p>
<p>The BulkLoaderResourceProvider has a <strong>function load(onLoaded:Function = null, onProgress:Function = null, onProvideResources:Function = null):void</strong> that can be used to start loading the resources.</p>
<ul>
<li>
<strong>param onLoaded</strong> is a callback function that is called when all resources of the current phase have been loaded.<br />
<strong>function onLoaded(phase:int):void</strong></p>
</li>
<li>
<strong>param onProgress</strong> is a callback function that is called when resources of the current phase are being loaded. Progress is a percentage (0-100)<br />
<strong>function onProgress(phase:int, progress:int):void</strong></p>
</li>
<li>
<strong>param onProvideResources</strong> is a callback function that is called to get the bulkResource objects (Array) of the current loading phase. These bulkResource objects specify the resources that have to be loaded.<br />
<strong>function onLoaded(phase:int):void</strong></p>
<p>If this parameter is ommited the function provideResources():void is called to get the current phase bulkResource objects.</p>
</li>
</ul>
<p>The <strong>Array of bulkResource objects </strong>that must be the result of the onProvideResources callback function or the overridden provideResources function is a normal Array that holds objects that has 2 attributes:</p>
<ul>
<li>
<strong>url : String</strong><br />
url/source of the resource to be loaded
</li>
<li>
<strong>type : Resource</strong><br />
type of Resource (ImageResource, XMLResource, MP3Resource etc )
</li>
</ul>
<pre class="brush: as3;">
   var bulkResourceObjects:Array = [
				      { url : "data/test1.xml", type : XMLResource },
				      { url : "data/test2.xml", type : XMLResource },
				      { url : "data/test3.xml", type : XMLResource }
				    ];
</pre>
<p>The BulkLoaderResourceProvider has a <strong>function provideResources():Array</strong> that <strong>can be overridden in a subclass </strong>that will be called when requesting the current phase bulkResource objects.</p>
<h2>2. Subclassing the BulkLoaderResourceProvider class</h2>
<p>If one wants to <strong>create a seperate class that will do multi-phase resource loading </strong>just subclass the BulkResourceProvider class and override the <strong>function provideResources():Array</strong></p>
<p>Multi-phase loading can be usefull when one would like to first load some resources (xml/images/sounds) in a first pohase and display a kind of splash-screen while all other resources (the big bulk) will be loaded in phase 2.</p>
<pre class="brush: as3;">
	public class SampleResources extends BulkLoaderResourceProvider
	{
		public function SampleResources()
		{
			super("sampleLoader");
		}

		protected override function provideResources():Array
		{
			switch(phase)
			{
				case 1:
				  // return this hard-coded array of resource objects so it will
				  // be processed
				  return [
				      { url : "data/test1.xml", type : XMLResource },
				      { url : "data/test2.xml", type : XMLResource },
				      { url : "data/test3.xml", type : XMLResource }
				    ];
				break;

				case 2:
				   // create the array of resource objects programmaticly
				   var resObjects:Array = new Array();
				   for (var i:int=4; i<=6; i++)
				   {
				   	  // create a resource object
				   	  var resObject:Object = new Object();
				   	  resObject.url = "data/test"+i+".xml";
				   	  resObject.type = XMLResource;
				   	  // add the resource object to the array
				   	  resObjects.push(resObject);
				   }
				   // return the array so it will be processed
				   return resObjects;
				break;
			}
			return null;
		}
	}
</pre>
<p>As you can see in the code above, we just extend the BulkLoaderResourceProvider. We call the super("sampleLoader") constructor so that our provider is registered with the ResourceManager and the bulkloader is prepared.</p>
<p>We have overridden the function provideResources():Array and use that to provide the array's with bulkResource objects for each (2) phase.</p>
<p>We start the loading in our main application like this :</p>
<pre class="brush: as3;">
// create subclass
var sampleResources:SampleResources = new SampleResources();
// initiate the load
sampleResources.load(resourcesLoaded , resourcesProgress);
</pre>
<p>The resourceLoaded and resourcesProgress function are used to display some loading information on screen.</p>
<h2>4. Using the BulkLoaderResourceProvider class to do a phased load</h2>
<p>We can do a multi-phased resource loading using the BulkLoaderResourceProvider using the load function and providing a <strong>onProvideResources callback function</strong>.</p>
<p>We would start the loading like this:</p>
<pre class="brush: as3;">
var bulkResourceProvider:BulkLoaderResourceProvider = new BulkLoaderResourceProvider("sampleLoader");
// initiate the load - provide the provideData call back function
bulkResourceProvider.load(resourcesLoaded , resourcesProgress, provideResources);
</pre>
<p>Where the callback <strong>function provideResources(phase:int):Array </strong>would look like</p>
<pre class="brush: as3;">
		private function provideResources(phase:int):Array
		{
			switch(phase)
			{
				case 1:
				  // return this hard-coded array of resource objects so it will
				  // be processed
				  return [
				      { url : "data/test1.xml", type : XMLResource },
				      { url : "data/test2.xml", type : XMLResource },
				      { url : "data/test3.xml", type : XMLResource }
				    ];
				break;

				case 2:
				   // create the array of resource objects programmaticly
				   var resObjects:Array = new Array();
				   for (var i:int=4; i<=6; i++)
				   {
				   	  // create a resource object
				   	  var resObject:Object = new Object();
				   	  resObject.url = "data/test"+i+".xml";
				   	  resObject.type = XMLResource;
				   	  // add the resource object to the array
				   	  resObjects.push(resObject);
				   }
				   // return the array so it will be processed
				   return resObjects;
				break;
			}
			return null;
		}
</pre>
<p>The callback function provideResources(phase:int):Array and subclassed function provideResources():Array are almost the same except the phase parameter of the callback. This because phase is a known property of the subclass.</p>
<p><a href="http://www.makeyourflashgame.com/content?co=/tutorials/pbe&#038;tu=loadresources&#038;w=700&#038;h=300">See this tutorial in action</a><br />
<a href="http://content.makeyourflashgame.com/pbe/tutorials/loadresources-src.rar" target="_blank" >Download the sources of this tutorial</a><br />
<a href="http://content.makeyourflashgame.com/pbe/tutorials/loadresources.rar" target="_blank" >Download the flash + assets of this tutorial</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.makeyourflashgame.com/316/using-the-bulkloaderresourceprovider-with-pbe.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The PBE Resource Provider Model explained</title>
		<link>http://blog.makeyourflashgame.com/267/the-pbe-resource-provider-model-explained.html</link>
		<comments>http://blog.makeyourflashgame.com/267/the-pbe-resource-provider-model-explained.html#comments</comments>
		<pubDate>Thu, 24 Sep 2009 13:49:05 +0000</pubDate>
		<dc:creator>mas</dc:creator>
				<category><![CDATA[makeyourflashgame.com]]></category>
		<category><![CDATA[PBEngine]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://blog.makeyourflashgame.com/?p=267</guid>
		<description><![CDATA[As of r485 the Pushbutton Game Engine (PBE) has implemented a Resource Provider Model to handle resources. This gives us some nice possibilities like loading resources ourselves or generating our own resources in memory.
]]></description>
			<content:encoded><![CDATA[<p>As of r485 the Pushbutton Game Engine (PBE) has <strong>implemented a Resource Provider Model to handle the loading and creating of resources</strong>. This gives us some nice possibilities like loading resources ourselves or generating our resources in memory.</p>
<p>This post will <strong>explain about the Resource Provider Model</strong> and will show how we can create our own resource provider by implementing the <strong>IResourceProvider interface</strong>. </p>
<p>We will create a resource provider that will create resources &#8216;on the fly&#8217; as they are requested by the ResourceManager. </p>
<p>We will also create a resource provider by <strong>subclassing the ResourceProviderBase</strong> and we will &#8216;fill&#8217; that ResourceProvider with some dynamicly generated graphics.</p>
<p><a href="http://www.makeyourflashgame.com/content?co=/tutorials/pbe&#038;tu=sampledynamicresourceprovider&#038;h=400">See this tutorial in action</a><br />
<a href="http://content.makeyourflashgame.com/pbe/tutorials/SampleDynamicResourceProvider-src.rar" target="_blank" >Download the sources of this tutorial</a></p>
<h2>1. The Resource Provider Model</h2>
<p>With the resource provider model implemented, the ResourceManager can have<strong> access to multiple resource providers</strong>. These resource providers are <strong>classes that implement the IResourceProvider interface </strong>and are registered with the ResourceManager using the <strong>function ResourceManager. registerResourceProvider(..)</strong>. </p>
<p>When a resource is requested by the engine using the <strong>function ResourceManager. instance.load(..) </strong>, the ResourceManager checks with each provider if it can provide the requested resource. If a resource provider can provide the resource the ResourceManager will request that resource from the provider and caches this resource for future retrieval.</p>
<p>Before we had this Resource Provider Model, a Resource object had to &#8216;load&#8217; itself when requested. With the Resource Provider Model implemented, <strong>the providers themselves are responsible for &#8216;loading&#8217; or &#8216;creating&#8217; the resources</strong>. This loading/creating can take place at the start of the game, as requested or any time really &#8230;</p>
<p>By implementing de IResourceProvider interface we can <strong>write our own classes that can provide resources </strong>to the ResourceManager. We could render these resources in memory, or load them from disk ourselves.</p>
<h2>2. The Resource Provider Classes</h2>
<p>You will find the resource provider classes in the library :</p>
<p><strong>src\com\pblabs\engine\resource\provider</strong></p>
<ul>
<li><strong>IResourceProvider</strong><br />
This interface has to be implemented by a class so it can act as a resource provider.</p>
</li>
<li><strong>ResourceProviderBase</strong><br />
This class can be subclassed to create your own resource provider class</p>
</li>
<li><strong>BulkLoaderResourceProvider</strong><br />
This class can be subclassed or used to load resources. It uses BulkLoader to load resourcs. Multi phase loading is supported.<br />
( this will be explained in another blog post )</p>
</li>
<li><strong>EmbeddedResourceProvider</strong><br />
This (singleton) class is used internally to provide the embedded resources that were specified using the ResourceBundle class or ResourceBinding class</p>
</li>
<li><strong>FallbackResourceProvider</strong><br />
This (singleton) class is used internally to act as a resource loader fallback if no resource provider can provide a requested resource. It uses BulkLoader to load the requested resource</p>
</li>
</ul>
<h2>3. The IResourceProvider interface</h2>
<pre class="brush: as3;">
    public interface IResourceProvider
    {
        /**
         * This method is called when the ResourceManager gets a load request
         * for a resource and will check all known ResourceProviders if it has
         * the specific resource
         */
        function isResourceKnown(uri:String, type:Class):Boolean;

        /**
         * This method is called when the ResourceManager requests a known
         * resource from a ResourceProvider
         */
        function getResource(uri:String, type:Class, forceReload:Boolean = false):Resource;
    }
</pre>
<p>The <strong>function isResourceKnown(uri:String, type:Class):Boolean</strong> will return a value of <strong>true</strong> if the resource provider has access to the requested resource with the specific uri and of that specific type. </p>
<p>The <strong>uri:String</strong> is usally the url or filename of the resource but could also be some internal format you choose yourself when you are generating your resources in memory.</p>
<p>The <strong>type:Class</strong> can by any of the Resource Class types like : ImageResource, XMLResource, SWFResource, MP3Resource and DataResource</p>
<p>The <strong><span style="text-align:left">function getResource( uri : String, type : Class, forceReload : Boolean = false ) :Resource;</span></strong> will provide the requested resource.</p>
<h2>4. Implementing the IResourceProvider interface</h2>
<p><a href="http://www.makeyourflashgame.com/content?co=/tutorials/pbe&#038;tu=sampledynamicresourceprovider&#038;h=400">See this tutorial in action</a><br />
<a href="http://content.makeyourflashgame.com/pbe/tutorials/SampleDynamicResourceProvider-src.rar" target="_blank" >Download the sources of this tutorial</a></p>
<p>In the code sample with this tutorial I implemented the IResourceProvider interface on my main application class so that the main application becomes a resource provider as well.</p>
<pre class="brush: as3;">
   [SWF(width="400", height="400", frameRate="32")]
   public class SampleDynamicResourceProvider extends Sprite implements IResourceProvider
   {
       ...
   }
</pre>
<p>I register this resource provider with the ResourceManager in the application class constructor , after I have initialized the PBEngine using the function Global.startup(this)</p>
<pre class="brush: as3;">
      public function SampleDynamicResourceProvider()
      {
         // Start up PBE
         Global.startup(this);
         // register our Dynamic Resource Provider
         ResourceManager.instance.registerResourceProvider(this);
         ...
      }
</pre>
<p>Our dynamic (render on the fly) resource provider will catch all resources of the ImageResource type that are requested using the format &#8216;@circle(width,height,color)&#8217;. </p>
<pre class="brush: as3;">
   	  public function isResourceKnown(uri:String, type:Class):Boolean
   	  {
   	  	// capture only @circle(..) resource source requests
		if (uri.toLowerCase().indexOf("@circle(")==0)
		  return true;

		// otherwise we dont know the requested resource
		return false;
   	  }
</pre>
<p>It will create the ImageResource by rendering a Bitmap with the specified width and height drawing a coloured circle on it. It will create this resource as it is requested (on the fly) by the ResourceManager.</p>
<pre class="brush: as3;">
   	  public function getResource(uri:String, type:Class, forceReload:Boolean = false):Resource
   	  {
   	  	// split the params of the '@circle(params)' source to an params:Array
	 	var sparams:String = uri.split("(")[1];
	 	sparams = sparams.split(")")[0];
	 	var params:Array = sparams.split(",");

	 	// convert params to the right types
	 	var width:int = int(params[0]);
	 	var height:int = int(params[1]);
	 	var color:uint = uint(params[2]);

	 	// create a Sprite object
	 	var sprite:Sprite = new Sprite();

	 	// draw a filled circle with a thick black line
	 	sprite.graphics.beginFill(color,1);
	 	sprite.graphics.lineStyle(2,0x000000);
	 	sprite.graphics.drawCircle(width/2,height/2,(width/2)-2);
	 	sprite.graphics.endFill();

	 	// draw this sprite onto a BitmapData object
	 	var bitmapData:BitmapData = new BitmapData(width,height,true,0);
	 	bitmapData.draw(sprite);

	 	// create an ImageResource
	 	var resource:ImageResource = new ImageResource();

	 	// set the image resource filename
	 	resource.filename = uri;

	 	// initialize this ImageResource using the BitmapData object
	 	resource.initialize(new Bitmap(bitmapData));

	 	// return the resource to the ResourceManager
	 	return resource;
   	  }
</pre>
<p>We can now create sprite entities that use SpriteRenderComponent where this @circle(..) will be provided as the loadFromImage property.</p>
<pre class="brush: as3;">
         createSprite(0,0,"@circle(75,75,0x00cc00)");
         createSprite(-20,-20,"@circle(35,35,0x0000cc)");
         createSprite(20,20,"@circle(50,50,0xcc0000)");
</pre>
<h2>5. Subclassing the ResourceProviderBase</h2>
<p><a href="http://www.makeyourflashgame.com/content?co=/tutorials/pbe&#038;tu=sampledynamicresourceprovider&#038;h=400">See this tutorial in action</a><br />
<a href="http://content.makeyourflashgame.com/pbe/tutorials/SampleDynamicResourceProvider-src.rar" target="_blank" >Download the sources of this tutorial</a></p>
<p>The ResourceProviderBase is a nice class we can derrive from to render or load resources &#8216;on beforehand&#8217; and store them so that the ResourceManager can access them using this resource provider.</p>
<p>When we create this Resource Provider class in our application&#8217;s constructor, the resources are created and stored within the resource provider.</p>
<pre class="brush: as3;">
      public function SampleDynamicResourceProvider()
      {
         // Start up PBE
         Global.startup(this);                                                

         // register our Dynamic Resource Provider
         ResourceManager.instance.registerResourceProvider(this);

         // create our SampleResourceProvider
         new SampleResourceProvider();
         ...
       }
</pre>
<p>If we subclass the ResourceProviderBase and call the super(); from within our constructor, the provider is auto-registered with the ResourceManager.</p>
<pre class="brush: as3;">
	public class SampleResourceProvider extends ResourceProviderBase
	{
		public function SampleResourceProvider()
		{
			// call the constructor of the ResourceProviderBase so this
			// provider is registered with the ResourceManager
			super();

			// create the resources of this resource provider
			createResources();
		}
                 ...
             }
</pre>
<p>Using the function addResource(src:String, type:Class, resource:Resource) we can add our own resources to this resource provider and the ResourceManager has access to them.</p>
<pre class="brush: as3;">
		/**
		 * This method will create a resource and add it to this
		 * ResourceProvider
		 */
		private function createResource(src:String ,color:uint):void
		{
		 	// create a Sprite object
		 	var sprite:Sprite = new Sprite();

		 	// draw a filled circle with a thick black line
		 	sprite.graphics.beginFill(color,1);
		 	sprite.graphics.lineStyle(2,0x000000);
		 	sprite.graphics.drawRect(0,0,150,150);
		 	sprite.graphics.endFill();

		 	// draw this sprite onto a BitmapData object
		 	var bitmapData:BitmapData = new BitmapData(150,150,true,0);
		 	bitmapData.draw(sprite);

		 	// create an ImageResource
		 	var resource:ImageResource = new ImageResource();

		 	// set the image resource filename
		 	resource.filename = src;

		 	// initialize this ImageResource using the BitmapData object
		 	resource.initialize(new Bitmap(bitmapData));

		 	// add the resource to this ResourceProvider
		 	addResource(src, ImageResource, resource);		 		 			 	 		 	 	

		}

		/**
		 * This method will create all resources this
		 * resource provider 'knows'
		 */
		private function createResources():void
		{
			createResource("yellow",0xffff00);
			createResource("blue",0x0000ff);
			createResource("white",0xffffff);
			createResource("green",0x00ff00);
			createResource("red",0xff0000);
		}		

	}
</pre>
<p>We can request the colored rectangles &#8216;yellow, blue, white, green and red&#8217; using this resource provider.</p>
<pre class="brush: as3;">
         createSprite(-100,-100,"blue");
         createSprite(100,100,"red");
         createSprite(100,-100,"green");
         createSprite(-100,100,"yellow");
         createSprite(0,0,"white");
</pre>
<p><a href="http://www.makeyourflashgame.com/content?co=/tutorials/pbe&#038;tu=sampledynamicresourceprovider&#038;h=400">See this tutorial in action</a><br />
<a href="http://content.makeyourflashgame.com/pbe/tutorials/SampleDynamicResourceProvider-src.rar" target="_blank" >Download the sources of this tutorial</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.makeyourflashgame.com/267/the-pbe-resource-provider-model-explained.html/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
