Funky Cam 3D goes FREE!

Recently we looked at ways of monetising apps and games by charging nothing for them. Yes, I know it sounds ridiculous doesn’t it. Well, its not quite as ridiculous as it sounds. Its possible to make money from apps and games by either a) giving the game away for free and inserting ads in there (usually called ad-ware) and b) again, giving the game away for free but selling optional extras within the game (usually called freemium).

We recently implemented a platform agnostic API that uses the Marmalade SDK and Inner-actives M2M protocol to serve ads to all Marmalade SDK compatible phones and tablets. Currently supported platforms include iPhone, iPad, Android, Samsung Bada, Blackberry Playbook, Symbian, Windows Mobile, WebOS, PC and Mac.

The great thing about our ads is that they are different. Our ads don’t just sit at the top of the screen crying like babies for attention, instead they leap out at the user with animations and transitions, hypnotising the user into clicking on them. We like to see the process as bringing gaming to ads and not bringing ads to gaming.

We are opening up our API very soon for all Marmalade SDK developers. The ad engine will also become part of the IwGame engine with additional support for MobClix, AdWhirl and InMobi. Depending up on the API’s success we may also create bespoke versions for the iOS and Android SDK’s for those die hard developers that won’t convert to the Marmalade SDK. We will put a proper blog together  when the time comes.

Our animating ads work very well and our click rate (CTR) is proof that the pudding is cooked well. Here are a few figures:

  • Android – 3.23%
  • iPhone – 7.34%
  • iPad – 3.54%
  • Samsung Bada – 5%

Our average CTR with static AdMob ads is 1.76%

Ok, now onto the real subject, we have released Funky Cam 3D across iPhone, iPad, Android and Samsung Bada (Bada 2.0 coming soon).

Funky Cam 3D FREE can be downloaded from the following stores:

So please feel free to download Funky Cam 3D for free and check out what our animating ads look like.

Marmalade SDK 5.2 has Arrived

Well, I’m very pleased to announce that the eagerly awaited version 5.2 update to the Marmalade SDK is finally here. Some great new features have made it into the build including:

Native UI (IwNUI)

Native UI is a cross-platform UI framework that utilizes native controls. This allows developers to create user interfaces with native look and feel using a simple cross platform framework. Currently Marmalade supports Native UI on iOS and Android platforms, with IwUI used as a backend for all other platforms.

What does this mean for us cross platform phone and tablet developers? I can tell you, it means a great deal. This single addition to the SDK makes Marmalade a very viable application development platform for regular app style projects using the phones / tablets own native UI look and feel.

Bada 2 support

Support for Samsung’s bada platform is extended with this release; Marmalade can now target bada 2.0 devices.

We get a new platform, woohoo, the is the main reason why I love Marmalade so much!

iOS 5 EDK Support

iOS support has been extended to support building extensions with iOS 5.0 SDK. Extensions can now include features from iOS 5.0.

So we get access to new iOS 5.0 features via the EDK, which is great. iOS 5.0 has over 200 new features, such as the new notifications centre, iMessage, Reminders and iCloud,

Xcode Plugin Upgraded to Support Version 4.2

The Mac OS X SDK now supports Xcode 4.2 and the compiler and editor changes that were introduced with the iOS 5.0 SDK. Support for Xcode 3.x has been officially dropped. Please upgrade to the latest version. If required, Xcode 4 can be installed in parallel to any existing 3.x installation by specifying a different install location and using the xcode-select command line tool.

iOS Remote/Push Notification Support

Added full support for remote/push notifications in s3eIOSNotifications, including support for embedding provisioning profiles in development builds.

EDK Support on OS X

Extensions are now supported for Mac OS X deployments.

WebView Enhancements

s3eWebView now supports transparency and local file access.

Also included are many bug fixes and other minor enhancements and changes, too numerous to mention in fact. The full list is available in the re,lease notes on Marmalade’s web site

IwGame Engine Update – v0.230

Well its been an interesting day to say that its a Sunday, some good news and some bad new . The good news is that I managed to sneak some time in today to add a few updates to IwGame. The bad news is that some robbing (insert lots of non-religious type words here) has skimmed my card and robbed my bank account! (Can’t these people just get jobs like the rest of us!). Anyways, anger vented, now to get back on topic. We have just updated the IwGame game engine to v0.230. If you don’t know what IwGame is then in short it is a cross platform game engine for smart phones and tablets based upon the awesome Marmalade SDK. Here are the new features:

  • Added CIwGameImage::CreatePNG(int& size) to CIwGameImage to allow the creation of memory based PNG files
  • Added pngilb and zlib dependents
  • Added helper support to CIwGameInput for detecting touched, tapped events, delta change and back / menu buttons
  • Added CIwGameSprite::HitTest(int x, int y) which basically tests to see if a screen point is inside a sprite (takes into account scaling and rotation)
  • Added CIwGameAudio, CIwGameSound and CIwGameSoundCollection classed to support playback of sound effects and music
  • Added visual layers to sprites and actor system allowing sprites / actors to be depth layered
  • Added support for clipping in CIwGameScene. The scene can now be clipped to a rectangular area of virtual canvas

