The Ultimate Cocos2D Project: Startup

On March 12, 2011, in Kobold2D, by Steffen Itterheim

The Ultimate Cocos2D Project is: Kobold2D!

Put simply: Kobold2D is designed to make Cocos2D developers more productive.

Original Post

Time for a weekly update. This time about startup code and configuration. One of the things that I frequently encountered following the development of Cocos2D and working with it, is how any change to the startup code - the main function, the App delegate and the root ViewController - caused issues and headscratching among developers.

I decided it doesn’t need to be this way.

The main() function

A code snippets speaks more than words:

int main(int argc, char *argv[])
{
    return KKMain(argc, argv, NULL);
}

That’s right, all of the startup code is now part of the project’s source code. You can still do whatever you need to do before and after the call to KKMain (probably nothing, except maybe anti-piracy code). And the third parameter (NULL) to KKMain is reserved for future use, to pass in any configuration parameters if the need arises.

Let’s see what KKMain does:

int KKMain(int argc, char* argv[], SMainParameters* userParameters)
{
    SMainParameters parameters;
    initMainParameters(&parameters, userParameters);
   
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
#else
    // Mac OS X specific startup code
    [MacGLView load_];
#endif

    // This makes the CCDirector class known to wax:
    [CCDirector class];
    // wax setup is sufficient for all intents and purposes
    wax_setup();
   
    [KKLua doString:kLuaInitScript];
    [KKLua doString:kLuaInitScriptPlatformSpecific];
    [KKLua doString:kLuaInitScriptForWax];
   
    // This loads the config.lua file
    [KKConfig loadConfigLua];
   
    // run the app with the provided general-purpose AppDelegate which handles a lot of tedious stuff for you
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
    int retVal = UIApplicationMain(argc, argv, nil, parameters.appDelegateClassName);
    [pool release];
#else
    int retVal = NSApplicationMain(argc, (const char**)argv);
#endif
   
    return retVal;
}

The usual, really, except that it also initializes Wax and thus Lua for your App as well as providing the necessary startup code for both supported platforms: iOS and Mac OS X. The KKLua class is an Objective-C wrapper around the most imortant Lua functions, most notably it has the doString and doFile methods which allow you to run any Lua code or file containing Lua code.

KKConfig is a class that loads a Lua table and stores it in a NSDictionary for fast access to Lua parameters at runtime. I’ll discuss it in detail another time. The main purpose of KKConfig is to loadConfigLua, which loads the config.lua script returning a table containing startup parameters and making those parameters available to Objective-C.

Config.lua in detail

Let’s have a quick look at an excerpt of the config.lua file. It contains all of the startup parameters a developer using Cocos2D would ever want to tweak in a conveniently editable Lua script:

local config =
{
    KKStartupConfig =
    {
        -- load first scene from a class with this name, or from a Lua script with this name with .lua appended
        FirstSceneClassName = "GameScene",

        -- set the director type, and the fallback in case the first isn't available
        DirectorType = DirectorType.DisplayLink,
        DirectorTypeFallback = DirectorType.NSTimer,

        MaxFrameRate = 60,
        DisplayFPS = YES,
        DisplayFPSInAdHocBuilds = NO,

        -- Render settings
        DefaultTexturePixelFormat = TexturePixelFormat.RGB565,
        GLViewColorFormat = GLViewColorFormat.RGB565,
        GLViewDepthFormat = GLViewDepthFormat.DepthNone,
        GLViewPreserveBackBuffer = NO,
        GLViewMultiSampling = NO,
        GLViewNumberOfSamples = 0,

        Enable2DProjection = NO,
        EnableRetinaDisplaySupport = YES,

        -- ... and many more settings!
    },
}

return config

Since you don’t want to guess what those settings mean, I’ve documented them for you:

Config.lua Parameter Documentation (PDF)

This should also illustrate the kind of documentation I’m striving for. Documentation will be available online. It’s created in a Confluence Wiki with the help of ScreenSteps for more visual, step-by-step documentation.

App Delegate & Root ViewController

You may be wondering how you can modify and tweak the App Delegate and Root ViewController if they’re both part of the distribution, rather than copied into each project? That’s actually very simple: both are regular Objective-C classes, so they can be subclassed and methods overridden as needed.

Both KKAppDelegate and KKRootViewController provide a default implementation which you can tweak with the config.lua parameters. If that shouldn’t be enough, for example if you have to plug in some 3rd party code into the App Delegate, each project will have a subclass of KKAppDelegate and KKRootViewController in which you can override any of the UIApplicationDelegate and UIViewController protocol methods. Usually you would first call the super implementation, unless you want to entirely replace the default behavior.

The KKAppDelegate method calls one specific method called initializationComplete at the end of the delegate method applicationDidFinishLaunching. This allows you to run any custom code right before the first scene is shown. You can use that to call the CCDirector runWithScene method manually, in case you have more than one scene which might be run as first scene depending on certain conditions.

