qq_tracker_code_advanced_default

I would like to start this post by introducing some new software that will make the lives of developers much easier. When I first starting developing my new game Elementals HD for the iPhone I had no idea that loading individual PNG’s as textures for sprites would result in a final memory consumption of over 130MB on load. That’s really bad considering that the newest iPod Touch only comes with 256MB of RAM which to this day I will never understand. Apple added the hi-res display to the iPod Touch which means that images will use twice the amount of memory that they were using before. With the iPhone 4 they did it right and doubled up on the memory which helps a lot with the HD images taking up twice the amount of memory as the SD ones do. So anyway, back to the topic.

I needed some way to minimize the amount of memory utilization, so I started reading about sprite sheets and image sizes in the power of 2, etc… I found a neat utility called Zwoptex to create sprite sheets of all my images. This ended up helping me quite a bit, not only did it reduce the amount of disk space but it also reduced the amount of memory being used. At this time I was able to get my memory utilization down to about 90MB. To me, this is still quite high and I was not satisfied with the result, so I continued to look for a solution. I started reading about PVR’s and how fast they load and then I read about compressed PVR’s. Next, I needed to figure out how to use these PVR’s to lower my memory utilization and speed up my loading times.

I found an awesome app called TexturePacker which runs natively on Mac OS X. TexturePacker is a very similar tool to Zwoptex in that it creates sprite sheets from images but is very different and far more advanced when it comes to optimization. Long story short, I was able to use TexturePacker to create *.pvr.ccz sprite sheets for HD and SD images and reduced my memory utilization down to 50MB… WOW.. Now that is a lot better then the 130MB I started with. What I’d like to do now is present a tutorial on the usage of TexturePacker and walk you through step-by-step to get HD images loaded into TexturePacker, optimize them, publish them and finally write the code in Xcode to make them work. I’ll also share some best practices for memory management at the end of the tutorial.

Software you will need:

  1. Texture Packer

After you are done downloading the software above, you can follow the below steps to install TexturePacker and start up the Demo Project

Install TexturePacker:

If you haven’t downloaded Texture Packer yet, you can download it here. After the download has completed you can double click on the DMG file so that it mounts a disk image. The disk image contains the Texture Packer installer package. The screen should look like the screen shot below:

Texture Packer - Disk Image Contents

Double-Click the TexturePacker Package File and you will see the install screen, like the one below:

Texture Packer - Install

Texture Packet - Install

From there just follow all of the prompts until Texture Packer has completed the install process. You will find Texture Packer within your applications folder. Go ahead and launch Texture Packer. You will get the following screen:

Texture Packer Essential vs Texture Packer Pro

Texture Packer Essential vs Texture Packer Pro

Unless you’ve purchased a license you should choose Essential. The main difference is that with the Essential (Free Version) anything you export will be exported in red. In the next section I will give a brief overview of Texture Packer and the features we will use the most.

Note: All typos within the installer have been fixed since version 2.1.3

Importing Sprites:

Texture Packer - Import Sprites

Texture Packer - Import Sprites

Referring to the screen shot above I used the Import Sprites button to import a selection of sprites to work with. Once I imported the sprites, Texture Packer automatically adjusts the sprite sheet size to fit the 3 sprites I imported. If you look to the bottom right of the application on the status bar, Texture Packer displays the size of the resulting sprite sheet and the amount of memory it will consume. In this case with the above images, my sprite sheet will be 128×128 and consume 64 kB of memory. 64kB of memory isn’t a whole lot but lets go ahead and do some optimization anyway and see if we can cut down on memory usage.

On the left hand side of the app you will see the Texture Settings menu that is divided into 3 categories; Geometry, Layout and Output. Scroll down to Output and find the Image format setting. The default for this setting is RGBA8888 which results in a sprite sheet with the highest quality and the most memory usage. Change this setting to RGBA4444 and watch what happens to the memory usage. 32kB is what the memory usage is now… WOW we just cut memory usage in half but at the cost of quality. Why? The reduced quality comes from taking a 32-bit image and converting it to a 16-bit image. Make sense?