And here are the general changes / bug fixes:

  • Changed CIwGameFile::Open(const char* path, const char* mode, bool blocking), we now use mode instead of read / write flag
  • Added new CIwGameFile::Seek(int offset, s3eFileSeekOrigin origin) method
  • Replaced CIwGameHttpPostData::AddHeader() with CIwGameHttpPostData::SetHeader() to allow replacement of http headers
  • Added ClearRequests() and CancelRequests() to CIwGameHttpManager() allowing us to clear the request queue and cancel any in progress http requests
  • Removed two bugs from CIwGameInput, one that was stopping button / key presses and another that was preventing keyboard update if touch screen wasn’t present (doh!)
  • Added helper support to CIwGameInput for detecting touched, tapped events, delta change and back / menu buttons
  • Fixed CIwGameScene::removeActor(CIwGameActor* actor) bug (could not remove unnamed actors)
  • Fixed CwGameScene::removeActor(unsigned int name_hash) (would not deallocate pooled actors for re-use)
  • Fixed sprites initial state as invisible bug in CiwGameSprite
  • Moved Width and Height from CIwGameBitmapSprite to CIwGameprite, makes sense that all sprites would need to have a size
  • IwGame has been made into its own standalone project
  • The IwGame Testbed has now been moved to the TestBed folder

Important note, IwGame now exists as a separate project from the test bed. You now have to add IwGame to your project by adding IwGame to the subprojects section of your MKB file. The test bed is also a separate project and is located in the IwGame sub folder named TestBed. Lets take a quick look at some of the changes

Sprite Depth Layers

Its now possible to layer sprites in a sprite manager. The feature is automatic, all you have to do is set the layer of the sprite using setLayer(int layer_number). To set the number of depth layers available to the sprite manager you pass the layer count into the sprite managers Init() method. The default is set to 10 layers. As a scene contains a sprite manager to handle its contained visuals, you can also specify the number of depth layers when you initialise a scene: int Init(int max_collidables = 128, int max_layers = 10); Again, the default is 10 layers. Note that sprites on higher layers will be drawn on top of sprites on lower layers.

Creating PNG’s

You can now create an in-memory PNG file from a  CIwGameImage using CIwGameImage::CreatePNG(): uint8* png_data = image->CreatePNG(png_size); The method currently only supports images in RGB_565 and RGB_888 format. more formats will be added when I implement a new pixel conversion helper class.

CIwGameInput Expansion

I decided to pan CIwGameInput out a little adding new methods to do common tasks such as:

  • bool hasTapped() – Returns true if user tapped the screen
  • bool isTouching() – Returns true if user is currently touching the screen
  • CIwVec2 getTouchedPos() – Returns the position at which the user is touching the screen
  • CIwVec2 getDragDelta() – Returns the number of pixels the user has moved their finger / stylus since the last frame
  • bool isBackPressed() – Returns true if the back button was pressed (nice for Android)
  • bool isMenuPressed() – Returns true if the menu button was pressed (nice for Android)

These should help if you want to get up and running quickly with input.

CIwGameSprite hit testing

CIwGameSprite got a new method called hitTest() that lets you check to see if a point is inside a transformed sprite:

// Generate transformed vertices bool CIwGameSprite::HitTest(int x, int y) { // Generate transformed vertices int w = Width / 2; int h = Height / 2; TransformedV[0].x = -w; TransformedV[1].x = w; TransformedV[2].x = w; TransformedV[3].x = -w; TransformedV[0].y = -h; TransformedV[1].y = -h; TransformedV[2].y = h; TransformedV[3].y = h; for (int t = 0; t < 4; t++) TransformedV[t] = Transform.TransformVec(TransformedV[t]); int i1 = 0; int i2 = 3; for (int t = 0; t < 4; t++) { int x0 = TransformedV[i1].x - TransformedV[i2].x; int y0 = TransformedV[i1].y - TransformedV[i2].y; int x1 = x - TransformedV[i2].x; int y1 = y - TransformedV[i2].y; if ((x1 * y0 - x0 * y1) >= 0) return false; i2 = i1; i1++; } return true; }

