My ActionScript Game Server with 15,000 Concurrent Connections

Goal

Create a game using ActionScript for both the server side game server and the client side game with the ability for a large number of concurrent (10,000+) socket connections. Make sure memory and performance of the application are up to the task.

What am I talking about?

This blog post will explain how I created a socket server running on an Amazon EC2 Ubuntu server with more than 15k+ concurrent connections. This socket server has all the game logic for a game called SpellTraction, for which both the server and client are written in ActionScript.

Server: Game built in ActionScript 3 and run as a shell process using a modified redtamarin build. The modified redtamarin has a libev based socket server.
Client: Client game built with ActionScript 3.

To check out a running version of the client go to either:

http://renaun.com/serveras/test/ – this version is driven by other Amazon EC2 instances that are running test scripts to create the 15k+ connections.
or
http://renaun.com/serveras/spelltraction/ – the game with any other player looking at it right now.

View the whole post »

Using Fullscreen Interactive and Mouse Lock in Flash Player 11.3

Fullscreen Interactive Feature

In Flash Player 11.3 (currently in beta on labs.adobe.com) there is a new feature that allows applications to use full keyboard input in fullscreen mode.

To use the new fullscreen interactive feature you must first set the "allowFullscreenInteractive=true" value in the HTML embed code. Then in ActionScript you set the display state correctly, stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE;, to launch the application into fullscreen interactive mode. This mode presents the user with a slightly different overlay then normal fullscreen mode. It presents the user with an overlay that has an "Allow" button which must be clicked before entering the fullscreen interactive mode. Here is what it looks like:

As a developer you can listen for the new FullScreenEvent.FULL_SCREEN_INTERACTIVE_ACCEPTED event to know when the user has clicked the allowed button.

Mouse Lock Feature

The mouse lock feature is supported in Flash Player 11.2 and beyond. You can only turn on mouse lock, stage.mouseLock = true, while in any fullscreen mode. There is a bug in 11.3 that will be fixed for 11.4 that I'll explain and show a workaround for 11.3. Since you can only use it in fullscreen mode, it makes sense to set stage.mouseLock = true in the function handler for the FullScreenEvent.FULL_SCREEN_INTERACTIVE_ACCEPTED event. This is where the bug is, if you do set stage.mouseLock = true in that function handler it will not get set correctly, it stays equal to false. That means you have to wait a frame or some amount of time before setting it. In my code example on github I add a flag and then listen on MOUSE_MOVE, which I am doing anyways, to set stage.mouseLock = true. Here is a code snippet:

ACTIONSCRIPT:
protected function mouseMoveHandler(event:MouseEvent):void
{
if (isFirstTime == true && stage.mouseLock == false)
{
isFirstTime = false;
errorMessage.text = "here: " + stage.mouseLock;
stage.mouseLock = true;
}
if (stage.mouseLock)
{
errorMessage.text = "here: " + event.movementX;
deltaX = event.movementX;
}
else
{
//deltaX = event.stageX - lastX;
//lastX = event.stageX;
}
}

protected function fullscreenHandler(event:FullScreenEvent):void
{
if (event.type == FullScreenEvent.FULL_SCREEN_INTERACTIVE_ACCEPTED)
{
isFirstTime = true;
//*****
// For Cyril (Flash Player 11.3) this is a bug that mouseLock does not get set to true,
// The workaround is using isFirstTime approach
// Flash Player 11.4 will have a fix for this behavior
//*****
stage.mouseLock = true;

trace("["+event.type+"]Set mouse lock: " + stage.mouseLock);
errorMessage.text = "["+event.type+"]Set mouse lock: " + stage.mouseLock;
}
else
{
isFirstTime = false;
}
}

The full source as a Flash Builder 4.6 project, with modified index.template.html, -swf-version, and latest playerglobal.swc for 11.3 is located on my github repo here.

Here is a running version of the example - http://renaun.com/flash/fullscreeninteractivemouselock/

How To Know That Your Flash Content Requires a Premium Feature License

A license is needed for your SWF if it uses premium features. The current premium feature that requires a license is a SWF that makes use of Stage3D and ApplicationDomain.domainMemory APIs at the same time. If only one is used without the other a license is not required.

