Posts Tagged ‘class’

Globals? Still?

Posted in Actionscript 3, Article, Best Practices on November 17th, 2010 by Ian Ford – Be the first to comment

I was just looking at some code for a colleague of mine and noticed something.


import lt.uza.utils.Global;

 public class Main extends Sprite {

 private var global:Global = Global.getInstance();

 public function Main() {

 global.stage=stage;

 setupStage();
 ApplicationFacade.getInstance().startup(stage);
 }
 public function setupStage():void {
 stage.quality=StageQuality.HIGH;
 stage.scaleMode=StageScaleMode.NO_SCALE;
 stage.align=StageAlign.TOP_LEFT;
 }

 }

What is this “Global” business?

I followed the trail and found Uza’s global class. I was going to chime in against globals but I was beaten to the punch. Robert Penner (!) said it best.

The developer explained himself as follows:

@Robert Penner

Thanks for dropping by! :)

Although I admit that global variables CAN cause problems, many programs can benefit from them if used in a controlled manner. I’m using development patterns myself everyday, however I find Global class a great addition to my toolset letting me create difficult systems with less code and clutter.

Another reason is that if you are doing real life development on a tight budget and an even tighter timeline (thus cannot invest time in using propper MVC), Global will most probably be your best solution to get things done fast and clean.

OOP strongly opposes any global variables, however I believe my AS3 implementation is quite compatible to pass the check.

Give it a try!

Am I the only person who finds this excuse inadequate?

Gesture Recognition

Posted in Article, Gesture Recognition, Links, Tips, User Experience on March 11th, 2010 by Ian Ford – Be the first to comment

Gesture Recognition

I’ve spent the last day or two reacquainting myself with what’s been done to achieve reliable gesture recognition in AS3. I have reviews of two different packages I tried, one of which is relatively new and one of which has been around for some time.

One note about all of the gesture recognition classes I’ve looked at is that they are direction-dependent. That is to say that if you’re attempting to capture the gesture corresponding to a vertical line, a stroke from top to bottom is not the same thing as a stroke from bottom to top. Furthermore, neither of those will necessarily be captured in a stroke from top to bottom to top. This all has to do with the algorithms being employed to detect gestures and attempts to make them run as efficiently as possible.

The first package I looked at was offered up by a Mr. Felix at bertiesbraum.de. Felix’s gesture recognizer consists of AS3 implementations of the “$1 Gesture Recognizer” and “ShortStraw Corner Finder” algorithms, which he has the decency to cite and link to (unlike me).

His post does a much better job of explaining basic usage of the classes than I care to at the moment, but what I will say is that I was unable to get the classes to function without false positives. This is likely because, as Felix notes, “The gestures are also rotation, position and scale invariant,” which is to say that a single stroke probably ends up being a single stroke, regardless of which direction it points. With more complex figures I was able, in the sample application Felix provides, to demonstrate direction dependence. In my case I’m trying to detect single strokes in distinct directions, and so it may be that these algorithms are over-engineered for my purposes.

The second package I looked into was posted in a short article at ByteArray.org by Didier Brun. I caught this post when it first came out (almost three years ago) and was very impressed with the concept but didn’t have any real use for it at the time. I toyed with it today and have been pleased with the results.

Initially Mr. Brun’s classes posed the same problem that most gesture recognition algorithms do: it was unable to recognize identical patterns if they proceeded in different directions. Additionally, all of the packages I’ve seen presume that the user will begin their gesture by pressing the mouse button down, and end the gesture by releasing it. I’m trying to detect whether orĀ  not a user is shaking an object they’ve picked up in an up-and-down fashion, so it’s important to me to recognize sub-gestures within a larger “gesture.” If I depend solely on button presses and releases, the gesture that ends up being analyzed consists of tens of motions at the least.

I came up with a solution using Mr. Brun’s classes that allowed me to achieve my ends. Brun’s gesture recognition class offers a custom event that fires when capture begins and ends, when a match is made or not made, and while capture is taking place. The last of those was most important to me. I added a public property to his existing GestureEvent class. The modified class looks like this:

