Archived entries for Flash

The Starling Clock

The Starling Clock

Was built on Adobe Air 2.6 platform, click here to view the site.

TextLayoutFormat for Arabic Text

Pretty straight forward and you can use fancy fonts as well, in the example I’ve used GE SS Two Medium font.

/**
* ...
* @author Rahmat Hidayat
*/

import fl.text.TLFTextField;
import flashx.textLayout.formats.TextLayoutFormat;
import flashx.textLayout.elements.TextFlow;
import flash.text.TextFormat;
import flash.text.AntiAliasType;
import flash.text.FontStyle;
import flash.text.Font;
import flash.text.engine.FontLookup;
import flashx.textLayout.edit.ISelectionManager;
import flashx.textLayout.edit.EditManager;
import flashx.textLayout.edit.SelectionState;
import flashx.textLayout.formats.Direction;

var tField:TLFTextField = new TLFTextField();
var applyFont:Font = new Arabic();

/**
* Things that matter
*/

tField.text = "أغنية لشعبولا عن مقتل معمر القذافي";
tField.direction = Direction.RTL;
tField.width = 300;
tField.x = (stage.stageWidth - tField.width)/2;
tField.y = 100;
tField.wordWrap = true;

tField.embedFonts = true;

addChild(tField)

var tFormat:TextLayoutFormat = new TextLayoutFormat();
tFormat.fontFamily = applyFont.fontName;
tFormat.color   = 0xffffff;
tFormat.fontLookup = FontLookup.EMBEDDED_CFF;
tFormat.fontSize    = 30;

/**
*  Just blindly copy and paste the below
*/


tField.textFlow.invalidateAllFormats();
tField.textFlow.hostFormat = tFormat;

var prevManager:ISelectionManager = tField.textFlow.interactionManager;
var editManager:EditManager = new EditManager();
var sel:SelectionState = new SelectionState(tField.textFlow, 0, tField.text.length);
tField.textFlow.interactionManager = editManager;
editManager.applyLeafFormat(tFormat, sel);
tField.textFlow.interactionManager = prevManager;

tField.textFlow.flowComposer.updateAllControllers();

iPhone OS 4

snow whiteThere is always something exciting about Apple, whenever they launch their product everybody just mesmerized by it, gasped and awed in unison to its shines, it reminds me of Willy Wonka when he unveils his Chocolate factory.

iPhone OS4 had just been released today and has introduced some new features such as:

  • Wallpaper on the home screen : Yes! Now we can change our wallpaper.
  • Multitasking/background tasks : Of course with some limitations.
  • Unified e-mail inbox : Browse different accounts in one inbox (that is what I’ve understood anyway).
  • iBooks! : Move over kindle and other product alike.
  • App folders: for all of you that is obsessive compulsive.
  • Open e-mail attachments in other apps.
  • Game Center.
  • Mobile advertising (iAds).

But out of these features, iAds seems to be the most prominent as Steve hinted.

The average user spends over 30 minutes every day using apps on their phone. If we said we wanted to put an ad up every 3 minutes, that’s 10 ads per device per day. That would be 1b ad opportunities per day.

I can almost see the dollar sign lit up in his eyes when he uttered that sentence, its no secret digital Ads worth of billions of dollars and Apple wants to take a massive bite of it.

iAds
Steve again had contended that Ads today is attractive (he was showing a flash banner as the bad example when mentioned this and I could have sworn he was smirking in triumph) but lacks the emotional value, although I will guarantee the iAds will be another of “Shoot [something] to win [something]“.

iPhone iAds 1
Steve said that there’s nothing like it, but didn’t I just developed something similar for flash banner a couple of weeks ago?

iPhone iAds 2
That’s so emotional, I had tears of joy in my eyes.

