Archive for 2007

Some notes on inheritance in ActionScript 2

Friday, December 7th, 2007

When implementing super and subclasses, Flash will call the superclass’ constructor automatically unless you call it yourself.
Imagine you have the following code:

class Super {
   public function Super () {
       trace ("super called");
   }
}

class Sub extends Super {
}

var myObject:Object = new Sub();

Result? Yes indeed, it traces “super called”. The constructor for Sub doesn’t exist, so the default constructor is used, which calls the super class constructor by default.
All’s fine…

Next example:

class Super {
   public function Super (pName:String) {
       trace ("super called with "+pName);
   }
}

class Sub extends Super {
}

var myObject:Object = new Sub();

Result? The super constructor is still called! (To my amazement, but anyway). It is called with no parameters since we didn’t pass any, so I guess that was to be expected. So although this is a little evidence that we should have called the constructor explicitly, it still wouldn’t have prevented us from calling it without parameters.

Ok, next bit of code:

class Super {
   public function Super (pName:String) {
       trace ("super called with "+pName);
   }

   public function mySuperMethod() {
   }
}

class Sub extends Super {
    public function Sub() {
    }
}

var myObject:Object = new Sub();

Result? Yes, the super constructor is still called, since that was the default behavior. Us defining a constructor doesn’t mean we have overridden the superclass constructor.

Ok, let’s move on!

class Super {
   public function Super (pName:String) {
       trace ("super called with "+pName);
   }

   public function mySuperMethod() {
   }
}

class Sub extends Super {
    public function Sub() {
        super.mySuperMethod();
    }
}

var myObject:Object = new Sub();

Result? The super constructor is NO LONGER called. Appearently something is getting messed up by the super. statement. In both the Flash IDE and the MTASC compiler the super constructor fails to run. If we replace super.mySuperMethod(); with mySuperMethod(); the super constructor is called again. Note that super.mySuperMethod is NOT a case of calling the superclass’ constructor, I’m simply calling one of the superclass’ methods.

Conclusions:

  • always called super ( … ) ; explicitly
  • do not use super. to clarify your code, unless you consequently follow the first rule

Blue Screen of Death on an ATI display device

Friday, December 7th, 2007

In this case the following applies:

  • BSOD ( blue of screen death ) occurs on system reboot through a RDP ( remote desktop connection )
  • The message is ati2dvag.dll TERMINAL_SERVER_DRIVER_MADE_INCORRECT_MEMORY_REFERENCE

then in my case the following steps fixed the problem:

  • Goto My Computer, Hardware, Display Devices, Delete ATI display device
  • reboot
  • download and install latest ATI driver only package (7.11)
  • install drivers
  • reboot

Done. Hope this helps you too.

Inverting the alpha of a bitmap image in ActionScript 2

Friday, November 30th, 2007

A piece of code and a demo says more than a thousand words :) . This code demonstrates inversion of an alpha channel in Flash8/AS2.

/**
* This example demonstrates inverting an alpha channel on an image.
* Since Flash premultiplies the alpha, we need to keep two separate images: one with the color data, and
* one with the alpha data. It demonstrates splitting the alpha from an image, inverting and proves
* premultiplying the alpha destroys color information.
*
* @author J.C. Wichman
*/
import flash.geom.Rectangle;
import flash.geom.Point;
import flash.display.BitmapData;
import flash.filters.ColorMatrixFilter;

//set up some default params for the images
var width:Number = 100;
var height:Number = 100;
var fillColor:Number = 0×000000;

/**
* Simple function that checks how many bitmaps have already been shown on stage and
* bases the location for the next one on that information. Never use code like this
* out of context, since its bad programming practice:).
*/
function showBitmap (pBitmap:BitmapData, title:String) {
var imageCount:Number = this.getNextHighestDepth();
var row:Number = Math.floor (imageCount/3);
var columns:Number = imageCount%3;

var newClip:MovieClip = this.createEmptyMovieClip(“image”+imageCount, imageCount);
newClip.attachBitmap(pBitmap, 0);
newClip.createTextField(“title”, 1, 0, 110, 10,10);
var textClip:TextField = newClip["title"];
textClip.autoSize = true;
textClip.text = “Image “+imageCount+”:\n”+title;
var tf:TextFormat = new TextFormat();
tf.font = “Arial”;
tf.align =”center”;
textClip.setTextFormat(tf);

newClip._x = (columns * 150)+10;
newClip._y = (row * 170)+10;
}