This basically transforms the sprite by the sprites current transform and checks to see if a point falls inside the sprite (takes into account rotation and scaling). If you are curious about the method it uses dot products . If the points liles on the outside of any of the lines that make up the sprite then it cannot possibly be inside the polygon.

CIwGameAudio - Let there be Sound

Yes, that’s right IwGame just got audio. I basically built a wrapper on top of IwSound that lets you easily play sound effects located in a resource file as well as music. New classes include:

  • CIwGameAudio – This is the singleton that is responsible for creating, destroying and updating the audio system
  • CIwGameSound – This class represents an instantiates sound effect
  • CIwGameSoundCollection – This class represents a collection of sound effects

if you are using IwGame then you do not need to do anything except load a resource file that contains your sound effects and set the CIwGameAudio’s group like this:

CIwResGroup* AudioGroup = IwGetResManager()->LoadGroup(""); IW_GAME_AUDIO->setGroup(AudioGroup);

You then play sound effects like this: IW_GAME_AUDIO->PlaySound(“explosion”); And music like this: IW_GAME_AUDIO->PlayMusic(“music.mp3″); Couldn’t get much simpler really However, if you want to set up and update the audio system yourself you will need to:

// Initialise audio system CIwGameAudio::Create(); IW_GAME_AUDIO->Init();

Then in your main loop, every frame call:

// Update audio IW_GAME_AUDIO->Update();

And finally on clean up call:

// Shut down audio IW_GAME_AUDIO->Release(); CIwGameAudio::Destroy();

CIwGameScene Scene Clipping

You can now set a rectangular area on a  per scene basis that all actors / sprites within that scene will be clipped to. Parts of sprites that fall outside the clipping region will not be drawn. To set up clipping simply call CIwGameScene::setClippingArea(int x, int y, int w, int h) where x and y are the top / left hand corner of the clipping area whilst w and h are the width and height. Note that clipping coordinates are not specified in pixels but in virtual canvas coordinates. The origin (0,0) is the centre of the screen. So if you virtual canvas is set to 480 x 320 pixels then use x = -240, y = -160, w = 480, h = 320 to clip to the full canvas, although you can just set w to 0 to disable clipping (that’s the default).

Well that’s it for this week, unfortunately I didn’t get the time to do a new Marmalade SDK tutorial but I will try and get that done mid next week. I have some free time coming up soon so I can knock lots of tutorials out. Also have some interesting news coming up soon about an SDK we just finished that pulls ads from inner-active and displays them all fancy :) Compatible with all Marmalade deployment platforms.

Marmalade SDK News – Marmalade SDK v5.1.10 Now Available

Version 5.1.10 of the Marmalade SDK was released by the Marmalade team last night, here are the changes:

- Android: fix application lockup issue on Ice Cream Sandwhich.
- iOS: Fixed image picker extension to support iPad via popovers.
- iOS: Fixed crash when double clicking an edit box in the webview.
- Multiple platforms: Added custom callback for s3eWebView extension.
- Multiple platforms: Added local files loading for s3eWebView extension.
- Android: Fixed s3eVideo to pass on touch events.
- Android: Fixed s3eOSExec to process mailto command properly.
- stdio.h: added implementation of tmpnam and tmpfile
- PlayBook: Fixed issue with gl screen corruption after video played. SysSuspendDuringVideo parameter in the icf file is no longer available, because the only use of this parameter was to workaround screen corruption bug.
- PlayBook: Updated version of underlying blackberry deploy tools.
- LGTV: Allow the –mips mkb option to be used from the command line.
- PlayBook: fix scale of s3eAudio volume controls.

As you can see, some very nice fixes in the mix, especially support for Android 4.0.

Github Here We Come

Well, I finally learnt how to use Github, well just enough to get projects on there (I’m quite lazy really).

I recently found the need to save PNG files from one of our Marmalade SDK based apps so I had to pull in the latest libpng and zlib projects. Anyway, i put the resulting projects onto Github for other Marmalade SDK developers to use. You will find these projects at: and

I also found the need to get the Android media library to scan images that my app was exporting. At present, it would appear that the Android system only rescans media when you insert or turn the SD card back on, so I had to find a way of making the Android system scan my created image files so they are available to my own and other Android applications immediately, which led to the MediaScanner project which is also on Github:

Marmalade SDK Tutorial – Downloading and Using an Image from a Web Based Image File

This tutorial is part of the Marmalade SDK tutorials collection. To see the tutorials index click here

Unfortunately my brother rang me last night and asked me to have a few quick battles with him on World of Warcraft (I just can’t resist PvP) so as it happens, I forgot all about the time and missed publishing my next blog. In case you plaw Wow and you’re wondering I have Level 85 Mage, Warlock, Paladin and Druid!