Still not sure if your application requires the license? Well there is a way to find out with using a debug version of Flash Player. Starting with Flash Player 11.2 you will get a message that is rendered on top of your SWF if you require a license. Here is what it looks like:

Premium Features Watermark

And here is the code to force the watermark:

ACTIONSCRIPT:
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.system.ApplicationDomain;
import flash.utils.ByteArray;
import flash.utils.Endian;

[SWF(width="320",height="160",backgroundColor="0x333333")]
public class PremiumFeatureCheck extends Sprite
{
    public function PremiumFeatureCheck()
    {
        addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
    }
   
    protected function addedToStageHandler(event:Event):void
    {
        trace("Stage3Ds Lenght: " + stage.stage3Ds.length + "");
        stage.stage3Ds[0].addEventListener( Event.CONTEXT3D_CREATE, initStage3D );
        stage.stage3Ds[0].requestContext3D();
       
        var testData:ByteArray = new ByteArray();
        testData.endian = Endian.LITTLE_ENDIAN;
        testData.length=0xffff*4; //4bytes
       
        ApplicationDomain.currentDomain.domainMemory=testData;
        var testValue:int=123;
        ApplicationDomain.currentDomain.domainMemory[0] = testValue;
        var readValue:int = ApplicationDomain.currentDomain.domainMemory[0];
        trace(readValue+"");//should print 123 
       
    }
    protected function initStage3D(e:Event):void
    {
        var context3D:Object = stage.stage3Ds[0].context3D;
    }
}
}

If you comment out "stage.stage3Ds[0].requestContext3D(); " or remove the domainMemory lines of code you will not see this watermark.

NOTE: If you get a context3D error you need to make sure you have swf-version=13 and wmode="direct" set up properly to run Stage3D content.

View the whole post »

Epic Games Unreal Engine in the Browser Try For Yourself

You can now try out the Epic Games Unreal engine running in the browser for yourself. All you need is the Flash Player 11.2 RC installed and then go to the http://unrealengine.com/flash/ website.

Here is a screenshot of it running in Chrome on my MacBook Pro:

Mark Rein form Epic Games talks about the latest Unreal demo at GDC.

At the Adobe GDC booth you can also see us show off Dungeon Defenders by Trendy which also uses the Unreal engine.
Look at what I playing at GDC in the Adobe booth on Twitpic

What does all this mean? Check out http://gaming.adobe.com for some more ideas of how AIR and Flash enable game developers to create great content.

Flash Game Summit 2012

Flash Game Summit is held before the big Game Developer Conference (GDC). The 2012 Flash Game Summit was a great turn out, with a wide variety of attendees. Because you get a crowd that usually comes in for GDC from around the world Flash Game Summit has people and companies from all over the world.

Adobe is a sponsor and this year they provided live streaming as well as recordings of the sessions. So if you were not able to attend in person you can catch some of the latest topics around gaming with the Flash platform. There were two rooms with with session through the day so here they are separate by room:

Title Speaker Recording
Robertson Auditorium
Welcome Josh Larson http://partners-ar.adobeconnect.com/p10j7raiidd/
Flash The Next Generation Lee Brimelow / Thibault Imbert http://partners-ar.adobeconnect.com/p84glz9113f/
SAS:  Zombie Assault 3 Chris Harris / Jonathan Hopcroft http://partners-ar.adobeconnect.com/p5g1mwjvvcu/
Mobile Gaming Goes Boarderless Peter Relan / Suran Markosian / Ben Savage http://partners-ar.adobeconnect.com/p8tzebm31ge/
Mochis Award Show Sponsored By Armored Games http://partners-ar.adobeconnect.com/p515odcc3xo/
Kingdom Rush Alvaro Azofra / Gonzalo Sande / Pablo Realini http://partners-ar.adobeconnect.com/p2am4xm3asx/
For Your Ice Onlye Reece Millidge http://partners-ar.adobeconnect.com/p3fdn7cvzy4/
It's The End of The World And We Know it. Ben Garney http://partners-ar.adobeconnect.com/p9dh8z22yjw/
It's A Long Way to The Top David Scott / Paul Preece http://partners-ar.adobeconnect.com/p20c2imvu74/
Chasing China Chris Shen http://partners-ar.adobeconnect.com/p5vzvma4a11/
Fisher Room
Panel: Flash Development Life 2012 Moderated by: Ethan Levy, Producer, BioWare San Francisco  Panelists: Sean McGee, Developer, Diseased ProductionsAndrew Sega, Lead Engineer, Sojo StudiosDan Stradwick, Developer, Monstrum http://partners-ar.adobeconnect.com/p9ewajrc1fq/
Two Dimensions of Awesome: Advanced ActionScript for Platform Games Iain Lobb, Managing Creative Director, Dull Dude Ltd. http://partners-ar.adobeconnect.com/p71gwods77j/
Getting Some Perspective: Away3D 4.0 & Friends Rob Bateman, Co-Founder, Away 3D http://partners-ar.adobeconnect.com/p3qpzsv9gw7/
Going Mobile Nate Beck, Principal Architect, ZaaLabs, Ltd. http://partners-ar.adobeconnect.com/p4k55h49x30/
Winning With Audio Selcuk Bor, CEO & Founder, Symphony of Specters http://partners-ar.adobeconnect.com/p3ja0j9hl6m/
Ponycorns & The Price of Popularity Ryan Henson Creighton, President, Untold Entertainment Inc. http://partners-ar.adobeconnect.com/p12ns4cb8l6/
Screenplay Tom Vian, Freelance Game Developer, Super Flash Bros. http://partners-ar.adobeconnect.com/p43hdz1tfs6/




