Fast Bitmap Fonts in Flash

FreeType Font Metrics Chart
I got fed up one day, and wrote a simple bitmap font renderer, BMFontRenderer. It parses bitmap font data from a generator like BMFont or Hiero (link on middle right of sidebar) and renders text of your choosing to a BitmapData.

BMFontRenderer is under the MIT license, so you can use it as you like.

Here’s an example:

// Load the font.
var bmfont:BMFont = new BMFont();
bmfont.parseFont(font);
bmfont.addSheet(0, (new fontSheet()).bitmapData);
            
// OK, draw some text!
var out:BitmapData = new BitmapData(200, 100, true, 0x0);
bmfont.drawString(out, 0, 0, "Hello, world!");

(You can see the complete example in BMFontRenderer’s GitHub page.)

Great. So – why would you want to use this, given TextField is right there, waiting for you? (Translation: why did you get fed up, Ben?)

It comes down to control. TextField has a TON of knobs and buttons you can set. They all do semi-obscure things which are, in and of themselves, very exciting, but confusing to work with if you aren’t a font expert. Worst of all, it pulls font data from hard-to-inspect places that are populated by mxmlc at compile time or located on the user’s system, so you get different visual results depending on who is running your app, where and when you compiled it, and maybe even what browser it’s in.

The Flash IDE does a good job of hiding all this, and for beautiful animated vector text created by an expert in the tool, there is a great workflow. But when I need to show a high score at an artist-selected size in an artist-selected-and-provided font that has artist-approved antialiasing so it looks good on top of the artist-created background, it can be a lot easier to let the artist export the exact characters they want, how they want them to look, to a PNG. Then all I have to do is copy pixels around.

Fonts are less restrictive about licensing if you ship pixels instead of TrueType/vector data. Shipping raster data can save you a couple grand in license fees, nevermind cut down on your download quite nicely.

Doing it this way also puts 100% of the font handling code under your control. There are no parts you can’t debug, analyze, optimize, timeslice, or otherwise fiddle with. Never underestimate the value of this when you have a deadline. This is why I love libraries like Sean Barrett’s stb_truetype.h, which is a self-contained TrueType font renderer in a single C file.

There’s another fantastic bonus. Once an artist has characters in a PNG, they can open them up and tweak them – distress them, add glows or cutouts, or anything else that Photoshop can do. That’s a big realm of possibilities, and a lot easier than learning a font authoring tool.

To be sure, Flash’s built in font rendering has solid uses. If you need to dynamically animate, scale, or rotate text, you need vectors, and Flash has got you covered. If you want to display fully arbitrary unicode text, you may need to fall back on system fonts to fit in your download budget (PushButton Engine has a nice glyph cache for speeding up rendering, though). Or if you are working with people who are very comfortable in the Flash IDE, why not use a system they are familiar with?

For everything else, there’s BMFontRenderer. Enjoy!

Flash Player: A Declining Asset?

4 YEARS AGO – “A DECLINING ASSET”

I’m working at a technology startup and today I am talking to one of the founders. He looks at me and says, “Our main product is a declining asset.

This is the product that generates 90% of our revenue and pays both of our paychecks. It’s the one that made our company a success, put us on the map.

Uh oh.

NOVEMBER 12, 2011 – ADOBE’S BIG IDEA

If you watched the Digital Media section of Adobe’s recent analyst meeting, you know that Adobe is putting a lot of focus on HTML5. Their recent announcement regarding dropping mobile web browser support for Flash Player caused a lot of turmoil, too, along with a shift in direction for the Flex SDK, their enterprise app framework.

If you look at the marketplace and the technologies at play, it seems that Adobe has realized that Flash’s position in the marketplace is eroding, that the erosion probably can’t be stopped, and they need to treat Flash as a declining asset. Just to review, here are some reasons that Flash’s position is eroding:

  • The many 3rd party mobile, native, and web-targeted development tools like Corona, Moai, Unity and others.
  • Non-Adobe Flash runtimes like Scaleform, Iggy. Companies like The Behemoth have their own Flash-compatible runtimes, too.
  • And of course the big one – HTML5. It can handle more and more enterprise apps, animation/multimedia content, and 3D. Browser vendors are in competition but increasingly targeting Flash-like capabilities.

