Showing posts with label actionscript. Show all posts
Showing posts with label actionscript. Show all posts

Monday, June 28, 2010

ActionScript: the htmlText, CSS and embedded fonts fiesta

Actionscript is usually great for simple font embedding and rendering purposes. Use the text property of a TextField with an embedded font and a TextFormat, and it works great. If, however, you want to get all ninja and use htmlText with CSS with embedded fonts, you're in for a bumpy ride.

Firstly, you may experience the unnerving phenomenon of text not appearing at all, as soon as you set the embedFonts property to true on the TextFormat object. Fear not, for Flash nuisances are easily tweakable. Check your css file and wherever you have more than one font enumerated in the 'font-family' property, just make it one single font name: the font you embedded. In the article linked above, adobe mention:

If using CSS styles to set fonts for TextFields, set the font-family CSS property to the name of the embedded font. The font-family property must contain a single name and not a list of names if you want to specify an embedded font.

What this might do for you is to show regular text, but completely omit formatted text (bold or italic), or simply replace it with unformatted text. If that happens, you have probably not embedded all the font faces. Read this article to find out how to embed all versions of a font (regular, bold, italic and bold-italic) within the same font family. If your embedded font already has these formatting inside the font file, try these tricks. If you're using the Flash IDE, it should be really similar. This forum thread might help.

The next problem which is very likely to occur is for the font to look aliased (i.e. blurry, hard to read). The solution is simply to create a TextFormat object with the font defined in the CSS style and assign it to the defaultTextFormat property of the TextField. Makes sense, right? No! I found this after considerable digging. Let me know if it works for you too.


Update:
if you're using multiple SWFs or RSLs and have issues with fonts, check out Alex's great post about that.

Wednesday, August 12, 2009

Ideas for optimizing flash / flex applications

Optimizing the memory consumption, processor cycles used and even user experience in a flash application is as complex as it is important. Not very many projects out there reserve time for the explicit task of optimizing the application, which is why I think developers should incorporate some of these techniques in their daily development, or in the initial planning of the architecture of the application.

A good place to start for optimization advice is Adobe's advice for reducing SWF file size in Flex applications. A lot of the ideas there pertain well to improving user experience as well - as is, for instance, splitting the application in modules, loading external swcs, and loading content at runtime where possible. Adobe also offer a rather valuable tool for Flex developers, the linker dependencies xml which you can export as part of the compilation process. Here's an AIR application called AIR Link Report visualizer which will spare you from having to read plain xml by presenting dependencies in nicely arranged lists and offering a nifty visualisation chart showing you the breakdown of the packages used in your application.

User experience is given a lot of attention in this tutorial about SWF framerate optimization done by Lee Brimelow.

As processor cycles are concerned, it usually comes down to fine-grained changes in your code. For me, this is the fun part.
Depending on your current knowledge, you might want to start off with Grant Skinner's great presentation about resource management.
A comprehensive list of possible code optimizations is maintained by Joa Ebert, read it with both eyes. Also watch out for valuable links to more details on particular subjects, such as this list of bitwise operations: Bit Twiddling Hacks. Next, you can get your head around the debate about the int / uint / Number types in Flash by reading Grant Skinner's discussion on them (prompted by this blog post), and this post which also looks at flash player versions for a more detailed approach.

I will keep adding to this list as I discover new articles on the topic. If you have your favourites, show them off.

Tuesday, April 28, 2009

PureMVC improved: commands can be singletons

While working with PureMVC on some games in Flash CS3 I thought it would be quite useful to be able to specify that some commands should not be recreated each time they are run (as is the default behaviour), but rather only once, and the same instance should be used all throughout. In games where certain commands occur often (eg. the one associated with the message 'Deal' in card games) this would be an important memory save.

So I set out to adapt PureMVC. I tweaked the Controller::executeCommand function the most, with some meddling with Controller:registerCommand, Facade::registerCommand, and their respective interfaces. Overall, only 4 files changed, with only the controller suffering essential functionality alteration. The only change in the API is that when you use registerCommand in your implementation of the Facade, you now have a third parameter, called 'singleton', of type Boolean, which defaults to false. If it is set to true, only one instance of that particular command will be created and then reused all throughout the life of the application.

Example of singleton command initialization:

this.registerCommand(STARTUP, StartupCommand, true);


You can download the changed PureMVC framework here.

Friday, March 6, 2009

Flash preloader mayhem. bytesTotal equals 0 or bytesLoaded and the misterious missing Content-Length header

There are times in programming when when the simplest of things turn out to be the most difficult to achieve.

I experienced this some days ago when I wanted to implement a preloader for a game I'd been working on.

After an unsatisfactory attempt at a first-frame preloader (the combination with PureMVC was to be fatal to me :), I went for the external one. Namely, there is a very small swf, which is the 'host', and which loads the actual game while displaying the loading progress. With no more fuss from PureMVC, and everything working fine, the progress bar appeared at 0%, as expected. It was good, simple and quick, like a preloader should. I happily deployed the game and test it in the browsers.

None of them worked! All of them displayed an empty progress bar, and after some seconds the game suddenly appeared. My gosh, what could it be, I wondered. I placed some strategic traces, only to learn that the bytesTotal property of the Loader.contentLoaderInfo object was either equal to the bytesLoaded property (only in Firefox), or simply 0. This was the strangest thing I'd seen in quite a bit of time...