Ok, lets fix the quality to make it look a little better. Two fields down, you’ll see Dithering. The default Dithering setting is NearestNeighbour which makes for some ugly gradients when going from 32 to 16-bit. Go ahead and change this to FloydSteinberg+Alpha and watch in amazement as your gradients start to look like gradients again. You may notice that this results in your sprites looking a bit noisy but remember, we are working with hi-res images here and every 4 pixels will equal 1 point so the image should look pretty sharp, at least that’s what I’ve experienced.

Let’s take a minute to go over the Output Category that’s in the Texture Settings Menu:

  • Data Format – This setting is for defining in what format the sprite sheet data should be processed in. We need to select cocos2d for this. What this will do is generate a plist file that we will load into frame cache a little later.
  • Data File – This will be the output location and name of the data file (plist file for cocos2d) You don’t need to set this as it will automatically be filled when you set the Texture File
  • Texture Subpath – Not sure what this is for, I’ve never used it
  • Trim sprite names – Leave this unchecked, I’m not sure what this is used for
  • Texture Format – Here you will choose the output format of your sprite sheet. You can choose any format you like, they are all compatible with cocos2d but I recommend Compressed PVR (.pvr.ccz). This will give you the most compression and pretty quick load times.
  • Image format - This is where we will get most of our optimization from. For most of the sprite sheets we create we should choose RGBA4444 as it will give you the best result. RGBA4444 is used for sprites with transparency’s. If you have a sprite that doesn’t use any transparency you should use RGB565. If you have a sprite sheet that absolutely needs to have the highest quality then use RGBA8888 but we aware that this will result in high memory use, especially if your sprite sheet is 2048 x 2048.
  • Texture File – This is where you would set the name of your texture file. Click on the browse button to select your location and then give a name. If you are working with hi-res images be sure to add -hd at the end of the filename, you’ll see why, later.
  • Dithering – I covered this earlier but just to re-cap, if you are using RGBA4444 you should use FloydSteinberg+Alpha and if you are using RGB565 then use FloydSteinberg
  • Premultiply alpha – This is used to limit the amount of artifacts and possible thin black borders around your sprites when sprite anti aliasing is on. Also semi-transparent pixels might get too dark without this setting. If this is enabled be sure to add the following to your code:
    [CCTexture hasPremultipliedAlpha:YES]
  • AutoSD – This is one of my favorite features of TexturePacker. What this little nifty checkbox does is automatically create a low-res sprite sheet and plist file for you but you have to make sure that you named your Texture file with a -hd at the end.

A Note from the author of TexturePacker: Whenever possible, you should use Add Folder to import your sprites because this uses smart folder. Every time you add sprites to the folder and update your sprite sheet it re-scans the contents of the folder and adds all sprites. This makes sprite handling much easier than adding single sprites.

Ok, so now we have our sprites imported and have everything optimized. Next we will talk about Publishing.

Publishing Sprite Sheets:

Before you click on the Publish button be sure that you’ve got all of your settings configured the way you want them. Here’s a quick step-by-step re-cap of the steps above:

  1. Import sprites either by using the Add Sprites or the Add Folder button.
  2. Set Data Format to cocos2d
  3. Set Texture format to Compressed PVR (.pvr.ccz)
  4. Set Image format to RGBA4444
  5. Set Texture file to something-hd
  6. Set Dithering to FloydSteinberg+Alpha
  7. Check AutoSD

With all of the above completed go ahead and click on the Publish button. Texture Packer will now export your hi-res and low-res sprite sheets and associated plist data files.

You should have something similar to the following screen shot:

There isn’t too much to say about publishing, the next section will cover how to get your sprite sheets to work with cocos2d.

Writing The Code:

After publishing your sprite sheets with Texture Packer, the next and last step would be to add this into your project and get them to show up in your scene. I’ll be walking you through adding your sprite sheets to your project and showing you code examples of how to make the best use of your new sprite sheets.