iPhone iAds 3
In conclusion despite of another unprepared PR charade and the implicit statement of “we don’t care about you, just shut up and buy the damn product”, but the matter of fact is Apple had successfully delivered one of the greatest invention of the century, and its glory had captivated the materialistic world ever since and until the charm still lingers, we -the gullible customer of the modern world- will still perceive that what glitters is always Apple.

PS: Applications that link to Documented APIs through an intermediary translation or compatibility layer or tool are prohibited. which means goodbye Flash CS5 and thanks for the effort (but at least my time learning objective-c didn’t go to waste :) )

AS3 to Cocoa : Part 1

I’ve been learning awful lot of Cocoa lately, and to be honest at first I thought the syntax would be somewhat similar to what AS3 is, but apparently I’ve found a massive gap separating between the two.

There are a lot of tutorials and forums out there that can guide you into the right direction and some of them are written by flash aficionados and one of the good one is what the revered Keith Peters has written in his blog, but again as an autodidact programmer reading those tutorials was difficult, what is pointers? why is NSObject? but eventually with much persistence and an occasional mental breakdown, I’ve finally had a grasp on the language.

If you want to follow this tutorial, first ensure you’ve downloaded all of the necessities and also I’m assuming have a decent understanding on AS3 and you’ve had a bit of a tinker with the Xcode otherwise click here.

What we are about to do is obviously nothing complex, just something to familiarize ourselves with the Objective-C concept.

First open your Xcode and select New Project which will open the New Project panel.

New Project Panel - AS3 to Cocoa Touch part 1
On the New Project Panel under Mac OS X tab select Command Line Utility and select the Foundation Tool.

Author Environment - AS3 to Cocoa Touch part 1
If everything went well you should now be at the author environment just as illustrated above and open the message file if you haven’t done so, which is denoted by the .m extension.

Objective-C is all about Object Oriented Programming (OOP) and its quite strict as oppose to AS3, creating a class has to be preceded by defining the method(s) and variable(s) on the interface first.

So let’s create a simple interface for MyPet class.

@interface MyPet : NSObject  {
    NSString *petName;
}

- (void) makeSound;
- (void) setName:(NSString*) n;
- (NSString *) getName;

@end

If this is the first time you’ve seen Objective-C it may appeared alien at the moment, but let see the AS3 equivalent of MyPet class interface.

package com.farm {

    public interface MyPet {

        function makeSound():void;
        function setName(n:String):void;
        function getName():String;

    }

}

As we can see there are some slight differences, a few elements to note are the NSObject, which is in a nutshell is a base interface, the definition of petName as the class variable and the absent of a package.

Now let’s proceed with the implementation.

@implementation MyPet

- (void) makeSound
{
    NSLog(@"Tweets");
}

- (void) setName:(NSString *) n;
{
    petName = n;
}

- (NSString *) getName
{
    return petName;
}

@end

and the AS3 equivalent.

package com.animal
{
    import com.farm.*;

    public class Bird implements MyPet
    {

        private var _petName:String;

        public function makeSound():void
        {
            trace("Tweets");
        }

        public function setName(n:String):void
        {
            _petName = n;
        }

        public function getName():String
        {
            return _petName;
        }  
    }
}

I think up to this point everything would made sense now and of course Objective-C has a few execution directives we have to follow, such as the @implementation and @end.

Finally the instantiation.

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    MyPet *bird = [MyPet new];

    [bird setName:@"Polly"];
    [bird makeSound];

    NSString *birdName = [bird getName];
    NSLog(@"%@",birdName);

    [bird release];

    [pool drain];
    return 0;
}

In here you must be wondering what the main method is doing there. Think about the initial execution inside a document class in AS3, every Objective-C will be initiated with a main method which the compiler will call, passing a few parameters along the way to check the code.

Other elements are the @”Polly” which is just the way you pass string inside Objective-C and NSLog(@”%@”,birdName); which is just an equivalent of trace in AS3 and the most important thing is the [bird release]; method which basically is how the compiler releases the bird instant from the memory, garbage collection is paramount if you trying to build an iPhone application since it has a limited resources.