If you set the FirstSceneClassName config.lua setting, the project will first check if there’s a classname.lua file. If so, it will run this Lua script, assuming it contains the implementation of the first scene (more on that some other time). Otherwise it checks if there’s an existing Objective-C class derived from CCScene with that name, and if so allocates and initializes this scene and calls runWithScene for you.

In essence

From your point of view, the execution of the App now starts with the first scene, before that there’s no code that you’ll have to concern yourself with. Any startup configuration tweaks that you need to do can be done comfortably via the config.lua file, and the only setting you’ll need to change is the name of the first scene’s class name or Lua script. In addition you’ll get access to some features out of the box, for example adding iAd banners is now a simple on/off switch.

Moreover, any time there’s a change in Cocos2D’s startup code, or the startup code in any other library (most notably Wax), I can just make those changes for you and release a new version. This isn’t something you need to concern yourself with anymore, and makes upgrading existing projects to new versions of Cocos2D and other libraries even easier.

Article Collection

On May 5, 2010, in , by Steffen Itterheim

Try out Kobold2D!

You may be interested to hear about the Kobold2D game engine. Kobold2D is designed to make Cocos2D developers more productive.

cocos2d for starters

The cocos2d homepage - this should be obvious but since most people land on the google source code repository page for cocos2d iPhone instead of the real homepage www.cocos2d-iphone.org i wanted to post it here. Usually the most noteworthy threads from the forum as well as important blog posts by others are posted on the blog, and of course any new releases and updates to cocos2d.

cocos2d iPhone documentation - a post on the official website explains where you can find what kind of documentation.

Things i wish i knew when i started with cocos2d - Troubleshooting, Tips & Tricks for everyone

Ray Wenderlich (formerly Mythic Entertainment) posted a great tutorial on how to make a simple iPhone game with cocos2d. Take a look around at his website as he keeps writing new tutorialistic articles such as creating buttons in cocos2d and an intro to the box2d physics engine which is also part of cocos2d.

Introduction to 2D game programming with cocos2d iPhone

The cocos2d iPhone programming guide in the cocos2d Wiki.

Introduction to cocos2d iPhone visual effects (aka Visual FX).

Apple’s excellent Objective-C Programming Language reference (PDF)

Open GL ES 1.1 reference - only needed if you intend to do OpenGL programming - you don’t need to know about OpenGL if you’re using cocos2d but it may come in handy sometimes.

As for books, i can NOT recommend iPhone Games Projects by Apress. Repeat: not recommended! It’s a badly written collection of blog posts about the kind of games most game developers would not want to make (chess etc). It does not contain particularly good or reusable examples of code and the choice of projects is questionable to say the least. It has generally very little value for a cocos2d iPhone developer as all examples are either written in Cocoa Touch or plain OpenGL.

cocos2d, Cocoa and Objective-C code fragments

Have a look at my proposed CCDirector drawScene method which redraws the screen anytime you may need to.

Blog Post: efficiently reusing Default.png for landscape mode - Note: Ricardo has since integrated this in Sapus Tongue source code.

Integrating other APIs into a cocos2d application or game

First of all, here’s a tutorial on how to integrate the cocos2d API reference into Xcode.

Integrating Facebook Connect with cocos2d. See also the forum post for the user comments. In addition watch this video about adding Facebook Connect to your Xcode project since the necessary steps aren’t covered in the integration tutorial. And once again, Stackoverflow strikes with an excellent link collection for Facebook Connect iPhone developers.

Integrating AdMob with cocos2d iPhone Applications

Integrating OpenFeint with cocos2d iPhone Applications

Integrating Agon Online into cocos2d iPhone

Combining SIO2 with cocos2d, with source code

SpaceManager - an Objective-C wrapper for Chipmunk

There are already ports for cocos2d iPhone, one focuses to port cocos2d iPhone to Mono .NET using C# and the other cocos2d port is Java-based for Android development.

Generally useful tools & knowledge for cocos2d iPhone developers

How to handle device orientation and how to implement autorotation for a cocos2d app or game.

A list of editors useful for cocos2d development is described on the cocos2d’s homepage blog in two parts: part one and part two. It includes tile editors, Texture Atlas and Bitmap Font generators.

Ernesto’s pseudo-code on Pixel-Perfect collisions. It was hard to find and others seem to have problems finding it as well yet people already know it as “Ernesto’s post”, so it deserves a mention here. In this forum post is one implementation of pixel-perfect collision code and here is another implementation of pixel-perfect collisions. Finally we learn about the intricacies of endianness in pixel data, meaning how pixel data changes depending on the platform (iPhone vs Mac).

Zwoptex Texture Atlas tool for use with cocos2d iPhone (and probably others)

Finding memory leaks using the CLANG static analyzer. Don’t leak memory. That’s terrible. Read how you can run a program that tells you with impressive accuracy where there are memory leaks in your code, at least potential ones. Make sure you also read the comments further down since they contain more command line samples that fix some issues for iPhone OS 3.x among other things.