Open up Xcode, create a new cocos2d Project from one of the cocos2d templates and copy the 2 sprite sheets and 2 plist files that were exported from TexturePacker into your Resources folder within your Xcode project, make sure that copy files is checked.

Copy Items

Copy Items

Once the sprite sheets and plist files have been added go ahead and click on your HelloWorldScene.m and find your init method. Once you’ve located your init method replace what’s inside the if statement with the following lines of code:

[CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGBA4444];
CCSpriteBatchNode *spritesDemoNode;
spritesDemoNode = [CCSpriteBatchNode batchNodeWithFile:@"demosprite.pvr.ccz"];
spritesDemoNode.tag = 805;
[self addChild:spritesDemoNode];
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"demosprite.plist"];

The code above does the following:

  1. Sets the current Pixel format to RGBA4444 to match that of our sprite sheet that we set in TexturePacker
  2. Creates a sprite batch node using the Compressed PVR
  3. Sets a tag ( has nothing to do with texture packer but I use tags for other reasons )
  4. Adds the node as a child to your current Layer
  5. Adds the sprite frames to cache from the plist file that was exported by Texture Packer

Next we need to create a CCSprite from the frames that are in cache, we do this with the following code:

CCSprite *spriteDemo = [CCSprite spriteWithSpriteFrameName:@"fireball.png"];
spriteDemo.position = ccp(size.width/2, size.height/2);
spriteDemo.tag = 1;
[self addChild:spriteDemo];

The above code does the following:

  1. Creates a sprite from the frames in cache. In this case I had an image named fireball.png that was one of the images that was imported into Texture Packer. When Texture Packer creates the plist file it uses the names of your sprites for the frame names, which makes it easy to use.
  2. Next I am setting the position to the center of the screen. size is a variable that I’ve setup that has the height and width of the screen as properties.
  3. Again I am setting a tag, not something you have to do
  4. Last we are adding the new sprite to our layer.

If all went well and you’ve followed all of the above directions then you should be able to build your project and see your sprite on the scene. Granted, this is more work then copying individual PNG’s into your project and just creating sprites from the PNG’s but that is a big waste of memory and will eventually crash your app. Remember, with Texture Packer I was able to reduce my memory to more then half of the original memory utilization even using Zwoptex did not make a huge improvement with memory usage. I would definitely recommend Texture Packer to anyone that is interested in optimizing memory.

If anyone has any questions or comments please feel free to leave them. If anyone has any more optimization tips, please share, I would love to hear them and I’m sure everyone else would appreciate it as well.

I’ve been following the cocos2d community for a while now and discovered that their latest release includes the ability to build your app for OS X. The folks over at cocos2d are trying to make it a simple process to port your iPhone / iPad app over to Mac OS X, probably in preparation of the newly anticipated Mac App Store that we should be seeing soon.

There doesn’t seem to be 100% full support for Mac OS X just yet but the basics are working. You might be asking yourself, how would I go about changing my project to build Mac OS X instead of iPhone? Honestly I haven’t found an easy way, so if someone wants to jump in and help me out I’d appreciate it but for the purposes of this tutorial I will be creating a new App.

Let’s review some of the steps we will need to perform to accomplish this task.

Begin by downloading the latest version of cocos2d here. When the download has completed, go ahead and extract this to a folder on your Mac.

  1. Start a New Cocoa Project
  2. Add Cocos2d Sources to Project
  3. Edit AppDelegate.h & .m files
  4. Import Frameworks
  5. Create a new Objective-C class
  6. Change Settings in Interface Builder for MainMenu.xib
  7. Import sample artwork files

I’d like to add in that I am not stating that this is the best or only way to setup a project with cocos2d to build on OS X and I may have taken some unnecessary steps and may have made a few mistakes. The following is what I did to get it to work for me. If anyone has any suggestions to make this a more accurate or better tutorial, please feel free to let me know.

Start a New Cocoa Project:

First we’ll need to open up Xcode and then start a new project. This time though, instead of starting with one of the pre-defined cocos2d templates we will be using the Cocoa Application template that you should find under Mac OS X -> Application. Please see the screen shot below:

Once you have created a new project you should see the Xcode interface come up. For the purpose of this tutorial I have named my App Demo Mac Port. Your screen should look similar to the screen shot below.

In the next step you will be adding the cocos2d sources to your project, so be sure you’ve downloaded the latest release of cocos2d to be sure you have the version that supports Mac OS X.

Add Cocos2d Source to your Project:

For this step you will need the cocos2d files, if you haven’t downloaded cocos2d yet you can download the latest version here. Once downloaded, go ahead and extract to somewhere on your hard drive.

After you have extracted Cocos2d you will need to navigate to the location on your hard drive where you extracted Cocos2d then open up the cocos2d-iphone-0.99.5-beta3 folder and locate the cocos2d folder. See the screen shot below:

We will need to add this folder to our project. I usually just drag it from the Finder window into the project. Drag the cocos2d folder into your project right under your App name on the very top. A dialog window similar to the screen shot below will pop up.

Click on Add and this will add the required Cocos2d sources to our project. Your Xcode Project interface should look similar to the screen shot below.

The next section will guide you through modifying the AppDelegate.h and .m files.

Modify AppDelegate.h & .m Files:

In this section you will need to modify the AppDelegate.h & .m files to work with Cocos2d. I will not be explaining the code her but I will list the code so you can see what these files should look like.

AppDelegate.h

#import "cocos2d.h"
 
@class CCSprite;
 
//CLASS INTERFACE
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
@interface AppController : NSObject
{
	UIWindow *window;
}
@end
 
#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED)
@interface Demo_Mac_PortAppDelegate : NSObject  {
    NSWindow *window_;
	MacGLView *glView_;
}
 
@property (assign) IBOutlet NSWindow *window;
@property (assign) IBOutlet MacGLView *glView;
 
@end
#endif // Mac

AppDelegate.m

//
// Actions Demo
// a cocos2d example
// http://www.cocos2d-iphone.org
//
 
// local import
#import "cocos2d.h"
#import "Demo_Mac_PortAppDelegate.h"
#import "DemoScene.h"
 
// CLASS IMPLEMENTATIONS
 
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
 
#pragma mark AppController - iOS
 
@implementation AppController
 
- (void) applicationDidFinishLaunching:(UIApplication*)application
{
	// CC_DIRECTOR_INIT()
	//
	// 1. Initializes an EAGLView with 0-bit depth format, and RGB565 render buffer
	// 2. EAGLView multiple touches: disabled
	// 3. creates a UIWindow, and assign it to the "window" var (it must already be declared)
	// 4. Parents EAGLView to the newly created window
	// 5. Creates Display Link Director
	// 5a. If it fails, it will use an NSTimer director
	// 6. It will try to run at 60 FPS
	// 7. Display FPS: NO
	// 8. Device orientation: Portrait
	// 9. Connects the director to the EAGLView
	//
	CC_DIRECTOR_INIT();
 
	// Obtain the shared director in order to...
	CCDirector *director = [CCDirector sharedDirector];
 
	// Sets landscape mode
	[director setDeviceOrientation:kCCDeviceOrientationLandscapeLeft];
 
	// Turn on display FPS
	[director setDisplayFPS:YES];
 
	// Enables High Res mode (Retina Display) on iPhone 4 and maintains low res on all other devices
	if ([UIScreen instancesRespondToSelector:@selector(scale)])
		[director setContentScaleFactor:[[UIScreen mainScreen] scale]];
 
	// Default texture format for PNG/BMP/TIFF/JPEG/GIF images
	// It can be RGBA8888, RGBA4444, RGB5_A1, RGB565
	// You can change anytime.
	[CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGBA8888];
 
	CCScene *scene = [CCScene node];
	[scene addChild: [nextAction() node]];
 
	[director runWithScene: scene];
 
}
 
// getting a call, pause the game
-(void) applicationWillResignActive:(UIApplication *)application
{
	[[CCDirector sharedDirector] pause];
}
 