//setting up demo rgb image, this is an image without alpha.
//Since flash uses premultiplied alpha, adding an alpha channel will ruin the image for
//further use when we want to invert the alpha channel, so we keep colours separate from alpha
//(omg pink shirts!)
var colorImage:BitmapData = new BitmapData(width, height, false, fillColor);
for (var x = 0; x < width; x++) {
for (var y = 0; y < height; y++) {
//fiddle with the pixel data to show a dark gradient
colorImage.setPixel( x,y, x<<16|y<<8|x+y);
}
}
showBitmap (colorImage, “Colour w/o alpha”);

//now we create a demo alpha bitmap. All color info is non existent, only
//alpha data is set. When x //we only use 0xAF and 0×10 instead of 0xFF and 0×00 to show partial alpha values are inverted ok as well
var demoAlpha:BitmapData = new BitmapData(width, height, true, fillColor);
for (var x = 0; x < width; x++) {
for (var y = 0; y < height; y++) {
demoAlpha.setPixel32( x,y, (x }
}
showBitmap (demoAlpha, “Alpha only”);

//now imagine you didnt have a separate alpha bitmap to start with, but a starting image with alpha
//which you needed to extract first:
var alphaSplit:BitmapData = new BitmapData(width, height, true, fillColor);
//copy the alpha channel of one image to another image
alphaSplit.copyChannel(demoAlpha, new Rectangle(0,0, width, height), new Point(0,0), 8,8);
showBitmap (alphaSplit, “Alpha channel copy\n (same as previous)”);

//now we are going to invert the alpha. This can be done on a pixel by pixel basis, but this might just
//be faster, you’d have to test it
var alphaInvert:BitmapData = alphaSplit.clone();
var matrix:Array = new Array();
matrix = matrix.concat([1, 0, 0, 0, 0]); // red
matrix = matrix.concat([0, 1, 0, 0, 0]); // green
matrix = matrix.concat([0, 0, 1, 0, 0]); // blue
matrix = matrix.concat([0, 0, 0, -1, 0xff]); // alpha, negate the alpha and add 255
alphaInvert.applyFilter(alphaInvert, alphaInvert.rectangle, new Point(0, 0), new ColorMatrixFilter (matrix));
showBitmap (alphaInvert, “Inversion of \nalpha channel”);

//now the real action, we combine our original color pixels with the inverted alpha channel
var comboImage:BitmapData = new BitmapData(width, height, true, fillColor);
comboImage.copyPixels(colorImage, colorImage.rectangle, new Point(0,0), alphaInvert, new Point(0,0));
showBitmap (comboImage, “Colours + \ninverted alpha”);

//now to prove premultiplied alpha destroys color information:
var colorImgWithAlpha:BitmapData = new BitmapData(width, height, true, fillColor);
for (var x = 0; x < width; x++) {
for (var y = 0; y < height; y++) {
//fiddle with the pixel data to show a dark gradient
colorImgWithAlpha.setPixel32( x,y, (x }
}
colorImgWithAlpha.applyFilter(colorImgWithAlpha, colorImgWithAlpha.rectangle, new Point(0, 0), new ColorMatrixFilter (matrix));
showBitmap (colorImgWithAlpha, “Colour with\n premultiplied \n inverted alpha”);

Old skool AJAX

Friday, November 16th, 2007

I was thinking about how I used to program Java before I got hooked onto Flash. I started on Java because of its conceptual beauty. And I loved how all the academic OO concepts taught and studied at the University could be tested and implemented in Java. Hell, I even swore Composition Filters amounted to Object Oriented Salvation for a while :twisted: .

My thoughts wandered back to my first java projects at TriMM back in 1999 and onwards. My boss at that time loved to set a challenge and this challenge involved hiding an applet in a hidden frame of your browser to abuse it for html code generation. The applet would implement a command style pattern, processing the given commands in an asychronous thread, generating HTML. Even back in 1999 it was possible this way to provide a LOT of functionality on the client side, relieving the server of heavy duty processing. The AppletWrapper principle, as it was called, used html, a javascript layer which hid the applet details from the html and provided a javascript command queue, which would wrap all asychronous communication with the underlying applet.

The applet could do a lot, and even more when it was signed. For example even back then, it could download a zip file containing a small database, extract it in memory on the client side and read and process the data to present it in a particular format. At one point the client decided he wanted to deliver the website on cd as well, and migrating the webcontent to cd was basically a copy and paste action (with respect to the applet). The basic principle was applied many many times, eg we had table selection mechanisms, dynamic tree displays, and an offline search engine on the cd. The applet could read zip files, access databases (the applet would run from the cd, open a nameless ODBC connection to an MSAccess database also on the cd, perform sql queries on the data and generate the results through templates from a zip file, and deliver the content back to the browser).

Now that Flash is catching up in AS3, a lot of people go oooohh and aaaaahhh, but the fact remains, java had some good things going. The reason I’m speaking in past tense is that I’ve been away from Java so long, that I’m not confident the problems it had have been solved. One of the biggest problems was the platform compatibility. These java applets had to run on all windows platforms, all mac platforms, linux, unix etc. And let me tell you, that was pretty difficult. Luckily since the applets were code generating applets, we didn’t have to deal with AWT or Swing, which made things a hell of a lot easier. And due to the generality of the codebase (a particular implementation of this principle could reuse about 90% of the codebase of a previous implementation), each application we built took less time.

Still, we might be migrating some of them to Flash and I’m excited to see whether this will be possible. One other fun fact is that for a few years AJAX and Web 2.0 have been buzzwords and we were building applications on this principle back in 1999 without fully realizing how damn cool it was.

I’ll post a demo of this soon (update: the files have been replaced after 9 years of duty, I’ll see if I can post them on my own site soon, 06-03-2010).

Of course during the years functionality was added, but the principle remained the same. Projects the other way around occurred as well, we started with a cd application which could be distributed and then the client decided he’d like the application to run on the web as well. In one particular case we simply copied the cd to the web, including the interactive applets, migrated the MSAccess database to MySql and updated the database connection string for the applet.

This turned out to work quite well, but we were defeated by simple firewall issues (the applet couldn’t make direct mysql server connections from the client’s side on a lot of locations, such as schools and company intranet sites). We rewrote the applet to a servlet which the same queue processing functionality, included a ServletWrapper in the HTML layer instead of an AppletWrapper, abiding by the exact interface the AppletWrapper had, and the problem was solved, a local application became a server application with minimum effort.

Casting to Array in ActionScript 2

Friday, November 16th, 2007

Imagine you have:
var my2dArray:Array = new Array();

my2dArray.push ([1,2,3,4,5]);
my2dArray.push ([6,7,8,9,0]);

And now you want to access and cast an element of myArray to an array:

var firstArray:Array = Array (my2dArray[0]);
trace (firstArray.length);

Right?

Yeah if you’re compiling in MTASC. The Flash IDE doesn’t regard Array(…) as a cast however. It considers the statement as a plz – construct – my – array – and – provide – me – with – hours – of – mind – numbing – debugging.

If you check the code, you’ll see compiling in MTASC prints 5 and compiling in the Flash IDE prints 1.

So how do we fool the compiler to provide a solution that works in both environments ?

var firstArray:Array = [my2dArray[0]][0];

In other words, construct a new array of the element you want to return and return its first element, preventing the compiler from type checking. Nice? No, but it works beautifully and it’s the shortest way there.

It’s okay, you can open your eyes now. So how safe is this? Well I wouldn’t use it across class boundaries for one. And you might wanna add some assert statements, but other than that, buckle up and enjoy the ride :) .

If you do want to do it in a more academic way, you can introduce a subclass of Array, for example ArrayCaster:

class ArrayCaster extends Array {

}

and override the constructor where necessary to be fully compatible with the Array class. Once that is done you can do:

var firstArray:Array = ArrayCaster (my2dArray[0]);

Whatever makes you tick :) .

Grants linked to Behrloo

Monday, November 12th, 2007

Today my project manager informed me that a dutch organization, M&ICT, which came about through an intensive cooperation of several departments of local government such as the department of Justice, Eduction, Culture & Science and more, is holding another competition (the 5th to be exact), called ‘Serious Gaming and Simulation for better safety’.

The documentation can be found here (although it’s in dutch) http://www.m-ict.nl/, and to my pleasant surprise, Behrloo, the system of which I am the lead frontend architect, is prominently featured as an example project and might even be a contestant as well. Check out page 11.

Another preliminary research report can be found here: http://appz.ez.nl/publicaties/pdfs/07ET09.pdf, check out page 40 onwards!

Very nice read, although not all the information is correct. For example they mention that Behrloo has been built in .Net using flash for the graphical elements. The truth is that the backend was built in .Net and the frontend is a fullfletched object oriented system, which -yes- displays graphical elements, but has no less than 300 classes and several subapplications under the hood. No timelines were hurt during the development of this system :) .

Nice to see TriMM is mentioned as well!

Create your own testserver with a fake domain (XP)

Tuesday, October 16th, 2007

When you are developing a theme for say Joomla, or editing a lot of content, it is easier now and then to do this offline.
However if you DO want to do this offline, you’ll need a testserver.

I’ve been using JSAS, Joomla StandAlone Server for that purpose (but switched to XAMPP recently).

Once installed, you’re good to go with apache, php, mysql and joomla.

By default it will give you a local webserver on your localhost, reachable on port 85, in other words, to test it, goto :

http://localhost:85/

Inside the JSAS directory you will find a http_root directory, with a www directory inside it, and that’s the directory that will show in your browser by default if you go to http://localhost:85/.

Now imagine you have a site www.mybogussite.com and a www.myothersite.com and you both want to test/develop these offline.
You probably end up with something like:
http_root/www/mybogussite
http_root/www/myothersite

or

http_root/www/www.mybogussite.com
http_root/www/www.myothersite.com

BUT since you have to access them through links such as localhost:85/myothersite/ links might be broken.

One other way to handle this is by using virtual hosts.

First we need a fake domain name address. In Windows XP we do this by editing the hosts file, found in:
C:\WINDOWS\system32\drivers\etc

Add a line to this file such as:
127.0.0.1                www.mybogussite.local

Now reboot your pc.

Next step is to edit your apache conf file, found in http_root/usr/local/apache2/conf/httpd.conf:

<VirtualHost *>
DocumentRoot /www/www.mybogussite.com
ServerName www.mybogussite.local
</VirtualHost>

Note that you should fill in the specific name of your local directory after documentroot and whatever you’ve put into the hosts file after the ServerName.

Now restart apache and you’re done, open your browser and enter www.mybogussite.local into the address bar.

Note that to keep the old one intact, you’ll have to add:

<VirtualHost *>
DocumentRoot /www/
ServerName localhost
</VirtualHost>

as well.

Commandline scripting in PHP 5

Wednesday, August 29th, 2007

At TriMM I am working on an eLearning environment consisting of a core engine and some 500 swfs (and growing). Some of these locations are very simple, like an image with hotspots and some are more complex such as an emailclient. The engine is refactored now and then, and extended, in addition the requests for some of the locations themselves might change.
All the work is done by different people in different roles, and some location versions might or might not be compatible with certain version of the core engine.

Why am I telling you this? Because I switched from Flash to PHP because of this? :) No way.

