Pushing the boundaries

…couldn’t be any simpler!

Archive for January, 2007

native function

Posted by vijayram on January 31, 2007

Ok, this is a cool modifier. While I was looking through the notes on ActionScript 3.0, I did notice a reserved keyword called “native”. I had worked with native implementation in JAVA(JNI), so this really got me excited.Why?!

The reason being, the use of native functions indicates that the method is implemented externally. In a DLL maybe? ;). So, there maybe possiblities to call native windowsAPI from the swf…hmmm. Using this abstract modifier means that the method implementation is not provided in the class.Because an external method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no braces ({ }) following the signature.

native function functionName();
class className {
native function methodName();
}

So I started rummaging through the Flash Player code, and voila they use native functions as a part of implementation. What this means is that the native functions available to the Virtual Machine is called for through this function call using ActionScript.

package
{
//pseudo-final – no user class can extend Class
public dynamic class Class
{
// {DontEnum,DontDelete,ReadOnly}
public native final function get prototype()

// Class.length = 1 per ES3
// E262 {ReadOnly, DontDelete, DontEnum }
public static const length:int = 1;
}
}

The above is the actual code for a top level Class construct in the Virtual Machine which is available on tamarin.
Ok, the next obvious step, can I call for it from my code and override it if possible?!

Sadly not!!!! It turns out that Flash Player uses this internally and I cannot use it in my code as explained here.

Posted in Adobe, AS 3.0, Flash, Programming | Leave a Comment »

Garbage Collector

Posted by vijayram on January 31, 2007

Adding to the post on Stacks and Heaps, I had to link to this blog about the internal workings of Garbage Collector in ActionScript 3.0.

Grant Skinner on Resource Management . If that’s not enough, he has published his talks on Garbage Collector using visual simulators here.

*Some side notes:
– You cannot delete class members in ActionScript 3, if you want to cause a variable to no longer reference an object or value in memory, you should set your variable’s value to null instead of deleting it. [ myVar = null; ]
If all variable references to an object are null, the Garbage Collector will mark it for deletion and it will eventually be cleared from memory.
There is a post hereby Gordon Smith explaning the same.
– Ted Patrick has an interesting post on “flash.system.System.totalMemory” saying it just represents the memory allocated to the FlashPlayer. So it might not be the best util to check for memory leaks when you remove objects by setting it to null. You can learn about System.totalMemory here.
– FlashLite has this profiling for sometime now showing the heap memory usage. Pretty cool using the emulator tool. Any questions on that can be directed to IndiMad which is managed by Mariam.

Technorati Tags: , , ,

Posted in Adobe, AS 3.0, Flash, Programming | Leave a Comment »

Stacks and Heaps

Posted by vijayram on January 30, 2007

Someone asked me this question and I wasn’t in the best position to reply back then. This time I will take the effort of writing it down for future reference and for the benefit of all.

Simple explanation would be, stack is allocated before the program executes, where the heap contains memory allocated during the program run.

Using ActionScript for Flash, you can keep track of how much memory Flash Player uses at run-time using the System.totalMemory method.

To begin with data can be of two types, Value or Reference. Although there are many data types, they are always treated: as primitive (also called Value) and by Reference. It is important to note where this data is stored. Value types are stored in “stack” and Reference types are stored in the “heap”. Lets look at this way, objects created on the fly(ie: using the “new” keyword) is stored in the heap while variables will be stored in the stack.

Both Stack and Heap work together. Stack works on basis of last-in, first-out (LIFO). This would be the top-most in the pile would be removed first. Once an object has been instantiated from a class, it is moved into the heap.

During the course of the program running, the heap is polluted with unused data reference which doesn’t exist anymore. This is when the Garbage Collector kicks in. It is the role of the Garbage Collector to clear the heap of unused references or data, else you will have a memory leak, causing the program to come to a grinding halt!

Garbage Collector which is part of the ActionScript Virtual Machine uses several techniques to clear up the data of the heap. There is a “reference counting” technique and there is also a “mark and sweep” technique. From my understanding Garbage Collector in Flash Player 9 uses a deferred method whereby, based on certain factors, the Garbage Collector will kick-in and not by merrily removing the reference to the object in code clears up the heap.

Technorati Tags: , , ,

Posted in Adobe, AS 3.0, Flash, Programming | Leave a Comment »

ActionScript code tricks

Posted by vijayram on January 30, 2007

Continuing with the post, today’s tricks are to do with bitwise operators for manipulation of colours.

After working on the visualizer, it became obvious to me that one needs to know the nitty grittys of assisgning colours and manipulating the same using ActionScript. Working through this reminded me of the days I implemented RSA encryption in FLash 5. Bits, Bytes, hex…..hmm…geek time!

Starting with basics of number theory, we in our day to day life deal with numbers using a base 10. For example, Shilpa Shetty in Celebrity Brother was paid £300,000 for apperance.
300,000 = (3 x 100000)+(0 x 10000)+(0 x 1000)+(0 x 100)+(0 x 10)+(0 x 1)
300,000 = (3 x 10^5)+(0 x 10^4)+(0 x 10^3)+(0 x 10^2)+(0 x 10^1)+(0 x 10^0)

