Monthly Archive for February, 2009

cocos Live v0.1.1 with device id filter


Cocos Live v0.1.1 introduces some changes in the Web front end. The most important change is that now it is possible to the display certain fields in the Web and send back to the iPhone another set of fields.
Use the Sendback property to send a field back to the iPhone and use the Display On Web property to display a field on the web page.
Eg: If you don’t want to send back the usr_playername property to the iPhone, but you want to display it on the web page, then set SendBack = False and Display On Web = True.

In Cocos Live v0.1.1 you can also filter games by device id:

// request scores posted by this device// request scores "all time"// request best 15 scores (limit:15, offset:0)[request requestScores:kQueryAllTime limit:15 offset:0 flags:kQueryFlagsByDevice category:@"easy"];

To filter by device id using the Web front end you need to enable the Display On Web property for the cc_device_id field.
Then, you can click on that field to filter by that device id.

Cocos Live client v0.1.1 will be available with cocos2d v0.7.1, but if you can’t wait, you can download it from the svn rev. 594.

Cocos Live service v0.1.1 is “live” now. To try this feature, you can play filtering the scores of DemoGame game.

cocos2d for iPhone v0.7 released

Download:
http://cocos2d-iphone.googlecode.com/files/cocos2d-iphone-0.7.tar.gz

New features since v0.6.3:

Effects (AKA mesh effects, AKA grid effects):
cocos2d v0.7 let’s you manipulate the CocosNode’s texture like a grid. You can create astonishing effects on your nodes by executing some of the Grid actions.
For further information read this post:
http://blog.sapusmedia.com/2009/02/introduction-to-effects-in-cocos2d.html

Cocos Live (High Score Server):
cocos2d v0.7 comes with an API that let’s you upload your high scores to a free high score server called Cocos Live.
For further information read this post:
http://blog.sapusmedia.com/2009/02/cocos-live-high-score-server-for.html

Improved TileMapAtlas:
cocos2d v0.7 let’s you read/write the TileMapAtlas in runtime.
For further information read this post:
http://blog.sapusmedia.com/2009/02/read-write-tilemapatlas-at-last.html

Improved Alias/Antialias support:
cocos2d v0.7 has a new API to handle your aliased/antialiased textures.
For further information read this post:
http://blog.sapusmedia.com/2009/02/antialiased-aliased-textures-in-cocos2d.html

PVRTC full support:
cocos2d v0.7 supports the “full” PVRTC format, including PVRTC images with mipmap textures.
For further information read this post:
http://blog.sapusmedia.com/2009/02/pvrtc-support-in-cocos2d.html

Fast Director:
cocos2d v0.7 has a new Director, that triggers the main loop every frame. This let’s you gain some FPS in certain conditions.
For further information read this post:
http://blog.sapusmedia.com/2009/02/gaining-some-fps-in-your-game.html

Attach/Detach:
cocos2d v0.7 has a new API that let’s you attach/detach run/restart the director.
For further information please see the AttachDemo example that comes with cocos2d.

How to convert a v0.6.3 project to v0.7.0 ?
Please read this file:
http://cocos2d-iphone.googlecode.com/svn/trunk/tools/convert_0_6_to_0_7.txt