// call got rejected
-(void) applicationDidBecomeActive:(UIApplication *)application
{
	[[CCDirector sharedDirector] resume];
}
 
// application will be killed
- (void)applicationWillTerminate:(UIApplication *)application
{
	CC_DIRECTOR_END();
}
 
// sent to background
-(void) applicationDidEnterBackground:(UIApplication*)application
{
	[[CCDirector sharedDirector] stopAnimation];
}
 
// sent to foreground
-(void) applicationWillEnterForeground:(UIApplication*)application
{
	[[CCDirector sharedDirector] startAnimation];
}
 
// purge memory
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
	[[CCDirector sharedDirector] purgeCachedData];
}
 
- (void) dealloc
{
	[window release];
	[super dealloc];
}
 
// next delta time will be zero
-(void) applicationSignificantTimeChange:(UIApplication *)application
{
	[[CCDirector sharedDirector] setNextDeltaTimeZero:YES];
}
 
@end
 
#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED)
 
#pragma mark AppController - Mac
@implementation Demo_Mac_PortAppDelegate
 
@synthesize window=window_, glView=glView_;
 
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
 
	CCDirector *director = [CCDirector sharedDirector];
 
	[director setDisplayFPS:YES];
 
	[director setOpenGLView:glView_];
 
	// Enable "moving" mouse event. Default no.
	[window_ setAcceptsMouseMovedEvents:NO];
 
	[[CCDirector sharedDirector] runWithScene: [DemoScene scene]];
}
 
@end
#endif

Within the applicationDidFinishLaunching method you will notice the [[CCDirector sharedDirector] runWithScene:[DemoScene scene]]; line.  This line specifies the Scene we want our project to start with. In the next section I will list some more code for a new Objective-C class.

Create a New Objective-C Class:

At this point we will need to create a new Objective-C class. Right click on the Classes group within your Xcode Project interface and click on Add -> New File. You will be presented with a dialog similar to the following.

Click on Next and you’ll be presented with the next dialog.

I’ve named my class, DemoScene.m be sure the check mark to create DemoScene.h file is checked. Click on finish, you should now see your new class files in your Xcode project interface. Below you will find the code you should put into these 2 files. If you are familiar with Cocos2d, then the code below should look familiar to you.

DemoScene.h

//
//  DemoScene.h
//  Demo Mac Port
//
//  Created by Chris Fletcher on 10/24/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//
 
#import
#import "cocos2d.h"
 
@interface DemoSceneLayer : CCLayer {
 
	CCDirector *Director;
 
}
@end
 
@interface DemoScene : CCScene {
 
	DemoSceneLayer *_layer;
 
}
 
@property (nonatomic, retain) DemoSceneLayer *layer;
 
+(id)scene;
 
@end

DemoScene.m

//
//  DemoScene.m
//  Demo Mac Port
//
//  Created by Chris Fletcher on 10/24/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//
 
#import "DemoScene.h"
 
@implementation DemoScene
@synthesize layer = _layer;
 
+ (id)scene {
 
	CCScene *scene = [CCScene node];
	DemoSceneLayer *layer = [DemoSceneLayer node];
	[scene addChild:layer];
 
	return scene;
 
}
 
- (id) init {
 
	if ((self = [super init])) {
 
		self.layer = [DemoSceneLayer node];
		[self addChild:_layer];
 
	}
	return self;
}
 
@end
 
@implementation DemoSceneLayer
 
- (id)init {
 
	if ((self = [super init])) {
 
		CGSize winSize = [CCDirector sharedDirector].winSize;
 
		CCSprite *starBG = [CCSprite spriteWithFile:@"starbg.png" rect:CGRectMake(0, 0, 960, 640)];
		starBG.position = ccp(winSize.width/2, winSize.height/2);
		[self addChild:starBG];
 
	}
	return self;
}
 
-(void) dealloc {
 
	[super dealloc];
 
}
 
@end