Whilst in computers, everything is represented using base 2 system (ie: 0 and 1).
100010 = (1 x 2^5) + (0 x 2^4) + (0 x 2^3) + (0 x 2^2) + (1 x 2^1) + (0 x 2^0) = 34

Moving on, colours are represented as hexadecimal. This basically means that, it is to the base 16. Simple!. They are represented as: numbers 0 to 9 and the letters A to F. For example, the decimal number 12 is C in hexadecimal.

Colour values in ActionScript is represented using a 32 bit hexadecimal or 4 pairs of hexadecimal digits( one hexadecimal digit = 4 binary digit). I said 4 pairs here, which means each channel makes a hexadecimal pair (Alpha, Red, Green and Blue). Opaque images are 24-bit, with 8 bits for each of its red, green, and blue channels. Transparent images add another 8-bit alpha channel for a total of 32 bits.

So far a 32-bit image, it is AARRGGBB.

Moving on, lets take case of bitwise OR (“|”). Do not confuse this with logical OR. This sets the result bit to 1 if either of the source bits is 1.
0101 OR 0011
= 0111
Several ActionScript gurus use this operator while playing with colours [ eg:graphics.lineStyle(num,0x0033FF|(num << 8)); ]
Lets just put it this way, its a celver way for combining colours. You can use the bitwise OR to combine BitmapDataChannel constants to indicate multiple color channels.
bitmap.perlinNoise(100, 100, 5, 500, false, true, BitmapDataChannel.RED | BitmapDataChannel.GREEN | BitmapDataChannel.BLUE,false, null);

The next operator is shift, Left Shift “<<” and Right Shift “>>”. The left operands value is moved left or right by the number of bits specified by the right operand.
In theory, 00001110 << 2 = 00111000.
Actionscript converts the result to a 32-bit integer, which is good in our case for colours.
Shift operators discard anything after the decimal place, so shifting by zero provides a faster way to floor your numbers:
trace(1234.567>>0); // 1234
Now coming back to our bitmap representation, AARRGGBB we know that it is represented as follows: aaaaaaaarrrrrrrrggggggggbbbbbbbb (8 bits for each channel).

Given an RGB colour, if we want to extract only red, we do as follows:
myRed = myRGB >>16; This would move the bits to the right by 16 place, thereby discarding all the G and B bits and we are left with only R :). But its still padded with those trailing zeros.

The next and the last operator we are going to look at is &. Again this is different from logical and”&&”.
The & operator performs a bitwise AND on two integers. Each bit in the result is 1 only if both corresponding bits in the two input operands are 1. For example:
0 1 0 1 0 1 1 0
& 0 0 1 1 0 0 1 0
—————
0 0 0 1 0 0 1 0
This is a clever operator and used for masking. Masking is nothing but to mask the other bits and extract the ones you want. Interesting!
Lets take the earlier example of extracting the red channel, its easier to do with this operator as follows:
var argb:Number = 0xFFAA341B;
var redChannel:Number = (argb & 0x00FF0000) >> 16;
trace(“redChannel: “+redChannel.toString(16)); //output redChannel: AA

Technorati Tags: , ,

Posted in Adobe, AS 3.0, AS code tricks, Flash | Leave a Comment »

computeSpectrum

Posted by vijayram on January 29, 2007

Greenbars


package {

import flash.display.Sprite;
import flash.media.Sound;
import flash.utils.ByteArray;
import flash.media.SoundMixer;
import flash.events.Event;
import flash.net.URLRequest;

[SWF( backgroundColor=”0x000000″, frameRate=”31″, width=”200″, height=”200″)]
public class wpSpectrum extends Sprite {

private var _bytes:ByteArray;

public function wpSpectrum() {
var s:Sound = new Sound(new URLRequest(“mySong.mp3”));
s.play();
_bytes = new ByteArray();
addEventListener( Event.ENTER_FRAME, onEnterFrame );
}

private function onEnterFrame( event: Event ): void {

SoundMixer.computeSpectrum(_bytes, true, 0);
var value:Number;

graphics.clear();

var spacing:Number = (stage.stageWidth / 256);
var color:Number;

for(var i:int = 0; i < 256; i+=16) {
value = _bytes.readFloat();
value = (value * 256) << 0;
color = 0x00FF00|(value << 16);
graphics.lineStyle(1, color, 1);
graphics.beginFill(color);
graphics.drawRect(i*(spacing/16),100,8,-value/8);

}
}
}
}

Posted in Adobe, AS 3.0, Flash | 1 Comment »

Visualizer in Actionscript 3.0

Posted by vijayram on January 26, 2007

Compute Spectrum

Spectrum analyzer using SoundMixer.computeSpectrum

Posted in Adobe, AS 3.0, Flash | 4 Comments »

Pure ActionScript 3.0 AudioPlayer

Posted by vijayram on January 26, 2007

AudioPlayer
AudioPlayer