Some take a ways for me after talking with people at the conference are there are still alot of students that are building Flash games. Although they say their teachers and schools could use some more love. If you have a large student base and doing senior gaming projects, and are thinking of using Flash as the platform feel free to reach out to me and I'll try and help as much as I can. Next thing I noticed is people are building a lot of Flash games, but people are still not quite using Stage3D in mainstream. This is for various reasons, dev cycles, Flash Player runtime releases, mobile AIR 3.2, etc... but uniformly people want to get their Flash games seen. So again if you have some great looking content, using the latest Flash Player features the better, send them my way and I'll take a look.

Good luck and on to a great future of Flash gaming. And if you are looking for some of the latest info check out Lee and Thibault session above. And the new http://gaming.adobe.com site to participate in the telling of the Flash for gaming story.

Upcoming Game Conferences I’ll be at

With the shift of my focus on Flash's gaming focus it means I get to attend game conferences. Adobe will have a presence at GDC and Flash Game Summit as well as other events through the year. I will be in San Francisco for both Flash Game Summit and GDC.

If you haven't taken the time to come up to speed on Flash Player's current useful gaming features and future features check out the stuff below.

Stage3D Desktop (Currently Available)
Stage3D Mobile (Coming Soon)
Epic Unreal demo running in browser through Flash Player
(Flash Player 11.2 Beta) Mouse Lock, Right, & Middle Click
Relaxing the drivers of GPU acceleration feature from 2009 to 2008 (maybe more in future releases)

There will be more information coming out over time, Flash Game Summit and GDC are a great place to come see what Adobe is doing. If you are a game developer and attending one of the conference be sure to come up to me and say hi.

An Approach to setting wmode for Stage3D project in Flash Builder

There are a lot of posts on how to configure projects to get up and running with Stage3D. With Flash Builder 4.6 and Flex 4.6 SDK some of the steps are not needed, like getting a different playerglobal.swc and setting the -swf-version=13. But you still need to set the wmode="direct" in the index.template.html for Stage3D content to run.

Reading a bunch of posts some people just change this by hand for each project. Others post about how to change the index.template.html in the SDK templates folder. A drawback with this last approach is then all your projects will have wmode="direct" turned on, which is not necessarily bad but could cause issues in some cases.

My approach is a middle ground, I add a new template file to the templates that has the wmode="direct" enabled. Then you have the option to use the wmode="direct" by just changing your run configuration to point to this new template html file. Which I call direct.template.html and it comes out as direct.html in the bin-debug folder along side the AppName.html file. The drawback here is if you have projects that have multiple applications it will only copy over this second template for the default application. For this specific drawback you can just copy the direct.template.html over index.template.html (since direct.template.html will be in the project) and then have all them set to direct. This still gives you control over what you project should run at but not go looking for how to modify the index.template.html for each new project. Read on to see the steps I take to setup this up.

View the whole post »

The Gaming Side of Renaun