package com.foxaweb.ui.gesture {

	import flash.events.Event;

	public class GestureEvent extends Event {

		// ------------------------------------------------
		//
		// ---o static
		//
		// ------------------------------------------------

		public static const START_CAPTURE:String="startCapture";
		public static const STOP_CAPTURE:String="stopCapture";
		public static const CAPTURING:String="capturing";
		public static const GESTURE_MATCH:String="gestureMatch";
		public static const NO_MATCH:String="noMatch";

		// ------------------------------------------------
		//
		// ---o properties
		//
		// ------------------------------------------------

		public var datas:*;
		public var fiability:uint;
		public var moves:String;

		// ------------------------------------------------
		//
		// ---o constructor
		//
		// ------------------------------------------------

		public function GestureEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false){
			super (type,bubbles,cancelable);
		}

		// ------------------------------------------------
		//
		// ---o methods
		//
		// ------------------------------------------------

		public override function clone():Event{
			return new GestureEvent(type, bubbles, cancelable) as Event;
		}

	}
}

I also made a change to the MouseGesture class to make sure that “moves” were being attached to GestureEvents dispatched during the “CAPTURING” phase. The modified function looks like this:

protected function captureHandler(e:TimerEvent):void{

	// calcul dif
	var msx:int=mouseZone.mouseX;
	var msy:int=mouseZone.mouseY;

	var difx:int=msx-lastPoint.x;
	var dify:int=msy-lastPoint.y;
	var sqDist:Number=difx*difx+dify*dify;
	var sqPrec:Number=DEFAULT_PRECISION*DEFAULT_PRECISION;

	if (sqDist>sqPrec){
		points.push(new Point(msx,msy));
		addMove(difx,dify);
		lastPoint.x=msx;
		lastPoint.y=msy;

		if (msx<rect.minx)rect.minx=msx;
		if (msx>rect.maxx)rect.maxx=msx;
		if (msy<rect.miny)rect.miny=msy;
		if (msy>rect.maxy)rect.maxy=msy;
	}
	// event
	var evt:GestureEvent = new GestureEvent(GestureEvent.CAPTURING);
	evt.moves = moves.join("");
	dispatchEvent(evt);

	//dispatchEvent (new GestureEvent(GestureEvent.CAPTURING));

}

The final step was to deal with the entire set of move data in my application. I configured my instance of the MouseGesture class to handle GestureEvent.CAPTURING events and created the following function to deal with them.

private function _captureHandler(e:GestureEvent):void {
	var reShake:RegExp = /(62|26)/g;
	var shakes:int = e.moves.match(reShake).length;
	field_shakes.text = "Number of Shakes: " + shakes;
	if (shakes >= 12) {
		stage.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_UP));
		field_shakes.text = "Congratulations!";
	}
	trace(e.moves);
}

The important thing to note here is the regular expression being used. The strings “62″ and “26″ correspond to the output that would be expected from a vertical shake gesture in the MouseGesture class (respectively “up->down” and “down->up”). What the function does is scan the entire list of movements and look for instances in which the patterns I’m trying to match have occurred in sequence. For each occurrence of either pairing, we know that the user has successfully “shaken” the can. A single call fired to the “_captureHandler” function might have a “moves” list that looks like this…

0666662255222666666222566222266222266672226666122561

…in which each digit corresponds to one of 8 possible directions the user moved his mouse. If you count carefully, you’ll find 8 instances of either the sequence “62″ or the sequence “26.”

Ultimately Mr. Brun’s class ended up being more useful for the project that I’m working on, but I hope to see other implementations in the future that will allow for more complex gestures to be recognized.

Vidiot – A Wrapper for Adobe’s OSMF

Posted in API, Downloads, Flash, OSMF, Video, Vidiot on March 6th, 2010 by Ian Ford – 3 Comments

I’ve been working, over the last few weeks, with Adobe’s Open Source Media Framework. The OSMF is Adobe’s initiative to provide a standard set of tools and interfaces for deploying video content on the Flash Platform.

The framework is built loosely according to a MVC pattern, in which the Model consists of various MediaElements, the View consists of a MediaContainer, and the Controller consists of a non-displayable MediaPlayer class. As of its current release (Sprint 9), methods of implementation are so varied that it’s hard to find reliable documentation or concrete examples of how to use many of the components of the framework. This makes it difficult to work with so far, but the capabilities being planned and exposed for the project make it very exciting to jump in and start coding.

Today I connected to the project SVN, updated to the latest revision, and jumped back into developing a wrapper that I originally began planning for Sprint 8. I’ve implemented a very simple class based on the latest revision of Sprint 9 which I’m offering you today. I’m calling the project Vidiot to reflect my hope that it will be so easy to use, even an idiot will be able to display video in Flash.

The demo above uses the Vidiot class to play a sample streaming video hosted by Akamai. Layout and playback controls are separate from the Vidiot class. The simplest use case for Vidiot looks like this:

var vidiot:Vidiot = new Vidiot();
addChild(vidiot);
vidiot.load("video path");