Long term, HTML5 and other non-Flash technologies are unlikely to go away. Adobe may as well be proactive about owning the space rather than fight an unwinnable battle to keep everyone on Flash.

One more point to consider: Flash is made up of three big pieces. You have the tools, like Flash Builder and Flash Pro. You have the runtime, like the web plugin, the standalone player binaries, and AIR for desktop and mobile. And finally, you have the platform itself – the file formats, AVM specification, compilers, and APIs that define the behavior of Flash content.

They are all independent to a greater or lesser degree. The only part that probably wouldn’t migrate to HTML5 is the actual runtime (but see Gordon). And Adobe has been rumbling about compiling AS3 to JS/HTML5 and supporting C via Alchemy 2.

LABELS AND COMMUNITIES

Now, the funny thing about that conversation from four years ago is that, because of the mental label of “declining asset” we assigned, (at least) two interesting things happened. First, the company got acquired and tried to diversify into a couple of new markets. Second, I along with a few other guys left the company and went on to start a new one.

But the “declining” product continued to make more money than ever before. And in fact, it lives on today, despite the original company getting liquidated by its owner when the diversification strategy didn’t work out. So what does it mean, exactly, to be a declining asset?

I think “declining asset” is a label you put on something to help you make decisions. In Adobe’s case, the decision they made was to move their long term focus toward HTML5 and away from Flash Player.

There are some important things to keep in mind with the communities that develop around technologies and products. First, realize that the conversation is often dominated by the vocal minority – so what is said most often and loudest often doesn’t reflect on the actual needs of your user base. Second, realize that the people who post on your forums are emotionally invested in the product, have it as part of their identity, and they will be deeply unsettled by any signs that support is fading. Finally, realize that users often have a limited perspective. Community members are not tracking major market trends, they are looking at how they can meet their immediate needs (like getting contract work or finishing a specific project).

In other words, the community tends to act like a mob.

And I saw no better example of this than when I was on a group video chat last week and saw Flash professionals practically weeping, calling out Adobe representatives, demanding, threatening to break up, over these announcements. It was more like seeing your drunk friend vent over his ex-girlfriend than it was watching a group of well-respected developers discuss their future. Everything is in a turmoil, it’s the end of the world, everyone is screwed, etc.

REPORTS OF FLASH’S DEATH

Ok, but that isn’t actually the end of “Flash” as a whole. Probably. Even though it really sounds like it. Let me explain.

Adobe has a ton of outs from this situation that let them preserve their and your investments. The most obvious out is replacing Flash Player with HTML5. You export from Flash Pro or Flash Builder and it runs directly on HTML5. In fact, they have been inching towards this in different forms for a while now (the conversion tool on Labs, Edge, Muse, etc.).

Even if they drop AS3 and go with JS, their tools can still be useful. If Flash Pro can still create banner ads and interactive experiences for a large audience, who cares what the output runs on? Life will continue relatively unchanged for a lot of Adobe customers.

There’s also a more subtle out:

HTML5 has its weaknesses. Lots of them. But public opinion supports it. Maybe it’s just a Betamax vs. VHS difference. Or maybe HTML5 is doomed due to the conflicting goals of vendors and the difficulty of the implementation task.

Maybe HTML5 ends up being great for less demanding uses – like basic enterprise apps, ads, motion graphics, etc. – but can’t get it together for highly demanding and integrated stuff like games. Adobe can keep Flash around and focus specifically on the game use case – which, by the way, is also highly beneficial for non-game apps, since they tend to use subsets of game functionality – and get as much value from it as possible for as long as possible.

Between the games angle and inertia, Flash could remain relevant for years. It could even end up totally dominating that space for a long time to come, even as HTML5 takes over the bottom of the market, due to being able to be more focused and agile.

CONCLUSIONS

Let me add two caveats. First caveat: At some point you can only expect so much out of a platform – you can’t get a guarantee that it will remain relevant for ten years. Even proven, still-relevant technologies like C have had their death announced many times. At some point you just have to say, “well, N years more relevance is good enough and I’ll re-evaluate in a year.”