I love games. Both PC and Board/Card games. I loved exploring different interests in college from computers, archeology, and music. Through all those years and up to now gaming has always been apart of me. Great memories around gaming shaped me up to day. Like having a paper route when I was 12, just to go buy 2 Nintendo games each month. Or family reunions of playing spoons and watching my 70 yr old great-grandma leap over the table to get to a spoon. Pursuing computers and programming was driven largely because of my interest in games.

The first AIR mobile application, nearly 2 years ago, I built for iOS was a game. It was so much fun using my skill set to built the application, it reminded me of the days when I was first learning how to program and how fun it is. The app is called Raining Blocks and been in the app store for almost 2 years now, it was just for fun and I don't tell many people about it - until now.

I did Flex, since 1.5, and Flash work before joining Adobe nearly 4 1/2 years ago. The different projects have given many different programming experiences, from libraries (Pacifica), code in the Flash Player (Pacifica), server side payment integration (Shibuya/InMarket), and many demo applications. At the core I understand the Flash Player and like building components and libraries. Since joining the evangelist team I get to build more and more examples. It shouldn't be a surprise that I augmented my examples with games when possible.

I just spoke at FITC Screens on "Digital Fun in the Digital Home" where I used applications like PickQuick and Eiden1. Both have all their source code available on github. Eiden1 was designed by my 5 year old at the time and has been to show since it uses WiiMotes through a Android IME with the Android device hooked up to the TV, a console in your pocket. Games just make sense to me when showing off cool features.

So I like games, whats all the fuss. Well, I am excited to say that my new focus as an Evangelist is Flash Gaming. I am joining the gaming evangelist team, so you'll be seeing more posts around this topic.

Customizing Flex applicationDPI for a multiple screen size application