At this stage, it doesn’t really get any more complicated than that. You can use Vidiot to play either progressive or streaming video (though thus far I’ve been unable to stream from Edgecast. Hmm….), and in theory this thing is also set up to play audio or still images as well, though I’ll have to test that out and probably update some of the code.

I hope to continue to release new versions of Vidiot and keep it up to date with the latest builds of OSMF. If all goes well you’ll see more posts about this in the future.

Download sample video player and Vidiot source code

UPDATE: Vidiot has been updated. Check out the most recent post.

Tips and Best Practices – Namespaces and Accessors

Posted in Article, Best Practices, Flash, Flex, Tips, Tutorial on February 14th, 2010 by Ian Ford – Be the first to comment

I’ve decided that in addition to posting code samples, applications, and packages for download I would also engage in trying to promote practices that I find helpful in making writing AS3 easier in the long run. What do I mean when I say these tips will make things easier? I mean that as you continue to work with code you’ve written, especially within larger projects, you should find it less difficult to track down bugs, interpret code you may not have looked at for some time, and share code with other developers.

The first tip has to do with namespaces and scope. If you’re at all familiar with object oriented programming and writing classes in AS3, you know that within a class you can declare variables to hold important data that are unique to each instance of the class. The built in namespaces available for these variables are public, private, and internal.

Today I’ll be discussing the public and private namespaces, and how you should use them when considering how an instance of your class will be used throughout your application.

For the purposes of making myself clear, suppose we’re tasked with creating a class intended to represent a person:

package {
     public class Person {
          public function Person() {}
     }
}

A “Person” may have a number of characteristics we’d like to keep track of. For example, we may want each “Person” to be aware of his name, age, and gender. We can declare these values as members of each instance of the class by placing variable declarations within the brackets corresponding to the class definition. The question I intend to answer today is whether we should declare these values as public or private.

If you intend to pass instances of your Person class around your application, and you intend to retrieve the values stored within, it may seem that the simplest thing to do is to declare your class variables as public.

package {
     public class Person {
          public var name:String;
          public var age:int;
          public var gender:String;

          public function Person() {}
     }
}

This may seem like a good idea, as in the future you may want to access a person’s name like so:

var guy:Person = new Person();
guy.name = "franz";
trace(guy.name) // output: franz

However, suppose you have a large number of people you need to represent. Furthermore, suppose these people have their values extracted and used in a large number of places throughout your code. Furthermore, suppose after you’ve done the leg work of getting most of your application ready, it occurs to you, for whatever reason, that a person’s name should be in all capital letters. Now, you could track down every declaration of a person and replace the name with capitalized text…

var guy:Person = new Person();
guy.name = "FRANZ"
trace(guy.name); // output FRANZ

…or you could find every instance in which you want to output a name and do the following…

trace(guy.name.toUpperCase()) // output: FRANZ

…or you could have saved yourself a lot of time and trouble by doing things right in the first place. Let’s amend our existing class definition by making our member variables private, and by adding getter and setter functions for each of those variables:

package {
     public class Person {
          private var _name:String;
          private var _age:int;
          private var _gender:String;

          public function Person() {}

          public function get name():String {
               return _name;
          }
          public function set name(val:String):void {
               _name = val;
          }

          public function get age():int {
               return _int;
          }
          public function set age(val:int):void {
               _age = val;
          }

          public function get gender():String {
               return _gender;
          }
          public function set gender(val:String):void {
               _gender = val;
          }
     }
}

Now, if you want to make sure that every name is displayed in all caps, you can modify the name getter function like so:

public function get name():String {
     return _name.toUpperCase();
}

…and voila! The next time you try to access a person’s name (any person, anywhere), you’ll get the desired output. Let’s enumerate the benefits of using this approach:

  1. You get application-level control over the values associated with your classes, without having to dig around for individual members.
  2. Because of the above, you’re less likely to miss members of your classes floating around in obscure functions, and so in the long run you’ll have fewer unpredictable bugs.
  3. You could theoretically call other functions every time a value is accessed for more complex interactions with your class.
  4. Using setters, you can filter values placed in your classes at an application-wide level.

One important point to remember is that the name of your getter and setter functions cannot be same as the name of the private variable you’re using them to access. I recommend prefixing the names of all of your private variables with some sigil (I’m fond of underscores) to deal with this, and later, when you’re making adjustments to your massive class, it’s easy to see at a glance while scanning through your code which variables are private and which are not.

That’s all for now. More tips will be coming down the pipelines in the future.