After some extensive Googling around, I found some hints of what might be wrong. The Adobe documentation for the URLLoader class (which I had not used) mentioned that "a missing Content-Length header will result in bytesTotal being indeterminate" (nothing of the sort was mentioned for the Loader class, which I had used). This prompted me to open Charles and spy on the headers returned by the server for the loader and for the game itself. Indeed, there was a single difference between them: the game's response was missing a "Content-Length" header. Eurika!

This, in turn, called for an .htaccess file to set things straight (I was using Apache 2). I dug some more and I discovered mod_proxy_http in the Apache documentation. They mention that the variables proxy-sendcl and proxy-sendchunks are responsible for the Content-Length header, which apparently works in conjunction with an operation called 'chunking', performed by Apache when serving larger files, whereby it starts sending the file to the requester before buffering it (which would allow it to know its size), making the whole process quicker. I presently set out to alter them, by using the SetEnv command: setenv proxy-sendcl 1. I put this in the .htaccess, and I made sure the variables were set by using a phpinfo() call in a test php script. Nothing changed! Then I added the other one: setenv proxy-sendchunks 0, hoping to finally force Apache to cut it out with the chunking. Didn't work this time etiher, everything looked pretty much the same. It dawned on me at this point that I didn't know the correct values for these variables (maybe it wasn't numbers, but rather some predefined enums? the documentation didn't say). But I had already wasted too much time on a preloader and decided to call for help from our hosting company. They suggested, quite strangely, that I turn gzipping off, by using this line in the .htaccess: SetEnv no-gzip dont-vary. I was quite sceptical of the solution, because the loader swf was being gzipped by Apache anyway and it did have its "Content-Length" header where it needed it. However, surprise surprise, the preloader started working! It was smooth and silky, as I was hoping.

Now, I still don't understand what gzipping had to do with proxy-sendcl. I have sent them an email back for clarification, I will be forever grateful if they can illuminate me. And I shall undoubtedly share my findings, so keep posted - or, if you know and are willing to help, drop a comment!

I hope this saves someone some precious time.

Thursday, February 5, 2009

Pure MVC - the good, the bad and the ugly

I just finished my first Flash game built with PureMVC for ActionScript3.0 (sorry, it's a work project and not released yet).

I'm going to share some bad experiences and some good experiences about it. Let's start with the bad ones, because they're most fun to read.

As Tony says, PureMVC makes you write quite a bit of boilerplate code in the beginning. I expected that anyway, sice I had just learned the system. But it's true, it is far from a pleasant prospect to imagine having to write it again. If I will use it in the future, I will most probably copy the entire project and start changing, or even create a 'blank setup', with all the initialization code ready for ordinary applications.

One of the complications is that when sending messages through the facade (a similar publish /subscribe mechanism to Cairngorm Events), any command and any mediator can respond and act upon them (proxies can't). This makes it difficult to know who and what is doing at certain stages of the application, especially when the project is getting bigger. There is no central point to see who is doing the work at "APPLICATION_INIT", for instance, because any and all mediators can listen to this event, and that signaling code is in the particular classes (through the listNotificationInterests method). I found myself using Ctrl+H in Eclipse (which searches through all project files) more often than should be the case for a good framework (or for a programmer with good memory - I should eat more fish).

A subsequent, unforseen oddity comes to life when linking to other mediators in a mediator. I wonder if this verges on bad practice, but on a few occasions I needed to link mediators directly, and in one instance I realised I had circular referencing between two mediators. This would generally be no particular problem, but the way PureMVC recommends registering Mediators is not compatible with such referencing. Namely, you register them in sequence in the top-level ApplicationMediator, as part of an application initializing command. This means that the circular referencing will break, because the second mediator will not have been created yet when we attempt to retrieve it in the constructor of the first.
My way around this was to move the mediators registration code at the end of the application initialization and then to send a "MEDIATORS_REGISTERED" message, which could be listened by all mediators who may be in danger of circular linkage. This had the nice effect of bloating almost all my mediators' class code.

Also, when coding commands which need to wait for view components to finish animating, it becomes cumbersome when other entities (commands or mediators) need to act when that animation finishess. For instance, a card placeholder needs to change colour when the card reaches it. You don't want to lose state in the command by just registering a new command to execute at the end of the animation, because you need to use previously obtained information. You basically have to dispatch two 'messages' in the view component's mediator -> one through the facade (eg. "CARD_RECHED_DESTINATION"), for the interested mediators, and the other, a regular Flash event (for instance Event.COMPLETE). The command will then respond to the Flash event and continue its functionality. (Alternatively you can dispatch the facade message in the waiting command; but what if that animation is at other times triggered by different commands as well? You still need the message to be sent out...).

Now moving on to good things.

What's cool is that once you've gone through the initial scaffolding, it is very easy to add bits of functionality in the application. That is, if you leverage copy-paste, because something like _cardsMediator = CardsMediator(facade.retrieveMediator(CardsMediator.NAME)); is not fun to write 5-10 times per class. Also, the linking between visual components becomes a breeze, because most of the times they will respond to existing notifications.

Also, if I am to think about my application generally, I feel it is very solid, robust. I have had very few bugs caused by my misusing the framework, so from this point of view PureMVC does not stand in your way.

Will post back with more insights.