Building a Flex mobile application that works across smartphones and tablets takes an understanding of screen sizes, screen dots per inch (DPI) and screen resolutions. In the current landscape of devices typically you consider a tablet something bigger then a 5-6 inch physical screen. Also in the current device landscape screen resolutions are for tablets are typically greater then 1024x600 (original Galaxy Tab 7' and PlayBook), while smartphones are typically less 1024x600. This of course will change as screens get better and have high resolutions.

How Flex works with helping you develop and design for multiple screens is provide a concept of applicationDPI. This applicationDPI is baked into the spark mobile skins, available in css media queries, and available to you any where in your code. Flex also provides a mechanism to override the applicationDPI for your needs, I will get to this in a bit. First for an example of an application making heavy use of the applicationDPI check out Caltrain Times. It is currently running across Android, iOS, and BlackBerry Tablet OS (PlayBook).

I have also personally tested it across these devices:

Device Name Screen Size Screen Resolution DPI
Motorola Atrix 4 540 x 960 275
Google Nexus 1 3.7 480 x 800 254
iPhone 3GS 3.5 320 x 480 163
iPod Retina Display 3.5 640 x 960 326
iPad 9.7 1024 x 768 132
PlayBook 7 1024 x 600 168
Galaxy Tab 7' 7 1024 x 600 168
Motorola Xoom 10.1 1280 x 800 150
Nook Color 7 1024 x 600 168

What is Flex's Application DPI really?

Lets start with what its not. Its not a reflection of what the device's actual DPI, for example the DPI values in the above chart. What Flex does for developers is provide 3 classifications you build your application against. They values are 160, 240, and 320, but you can think of them as small, medium, and large. Its also important to think of the Flex three DPI classification approach as your way to define what your application looks like and how it acts not relative it directly to device DPI. I explain two examples of why this is important with my Caltrain Times application. First is how to handle incorrect DPI values from the OS level. Second is applying your look to a set of devices by customizing the DPI classification in Flex. I'll get to the detail of those two examples later in the article, first lets explain application DPI.

The definition, Flex's applicationDPI takes on two meanings. If you explicitly set the value your are telling Flex that this application is skin to applicationDPI=XXX (160,240, or 320) and for the application to automatically scale the SWF and contents to the ratio of XXX/runtimeDPI. The applicationDPI classification strings can be found in mx.core.DPIClassification. For more control of how your application looks for the different DPI's do not set this value. Then the value of applicationDPI is just a classification of 160, 240, or 320 (or some arbitrary value if you wanted to your own classification). By default Flex considers any device DPI of < 200 = 160, > 200 = 240 = < 280, and > 280 = 320. Now you can override the class mx.core.RuntimeDPIProvider, in the first case this controls the scaling, the second case it sets the applicationDPI value.

The rest of the post will make use of extending mx.core.RuntimeDPIProvider to handle incorrect DPIs from the OS and control the look between phones and tables.

Handling Incorrect DPIs

It just happens that on the Android devices depending on the OS and manufacturers there is a chance of the device reporting their DPI incorrectly. I address this problem in Caltrain Times application, specifically on the Motorola Atrix, in my custom extended mx.core.RuntimeDPIProvider class. The basis of my thoughts go back to the current landscape screen resolution and screen size values. I check the resolution threshold of 1024x600=614400 and screen size to figure out case that just don't make sense. Here is the code for screenSize and pixel checking:

ACTIONSCRIPT:
var screenX:Number = Capabilities.screenResolutionX;
var screenY:Number = Capabilities.screenResolutionY;
var pixelCheck:Number = screenX * screenY;
var pixels:Number = (screenX*screenX) + (screenY*screenY);
var screenSize:Number = Math.sqrt(pixels)/Capabilities.screenDPI;

In the case of a high resolution 4 inch Android device with incorrect DPI of < 220 you'll find that the screenSize is getting larger then 5 inches. In my application I just looked for any device that was larger then 4.3 screen size (might have to change that as phones get larger displays) and its screen resolution < 610000 with a report DPI of < 220. If all those criteria are found I force it to return a value of 240 which the correct value I want.

Here is the code (with some checks for the my desktop case in there too):

ACTIONSCRIPT:
if (screenSize> 4.3 && pixelCheck> 510000 && pixelCheck <610000 &&
    Capabilities.screenDPI <240 && pixelCheck != 1296000)
{
    //trace("Force 240");
    return DPIClassification.DPI_240;
}

Note: The source code can be found at https://github.com/renaun/CaltrainTimes/blob/master/src/com/renaun/mobile/dpi/CustomDPIProvider.as.

Applying your look to a set of devices by customizing the DPI classification in Flex

In this example I use similar calculations to figure out if the device is of a tablet size. The reasoning for my Caltrain Times application is that I wanted to overrider the typical DPI classification of 160 for tablets to be rendered at the DPI classification of 240. For my application with the larger look on the bigger tablet screens it feels the screen out nicely and works well. Again I go into the custom runtime DPI class to do this. Here is the code:

ACTIONSCRIPT:
else if (screenSize> 6.9 && screenSize <11 && pixelCheck> 610000 && pixelCheck <1920000 && pixelCheck != 1296000)
{
    //trace("Force 240 Tablet");
    return DPIClassification.DPI_240;   
}

The "pixelCheck < 1920000 && pixelCheck != 1296000" part is to handle running it through adl on my desktop. The rest probably makes sense, in the current device landscape tablets are typically larger then 7 inches and smaller then 11 inches with a resolution greater then 1024x600. If these values show up then I apply the DPI classification of 240.

Summary

The main take away is don't take the devices DPI at face value. If you want more control of your application across various devices make use of some classification constraints and check screen size, resolution, and DPI. It might seem like a bunch of work but this class can be used across applications and projects with minor tweaks depending on content requirements. Its also a good way to figure out if its a tablet or smartphone and outside of Flex DPI classification. Enjoy.

Check out my MAX 2011 talk where I go through Caltrain Times in more detail, as well as the source code available on github.com/renaun/CaltrainTimes.

Flash Embed Font Unicode Range Generator

First off I am not sure why I haven't made this before. I have needed this over the years on a couple of projects. If you are embedding strings in an application and you know exactly what characters are being used this will come in handy to save on the SWF size.

You can tell Flash what glyphs of a font to embed with the unicodeRange property. Here is an example:

CSS:
@font-face
{
  src: url("/assets/fonts/Arial.otf");
  fontFamily: myArial;
  embedAsCFF: true;
  unicodeRange: U+0018, U+0020-U+007F;
}

What is not obvious is how to get those unicodeRange values. I created a web application that lets you input any text you want, in any language, and get back the correct unicodeRange for the exact glyphs in the input text.

Its called Flash Embed Font Unicode Range Generator.

View the whole post »