But I do have to write a script to automate the release process, which will collect the latest versions of all location swf’s that go with a certain core engine version. I thought about using Ruby or Python for that, but since TriMM does a lot of Java, PHP and Flash, I decided it had to be one of those 3.

My first choice was PHP since it is a scripting language and doesn’t have to be compiled. Having written a little bit in it, I’m not so sure if I’m gonna stick with my choice since me and untyped functional languages dont really match, but okay okay I’ll try.

I tried PHPEclipse but that wasn’t working for me, so hopefully this setup will work, these are the steps I took. By the way this cost me the better of 2 days to figure out, all because of the all so wonderfull platform called eclipse. Installing everything separate was easy, getting it to work was next to impossible, due to missing depencies. The fun thing is that eclipse tells you what it’s missing, but not where to find it. Neither does Google, except in some very obscure way. In the end, there is apparently an all in one bundle for PDT, so I settled for that.

God I’m loving folks who keep it simple such as the FlashDevelop crew. This is a good example of expensive open source software, since with all the hours I invested to get this damn simple PDT thing to work I could have bought a lightweight php editor.

  1. download the pdt-all-in-one-incubation-S20070815_M2-win32.zip. I downloaded the latest WTP releases first, but couldn’t get them to work.
  2. extract the zip to a directory c:\program files\eclipse\
  3. drag the eclipse.exe to the startmenu to add it:) (right mouse button, create shortcut)
  4. install the java runtime environment if necessary from java.sun.com
  5. run eclipse
  6. I am executing my php on the commandline, and using a batch file to do so, which has the following content:
    php -a sources\generateDeploymentScript.cmdphp -include=%CD%\include.txt -alwaystrunk

    As you can see, I’m using the -a option to show how far the script has gotten even if errors are occuring and I’ve renamed the .php to cmdphp to show that the script is meant to run from a commandline and should’nt be mistaken for a webserver script.
    Dragging this batchfile to the eclipse environment causes it to be executed, which is not what we want.
    Fix this by following these steps:
    Goto Window -> Preferences -> +General+Editors+File Assocations -> Add *.bat and associate a Text Editor with it

    In addition the cmdphp isnt recognized so add that as well, and associate it with the PHPEditor.

  7. Open the cmdphp file, in my case it gave another warning, and a content type link to fix the problem. I looked up the PHP Content Type in the Filtered Preferences dialog, and added cmdphp there as well. Close the cmdphp file and open it again and voila!
  8. In order to run the script within eclipse and see some output, goto Run, External Tools, Open External Tools Dialog. I added my batch file as an external tool, entering only the location and working directory.
  9. Next in order to have the errors be shown in the console as well, I went into my PHP 5 directory (downloaded from http://www.php.net/get/php-5.2.3-win32-installer.msi/from/a/mirror) and opened the php.ini file and changed this setting:
    display_errors = On
    Note that you shouldn’t do this if the same PHP 5 distribution is being used for live website deployment, due to security issues that could arise.
  10. If necessary goto Window -> Preferences -> General -> Editors -> Text Editors and turn on line numbers

And tadaa done.

When you’ve finally figured something out, it’s always so simple in hindsight.
So what took me so long? Downloading the wrong distributions, downloading the wrong plugins to try etc.

Wrapping function calls in ActionScript 2

Friday, August 24th, 2007

Also known as:

  • debugging function calls
  • displaying the name of a called function
  • tracing function calls director like

Today I finally got to try something I had been wanting to try for a long time: wrapping function calls in a nice way.

I had been playing around with function pointers etc, which was ok in itself, but I was forced to create the messy pointer bit each time over again. So I implemented a FunctionWrapper class.

Say we have a class Test, with a method testMethod.

Now we want to execute some code before calling testMethod and after calling testMethod. “Well write another function to do so”, you might say. Of course that is one option, but assume we are looking for another way to do so (I’ll discuss some scenario’s in a minute).

Using function pointers you can let the Test.testMethod reference point to your own method and from your own method execute the original method, pre and postpending it with some functionality. I think this is a bit like the AOP mechanism, but I’m not too sure.

The FunctionWrapper class takes care of all this reference shuffling for you:

FunctionWrapper.wrap (
	TestClass,
	"testMethod",
	_preFunction,
	null,	//no additional args to pre
	_postFunction,
	null  //no additional args to post
);

Now I won’t explain a lot more about that on this page, since I’ve got an example for download here, which contains all required classes and documentation. Note that the example requires some support classes which aren’t ‘really’ needed, but I don’t like to write anything twice and I hate searching for null pointer errors, so I use a lot of utility functions and a lot of assertions.

So I’ll skip to the uses.

I see one major use: debugging.
And then debugging without modifying your existing code!

Imagine these scenario’s:

  • you are refactoring your code, and want to get a signal when some old code is being executed.
  • you want to print whether a function is executed, with what arguments and inspect the return value, but you don’t want to or can’t change the source code
  • you want to see a nested function trace without using the debugger
  • you have all these debug statements, but it might be harming performance so you want to take them out

Note that for these scenario’s, the FunctionWrapper isn’t enough, but it’s a start. For example using my upcoming reflection package you can traverse all functions in a class and have them wrapped with a debug mechanism automatically. At this time you still have to specify each functionname manually.

A small example of what it looks like, imagine I have the following class:

class TestClass {

	/**
	* Just a simple test method, which returns a value as well so we can test the post process mechanism.
	*
	* @return a string
	*/
	public function testMethod() : String {
		trace ("This is printed by testMethod");
		testMethod2();

		return "I am testMethod's returnvalue";
	}

	/**
	* Just a simple test method without a return value
	*/
	public function testMethod2() : Void {
		trace ("This is printed by testMethod 2");
	}
}

Now we execute the following code:

var lTestClass:TestClass = new TestClass ();
lTestClass.testMethod(1,2,3);

it will print:

This is printed by testMethod
This is printed by testMethod 2

Now assume for a moment that those werent trace statements but silent operations, you would see:

Yes exactly nothing….

Now we wrap our function calls, as mentioned before, at this time this has to be done manually, or you have to create a simple prototype/class iterator looking for functions on a class, but for the sake of simplicity, we’ll do it manually:

FunctionWrapper.traceWrap (TestClass, "testMethod");
FunctionWrapper.traceWrap (TestClass, "testMethod2");

Note that this is done WITHOUT altering the TestClass, so the TestClass stays the same.
If we re-execute our example again (lTestClass.testMethod(1,2,3);), you will see the following:

=> Entering testMethod with arguments 1,2,3
This is printed by testMethod
  => Entering testMethod2
This is printed by testMethod 2
  <= Exiting testMethod2 with no return value.
<= Exiting testMethod with return value:I am testMethod's returnvalue

You can see testMethod is called first, and with which arguments. You can see it then calls testMethod2, which is nested one level deeper and that testMethod2 exits again with no return value. In turn testMethod returns with its original return value.

So we get to see the method flow including parameters and return types without ever touching the original functions themselves.

There is more but you’ll have to check for yourself by downloading the example and all required code here: FunctionWrapper (66).

Local Flash Content and SSL

Tuesday, August 14th, 2007

We are in the process of migrating one of our largest eLearning systems to SSL and Active Directory. Some of the Learning Objects within this system are pretty complex and I’ve implemented a mechanism which allows you to test them standalone.

However during the migration to SSL these objects stopped working when run locally, from the IDE or from FlashDevelop.

I tried to wrap my head around why this was happening, since I’ve been doing less and less with serverside content and certificates these past few years.

Luckily I found this URL which described the problem quite accurate.

Http:// content cannot always access https:// content it seems, but the invalid security certificate was the biggest issue for us.

Our system admin Roy Olthof quickly jumped in, installed a valid certificate and tadaaaaa. Local content could access https content again. Note that we were accessing https content on our own test server, which didnt have a certificate installed.

In addition the Flash content kept giving me the mixed content (secure and unsecure) warning. After changing all the http://’s in the macromedia/adobe codebases (contained within the object and embed tags) this disappeared as well.