Now run the code by pressing command-return and open the console window to see the output by pressing command-shift-R, if you are correct you will see the bird name and the “Tweets”.

So that’s the end of part 1 there are a lot of things that can be explained here, by I’ll leave it as it so it’s easier to understand.

And the AS3 equivalent.

package
{
    import com.animal.*;

    import flash.display.MovieClip;

    public class Main extends MovieClip
    {
        public function Main()
        {
            var bird:Bird = new Bird();

            bird.setName = "Polly";
            bird.makeSound();
           
            var birdName:String = bird.getName();

            trace(birdName);
        }
    }
   
}

and here’s the entire code.

@interface MyPet : NSObject  {
    NSString *petName;
}

- (void) makeSound;
- (void) setName:(NSString*) n;
- (NSString *) getName;

@end

@implementation MyPet

- (void) makeSound
{
    NSLog(@"Tweets");
}

- (void) setName:(NSString *) n;
{
    petName = n;
}

- (NSString *) getName
{
    return petName;
}

@end

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    MyPet *bird = [MyPet new];

    [bird setName:@"Polly"];
    [bird makeSound];

    NSString *birdName = [bird getName];
    NSLog(@"%@",birdName);

    [bird release];

    [pool drain];
    return 0;
}

Imagination is more important than knowledge

A series of internet memes has again sparked another heated debates, first it was the first javascript website showcased in the FWA and later the YouTube- HTML5 integration.

Since the dawn of the internet-era, infinite debates amongst these developer elitists were always inundated the World Wide Web and one of the revered topic is of course who has the better developing platform.

The advent of HTML5 and the mission and vision which it carries is truly spellbinding for the internet community, but if you remember so had actionscript 3 during its inception.

Every technology has its share of flaws.

The impending problem that HTML5 has had to be adaptations and compatibility issues, the browser war will always be diluted by strategic marketing, business goals, and of course ego -which can be dubbed as the company ideology- and never in the interest of the developer.

The first HTML5 conundrum which has begun is the new video which its support is limited to web browsers that support the H.264 video codec mainly because W3C declined to specify a standard video codec to go along with new video element and you can guess it, IE deviates the notion completely and this just the beginning of other impediments which will come along.

