Showing posts with label cocos2d. Show all posts
Showing posts with label cocos2d. Show all posts

Monday, March 8, 2010

Network Availability and Transparent OpenGL

Two more blog posts are online on http://apptech.next-munich.com.

The first post goes into details on how to use the Reachability class provided by Apple to detect network availability on iPhone and iPod touch.

The second post describes my first dive into augmented reality apps. In this particular case I give some information on how to integrate an OpenGL view managed by cocos2d with the UIImagePickerController. It details where you have to modify cocos2d code to make the OpenGL view transparent - which is a requirement in case you want to overlay the camera image with the OpenGL view.

Tuesday, February 2, 2010

So Close! and the Global Game Jam 2010

I don't know whether you're aware of this but last weekend saw the Global Game Jam 2010, an event organized by the International Game Developer Association promoting the development of and experimentation with the concepts of games.

The Jam itself is an event held at a single weekend all around the world. People who love developing games gather for a 48 hours hackathon, creating a full-blown game from scratch. To give you an impression of what such an event is capable of: last weekend, more than 4000 people were registered as participating in the event creating a mind-boggling 900+ games in only 48 hours. Impressive, isn't it? For a full list of games developed in Munich, have a look at our event's page.

For me, it was the first time I participated in GGJ - and I had hell of a good time. We met up Friday at 5pm for an initial brainstorming session which eventually led to a couple of game concepts which were pursued over the next two days. The team working on our game "So Close!" featured two Graphics Artists (Thorsten Folkers and Willi Kunth) along with our Game Design lead (Daniel Helbig of remote control productions), the Sound Masterbrain (Daniel Pharos of Knight's of Soundtrack) and myself starring as Coder of the Day. Once the initial game design was fixed, we started developing an initial prototype using cocos2d which quickly proved that our concept was indeed feasible. After a lot of initial headaches trying to get Chipmunk (a physics / collision detections engine) to work, the platforming aspect of the game fell into place and revealed a very rewarding gameplay. We spent pretty much all of Saturday evening polishing the gameplay and added some last minute mechanics on Sunday. Unfortunately, time was too short to implement Online Highscore posting using cocoslive by Sunday 5pm (the official deadline) but is scheduled for inclusion. Since we really believe in this game's concept, we're even going to release the game on the AppStore later this month!

For all you coders out there, you can grab the source code on the official GGJ website. For anybody else, you can find video footage of the game on YouTube.

GGJ has been a fun experience which I can only highly recommend to anyone who enjoys developing games or would like to have a closer look at what game development is like.

Tuesday, December 22, 2009

NEXT Munich

We have finally created a web presence for our new iPhone / iPod touch and Android development studio. You can find our site (German only for now) at the following location:

http://www.next-munich.com

I will start to move most of the tech-related topics to my new tech blog AppTech which is hosted on our website. I'll keep posting in English so that no reader is left behind! The first post on the new blog just presents a small piece of code which can help in case you're having flicker-issues on launch of your cocos2d-enabled application.

Hope to see you on the new site!

Saturday, December 12, 2009

Background Music & SFX on iPhone

I'm so glad that many people are sharing their findings and how they are getting things done in iPhone:

First of all, there is a super-convenient set of classes in the cocos2d package that can be used for playing background music and sound FX. The only thing I have to figure out is how I can tweak these guys to stop iPod music in case the user explicitly wants to enable in-game sound. But that's probably a piece of cake, too!

The next help comes from Tinker Blog which lists suitable file formats and conversion commands. Essentially, iPhone allows you to play one compressed file (like MP3) and several uncompressed files in parallel. Since there's only a single hardware decoder for compressed files available, not more than a single compressed file can play at the same time, though. The idea is to take your most expoensive sound and use it as an MP3 within your application (eg background music) and convert the smaller sounds (typically sound effects) to a format like "IMA4" packed inside of a "CAF" file.

Friday, December 11, 2009

Shear Transformations in cocos2d

To properly map a 2d texture onto a cube, I needed a shear transformation to properly transform the texture. Cocos2d does not support shears out of the box but this piece of code suggested by codem01 does the trick very nicely.

Keep in mind that the default shear values should be 0.0 (= no shear) and values used can be both, positive and negative and are restricted in magnitude only by your application.

You can find some more background on shear transformations on Wolfram MathWorld and on Wikipedia.

Thursday, December 3, 2009

Leak Hunting in iPhone Code

Eventually, when you're closing in on the release candidate of the software you're working on, you're probably going to check your app for memory and performance issues.

Same for me. On my current iPhone project, we're getting closer to our first beta and I felt I had neglected checking my memory usage and whether there are any apparent memory leaks in my app. Firing up Instruments, Apple's tool for analyzing Mac and iPhone software in many different ways (Memory, Disk Access, Open GL, Leaks, Core Data to name just a few), I was pretty happy with what I saw: the Leak-Detection tool did only find a couple of minor places in the code where I was leaking memory.

The output of Instruments, though not very intuitive at first, helped me identify the places in my code where I was allocating and / or retaining objects which I never released when it was time for them to be released. After patching those holes only a couple of leaking places were left that did not trace back into application code but into system APIs. Good job, I thought.

Coming from a Java background where I never had to spent a lot of thoughts to memory management (unless, of course, the occasional image = null; System.gc(); calls), switching to a reference-counted environment on the iPhone seemed to easy to be true. And sure enough I was going to find out that things are slightly more involved than checking the Leak tool in Instruments!

My colleague discovered the issue when he kept playing the game for longer than I had ever done. At some point in time, loading one of the included mini games, the application just crashed. Memory was his first thought and I also felt like it was some problem with running out of memory. Fortunately I was able to reproduce the bug and could see memory usage increase in Instruments while navigating the game.

After some time of digging for an answer I discovered an issue that was not detected by the Leak tool: cyclical references. Here I retained an object representing my scene for it to render properly while active. Within that object I created another object, however, which was retaining the scene. Once the scene was removed from screen, deallocation did not take place since the retain count of the scene did not reach 0.

How did I catch that one? A good indicator is ever increasing memory usage within your application. Monitor that while running on the phone itself to get a more accurate picture of your memory's distribution between Open GL ES memory and "regular" memory. I tried to explicitly free all my textures by calling cocos2d's [[TextureMgr sharedTextureMgr] removeAllTextures] method. Since this did not free any Open GL memory at all, something was going on. Finally, I carefully tracked memory usage using the Memory instrument when taking well-defined steps within the app. Once I had discovered a point where memory did not go back to where it was supposed to be (in case all of the memory had been free'd), I added some logging to see whether the object's I wanted to be dealloc'ed really were disposed of. That step let to the discovery of the the leak - maybe this will help you find some in your code, too!

Here's some sample implementation code to highlight what was happening:



This code kind of looks ok at first but soon you'll notice, that MyScene is never going to be dealloc'ed unless you explicitly call its' release selector twice somewhere outside of this code (which is going to lead to other problems - so don't do this!).

Assume the following code to understand why this is happening:



As you will probably know from Apple's documentation, whenever you're using alloc / init to create an instance of a class, you've implicitly retained the object. You have to explicitly release the object to properly dispose of the object. Now pay attention to the object's retain count:

1. The call to [[MyScene alloc] init] gives you an implicit retain count of 1.
2. Additionally, MyObject retains the allocated scene thus increasing its' retain count to 2.
3. Once [scene release] is called, the retain count is reduced to 1.

As you can see, the retain count is not going down to 0 as it should because of the retain by MyObject. Since MyObject only releases its' reference to MyScene in dealloc, this is not going to happen unless you explicitly send the MyObject instance the release selector.

The easy fix: if MyObject only lives as long as the scene is living, just don't retain the scene. It's going to be alive as long as MyObject is alive so there is not going to be a problem.

If you think this is happening to you, too, make sure you log the retain count of the object in question at appropriate times (whenever you think this object should be dealloc'ed but isn't). You can do this with a single line of code:



Hope this helps you find the pesky cyclical memory leaks. When is there going to be an app for that, too?

Did you find any other common patterns of leaks that are not detected by Instruments? Share your findings in the comments! I'm surely going to be thankful but so are probably all the other readers / Google users.

Friday, November 27, 2009

TextField update

There was a small bug inside the TextField code with regards to accessing the latest strings in textFieldUpdated method. The protocol has been adapted to reflect this.

Updates are available here.

Enjoy!

Wednesday, November 25, 2009

The Quest to implement a custom Text Field

To match the UI of the App I'm working on right now, I needed a text field with a custom look and feel that would nicely integrate with cocos2d.

I thought there must've been someone out there who has already accomplished / implemented something like this but after a while of google'ing and browing the cocos2d forums, I figured that there seems to be no final, working source code of something like this available.

With some help from this post by Jack and David (and some other stuff I don't seem to be able to remember), I eventually managed to code something myself which combines the rendering abilities of cocos2d (Sprites and BitmapFontAtlas) with the input capabilities of UITextField. This sure feels like a hack as I'm using an "invisible" (read: very tiny) UITextField to handle the text input while rendering the intercepted text using BitmapFontAtlas and some other Sprites but - hey - it works just fine.

I'll check with the people at cocos2d whether it would be worthwhile to include such a class in the main distribution. In the meantime, the files are available here.

Here's how you'd use the TextField class in your own projects:



Hope this gets you going much quicker than me! Now enjoy the code and let me know what you think!

Monday, November 23, 2009

Line-break code for BitmapFontAtlas available

I finally got around to submitting my cocos2d enhancement for BitmapFontAtlas to the cocos2d for iPhone issue tracker. The respective issue #637 contains the modified source code and is up for grabs if you can't wait to give this thing a try.

Here's a quick snippet of sample code for you to better understand how to use the added features:



Let me know in case you're having problems with the code or in case something's unclear. Enjoy!

Thursday, November 12, 2009

Enhanced Fonts in cocos2d

One thing I came across in cocos2d was an issue with the font rendering. Since the fonts produced by Hiero bitmap font editor are very tightly packed on their containing images, rendering artefacts can appear when cocos2d displays the characters on screen.

Several people have reported these issues but I did not find a solution that fixes the problem in all cases. For that reason I have slightly amended the Hiero bitmap font editor: the modified editor outputs the fonts with more space between individual characters and amending the characters rectangles in the font definition files. This works very well and fixes the issue for me. I'll try to get in touch with Hiero's maintainer (who seems to be this guy) and will check whether there is any chance of having this feature integrated into the official version of the editor.

Another thing relating to fonts is the calculation of a string's width and, based on these calculations, a proper algorithm for line and page breaking. As I did not find such a facility within cocos2d source code, I enhanced the BitmapFontAtlas class to provide all of these. Basically, before calling [label setString:@""] to set the text for a label, you can assign a size to the label using

label.size = CGSizeMake(width, height);

If such a size has been assigned, a call to

[label setString:@"A very long string with reeeeeaaaaalllllllyyyyyyyyyyyyyyyyyyy long words and\nforced line breaks."];

will split the string according to the given size. The string will first be divided into lines (obeying the maximum width assigned earlier), then into pages (additionally obeying the maximum height). The first page will then be used as the string displayed by the label.

To choose a different page and figure out the amount of pages available within the label, you can then use the properties label.currentPage and label.pages respectively. If you assume that you want to switch to page 1 and this is within the amount of pages available, you can just assign label.page = 1 and be done.

If you don't assign a size before your call to [label setString:@""], the text is going to be rendered as with the unmodified version of BitmapFontAtlas. The only added benefit is that forced line-breaks using @"\n" are supported.

For this change, too, I'll try to contribute back to the cocos2d project. I will keep you updated!

Friday, October 30, 2009

Running Actions in cocos2d during onEnter

I just discovered a requirement in the onEnter method when you try to run a duration-based Action in cocos2d. Whenever you're trying to do something like this within the onEnter method of a subclass of Layer:

[node runAction:[FadeIn actionWithDuration:1]];

make sure you call the super class' onEnter method. Otherwise the action will not perform what you try to achieve. Working code looks like this:



Hope this helps someone and saves some time!

Thursday, October 29, 2009

Note to Self on Void Pointers and CallFuncND

This is no news to anyone except for people who have never been exposed to void pointers (void*) before. Coming from a Java-background, I never had the opportunity (or dare I say hassle) to deal with pointers, obtaining memory addresses and de-referencing those. Whenever I was confronted with C / C++, I tried my best not to dive too deep into that matter.

Now in Objective C, I finally wanted to get rid of a compiler warning I was getting because I was dealing with void* as a data type. Basically, void* is a pointer to some data in memory of which the type is unknown to the compiler. Therefore, any address to some data in memory can be stuffed into a variable of type void*. Both of the following is valid:

void* data;
int i = 5;
float f = 6.5;

data = &i; // first assignment: works
data = &f; // second assignment: works, too

Now to get back to the data you stuffed inside, you cannot just de-reference it just like that. You need to cast it to the proper pointer type of the data that is stored at the particular address you're pointing to. In other words, you'd have to do the following (continuing the code above):

int* iPtr = (int*) data; // if data contains &i
float* fPtr = (float*) data; // if data contains &f

Since cocos2d uses void* as the data type to piggy-back any kind of user data within a CallFuncND action, I at least had to get that straight!

Sunday, September 6, 2009

Menus with cocos2d

If you intend to use the Menu class in cocos2d, remember that each method used as an invocation target by a MenuItem must take exactly one argument which is going to receive the object that invoked the method. If you don't conform to this, you will see an error message like:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSInvocation setArgument:atIndex:]: index (2) out of bounds [-1, 1]'

Here's a sample method that will work:

- (void) doMenuItemAction: (id) sender;

Thursday, September 3, 2009

Extending cocos2d

Today was my first real day of doing something vaguely productive using cocos2d on the iPhone.

I coded an animation creation framework (aptly called Pixel Animation Studio) some months ago which can be used to compose animations using 2d pixel graphics. Basically, an animation is broken down into frames which in turn are broken down into small fragments. This technique encourages reuse of image fragments and can save a lot of space normally wasted by duplicate content in images. I guess you can see my background as a J2ME engineer shine through ...

Anyways, to support the animations created using this tool, I need a Sprite class that can be assembled by rendering multiple images instead of a single texture. To get this working, I investigated the CocosNode, TextureNode and Sprite source code to see, how rendering is performed deep within cocos2d. Turns out it's fairly easy to do:

cocos2d already handles most of the behaviour you need for a Sprite in CocosNode. It takes care of position translations and rendering all the sub-nodes added to a CocosNode. Now you just go ahead, sub-class CocosNode and add all the images you'd like to render as children of type Sprite (or AtlasSprite). cocos2d will take care of the rest!

Since the animations produced with Pixel Animation Studio are slightly more advanced than the ones provided out of the box by cocos2d (btw, I didn't realize plain 2d, frame-based animations were supported out of the box to begin with - they are just not properly highlighted as a feature on their site), I also had to implement a new IntervalAction. That's pretty straight-forward, too: just subc-class and override the + (void) update: (ccTime) time method. When instantiating, keep in mind that cocos2d takes parameters in seconds for the actions which accept a duration parameter, not in milliseconds.

Sunday, July 19, 2009

cocos2d

First time really trying to get something done in iPhone SDK. After struggling ages getting a simple game loop to work - only to discover that I was calling the update routines on the wrong thread - I found a forum post which talked about the cocos2d iPhone 2D game engine.

Have now spent most of the day working on a simple Memory-like game. The engine is pretty straight forward to use once you get to know the APIs. There are a couple of things I didn't quite figure out this time, though - any insights are appreciated:

  1. Is there any reason why rendering origin in iPhone / cocos2d / OpenGL seems to be lower left corner instead of upper left? It sure matches the mathematical way of thinking about an origin but AFAIR most of the other frameworks have their origin in the upper left, don't they?
  2. To render the game board, I have assembled a Scene using a Layer and a couple of Sprites contained in that Layer where each of the Sprites was supposed to be touchable. I haven't found a way to get that working other than reacting to touches on the Layer and manually checking whether the touch fell within the bounds of one of the Sprites. There must be a better way to do this, right?
  3. How does memory management work when you replace Scenes using the Director singleton? You access the Scenes via [Scene node]; so I assume there's autorelease at work.
  4. Why do Texture2D.pixelsHigh / .pixelsWide return different values than Texture2D.contentSize?