How to obtain the iPhone crashlogs from your beta-testers and costumers. And then there’s Apple’s manual on how to debug crashdumps. In short: always compile both debug and release builds at the same time, then keep both dSYM files and make sure you can later identify to which version and build they belong to. It’s easiest to use source control here and simply flag or label the version you used to create distributed Ad-Hoc or App Store versions with.

iPhone Apps can be opened via URLs that also allow passing what some might call “command line arguments”. Here are a few websites that document those URLs for various apps: URL schemes for various iPhone Apps, then there’s the handleOpenURL: website and finally AppLookup.com.

Specifically for linking to the App Store you will find Apple’s iTunes Link Maker useful. On Stackoverflow you can learn how to create links to your App that you can send via email. And finally, this Ars Technica article covers all the finer details of creating an App Store link that works for the iPhone’s App Store, including opening the App Store app with a search term - which is the only way to show all the apps of a particular company or developer on the iPhone’s App Store.

8 confusing Objective-C Warnings and Errors explains some of the more confusing things Xcode (actually: GCC) throws at you and leaves you wondering. After reading this article you’ll know what you’re dealing with the next time it comes up.

Provisioning Profiles Gotchas - we all have one of these issues sooner or later (or frequently).

App Store Rejection reasons - be sure to go through this checklist before submitting your App to iTunes Connect to avoid your App being rejected due to some commonly made mistake or oversight.

How to build an IPA file from Xcode shows you how to setup a build target in Xcode that will output an IPA file. Those are very helpful for Ad-Hoc distribution of your App, as IPA files do not get as easily mangled (leading to errors such as “resources have been modified”), especially on Windows machines. It also makes installing Ad-Hoc builds easier since a simple double-click suffices to open iTunes and install the App. Plus it’ll have a proper icon in iTunes’ Application folder.

How to properly set your App’s iTunes Release Date and the things to watch out for. If you’re about to release an App you must read this otherwise you risk your App not being listed on the “What’s New” list.

How to calculate the App Store size of your iPhone App before approval. It’s not magic nor random, it can actually be calculated to within a rather small margin of error. The good thing is, the error will be that the calculation gives you the maximum size your App could possibly have on the App Store. With experience you’ll learn how good your Apps compress after approval, and that depends highly on the game engine used. Unity is hit especially hard by this, typically Unity apps get added another 4-5 MB to the zipped App you’re uploading, in some cases even more.

How to set and change the list of supported languages in iTunes: according to this post on Stackoverflow all you need is one localized file. What i do is, under Resources, i add a new .strings File and leave it empty. Then right-click, choose Get Info and on the General tab click “Make File Localizable”. Then go back to the General tab and click “Add Localization” until you’ve added all languages your App supports. Note that you do not have to reference or otherwise use that file in your code - it just needs to be there. If you look into your App Bundle (right click: Show Package Contents) you’ll notice that new folders like English.lproj, German.lproj etc. exist. Those are scanned by iTunes to create the supported languages list.

How to change an App Icon’s name depending on the iPhone’s language setting. While we’re at it you can also learn how to figure out more quickly if a specific name still fits under the App Icon without being shortened.

My iPhone & iPad Design Templates for OpenOffice Draw

Open Office Draw Templates for designing iPhone & iPad games. They offer you a canvas to create the visual elements of your game and pitch your ideas. I use them to pitch my ideas or create concept drawings of iPhone/iPad apps and games.

You can either use Open Office Draw to draw on them, or just print out the images and draw on it. Both versions have at least one image where the screen background is white, so you can easily draw on it. The iPad version also has a vector graphics representation, so if you worry too much about the completely dark space for printing - turn it into light gray or even transparent with just the border lines shown.

Download the iPhone Design Template for OpenOffice Draw.

Download the iPad Design Template for OpenOffice Draw. For the iPad i took extra-care to scale the images to close to original size, and i also recreated the iPad as vector graphics in almost exact original size.

Tutorial: cocos2d Xcode Proj.

On April 23, 2010, in , by Steffen Itterheim

This Tutorial is superceded by Kobold2D

This tutorial was designed for Xcode 3 and most of the steps do not apply to Xcode 4.

All the experiences described in this tutorial have been utilized to help create the Kobold2D game engine.

Kobold2D is designed to make Cocos2D developers more productive. If you use Kobold2D you can bypass this tutorial and instead rely on a working solution with many improvements not described in this tutorial.

Search my cocos2d for iPhone FAQs & Tutorials

Please note that the blog search in the upper right corner doesn’t search my FAQs and Tutorials.
 

  • Note: please do not share direct download links to PDF files, the download links expire after a couple minutes!

Download Manual PDF

Introduction

Getting the latest cocos2d version from github

Creating a future-proof Xcode Project Template

Issues with physics: integrating Box2d and Chipmunk

You want to see the results?

Visit www.learn-cocos2d.com for more!

Tagged with: