Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon Join the GFS Discord Server!
22. October 2012

This post is going to look at getting your Moai app to run under NaCL, which is Google’s mechanism for allowing you to execute C++ code within Chrome.  There are a number of restrictions, but fortunately Zipline have done most of the hard work for us.


Like any other platform, your code is run within a host.  If you are working from the binary ( non-GitHub ) distribution, the host is already built for you and you can skip ahead until you encounter the text “STOP SKIPPING AHEAD!”.  If you are working from Github sources, you need to build the host first.  That is what we are going to do next.


Building the Chrome Host


First is a matter of locating it.  The source for the NaCL host is located at moai-install-dir/scons/

There are a few things you are going to need to continue…


First off, if you haven’t already installed Cygwin, I highly recommend that you do.  The Android  build process basically requires it, so I am going to assume you already have it.  If you don’t, refer to the Android installation guide Cygwin section for details.

You also need to have Python 2.6 or 2.7 installed.  To check, fire up Cygwin terminal and type:

python –V

If you get an error that the command wasn’t found, Python isn’t installed so let’s install it.  The easiest way is to run the Cygwin setup application, then click Next next next until you get to the Select Packages screen.  In the search box enter Python, in the results expand Python and select python: Python language interpreter.


Make sure you don’t have any Cygwin Terminal windows open, then click Next and let Cygwin do it’s thing.


Now that you have Python installed, we need to download the native client SDK. (That’s the direct download link btw… )

Save it somewhere you can remember.  Open the archive and extract the folder nacl_sdk.  I went with c:\dev\nacl_sdk, but choose whatever you want, just be sure to update your paths accordingly.

Now open a Cygwin terminal window and change in to the nacl sdk directory, which in my case is:

cd /cygdrive/c/dev/nacl_sdk/

Now we want to run the installer/downloader.  In the terminal window type:

./naclsdk update pepper_17

Even though the current version is 22, you need to install 17, as it ships with developer tools Moai depends on.  For some reason, Scons has been removed from future versions.  That is what the above command does, gets and attempts to install pepper version 17.



OK, here’s the thing, we are dealing with Google developer tools, and Google developer tools are always broken in some way, especially on Windows, naclsdk is of course no exception.  After running the above command you will be greeted with the following error:


Updating bundle pepper_17 to version 17, revision 112997
Traceback (most recent call last):
  File "/cygdrive/c/dev/nacl_sdk/sdk_tools/", line 759, in <module>
  File "/cygdrive/c/dev/nacl_sdk/sdk_tools/", line 752, in main
  File "/cygdrive/c/dev/nacl_sdk/sdk_tools/", line 741, in InvokeCommand
    command(options, args[1:], config)
  File "/cygdrive/c/dev/nacl_sdk/sdk_tools/", line 583, in Update
  File "/cygdrive/c/dev/nacl_sdk/sdk_tools/", line 564, in UpdateBundle
    RenameDir(bundle_move_path, bundle_path)
  File "/cygdrive/c/dev/nacl_sdk/sdk_tools/", line 56, in RenameDir
    shutil.move(srcdir, destdir)
  File "/usr/lib/python2.6/", line 260, in move
    copy2(src, real_dst)
  File "/usr/lib/python2.6/", line 95, in copy2
    copyfile(src, dst)
  File "/usr/lib/python2.6/", line 50, in copyfile
    with open(src, 'rb') as fsrc:
IOError: [Errno 2] No such file or directory: u'/cygdrive/c/dev/nacl_sdk/pepper_17_update'

YAY!  Don’t worry, it’s pretty easy to work around.  The installer is trying to execute a program that doesn’t exist, but the installer was downloaded as part of the above process.  Go in to the folder sdk_cache and locate the file naclsdk_win.exe and run it.  When prompted for an install path, install it to your NACL_SDK folder/pepper_17.  In my case that means C:\dev\nacl_sdk\pepper_17

Now we need to set an environment variable with the path to the NACL SDK.