In our previous tutorial we added the ability to send and receive data to and from a web server. We also created a new file class that deals with local and remote file access, allowing us to download files from the web and use them in our game. We also briefly mentioned that we had updated the CIwGameImage class to support JPEG’s and creation of images from memory based files. In this tutorial we are going to go into that a little more as well as show you how to use CIwGameFile and CIwGameImage to download and display images from the web inside your games and apps. If you just want the code to this tutorial then download it from here.

Imagine a situation whereby you can distribute your basic game without having to carry around any of its content, so no graphics, no audio, no level files etc. Whilst that may not be completely practical for some types of games it is for many others. Imagine your game running completely on dynamic content that lives on a server and you can modify it at any time, Your players will benefit greatly from new fresh content regularly. Well, this is all possible using the Marmalade SDK and IwGame (wow that sounded a bill salesy!)

IwGameImage Changes

Ok the first change we made was to add the ability to create a CIwGameImage image from a JPEG. This feature is unfortunately not supported by Marmalades image classes and missing out on JPEG compression for larger images is a bit of a pain. That said, Marmalade does provide access to LibJPG, allowing you to implement your own JPEG loader. However, seeing as we have already done the work for it, you may as well just rip the code straight out of IwGameImage.cpp.

The main method that takes care of JPEG decompression is CIwGameImage::DecompressJPEG(). Note that this method will create a RGB888 image from the JPEG file, I will add support for conversion to different image pixel formats in a future release.

The next change to CIwGameImage is the ability to create an image from a file that has already been loaded into memory. This is very useful if you want to cache the compressed versions of images in memory:

bool CIwGameImage::Init(const char* name, void* memory_file, int memory_file_size, bool is_jpeg)

name – The name you would like to assign to the file
memory_file – A pointer to the memory based file
memory_file_size – The size of the memory based file
is_jpeg – Determines if the memory based image file is a jpeg

Note that future versions will not rely on is_jpeg and instead, the header data will be checked to determine file type.

How to Create a CIwImage or CIw2DImage from a Memory Based File

Ok, lets take a look how we create an image from a memory based file in the CIwGameImage::Init() method:

bool CIwGameImage::Init(const char* name, void* memory_file, int memory_file_size, bool is_jpeg) { CIwGameFile file; if (file.Open(memory_file, memory_file_size)) { if (is_jpeg) { if (!DecompressJPEG((char*)memory_file, memory_file_size)) return false; } else { CIwImage image; image.ReadFile(file.getFileHandle()); Image2D = Iw2DCreateImage(image); Width = Image2D->GetWidth(); Height = Image2D->GetHeight(); } } State = CIwGameImage_State_Loaded; return true; }

As you can see we create a CIwImage by calling CIwImage::ReadFile() passing in the file handle of the memory based file (to find out how to create a file from a memory buffer take a look at CIwGameFile::Open(void* memory_buffer, int memory_buffer_len)).
To turn the CIwImage to a CIw2DImage we call Iw2DCreateImage() passing in the CIwImage.

How to Create a CIwImage or CIw2DImage from a Pixel Data

In our CIwGameImage::Init() method you will notice that if the image file is a jpeg then we call DecompressJPEG(). If you look towards the end of our DecompressJPEG() method you will notice that we create our CIwImage / CIw2DImage a slightly different way.

Because we are manually loading and decompressing the pixel data within the JPEG image we are left with a memory buffer containing our raw uncompressed images pixels. Marmalade’s usual create from file style image creation methods do not cover this, so instead we create the image ourselves from the pixel data like so:

CIwImage image; image.SetFormat(CIwImage::RGB_888); image.SetWidth(Width); image.SetHeight(Height); image.SetOwnedBuffers((uint8*)data, 0); Image2D = Iw2DCreateImage(image);

Basically we create a CIwImage, set its format and dimensions then tell it where our pixel data is using SetOwnedBuffers(). Like we did in the previous example, to turn the CIwImage into a CIw2DImage we call Iw2DCreateImage() passing in the CIwImage.

Creating an Image from a Web Based Image File

The new demo shows how to download an image file from the web and create an image from it then display that image as a sprite. Lets firstly take a look at how we download and create the image:

// Download an image file from the web CIwGameFile* image_file = new CIwGameFile(); image_file->Open("", false, true); image_file->Close(); // Create an image from the downloaded gif file CIwGameImage* image = new CIwGameImage(); if (image_file->isFileAvailable() && image_file->getError() == CIwGameFile::ErrorNone) image->Init("", image_file->getContent(), image_file->getContentLength(), false); delete image_file; // We are done with the image file so we can delete it