Second caveat: Maybe Adobe screws the pooch and that’s that. Maybe they cut too many resources from Flash. Maybe they don’t build good stuff on HTML5. Maybe they ruin everything. So don’t bet the farm. Make sure you learn a few different technologies well. It will make you a better developer, even if you still just do Flash work day to day. And you’ll sleep easier knowing that if worst comes to worst you have an out. I’ve never seen a successful programmer regret having learned a new language or paradigm.

I don’t think Adobe is making bad decisions, just difficult ones.

Bottom line: Flash is a declining asset, but declining assets aren’t dead or even out of the fight. Everyone needs to look at technologies on their merits and see if it’s a good fit for your needs. There are a lot of places where Flash will continue to be a good fit for a while to come – and the places where it is ambiguous deserve careful consideration regardless of Adobe’s stated plans.

(Thanks for reading! If you liked this article, please consider voting it up on HackerNews or Reddit)

Game Articles Online

I wrote some game reviews/articles a while ago in collaboration with Blockland creator Eric Hartman.

All 12 are now online again, thanks to Eric. I’m especially proud of the history of every MAME-supported baseball game from 1976-1985, the article we did for GameDev.net titled Learning from the 3000 Classics, and our review of the 90s arcade version of Aliens.

Check ’em out!

Building the Best Gameplay @ Adobe MAX 2011

UPDATE: The talk is now available on Adobe TV! The slides are available, too.

You can find the code for the talk at https://github.com/PushButtonLabs/PushButtonEngine/tree/PBE2. They are fully explained via dokko, a literate code documentation tool. You can read the docs online at http://pushbuttonlabs.github.com/PushButtonEngine/v2/docs/PBEDemos.html.

A big thank you to everyone who came, and to Adobe for inviting me to speak! It was a real pleasure. MAX was great, and I’m already excited about attending next year.


I’m doing a session, Building the Best Gameplay, on Tuesday, October 4, 1-2pm at Adobe MAX in Los Angeles:

Take a dive deep into the techniques required to build the best games. Building games is fun, but building them well takes skill and experience. Ben Garney, core Flash architect at Push Button Engine and one of the most well-known names in the Adobe Flash gaming industry, will put some powerful tools into your game development toolkit: finite state machines, numerical simulation, components, data-driven definitions, and more. Build better, more interesting games faster and with less risk.

If you’re a Flash game developer and/or PushButton Engine user and you’ll be in the LA area around that time, I’d love to meet you. Tweet me at @bengarney or drop me a line via other means.

Molehill and the Display List

One of my posts on the Flash display list was quoted recently in a post by Amos Laber on his excellent blog. He said:

So developers like Ben Garney are opting to write their own renderers in order to gain better performance, but that is not an ideal long term solution. A much better one would be to utilize both multi-threading and GPU hardware acceleration for the standard flash Display List.

An example of a very basic game UI. We are seeing an uneasy alliance between Stage3D and DisplayObject. They work together but not fantastically. How can Adobe reconcile these two different worlds? As Amos points out, it’s a lot like the bad old days in the early 90s when UI libraries were non-existant for OGL/DX and games got by with the bare minimum in terms of UI.

Flash is pivoting from a rich content web runtime to a platform. Things that were previously built into the player need, in my opinion, to become a minimal native API that is enriched by powerful libraries. The display list is a great example of this. 90% of what the display list does can be done as well or better by pure AS3 (in fact, if you look carefully, many of the native DisplayObject methods are actually implemented in AS3). So why not move all that functionality into an AS3 library that comes with the platform, and focus on making the remaining 10% as good and generally useful as possible?

It’s like how an operating system has just a few basic routines for working with the file system, on top of which people build a wide variety of powerful tools like Finder, Explorer, Google Desktop, Alfred, bash, and so on.

The Flash team and the surrounding community has done the software world a tremendous service by developing great ways to build rich interactive experiences. Tweening and the display list are key foundations to those techniques. But they can work anywhere, and in almost any language – take a look at Sparrow, for instance, which provides a lot of the Flash API on iOS.

If I was going to make a prediction for Flash’s future, it would be that long term the display list will take a step back in favor of core APIs like Molehill. Of course, there will still be a display list or display list like APIs, but they will be conveniences on top of fundamental capabilities. This not only follows the trends seen in OS X, Windows, Java, and other platforms, but also enables more innovation and choice on the part of developers.