setx NACL_SDK_ROOT /cygdrive/c/dev/nacl_sdk

Keep in mind, the setx command requires administrator rights, so be sure to run your cygwin terminal as administrator if you aren’t already.

Now the bummer part, exit and restart Cygwin terminal, system level environment variables don’t take immediate effect.


Are we there yet? Nope… it’s FMOD install time

Close… one more dependency left… FMOD.  FMOD is a commercial audio system ( AKA, if you ship a product, you’ve got to pay to use it ).  With most of Moai, you can get by using the free Untz audio system, but with NaCL, FMOD is required.  So you either have to gut the FMOD library from the build dependencies or download and configure FMOD.  I’ve opted for the second ( audio is after all, kind of nice! ), but either option is open to you.

Head on over to the FMOD download page and download the archive for FMOD for Google Native Client. Unfortunately you need to download a version that supports the same Chrome version as Moai (17).  The following direct link will download the correct version. (Direct linkIT IS VERY IMPORTANT YOU DOWNLOAD THIS VERSION…. just so you know.

Save and extract that archive somewhere.  This file is a tar.gz, so if you are using a program such as 7zip, you need to extract it, then extract the file you just extracted.  I took the resulting folder, renamed it fmodchrome and copied it to c:\dev\.  The resulting directory should look like:


Now we need to set yet another environment variable, one named FMOD_CHROME_SDK_ROOT and pointing at this new directory.  Once again in Cygwin terminal type:

setx FMOD_CHROME_SDK_ROOT /cygdrive/c/dev/fmodchrome

Once again, you need to exit and restart Cygwin terminal for this variable to take effect.


It’s building time!


At this point in time, there seems to be a problem with the scons build script so that the paths ../3rdparty and ../src aren’t working, at least, not on Windows.  The following is a brutal hack, and I will post a better solution when I come up with it.  For now, we simply copy all the source into the scons folder.  Copy the contents of [moaifolder]/src, [moaifolder]/3rdParty and [moaifolder]/scons/src to the scons directory.

Now cd in to the maoi scons directory, on my pc /cygdrive/c/dev/moai-dev/scons and run


Hopefully all went well.  If you get errors… something didn’t go so well… if you want, just skip ahead and download the version I compiled.  You only really need the build process working if you intend to alter the host.


Now copy the following files to a new folder:





This is your Moai Host ready to go. 


If for some reason you couldn’t get your host to build, you can download mine.




Packaging your app to run in Chrome

Now you need to package your application up into Chrome friendly goodness.  The steps are fairly straight forward

In the folder you copied the .nmf and .nexe files, create a new file called manifest.json here is what I put in mine:


    "app": {
        "launch": {
          "local_path": "moai.html"

Now you need an html file to actually host your application. As you probably guessed by the manifest file, I called mine moai.html:


<!DOCTYPE html>

  <title>Hello Moai!</title>
    <embed name="nacl_module"
           width=480 height=320
           type="application/x-nacl" />


Finally you need your Moai application ( the lua bits ).  Just copy your project sources into the same directory, just be sure a file is called main.lua, this is your app entry point and will automatically be called the the host.  Here for example is my folder:


I simply grabbed the sources from this tutorial.



Configure Chrome to run your app

Now you need to let Chrome know you want to enable NaCL applications.  In Chromes location bar enter chrome://flags, the following window should appear.


Scroll down and enable Native Client as shown by the arrow. You need to restart Chrome for this to take effect!

So, um, restart Chrome.


Now you need to add your application.  To do this, in Chrome, drop down the Menu and select Tools->Extensions.



In the resulting window, enable Developer Mode, then click Load unpacked extension…


In the browse dialog, navigate to the folder you’ve saved everything in then click OK.



Your extension should now be installed.  Launch a new tab ( CTRL+N ) in Chrome, and at the bottom of the screen, select Apps



Your app icon should appear on the page:



Click it.


Voila, a Moai application running in Chrome:





20. October 2012

A month ago I started looking for a Mac based alternative to the excellent Windows Live Writer and thought I may have found one in the form of MarsEdit. It came with a 30 day trial and my final verdict was a bit mixed.  It was a very pleasant writing experience, if that makes any sense.  It was like when you write with a quality pen, the actual experience itself is just better.  On the other hand, some things were a bit unwieldy too.  The picture formatting tools are primitive to nonexistent, it's hard to format source code ( something of key importance to me ), it didn't do site preview all that well ( although frankly, neither did Live Writer, at least with my site ) and it didn't support tags.  None of those is a deal breaker, but all of them make the experience slightly worse than Live Writer, to the point when I needed to do code related blogs, I rebooted in to Windows to use Live Writer.  It's a great little product, but the limitations make me a bit hesitant to pull the trigger.  If it had good source code pasting options and better image formatting, I would have purchased already.


At the end of the day, I was resigning myself to having to work in Windows only, which is certainly unfortunate.  There are a couple open source cross-platform options, but they all seem pretty much terrible.  There are a couple other commercial options such as Blogo and Ecto, but let's just say their online presence just doesn't fill me with a ton of optimism. So I figured it was either MarsEdit ( which I may still buy ) or reboot to use Windows Live Writer ( not a great option ).  Then I discovered Adobe Contribute, which apparently started life as Macromedia Contribute.

First things first, Contribute is expensive compared to the other two products.  MarsEdit is 40$ ( plus they charge for updates ), Windows Live Writer is free, which is hard to compete with.  Adobe Contribute on the other hand is 100$.  That said, I have no qualms about paying for software, it's what I do for a living after all, and I spend so much time in my blog editor, that I will gladly pay that price if the experience is an improvement.  Now, I just need to decide if Contribute is an improvement!  Fortunately, like MarsEdit, it comes with a 30 day trial.


One immediately appealing feature of Contribute is that it is available cross-platform.  I need to confirm that if I buy a seat I can use it under either operating system ( I am not buying it twice! ), but if I can, have a familiar editing environment on either platform is a big plus to me.  The rest of this post is a bit of a playground for testing Contibute out.  First of all, Contribute certainly has more imaging options than MarsEdit.  Actually it may have more options than Windows Live Writer!  At the same time though, I've run in to a couple of limitations.  For some reason, and this is a shame as it is a feature I use all the time, but I can't copy and paste images for some reason.  I pulled the above image in to Preview and resized it, did a select all and... nothing.  The entire Edit->Paste menu in Contribute just stayed disabled.  Need to see if this is a bug or not. 

That said, I didn't actually have to pull the image in to Preview in the first place, you can actually in place resize and crop images in Contribute.  You can also rotate, sharpen, adjust contrast and brightness, or send it to an external program for editing.  Unlike MarsEdit, you can also apply image padding, borders and edge colours, although unlike Live Writer, you cannot set padding on a side by side basis.  In the end, I would say the image handling is better than MarsEdit, and on par with Live Writer, if I can get paste working that is.

I am running in to some other problems in addition to the inability to paste images, I can't choose categories.  According to my blog settings it is allowed, but the Categories menu is disabled, and refreshing categories results in the Window:

Which by the way, not being able to copy paste the above was really disruptive, requiring me to capture it, convert it to png, import it.  Blah. On an unrelated note, why the heck does grab save things to tiff format?  Tiff? Is this 1992?

One other thing I have noticed is, I cannot drop directly to the HTML level.  I may be missing how to do it, but I don't see any menu option for editing as HTML or sending to an external editor.  This feature is handy when you run in to limitations of the blogging software and is something that MarsEdit does quite well, while Live Writer does it, but can be a bit destructive at times.  Contribute doesn't seem to do it at all.  There is however the ability to enter an HTML snippet, which should accomplish the same thing, at least most of the time.  As mentioned above, Categories are supported ( as the are in MarsEdit and Live Writer ), but do not work with my blog.  Tags are also supported, unlike MarsEdit, but it doesn't have the ability to download a list of tags to choose from.  Considering my blog treats HTML and Html as different tags, this missing feature is well, missed.

Contribute does seem to support pretty good table formatting...

  A B
1 DataData
2 DataData
Merged cells work!
So does per cell formatting

I have to say, table support is exceptional.  I never could get merged cells to work in Live Writer.  Tables are still a damned handy feature, so it's nice to see how well they work.  I never really tested table functionality in MarsEdit... oops.


Now what about code... does it preserve formating... a straight paste from XCode:

bool demo::drawScene(Node* node)


// If the node visited contains a model, draw it

Model* model = node->getModel();

if (model)




return true;



UGH, not be default anyways. There certainly doesn't appear to be an option for pasting as RTF either. Let's try pasting from Sublime Text Exported HTML:

-- create text to display on screen in 72point font
local helloText = display.newText("Hello World!",0,0,native.systemFont,72)
-- center to screen
helloText.x = display.contentWidth/2
helloText.y = display.contentHeight/2



Now the same HTML as a snippet:

Strike that... didn't work.



Ok, that's enough for me.  For 100$ price tag, Contribute doesn't work for me.  Hell, for a 40$ price tag, it doesn't work for me.  One last test to see if this publishing even works...


Anyone know any other options I should look in to for Mac based blogging?  As of right now, it's seeming like MarsEdit or bust.

19. October 2012


Sony, actually… and file this under the category of longest most unwieldy names ever, Sony Computer Entertainment Worldwide Studios Europe External Development Studio (yeah… really) in collaboration with Creative England and Birmingham Science Park have put together a contestimage called PlayStation Pioneers, with a grand prize of £25,000.  That’s about 40K in real money! Smile


So, how then do you go about winning this money?  Well, here are the details:

  • The opportunity is open to UK-based developers only
  • The goal is to take a concept/prototype and develop a playable ‘vertical slice’ suitable for consumer trial/user testing in summer 2013.
  • The deadline for submissions is 31st October 2012
  • Five finalists will then be selected to exhibit at this year’s LAUNCH conference taking place at Birmingham Science Park on 13th and 14th November 2012 and present their concepts to a panel.
  • £25,000 will be awarded to the winning entry
  • XDev will have the first right of refusal in regard to publishing the final game.
  • The winner will be announced by the panel at LAUNCH on 14th November 2012.


What isn’t explicitly listed in those requirements, your project will be for PlayStation Mobile.


That deadline is fast approaching (less than 2 weeks!).  Keep in mind though, you are submitting a *concept* by October 31st, not a complete game. 


The other line of note you should be aware of was:

XDev will have the first right of refusal in regard to publishing the final game

In other words, if they like you game, they get first crack at being the publisher.  Given that most indie developers would love to have a publisher, this shouldn’t be a huge deal, but is certainly something you should be aware of.



If you have never heard of it before, PlayStation Mobile is cross platform game development system based around Mono.  It is C# based, built over OpenGL ES and able to target the PlayStation Vita, as well as select Android mobile devices ( most Sony Android devices, plus select devices from HTC, Asus and a few other manufacturers ).  This site has a series of tutorials you can used to get started.


You can read the original announcement thread right here.


If you are interested in proceeding, be sure to read this guide (PDF link).  It gives more details of what is involved.  From that document, here is what is recommended in your proposal:

1. Concept summary (ideally one page).
2. A walkthrough/storyboard detailing the proposed ‘vertical slice’ playable.
3. Artwork/Visualisation that is representative of proposed final quality.
4. Design briefs (prototypes where possible) explaining key features.
5. A summary schedule and risk assessment re delivery of the ‘vertical slice’ playable to be delivered for full
consumer trial/user testing in summer 2013.
6. A commercial/financial business model, illustrating market potential for the concept on PS Mobile certified
platforms; (PS Vita, Xperia, Sony Tablet S etc.)
7. Details of relevant prior experience.


The PDF however has no more legal issues regarding publishing or IP ownership.


17. October 2012


A level is made up of sprites and sprites come from somewhere.  In our editor, we are going to allow the user to “upload” multiple image files containing sprite sheets.  However, are server is not required and that is going to require a bit of work.  Also, we are going to need some form of UI where users can upload the spritesheet, without cluttering our main UI too much, so we will implement it as a modal dialog box.


Well, let’s get to it.  First lets create a data type for holding our sprite sheet collection.  For now, a spritesheet is simply an image, the dimensions of each sprite and a name.  In your models folder create a new file named spriteSheet.js



    Y.SpriteSheet = Y.Base.create('spriteSheet', Y.Model, [],{
                return this.get('spritesheets').length;
                spritesheets: {
                    value: []
}, '0.0.1', { requires: ['model']});

Nothing really special.  Our spritesheets attribute is just an empty array for now.  We also included a pair of methods, add, for adding a new spritesheet and count for getting the current count of spritesheets already declared.  Everything else here should already be familiar at this point.


Now we want to create a dialog that will be displayed when the user wants to add a spritesheet.  As a bit of a spoiler, here is what we are going to create:


This isn’t a View and it isn’t a model, so we create a new folder called classess and create the long-winded file named AddSpriteSheetDialog.js


YUI.add('addSpriteSheetDialog', function(Y){

    Y.AddSpriteSheetDialog = new Y.Base();
    var spriteSheets = null; = function(ss,onComplete){
        spriteSheets = ss;
        var panel = new Y.Panel({
            headerContent:'Select the image file containing your sprite sheet',
                <input type=file id=spritesheet /> \
                <br /> <div id=imgName style='padding-top:25px;padding-bottom:25px'> \
                Click above to select a file to download</div>\
                <br />Sheet name:<input type=Text id=name size=30 value=''> \
                <br />Sprite Width:<input type=Text id=width size=4 value=32> \
                Sprite Height:<input type=Text id=height size=4 value=32> \
                <br /><input type=button id=done value=done />\

        var fileUpload ="#spritesheet");
        fileUpload.on("change", Y.AddSpriteSheetDialog._fileUploaded);

        var buttonDone ="#done");
        buttonDone.on("click", function(){


    Y.AddSpriteSheetDialog._fileUploaded = function(e){
            alert("NOT AN IMAGE!");
        var selectedFile =[0];
        var fileReader = new FileReader();

        var that=this;
        fileReader.onload = (function(file){
            return function(e){
                if( == 2)
                    var imgData =;
                    var img = new Image();
                    img.onload = function(){
              '#imgName').set('innerHTML', + " selected");
                        var name ='#name').get('value');
                        var width ='#width').get('value');
                        var height ='#height').get('value');
                    img.src = imgData;



},'0.0.1', {requires:['node','spriteSheet','panel']});

The editorView owns the spritesheet collection, and passes it in to the show() method of AddSpriteSheetDialog.  We also pass in a callback function that will be called when we are done.

We start off creating the panel which is a Y.Panel.  Most of the properties should be pretty straight forward, headerContent is the title and bodyContent is either the ID of the object to render the panel in, or in our case, we actually create a new node with our dialog HTML.  We then wire up a change handler on our file upload button, this will fire when a file is uploaded and call the _fileUploaded function.  We then wire up the Done button’s on click handler to hide the panel then call the callback function that was passed in.  Finally we display the panel.


When the user clicks the Choose File button, _fileUploaded is called.  First thing we check to make sure it is an image that is uploaded and error out if it isn’t.  We then want to read the selected file, which we do with the FileReader api.  Word of warning, this isn’t completely supported in every browser… frankly though, I don’t care about supporting IE in a project like this, cross browser support takes all of the fun out of web app development! Smile


Next is well… JavaScript at it’s most confusing. We are registering an onload event that will be fired once the file has been loaded, which in turn fires off an anonymous method.  It checks the readystate of the file to make sure it is ready and if so, our “uploaded” file will be in  We then create an Image object, then register yet another onload handler, this one for when the image has completed loading.  Once the user has uploaded the file, its finished loading and populated in our newly create Image, we then get the width, height name and our newly populated image and at it to the screenSheets object we passed in during show().  Yes, this is a bit screwy of an interface, in that you need to populate the text fields before uploading the interview.  I will ultimately clean that up ( and add edit ability ), but it would needlessly complicate the code for now.  Finally, no that our fileReader.onload() event is done, we actually read the file now with readAsDataUrl() the file that was chosen, which fires off the whole onload event handler in the first place.   Welcome to asynchronous JavaScript programming!  Don’t worry, if this is new to you, thinking async will come naturally soon enough…


So, that is how you can create a modal dialog to edit app data.  Now we wire it up and deal with a bit of a gotcha.


The gotcha first…  the Panel dialog requires a parent HTML element in the DOM to have a YUI skin CSS class declared.  At the bottom on the render function in editor.View.js add the following code:'body').setStyle("margin",0);'body').setStyle("overflow","hidden");
// The below needs to be added as some controls, such as our add sprite dialog, require a parent container
// to have the YUI skin defined already'body').setAttribute("class","yui3-skin-sam");
return this;

This adds the yui3-skin-sam class to the page’s body, which brings in all the styling for the Panel ( and other YUI widgets ).


While we are in editor.View.js, we wire up a menu handler for when the user clicks the add spritesheet button ( we will add in a second ).  That handler is basically the same as the menu:fileExit handler we created earlier.  Right below that handler in the initializer function, add the following:


var that = this;
    var dialog =,function(){
        var sheet = that.spriteSheets.get("spritesheets")[0];

There is the that=this hack again, there are alternatives ( you can pass the context in to the Y.Global.on event handler ), but this is a fair bit easier at the end of the day, as we would lose this again when the callback is called.  Otherwise, when the menu:fileAddSpriteSheet event is received, we simply call, passing in our spritesheet and the function that is called when the panel is complete.  For now we simply log the spritesheet out to the console to prove something changed.

We also need to add the SpriteSheet to our editor.View.js, like so:


 Y.EditorView = Y.Base.create('editorView', Y.View, [], {
        spriteSheets:new Y.SpriteSheet(),


Now we need to add the menu item.  First add it to the template mainMenu.Template,like so:

    <li class="yui3-menuitem" id="menuFileAddSpriteSheet">
        <a class="yui3-menuitem-content" href="#">Add SpriteSheet</a>
    <li class="yui3-menuitem" id="menuFileExit">
        <a class="yui3-menuitem-content" href="#">Exit</a>

And we wire it up in the mainMenu.View.js, add the bottom of render() add the following code:

var menuFileAddSpriteSheet ='#menuFileAddSpriteSheet');
            menuFileAddSpriteSheet.on("click", function(e){
      'menu:fileAddSpriteSheet', {msg:null});

Oh, and our newly added script AddSpriteSheetDialog.js is added to index.html to guarantee it gets loaded and evaluated.


And done.  We now added a dialog for adding sprite sheet images, and can store the image results locally without requiring any server interaction at all.


Here is the end result, select File->Add Spritesheet to bring up the newly created dialog:


You can download the entire updated source code here.

One step closer to a full web based game editor, one very tiny step. Smile

Programming General

16. October 2012


I recently read this ( very good ) blog post documenting the process of developing and publishing the game Pumped BMX and was struck by one thing.  I really really liked the font he used on his site, it was clean but not gimmicky.


It turns out the font is Open Sans, created by Google.  I have decided to adopt it on  With the recent increase of page width I also decided to increase the font size from 12 to 14pt.


Here are before and after results:



What do you think?  Like it better the new way, or prefer the old font?  All told they are both fairly similar fonts, so it’s not a very massive change.

Totally Off Topic

AppGameKit Studio

See More Tutorials on!

Month List