Now we will create a sprite to display our downloaded web image::

// Create a test sprite to display our downloaded gif CIwGameBitmapSprite* test_sprite = new CIwGameBitmapSprite(); test_sprite->setImage(image); test_sprite->setDestSize(image->getWidth(), image->getHeight()); test_sprite->setSrcRect(0, 0, image->getWidth(), image->getHeight()); test_sprite->setPosition(image->getWidth() / 2, image->getHeight() / 2);

And that’s about all there is to it.

Some of you probably already have ideas buzzing around your heads on how to use this cool new system. I’m going to put some more time into the image class this week because I’m not happy about the way loading a jpeg and a web based image is different to the way we load images from a resource collection. I want to change the CIwGameImage class to basically allow you to specify not just a resource name, but also local file names and remote file names.

Well that’s it for this blog, as usual you can download the latest code from here

Happy coding and don’t eat too much tuna!

Marmalade SDK Tutorial – Sending and Retrieving Data From the Web

This tutorial is part of the Marmalade SDK tutorials collection. To see the tutorials index click here

In our previous tutorial we tidied up the IwGame engine and properly separated our engine calls away from our game code. We ended up with a nice system that allows us to begin building a game. This week we are going on a slight diversion because I have recently been working on sending and retrieving data from the web. I think that its important for any game engine to be able to pull in data from outside itself as it allows us to create games that are easily upgradable without having to put a new version of the game through the app store approval process. Its also cool to be able to send data to the web as it allows us to do cool stuff such as communicating with web services, accessing functionality that could add a lot of value to our games or apps. If you just want the code to this tutorial then you can download it from here.

I am actually going to do a couple of tutorials today that cover this subject, the first is covering the basics of interfacing with Marmalade’s IwHttp module that allows us to send GET and POST requests to a web server.

Oh, the reason for this diversion is because over the last few days I have been working to produce a cross platform ad API that allows Marmalade SDK developers to use Inner-active’s ads on any platform by writing a system that interfaces with Inner-active’s ad server and pulling back text and image based ads. Thus far I have the system returning and displaying ads. I just need to write the display system into its own view control and get the click system working. once that’s finished, it will become part of the IwGame game engine. I will blog about that when its finished. If you are interested in beta testing it then please get in touch.

IwHttp – Marmalade’s API for Performing HTTP Requests

IwHttp is the base module used by the Marmalade SDK that allows you to send and receive data from a web server over http and https. IwHttp allows you to perform both GET and POST operations. We have gone one step further however and simplified and extended its usefulness creating a new class called CIwGameHttpManager. If you would like to see how to use the IwHttp class in the manager then take a look at IwGameHttp.cpp and iwGameHttp.h.

CIwGameHttpManager – A Queued Http Request Manager

CIwGameHttpManager is a singleton class that allows you to throw GET and POST requests to it. The manager will queue the requests and them one by one until no requests are left in the queue. Note that the next request is only sent after the first returns. I’m not going to go into the internals of CIwGameHttpManager because the it and its associated classes constitute a lot of code. I will however explain how to use them.

Firstly you need to instantiate and initialise the CIwGameHttpManager singleton using:

// Initialise the http manager CIwGameHttpManager::Create(); IW_GAME_HTTP_MANAGER->Init();

And before you exit your game / app clean-up the manager using:

// Clean up http manager IW_GAME_HTTP_MANAGER->Release(); CIwGameHttpManager::Destroy();

In your main loop, you will also need to call the manager update so that it can do its stuff using:

// Update http manager IW_GAME_HTTP_MANAGER->Update();

Making a GET Request – Getting Data From a Server

To make a GET request we need to create a persistent instance of CIwGameHttpRequest and set it up, like this:

CIwGameHttpRequest* Request = new CIwGameHttpRequest(); Request->setGET(); Request->setURI(“”); Request->setContentAvailableCallback(&DataRetrievedCallback, (void*)this); IW_GAME_HTTP_MANAGER->AddRequest(Request);

Note that we have set a callback function that will be called when our data is available to use. Here is an example callback:

int32 DataRetrievedCallback(void* caller, void* data) { CIwGameHttpRequest* request = (CIwGameHttpRequest*)caller; if (request->getProcessed()) // Check to see if our request was processed by the http manager { // To get to our data we call request->getContent(); // To get to our data length we call request->getContentLength(); IW_GAME_HTTP_MANAGER->RemoveRequest(request); // Remove request from http manager queue } return 0; }

As you can see its ultra simple to retrieve data from the web.

Making a POST Request – Sending Data to a Server

To make a POST request we need to create a persistent instance of CIwGameHttpRequest and set it up, like this:

CIwGameHttpRequest* Request = new CIwGameHttpRequest();; Request->setPOST(); Request->setURI(“ ”); Request->setContentAvailableCallback(&DataRetrievedCallback, (void*)this);

Note that up to this point the setup is very similar except we specify setPOST() instead of setGET().

However we want to send some data to the server we have to, so we have to put it somewhere, this is done using the posts body llke this:

char length[32]; const char* body = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap12:Envelope xmlns:xsi=\"\" xmlns:xsd=\"\" xmlns:soap12=\"\"><soap12:Body><HelloWorld xmlns=\"\" /></soap12:Body></soap12:Envelope>"; Request->AddHeader("Content-Type", "application/soap+xml; charset=utf-8"); sprintf(length, "%d", strlen(body)); Request->AddHeader("Content-Length", length); Request->setBody(body);

Then we add the request to the http manager


In the above example the body string holds an XML based SOAP request that we are sending to my test ASP.NET web service. In this case when the server gets this SOAP request it will call a method called HelloWorld which returns some data to us.

Note that when we send data to a web server we need to send some details about that data such as its type and length. In the above example we accomplish this by adding headers to our POST request.

When the POST has been made the web server will return a response which can be picked up in our callback function.

Ok, that all looks quite straight forward, but we can make things much simpler if we just want to download files from our web server, in steps the IwGameFile class

CIwGameFile – File Class That Handles Loading of Local and External files

Yes, we decided to put together a quick file class that handles loading of files from local storage and from an external web server. All you have to do is pass the URL and an optional callback (my kindness knows no bounds!)

Again, I don’t want to go into the intricate details about the implementation, instead I am opting for the telling you how to use it approach. IwGame is starting to become a small beast and I would rather spend the time improving it.

CIwGameFile is a basic general purpose file system class that allows you to open, create, read and write files. In addition it allows you to open a file located somewhere on the web using the http protocol.

Heres an example on how to open a local file, read some data and close the file:

CIwGameFile* file = new CIwGameFile(); file->Open("monkey_magic.txt”); file->Read(my_buffer, 1024); file->Close();

And here’s an example showing how to open a read the same file located on the web:

CIwGameFile* file = new CIwGameFile(); file->Open("”, false, true); file->Read(my_buffer, 1024); file->Close();

Note that the above method blocks the main loop and does essentially stops all processing of the game until the file is returned. I would instead recommend using a none blocking method like this:

CIwGameFile* file = new CIwGameFile(); file->Open("”); file->setFileAvailableCallback(FileLoadedCallback);

And our callback would look something like this:

int32 FileLoadedCallback(void* caller, void* data) { CIwGameFile* file = (CIwGameFile*)caller; file->Read(my_buffer, 1024); file->Close(); return 0; }

IwGameFile still requires a few upgrades to complete its functionality. Here are a few planned updates:

  • None blocking local file I/O
  • Timeout check needs adding to blocking http downloads
  • Add methods for reading / writing common types

Other additions to IwGame

You will notice that a few other bits and bobs have appeared in the game engine that i have not mentioned thus far. These include:

  • IwGameString – This is a basic string class that supports string builder type string building to cut down on memory allocations as well as stream type searching and some other utility stuff
  • IwGameImage – This class has been upgraded to support JPEG as well as creation of images from memory based files. Will cover this in more detail in my next blog

Well that’s it for this blog, as usual you can download the latest code from here

See you soon, with another (smaller thankfully) article.

Marmalade SDK Tutorial – Turning IwGame into a Real Game Engine

This tutorial is part of the Marmalade SDK tutorials collection. To see the tutorials index click here

In our previous tutorial we created created an actor, scene and camera system to automate the handling of game objects for us as well as allow us to create different types of actors derived from a common actor base. This week we are going to take the previous IwGame code base and turn it into a proper game engine. If you just want the code to this tutorial then download it from here.

Cleaning up the Mess

If you take a look at last weeks Main.cpp, you may agree that it just looks static, messy and not very readable. This week we are going to clean up our act and turn IwGame into a real usable game engine. Lets take a quick look at our new Main.cpp to see how much tidying up has been done:

int main() { // Init Game Game::Create(); GAME->Init(); // Main Game Loop while (!s3eDeviceCheckQuitRequest()) { // Update the game if (!GAME->Update()) break; // Check for back button quit if (IW_GAME_INPUT->isKeyDown(s3eKeyAbsBSK)) return false; // Draw the scene GAME->Draw(); } GAME->Release(); Game::Destroy(); return 0; }

Wow, ok, where’s everything gone? our game has been whittled down to initialisation, update, draw and clean-up. Well not quite, the code has gone somewhere, some of it has been integrated into the IwGame engine whilst the game specific code has been moved into a proper game class. Remember last week, we created scenes to manage actors? Well this week we have created a CIwGame class to manage scenes.

IwGame Class for Managing our Game

if you check out the engine code you will notice some new files:


Lets take a quick look at the CIwGame class:

class CIwGame { public: // Public access for scene iteration typedef CIwList::iterator _Iterator; _Iterator begin() { return Scenes.begin(); } _Iterator end() { return Scenes.end(); } protected: //// Properties CIwGameScene* CurrentScene; // Scene that has current input focus CIwGameScene* NextScene; // Scene that we wish to switch focus to CIwList<CIwGameScene*> Scenes; // A collection of game scenes public: void addScene(CIwGameScene *scene); void removeScene(CIwGameScene* scene); void removeScene(unsigned int name_hash); CIwGameScene* findScene(unsigned int name_hash); CIwGameScene* findScene(const char* name); CIwGameScene* getScene(int index); void clearScenes(); void changeScene(CIwGameScene *new_scene); bool changeScene(unsigned int name_hash); //// Properties end protected: uint64 LastFrameTime; // The time at which the last frame ended public: virtual void Init(); virtual void Release(); virtual bool Update(); virtual void Draw(); virtual void Save() {} virtual void Load() {} private: public: void SetBackgroundColour(uint8 r, uint8 g, uint8 b, uint8 a); };

As you can see its basically a class that allows us to add / remove and change scenes. It also provides initialisation, release, update, drawing and save / load functionality.

These methods represent the most basic functionality that I believe any game would need. If you take a look at IwGame.cpp you will notice that there is quite a lot of code in there. Lets take a quick look at what CIwGame::Init() does:

CIwGame’s Init() method carries out some basic Marmalade SDK and game specific initialisation:

void IwGame::Init() { CurrentScene = NULL; NextScene = NULL; // Initialise Marmalade SDK graphics system and Iw2D module IwGxInit(); Iw2DInit(); // Initialise the input system CIwGameInput::Create(); IW_GAME_INPUT->Init(); // Init IwSound IwSoundInit(); // Initialise Marmalade SDK resource manager IwResManagerInit(); #ifdef IW_BUILD_RESOURCES // Tell resource system how to convert WAV files IwGetResManager()->AddHandler(new CIwResHandlerWAV); #endif // Set default background colour SetBackgroundColour(0, 0, 0, 0); // Get initial time stamp LastFrameTime = s3eTimerGetMs(); }

You will notice that much of this code was present in our previous tutorials Main.cpp initialisation code. We have moved it into our CIwGame base so that we have some basic initialisation code that allows us to get our games up and running quickly.

Similarly our CIwGame::Release() method:

void IwGame::Release() { // Clean up scenes for (_Iterator it = Scenes.begin(); it != Scenes.end(); ++it) delete *it; Scenes.clear(); // Shut down the input system IW_GAME_INPUT->Release(); CIwGameInput::Destroy(); // Shut down the resource manager IwResManagerTerminate(); // Shutdown IwSound IwSoundTerminate(); // Shut down Marmalade graphics system and the Iw2D module Iw2DTerminate(); IwGxTerminate(); }

The only thing new here is the recursive release of all of the attached scenes

The last method I am going to look at is our CIwGame::Update() method

bool IwGame::Update() { // Calculate how long the last game frame took (capped at 60 and 10 fps) - We use this to scale all of our transient variables that rely // upon time so that everything movess at the same rate regardless of our devices frame rate float dt = (float)(s3eTimerGetMs() - LastFrameTime) / 16.67f; if (dt < 1.0) dt = 1.0f; if (dt > 6.0f) dt = 6.0f; LastFrameTime = s3eTimerGetMs(); // Clear the screen IwGxClear(IW_GX_COLOUR_BUFFER_F | IW_GX_DEPTH_BUFFER_F); // Update pointer system IW_GAME_INPUT->Update(); // Update Iw Sound Manager IwGetSoundManager()->Update(); // Check for scene change if (NextScene != CurrentScene) { // Notify scenes that there is a change of circumstances if (CurrentScene != NextScene) { if (CurrentScene != NULL) { CurrentScene->NotifyLostFocus(NextScene); if (CurrentScene->getAllowSuspend()) CurrentScene->NotifySuspending(NextScene); } if (NextScene != NULL) { NextScene->NotifyGainedFocus(CurrentScene); if (NextScene->getAllowSuspend()) NextScene->NotifyResuming(CurrentScene); } CurrentScene = NextScene; } } // Update all scenes that are not suspended for (_Iterator it = Scenes.begin(); it != Scenes.end(); ++it) { if (CurrentScene == *it) { (*it)->Update(dt); } else { if (!(*it)->getAllowSuspend()) { (*it)->Update(dt); } } } return true; }

Update() basically does most of what we were doing in our previous tutorials main loop, except that we use the concept of a “current scene”. Because scenes can potentially be overlaid over one another and we do not want to always be processing all scenes within our game, we use the concept of a current scene which has the focus of the player.

Now that we have the ability to change scenes, we ideally need a mechanism for notifying the other scenes that they have been switched to or switched away from, allowing our scenes to carry out processing specific to handle such events.

Another important addition to our game update loop is the measurement of time. At the start of Update() we calculate how much time has passed since Update() was last called. We can use this value to scale all of our transient variables (animations, movement etc..) within our game to ensure that they move in a consistent manner regardless of variations in frame rate. The variable dt holds our scaling factor, which is how much we need scale our transient variables by to ensure that they remain in step with our frame rate. If we did not handle time within our game then animations and movement / spinning etc.. would slow down when our games frame rate drops and increase when our frame rate increases.

Building Our Own Game Class

The idea of the CIwGame class is to provide the most basic functionality required to initialise, clean-up and update / draw our game. In order to create a real game we should derive our own class from CIwGame and add our own game specific code, not forgetting to call the CIwGame base methods so we do not miss out on our already implemented functionality.

In this case we create a class called Game.cpp which is a singleton class that derives from CIwGame and implements Init(), Release(), Update() and Draw() methods. if you take a quick look at Game.cpp you will notice that the game specific code from our old Main.cpp has been moved here.

We also go a step further and remove our dependency on storing references to scenes, images and animations etc, instead opting for finding them within their respective managers as and when needed. For example:

In Game::Update() we have:

CIwGameScene* scene = findScene("GameScene"); if (scene != NULL) { // Get tapped position in our virtual screen space CIwFVec2 pos = scene->ScreenToVirtual(IW_GAME_INPUT->getTouch(0)->x, IW_GAME_INPUT->getTouch(0)->y); // Find our sprite atlas CIwGameImage* image = scene->getImageManager()->findImage("sprites"); // Find our manic face animation frames CIwGameAnimImageFrame* anim = scene->getAnimFrameManager()->getImageFrames(0); // Create 10 player actors for (int t = 0; t < 10; t++) { ActorPlayer::Create(pos.x, pos.y, scene, image, anim); } }

Notice how we now search for our game scene, instead of accessing it via the local game_scene variable. We also do the same with image and anim.

This brings me to another new addition to the CIwGame engine.

CIwGameImage and CIwGameImageManager – Managing Images

After I had finished factoring out most of the code from Main.cpp I was left with what to do about the sprite atlas images that my game is going to use. I didn’t really want to be storing pointers to images all over the place that may or may not still exist, this can lead to some nasty and hard to find bugs. instead I opted to create a class that will manage all of the images that my scene allocates. This way we have them all in one central location and the manager can manage their lifetimes for us.

In addition, I thought that I would extend the CIw2DImage class a little by wrapping it up inside the CIwGameImage class, allowing us to add other cool functionality such as on-demand load and eventually streaming from an external web server (future blog will cover this).

So you will find that all instances of CIw2DImage throughout the engine have been replaced with the more manageable CIwGameImage class.
An important thing to note about CIwGameImage based images is that they rely on a CIwResGroup resource group, this is to allow them to be loaded on-demand.

To create and add an image to the game engine its a simple case of:

CIwResGroup* Level1Group = IwGetResManager()->GetGroupNamed("Level1"); game_scene->getImageManager()->addImage("sprites", Level1Group);

This creates our image based on its resource name and group and adds it to our scenes image manager. Note that the underlying CIw2DImage is not yet created. This gets created when you first call CIwGameImage::getImage2D() (on-demand). You can however force the loading / creation of the underlying CIw2DImage by passing true to addImage():

game_scene->getImageManager()->addImage(“sprites”, Level1Group, true); or by calling the Load() method on the CIwGameImage.

Well that brings us to the end of this tutorial, I’m very rushed this week so I will probably not get the time to create additional tutorials until next week. I did want to create an actual game this week using the engine, but I thought that with the engine tidy up is probably best to do that next week so readers don’t get lost. I may be able to fit a short blog update in early next week covering the wrapping up of Marmalades sample audio engine into IwGame.

If you want the source code that accompanies this tutorial then you can download it from here.