Quite a while back I started playing with Flashdevelop which was introduced to me by one of my work mates. I couldn’t let time go by until Flash9 IDE is eventually released. There are a lot of info out in the www space on how to get it working for Flex 2 and AS 3.0 projects. I am amazed by its simplicity. Kudos to the team behind it.

Back to the post. Since not many projects and resource are out there for AS 3.0 projects, it took me sometime to figure out on how things work. What I was after was pure ActionScript 3.0 code and hence I made this rough AudioPlayer using the power of AS 3.0. One source of inspiration were the experiments done by “andré michelle“.

If anybody does need the source or need to know how things work, drop a note. This might not be the best implementation but certainly gives a head start. I can think of ways to make things look better….

Posted in Adobe, AS 3.0, Flash | 1 Comment »

ActionScript code tricks

Posted by vijayram on January 26, 2007

Continuing this topic, today I shall discuss the benefits of CONSTANTS. I have seen several programmers use it in AS 2.0, but with AS 3.0 to me, it all made sense.

CONSTANTS are all uppercase and spaces converted to underscore. (eg: SERVER_NAME=”god”;)
Values assigned to CONSTANTS do not change as it implies. Declaring a CONSTANT is rather straight forward as declaring a variable with the var keyword.
public static const SERVER_NAME:String =”god”;

In ActionScript 3.0, the one place you will always encounter CONSTANTS are Events. It is best code of practice to use static CONSTANTS property of the Event class.(eg: addEventListener(Event.ENTER_FRAME, onEnterFrame); )

Lets just understand why we require to use the static CONSTANTS, as supposed to using just “enterFrame”. ActionScript 3.0 is a dynamically typed language and also supports compile-time type checking using the “strict mode”. I could type the above Event as follows, which is still valid – addEventListener(“enterFrame”, onEnterFrame);
But what if I were to type it as follows – addEventListener(“enterFame”, onEnterFrame);

I would definitely have “entered Fame” but for all the wrong reasons. The above code would be still compiled by the compiler though no errors will be reported. I would be spending unnecessary time to debug this. To avoid any such mistakes it is better to use the CONSTANT property of the class. How to we create one for our class?

This brings us to another topic of Enumerations. Enumerations are custom data types that you create to encapsulate a small set of value. ActionScript 3.0 does not support a specific enumeration facility like C++ or Java, however you can create this behaviour using classes and static CONSTANTS.

For example, a visitor to a web-page has a choice of language. The LanguagePreference class will use an enumeration PrefLanguage to store a set of language values.
public final class PrefLanguage {
public static const ENGLISH:String = “english”;
public static const FRENCH:String = “french”;
}

Now you can access the enumeration values as follows:
var myLanguage:LanguagePreference = new LanguagePreference();
if ( myLanguage.Language ==PrefLanguage.ENGLISH){
…….
}

The advantage of using the above method is that your code is type-safe, thereby catching errors at compile time. The only disadvantage that I can think of is the need for an additional class to be written to hold your enumeration types.

Posted in Adobe, AS 3.0, AS code tricks, Flash | 4 Comments »

Airport Screening

Posted by vijayram on January 25, 2007

I for one patronize with this cartoon. During the last couple of months, I had visited the United States on several business trips. Right, I understand the need for security screening but sometimes it becomes little too ridiculous when you know you have nothing to hide. Ok, that aside, I have lost about 4 or more locks on my trips. I understand the need for checked in baggage inspection being carried out. Its not every suitcase which is being checked.

Would they refund us if stuffs were stolen out of the suitcase. NO!….also, I would appreciate it, if they hand us back those locks. All they do is, cut the zip thereby saving the trouble of cutting the locks open. I end up paying couple of quid to buy a new one for my next trip.
Security Checks

Posted in General | Leave a Comment »

ActionScript code tricks

Posted by vijayram on January 24, 2007

Ok! This post will be ever growing as I come across tricks used by the geek community to write code. I was always baffled by code which didn’t stick to the book. Hoping this post will clear out those myths that if you use this structure whilst coding, you are “god” of the geek land….maybe you are!!!..whatever.

Compound Assignment Operators:
Compound assignment operators provide two benefits. Firstly, they produce more compact code.Saves the trouble of over exercising those fingers. Secondly, the variable being operated upon, or operand, only needs to be evaluated once in the compiled application. This can actually make the code more efficient when executed.In contrast, the statement using the simple operators makes a copy of the variable A, performs the operation on the copy, and then assigns the resulting value back to A, temporarily using extra memory.

Lets take the case of arithmetic operators (+ – * / %).
var += expression; // var = var + expression
var -= expression; // var = var – expression
var *= expression; // var = var * expression
var /= expression; // var = var / expression
var %= expression; // var = var % expression

This statement adds 1 to value :
value ++;
This statement subtracts 1 from value :
value –;

You can use the increment and decrement operators (– and ++) either before or after the variable or property they operate upon. If used before the operand, they are called prefix operators. If used after the operand, they are called postfix operators.
var value :Number = 5;
trace(value ++); // 5
trace(value ); // 6

var value :Number = 5;
trace(++value ); // 6
trace(value ); // 6

Posted in Adobe, AS 3.0, AS code tricks, Flash | 1 Comment »