Full Changelog:

  • Action: elapsed is a property (issue #203)
  • Actions: EaseIn/Out added. Cubic/Quad removed (issue #195)
  • Atlas: Fixed black line (issue #135 and issue #47)
  • Atlas: Works when GL_CULL_FACE is enabled (issue #179)
  • Atlas: updateAltasValues renamed to updateAtlasValues (issue #198)
  • CocosLive: added client and example that uses the CocosLive service (issue #175)
  • CocosNode: children is a property (issue #185)
  • CocosNode: rotate before scale (issue #217)
  • Demos: Creating Window and attaching cocos2d to it (issue #180)
  • Demos: Texture2dDemo shows how to load PVR images and PVR Mipmap images (issue #112)
  • Demos: Added AttachDemo (issue #180)
  • Demos: Added EffectsDemo and EffectsAdvancedDemo (issue #183)
  • Director: OpenGLview is attached to a given UIView/UIWindow (issue #180)
  • Director: winSize returns a CGSize (not a CGRect) (issue #159)
  • Director: added FastDirector (issue #145)
  • Director: dispatch missing events in main loop (issue #146)
  • Director: renamed runScene with runWithScene (issue #194)
  • Director: SignificantTimeChange fixed (issue #6)
  • Effects: Added Effects support (Grid and TiledGrid) (issue #183)
  • Effects: Basic: StopGrid, ReuseGrid (issue #183)
  • Effects: Grid: Waves3D, FlipX3D, FlipY3D, Lens3D, Ripple3D, Liquid, Shaky3D, Waves, Twirl (issue #183)
  • Effects: Tiled: ShakyTiles3D, ShatteredTiles3D, ShuffleTiles, FadeOutTRTiles, FadeOutBLTiles, FadeOutUpTiles, FadeOutDownTiles, TurnOffTiles, WavesTiles3D, JumpTiles3D, SplitRows, SplitCols (issue #183)
  • Experimental: Added StreakDemo (issue #171)
  • Menu: aligItemsVerticallyOld removed. (issue #196)
  • MenuItemFont: can be changed in runtime (issue #202)
  • MenuItemFont: assign correct size and documented isEnabled (issue #132)
  • Particle: Buffers updated on update (issue #163)
  • Sprite: initWithPVRTCFile is deprecated. will be removed in v0.8 (issue #197)
  • Texture: Support for full PVRTC (issue #112)
  • Texture: Easier to set Alias and/or AntiAlias texture parameters (issue #135 and issue #47)
  • TileMapAtlas: it is readable / writeable now (issue #200)
  • Transitions: added new Effects transitions: SplitRowsTransition, SplitColsTransition, TurnOffTilesTransition, FadeTRTransition, FadeBLTransition, FadeUpTransition, FadeDownTransition (issue #187)
  • Xcode: treat warnings as errors (issue #201)

Thank you for sending patches, opening issues, fixing bugs, helping people in the forum, sending suggestions, testing the beta and rc versions.

Special thanks to Ernesto Corvi and On-Core for porting all the Effects code from cocos2d-pyhton to cocos2d-iphone!

cocos Live: a high score server for cocos2d

Cocos Live is a service that tries to help iPhone Indie Game Developers by giving them an API to solve their online requirements.

As of version 0.1, the only feature available is the High Score Server. Future versions will have more features.

To use the High Score Server you need to:

  1. Have a valid Google account
  2. Sign in into Cocos Live with that account
  3. Create a game, customize it, and copy the secret key

Requesting a score

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
-(void) requestScore {
    // create a Request object for the game "DemoGame"
    // You need to implement the Score Request Delegate
    ScoreServerRequest *request = [[ScoreServerRequest alloc] initWithGameName:@"DemoGame" delegate:self];
 
     /* use kQueryFlagIgnore to request World scores */
     tQueryFlags flags = kQueryFlagIgnore;
 
     /* or use kQueryFlagCountry to request the best scores of your country */
     // tQueryFlags flags = kQueryFlagByCountry;
 
     // request the first 15 scores ( offset:0 limit:15)
     // request AllTime best scores (this is the only supported option in v0.1
     // request the scores for the category "easy"
     [request requestScores:kQueryAllTime limit:15 offset:0 flags:flags category:@"easy"];
 
     // Release. It won't be freed from memory until the connection fails or suceeds
     [request release];
 }
 
// ScoreRequest delegate
-(void) scoreRequestOk: (id) sender {
    // the scores are stored in a
    NSArrayNSArray *scores = [sender parseScores];
 
    // Display them as you wish: using a UITableView,
    // a custom CocosNode, etc...
 }
 
-(void) scoreRequestFail: (id) sender {
    // request failed. Display an error message.
}

Posting a score

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
-(void) postScore {
    // Create que "post" object for the game "DemoGame"
    // The gameKey is the secret key that is generated when you create you game in cocos live.
    // This secret key is used to prevent spoofing the high scores
    ScoreServerPost *server = [[ScoreServerPost alloc] initWithGameName:@"DemoGame" gameKey:@"e8e0765de336f46b17a39ad652ee4d39" delegate:self];
 
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:4];
 
     // usr_ are fields that can be modified.
     // set score
     [dict setObject: [NSNumber numberWithInt: 340 ] forKey:@"cc_score"];
     // set speed
     [dict setObject: [NSNumber numberWithInt: 120 ] forKey:@"usr_speed"];
     // set angle
     [dict setObject: [NSNumber numberWithInt: 92 ] forKey:@"usr_angle"];
     // set playername
     [dict setObject:@"Ricardo" forKey:@"usr_playername"];
     // set player type
     [dict setObject: [NSNumber numberWithInt: 0 ] forKey:@"usr_playertype"];
 
     // cc_ are fields that cannot be modified. cocos fields
     // set category... it can be "easy", "medium", whatever you want.
     [dict setObject:@"easy" forKey:@"cc_category"];
 
    [server sendScore:dict];
 
     // Release. It won't be freed from memory until the connection fails or suceeds
     [server release];
 }
 
// PostScore Delegate
-(void) scorePostOk: (id) sender {
    // Score post successful
}
 
-(void) scorePostFail: (id) sender {
    // score post failed
    tPostStatus status = [sender postStatus];
    if( status == kPostStatusPostFailed ) {
        // an error with the server ?
        // try again
    }else if( status == kPostStatusConnectionFailed ) { 
        // a error establishing the connection ?
        // turn-on wifi, and then try again
    }
}

For further information download cocos2d for iPhone v0.7, try the cocosLiveDemo example and read the cocosLiveDemo.m file.

cocos2d number-one open source project for iPhone


According to The Register, cocos2d for iPhone, is the number-one opensource project for iPhone.

“Mobile saw 120 new open-source projects, with 40 targeting the iPhone. The number-one project was 2D famework cocos2d-iphone, followed by zipper image viewer iphone-comicviewer and iphone-com, for iPhone applications that use Win32 serial COM ports

Introduction to cocos2d’s effects

Special thanks to Ernesto Corvi and On-Core for porting all the Effects code from cocos2d-python to cocos2d-iphone.
THANK YOU!

Effects are a special kind of action. Instead of modifying normal properties like opacity, position, rotation, or scale, they modify a new kind of property: the grid property.

A grid property is like a matrix, it is a network of lines that cross each other to form a series of squares or rectangles.

These special actions render any CocosNode object (Layer, Scene, Sprite, etc.) into the grid, and you can transform the grid by moving its vertices.

There are 2 kind of grids: tiled grids and non-tiled grids. The difference is that the tiled grid is composed of individual tiles while the non-tiled grid is composed of vertices.

The following is an example of Ripple3D action, who uses a Grid3D (non-tiled) grid:

and the following is an example of FadeOutTR action, who uses a TiledGrid3D (tiled) grid:

How do I use them ?

Like any other action, it is executed by the do: selector. eg:

// Create an spriteSprite *grossini = [Sprite spriteWithFile:@"grossini.png"];

// Tell the sprite to execute the Liquid effect[grossini do: [Liquid actionWithWaves:4 amplitude:20 grid:ccg(10,10) duration:5]];

Liquid, like any other grid action, receives the grid parameter. You can adjust the quality of the effect by increasing the size of the grid. But it also implies less FPS.

The Effects are IntervalAction actions so you can treat them like any other action. eg:

// create a Lens3D actionid lens = [Lens3D actionWithPosition:cpv(240,160) radius:240 grid:ccg(15,10) duration:8];

// create a Waved3D actionid waves = [Waves3D actionWithWaves:18 amplitude:80 grid:ccg(15,10) duration:10];

// create a sequence an repeat it forever[grossini do: [RepeatForever actionWithAction: [Sequence actions: waves, lens, nil]]];

The following is the list of the available Grid3D (non-tiled) actions in v0.7:

Shaky3D Waves3D FlipX3D FlipY3D
Lens3D Liquid Waves Twirl
Ripple3D

The following is the list of the available TiledGrid3D (tiled) actions in v0.7:

ShakyTiles3D ShatteredTiles3D ShuffleTiles FadeOutTRTiles
FadeOutBLTiles FadeOutUpTiles FadeOutDownTiles TurnOffTiles
WavesTiles3D JumpTiles3D SplitRows SplitCols

Edit: fixed grammar errors, improved the layout

read-write TileMapAtlas (at last ;)

The TileMapAtlas object was introduced in cocos2d v0.5.0. Although it helped in creating big scenarios, a lot of functionality was missing, like the possibility to read and modify the atlas in runtime, isometric tiles, hex tiles, animations, etc.

From cocos2d v0.7 onwards, you can read/write the TileMapAtlas (the rest of the features will be included in v0.8)

So, how I do a read / write my TileMapAtlas in v0.7 ?

Let’s start by recalling how to create a TileMapAtlas. The API is same you were using since v0.5:

TileMapAtlas *tilemap = [TileMapAtlas tileMapAtlasWithTileFile:@"tiles.png" mapFile:@"levelmap.tga" tileWidth:16 tileHeight:16];
[self add:tilemap];

Since v0.7 you can read/write the TileMapAtlas but if you don’t want to, you might want to release the map from memory:

// Release the map from memory ONLY if won't read or write the tile map
[tilemap releaseMap];

But if you are going to read or write the map, DON’T release the memory. Otherwise, you won’t be able to read or modify the atlas.

To read the the value of a certain tile, or to iterate over all the tiles you can do the following:

// For example you can iterate over all the tiles
// using this code, but try to avoid the iteration
// over all your tiles in every frame. It's very expensive
 
for(int x=0; x < tilemap.tgaInfo->width; x++) {
for(int y=0; y < tilemap.tgaInfo->height; y++) {
 ccRGBB c =[tilemap tileAt:ccg(x,y)];
 if( c.r != 0 ) {
    // only the channel 'r' (red) is used
    // if r == 0 it means that it is transparent, it won't be rendered
 }
}
}

And to modify a certain tile of the TileMapAtlas object you can do as follows:

int x = 20;
int y = 30;
 
// read value
ccRGBB c =[tilemap tileAt:ccg(x,y)];
 
// modify it
c.r = 21;
 
// and store it on the tile map atlas
[tilemap setTile:c at:ccg(x,y)];

Limitations: you can’t modify a position whose tile value is 0. If you know that you are going to modify a certain position of the atlas, don’t set the initial value with 0.

For more information see the AtlasDemo example: TestAtlas.m

AntiAliased / Aliased textures in cocos2d

From cocos2d v0.7 onwards it is easier to customize the texture’s parameters like GL_LINEAR, GL_NEAREST, CLAMP_TO_EDGE, etc.

By default all cocos2d’s textures are created with these values:

GL_TEXTURE_MIN_FILTER = GL_LINEAR;GL_TEXTURE_MAG_FILTER = GL_LINEAR;GL_TEXTURE_WRAP_S = GL_CLAMP_TO_EDGE;GL_TEXTURE_WRAP_T = GL_CLAMP_TO_EDGE;

You can change the default parameters. eg:

// Change default texture's parametersccTexParams texParams;texParams.minFilter = GL_NEAREST;texParams.magFilter = GL_NEAREST;texParams.wrapS = GL_REPEAT;texParams.wrapT = GL_REPEAT;[Texture2D setTexParameters: &texParams];

You can also change the texture’s parameters just for 1 texture. For example, if you want to create a TileMapAtlas with GL_NEAREST you should do this:

// save current state[Texture2D saveTexParameters];

// set GL_NEARESTccTexParams texParams = [Texture2D texParameters];texParams.minFilter = GL_NEAREST;texParams.magFilter = GL_NEAREST;[Texture2D setTexParameters: &texParams];

// create the textureTileMapAtlas *tilemap = [TileMapAtlas tileMapAtlasWithTileFile:@"tiles.png" mapFile:@"levelmap.tga" tileWidth:16 tileHeight:16];

// restore state[Texture2D restoreTexParameters];

or, you can use the helper function setAliasTexParameters:

// Save state[Texture2D saveTexParameters];

// set Alias parameters[Texture2D setAliasTexParameters];

// create the textureTileMapAtlas *tilemap = [TileMapAtlas tileMapAtlasWithTileFile:@"tiles.png" mapFile:@"levelmap.tga" tileWidth:16 tileHeight:16];

// restore texture's parameters[Texture2D restoreTexParameters];

For more information see the Texture2dDemo example file: Texture2dTest.m

PVRTC support in cocos2d


From cocos2d v0.7 onwards you can use non-raw PVRTC (PVR Texture compression) images. (Raw PVRTC images are supported since v0.5.2)

In order to load a non-raw PVRTC image you can use the same API that you were using to load PNG/BMP/JPEG images. eg:

// Sprite using PVRTC fileSprite *img = [Sprite spriteWithFile:@"test_image.pvr"];

// Texture Atlas with PVRTC fileTextureAtlas *textureAtlas = [TextureAtlas textureAtlasWithFile: @"atlastest.pvr" capacity:3];

// TileMapAtlas with PVR fileTileMapAtlas *tilemap = [TileMapAtlas tileMapAtlasWithTileFile:@"tiles.pvr" mapFile:@"levelmap.tga" tileWidth:16 tileHeight:16];// LabelAtlas with PVR fileLabelAtlas *label = [LabelAtlas labelAtlasWithString:@"123 Test" charMapFile:@"tuffy_bold_italic-charmap.pvr" itemWidth:48 itemHeight:64 startCharMap:' '];

As you can see, the PVRTC support is transparent .
Using PVRTC files has the following benefits:

  • It reduces the loading time (less footprint)
  • It is faster, for it consumes less bandwidth
  • It is also faster, since it implies less texture switches because more textures can be in memory at the same time (I might be wrong on this one :)

To convert a PNG file to PVRTC use this step:

/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/texturetool -e PVRTC -f PVR --channel-weighting-linear --bits-per-pixel-4 -o test_image.pvr test_image.png

Edit: Fixed grammar errors

Gaining some FPS in your game


So, you want to gain some FPS in your game.
Here is the checklist:

  • Optimize Chipmunk. Follow Skorche’s (the author of Chipmunk) tips
  • Compile your code with Thumb support disabled
  • And from cocos2d v0.7 onwards you can use the Fast Director

To enable the Fast Director you need to call:
[Director useFastDirector];

before calling any other Director’s method.

Fast Director pros/cons:

  • Calls mainLoop as fast as it can
  • But no faster than 60 FPS (iPhone limitation)
  • Doesn’t support IntervalAnimation yet, so you can’t force it to, let’s say 30 FPS.

For example, the ChipmunkDemo example is running 10 FPS faster using the Fast Director.

In conclusion:

  • If don’t need a lot of speed, and you are OK with 30 FPS, then use the old Director since it supports the setIntervalAnimation method.
  • But if you want all the possible FPS then use the Fast Director

Remember: The more FPS, the more battery is consumed.

For more information regarding the FastDirector and how it was implemented see issue #145

[Edit]: Fixed grammar errors, added ‘in conclusion’

cocos2d for iPhone video #2

This video shows the new features of the soon-to-be released cocos2d for iPhone v0.7