Flash, as I’ve had mentioned its flaws and the prevalent hate memes such as the CPU hogger, the battery drainer, etc which all is true, and of course the choreographed demo of Flash player 10.1 in Nexus, was mainly caused by Adobe complacent and other aspect which mainly had to be the economy, the decrescendo of demand in Flash during this post-recession period has been abysmally loud (a bit of oxymoron there) and based on my experience, building a good Flash site needs a bit of an investment in time and money as oppose as HTML/JS sites, hence unless if it’s a niche market such as social-game company, almost nobody dares to invest such luxury or even has the needs that requires Flash to fulfill their business objective, except for that annoying ad banners which I mostly am doing now :( .

But from the Technology stand point, Flash I think can still accomplish, and I’m not trying to be subjective here, something that is better than what HTML/JS does, a few sites worth mentioning are:

http://sketch.odopod.com/
http://www.picnik.com/app

I dare you to build something like that with HTML/JS, but again I’m not trying to devalue HTML/JS here, check out google, digg, etc.

But in conclusion these ridiculous dialogs are unfounded, history has repeatedly shown us that technology is merely a tool, a transient breeze that bound to be superseded by a better and in-your-face contender ergo we shouldn’t be trying to be a platform zealots, I’ve been experimenting with Unity3D, Cocoa, Jquery and of course Flash, I think exploring new Technology is the beauty of this keyboard-cat and Rick’n Roll’d era.

As an epilogue I will depart from this post by paraphrasing some guy with a weird hairdo who invented the theory of relativity:

Imagination is more important than knowledge. For knowledge is limited to all we now know and understand, while imagination embraces the entire world, and all there ever will be to know and understand.

Polygons count of a 3D object in flash

Determining the perfect balance between performance and quality was a very tedious experience for me and I was flabbergasted since hours of digging through google I realized that no one has ever documented the mantra (or maybe I was googling at a different direction).

After a few grueling days of publishing, remodeling the 3D (which wasn’t done by me thankfully), sending yet another dubious budget proposal to the client, and watching jagged 3D object floating on my computer screen, I’ve discovered a poly count between 2000 to 5000 has the most perfect mixture between quality and performance, yes the possibilities of adding more polys is feasible but considering that people (especially in the middle east region) mostly owns a mid-range computer platform, this is the most sensible approach.

iPhone application is Flash Professional CS5

If you have been living on the moon and just recently got bombed, you probably haven’t heard the infinite rumors of Flash versus iPhone.

But now the perplexity has finally been answered, a few weeks ago Adobe has presented a demo of Flash Professional CS5 with a native iPhone apps builder!

In a nutshell, what Flash does is compiles the AS3 encoding into native ARM format which can be deciphered by an iPhone, here’s the step by step of the procedure in case you don’t have the time to watch the video:

ABC Extraction & Compilation
AS code is pulled out and compiled by LLVM.
Optimization
LLVM’s global optimizer looks for efficiencies.
Linking
Native ARM version of app linked against iPhone libraries.
Signing
App signed with dev certificate.
Packaging
App and assets placed in an APP bundle then zipped to IPA.

Albeit it has a few imperfections which Flash shares, but I have to admit this is one of the most orgasmic feature that Flash has ever unleashed.

So hopefully as the momentum of the Open Screen Project continues to swing, it will allowes Adobe to keep moving forward and more importantly keeps their humble aficionados, such as myself :D , earning more living.

UPDATE apparently no matter what adobe does apple simply won’t let them in, so forget everything I’ve said above.

Augmented Reality

The first time I saw Augmented Reality I think when I was 14 years old, it was a footage about an invention in gaming, I remembered it quite clearly it was racing game but with a real desk projected as its terrain, the car was hoping through the books and dodging stationaries as if they were gorges.

And about a year ago Augmented Reality was again dubbed as the zeitgeist of the internet, its so easy to implement in flash, thank you to Saqoosha.

But it didn’t stop there, the zeitgeist continues to permeates to a level that is insanely creative and as I spent my time procrastinating and watching others whizzing through the moon leaving me behind, I’m finally able to immerse my self in Flash Augmented Reality, below, albeit minuscule, is the taste of things to come.

or if you have a webcam, first download and print the marker and go try it out yourself.

Arabic Flash

The first time I came to Dubai I had to do the inevitable, grueling with bidirectional text with dubious deadlines, at first I was shocked, appalled, and frustrated with flash, here’s a software which has been established for a decade but still couldn’t manage how to parse a proper Arabic yet Arabic is one most spoken language in the world you can imagine how massive the market is.

But after the 4th stages of grief I have finally come to accept flash weaknesses and tried to explore new circumvention.

There is a licensed parser out there but like a cat I’m curious.

As you can see although is not perfect, because it doesn’t support embedded Text (and only for windows) so if you don’t have any Arabic language supported you wont be able to view the proper sentences also it only supports a few major fonts which has Unicode Arabic glyph, such as Tahoma and Times Roman. But despite all the flaws I had finally managed to have dynamic Arabic text directly feeding the Flash TextField.

How the Arabic is parsed, in a nutshell, is simply just inverting the letter order, basically when you add an Arabic text in Flash, it will ignore that as an bidirectional text. To illustrate plainly in English “how are you” in flash will be parsed as “uoy era woh”, below are the core function which I’ve used to reversed the order.

package com.arabicDecoderAS3.core {
   
    /**
    * ...
    * @author Rahmat Hidayat
    */

   
    import com.arabicDecoderAS3.tools.*;
    import com.arabicDecoderAS3.data.Constant;
   
    public class Decoder {
       
        protected var _count:int = 0;
       
        protected var _currValue:*;
        protected var _prevValue:*;
       
        public function Decoder()
        {
           
        }
       
        private function restructureString(aTarget:Array):Array
        {
            var aSentence:Array = [];          
                       
            for(var i:int = 0; i < aTarget.length; i++)
            {              
                if(ASCIIChecker.isLatin(aTarget[i].charCodeAt(0)))
                {
                    _currValue = (aTarget[i].charCodeAt(0) == 32 && _currValue != -1) ? Constant.SPACE : aTarget[i].charCodeAt(0);
                   
                    aSentence.unshift(aTarget[i].charCodeAt(0));   
                                                       
                    return aSentence;              
                }          
                else
                {
                    _currValue  = -1;
                    _count      = 0;
                }
               
                aSentence.push(aTarget[i].charCodeAt(0));      
               
            }
           
            return aSentence;
        }

        private function rebuildText(aTarget:Array):String
        {
            var sResult:String  = '';
                   
            for(var i:int = 0; i < aTarget.length; i++)
            {                      
                for(var j:int = 0; j < aTarget[i].length; j++)
                {          
                    if (ASCIIChecker.isLatin(aTarget[i][j])) sResult += String.fromCharCode(Constant.RLM);
                   
                    (aTarget[i][j] == Constant.SPACE) ? sResult += String.fromCharCode(32) : sResult += String.fromCharCode(aTarget[i][j]);         //Temporary Solution, for what??                   
                }                  
            }  
           
            return sResult;        
        }
       
// EXECUTION
// -------------------------------------------

        /**
         *
         * @param   aTarget: is the splitted string
         * @return
         */

        public function getCode(aTarget:Array):String
        {          
            var aTemp:Array     = [];
            var aResult:Array   = [];
            var n:int;
               
            while(aTarget.length > 0)
            {                                              
                aTemp   = restructureString(aTarget);
                n       = aTemp.length;                                
               
                if (ASCIIChecker.isNumber(_currValue) || ASCIIChecker.isLetter(_currValue) || _currValue == Constant.SPACE )    // SPACE still a hack
                {                      
                    (_count == 0) ? _count = IndexChecker.getIndex(aResult, _prevValue) : _count++;
               
                    if (_count != -1)
                    {
                        // This when we reversed the Latin text
                        aResult = aResult.splice(0, _count + 1).concat(new Array([ _currValue ])).concat(aResult); 
                    }
                    else
                    {
                        aResult.unshift(aTemp);
                    }
                   
                }
                else
                {
                    aResult.unshift(aTemp);
                }                  
               
                aTarget.splice(0, n);
               
                _prevValue = _currValue;                   
           
            }
           
            return rebuildText(aResult);
        }
       
       
    }
   
}

The other significant elements are the ASCIIChecker and English reversing-reversal, Tahoma for example has a complete array of glyphs and the Latin glyphs are addressed in the range of decimal order of 32-255 as for Arabic glyphs it will be addressed in Unicode order, using a simple ASCIIChecker we can segregate the Latin character from the Arabic character.

And the last element is the English reversing-reversal ( it’s a funny name I know ) which is simply reversing the Latin words back to its correct order.

But again without embedding the ultimate solution cannot be achieve and due to my lack of knowledge in Arabic I’ve reached the cul de sac of Arabic Flash, because embedding Arabic is highly possible but the problem is Arabic fonts are encoded differently from Unicode fonts. One example is the AXT font, by dissecting the character code it can be found that it does not employ Unicode to wrap the Arabic glyphs which is why windows fail to translate this as a bidirectional text.

I really want to make this Arabic parser as an open source project, if anybody could help me perfecting this -at least until Adobe unleash a real parser- hop in and join my band wagon.



Copyright © 2004–2009. All rights reserved.

RSS Feed. This blog is based from Modern Clix, a theme by Rodrigo Galindez.