As you can see from the code above, we are simple creating an Interface and Implementation for a layer and a scene and then adding a CCSprite to the layer. This is very simple Cocos2d functionality but should be enough code to get you started.

We can’t Build & Run the project just yet. We have a few things left to do, mainly importing some frameworks & images and then making some changes in Interface Builder. The next section will cover the frameworks we will need to import.

Importing Additional Frameworks:

In this section of the tutorial I will cover which frameworks we will need to add to our project and how to add them. The frameworks we will add are as follows:

  • QuartzCore.framework
  • OpenGL.framework
  • ApplicationServices.framework
  • libz.dylib

To add a framework to our project, right click on Frameworks and then  Add -> Existing Frameworks. You will be presented with a dialog similar to the following screen shot.

Find the QuartzCore.framework and click Add, then right click on Frameworks and then Add -> Existing Frameworks and find the OpenGL.framework and click Add. Repeat these steps for the ApplicationServices.framework and the libz.dylib.

When you are done adding all of the frameworks your Xcode Project interface should look similar to the screen shot below:

At this time all we have left to do is is import some images and then make some Interface Builder changes. This is turning out to be a pretty lengthy tutorial but I promise we are almost at the end. In the next section I will quickly cover the images that need to be added.

Add Images To Our Project:

The code in the DemoScene.m file uses a CCprite that uses an image named starBG.png. You can download this image from the link below:

Download:

  Star Background (1.3 MiB, 1,699 hits)

The Cocos2d source requires that an image called fps_images.png exists in our resources folder to render the FPS image that you are used to seeing on the bottom left hand corner. You can find this file in the Cocos2d/Resources/fonts folder within the extracted folder from the cocos2d sources.

When you have both files located, drag them into the Resources folder of your Xcode project.

At this point we have done all that is required within our Xcode Project, the only thing left to do is to make some changes and additions to our MainMenu.xib file within interface builder.

MainMenu.xib & Interface Builder:

Go ahead and locate your MainMenu.xib file inside of your Xcode Project interface. It should be located inside of your Resources folder. Double Click on MainMenux.xib, this should launch interface builder.

After Interface Builder has launched, the first thing I like to do is resize the window to what the size of my application will be. For simplicity I will set the size of my window to 960×640 since I already have all of my images created at that resolution to support the iPhone 4.

After you have resized your window to 960×640, it should look similar to the following screen shot.

While we have focus on the window lets make a quick change. You will need to change a setting in the Window Attributes. At the bottom find the check mark for One Shot and uncheck this box. See the screen shot below:

After changing the size of the window and unchecking the One Shot mode we need to add an OpenGL View to our window. In your Library scroll down until you see OpenGL View. Select this and drag it onto your Window. You should now see something similar to the screen shot below:

Go ahead and resize the OpenGL View to the size of the window. Your resulting window should look similar to the screen shot below:

Now that we have our window and our OpenGL view resized to 960 x 640 we will need to make some changes to the OpenGL View. First, you’ll want to change the Class to MacGLView. With the OpenGL View selected go to the Identity tab and change the class name to MacGLView. See the screen shot below:

Next, click on the Attributes tab and make the changes as in the provided screen shot below:

After you have finished making the changes above, we will need to make one final change. We need to create a link to the glView outlet in our AppDelegate to the OpenGL View, so drag a connection from glView to OpenGL View. You can reference the screen shot below:

Now we are done with Interface Builder so go ahead and save and then exit Interface Builder and go back to your Xcode Project. At this point we have everything setup to properly run a cocos2d app on Mac OS X. You should see your app start up and it should look similar to the following screen shot.

Congratulations, you now have the basic building blocks to create / port your app for Mac OS X. I’ve tried to be as thorough  as possible when creating this tutorial and I am hoping that I didn’t miss anything. You can download a working project which includes everything from this tutorial below.

Download:

  Demo Mac Port (6.9 MiB, 1,908 hits)

Was this tutorial useful? Have you used this tutorial to create a Mac App using Cocos2d? I’d like to hear stories