brandontreb.com Tips And Resources For Software Consultants

New Year – New Theme: Focus On The Content

As you may have noticed, my blog has a new (much cleaner) theme. For 2012, my blogging goals are to focus much more on content rather than flashy visuals.

I have also minimized my set up to save blogging costs (I now blog for FREE) and to simplify things greatly. Here is my new setup:

  • Jekyll as my “blog engine”
  • The WPTypo WordPress Theme I ported this to Jekyll
  • GitHub for hosting (it’s free).
  • Vim – I’m using this as my “blog editor”. There are some incredible plugins that I am using to help facilitate blogging using Jekyll (post on how I do this to follow)

That’s about it. I am now free from server costs and my blog is always backed up and easily accessible.

2011 has been a very successful year in terms of blogging for me. In addition to writing here and on iCodeBlog, I have recently started blogging for Mobile Tuts + on the Envato Network. You can check out my 7 part game series on creating a caterpillar game using Cocos2D here.

I can’t wait to start posting some great content in this new year. Given my new setup, I literally have to adhere to the title of this post as blogging in VIM doesn’t really lend itself to visuals ;).

Happy New Year and Happy Hacking in 2012!

SVProgressHUD Is Quickly Becoming My Favorite iOS Library

From the first time I saw this effect in the Tweetie (now Twitter for iPhone), I was crazy about it. I had written my own hacks to make something close, but it was always terrible. Within the past few months, I have been using a perfect/elegant solution to this problem called SVProgressHUD.</p>

Using this in your project is as easy as calling:

// showing
[SVProgressHUD showWithStatus:@"Logging in…"];
// hiding
[SVProgressHUD dismiss];

Clone SVProgressHUD On Github

Tether Your iPhone Without Jailbreaking (Or Paying For It)

With all of the buzz around the iTether App, I figured I’d offer a more permanent solution since Apple will surely yank this soon

Last year, a developer published his code for an http SOCKS proxy called iProxy. This will give your iPhone the ability to create a SOCKS server in which your laptop can connect to via the Bonjur protocol.

Once connect, all of your computer’s http traffic will be routed through the server on your iPhone essentially giving you free tethering. Since this isn’t using the iPhone’s built-in tethering method, I’d assume At&t could not detect it*. After looking at the code, it becomes pretty obvious how the SOCKS proxy works and makes me kick myself that I didn’t write it (or find this code sooner).

The setup is a little complex, but you only need to do it once. I would love to hear in the comments if any of you has had some experience with this. I will also share my own as soon as I can get it installed later today.

Download the project over at github.

Happy Coding!

*This has not been verified by me

Caterpillar 1.1 Released

I have just released the update to my Centipede clone called Caterpillar. For those of you who don’t know, I am doing a 6 part series on how to create this game over at MobileTuts+.</p>

This update adds some interesting functionality on which I will be blogging about in the near future.

I have added iAds to my cocos2D project and when the iAds fail to serve (which is about 75% of the time), I replace them with Admob ads. This was achieved by creating a new Admob ad view inside of the bannerView:didFailToReceiveAdWithError: delegate method.

I will either post a full tutorial about doing this Here or on Mobile Tuts. Either way, I’ll keep you posted.

Also, be sure to download the game, test it out, and lemme know if you have suggestions. Version 1.1 addressed quite a few issues from feedback (namely poor controls).

Happy coding!

WordPress Plugin For iOS Developers And Bloggers

This plugin looks to be super useful for people wanting to blog about iOS apps. It even supports the affiliate urls.

In any post or page, insert the following shortcode: [ios-app id=”1234”] (where “1234″ is your application’s App Store ID).
You can also specify a download link like this: [ios-app id=”1234” download_url=”http://www.yourlinktrackerurl.com”]

Download The Plugin Here

Voices That Matter Conference: Highlights

This past weekend, I attended the voices that matter conference as a sponsor for a new product my team is working called MaaSive. We had an absolute blast at the conference and I learned quite a bit from all of the speakers.

Here were a few of my favorite parts:

Keynote by Graeme Devine

For those of you who don’t know Graeme is a legend in the game development industry. He was responsible for titles such as Quake 3, 7th guest, and Halo Wars. His presentation entitled “Social Gaming is Dead” was spot on. In it Graeme talked about how game developers have become less focused on the quality of games and more focused on “how do I make a profit?”. A statement that has stuck out to me is:

“Be generous with fun. We are mean with it!”

Basically, we are charging our users for fun or making them do real work (see Farmville) in order to obtain it. His message was “stop it, make something fun, and dont’t focus on profit”. Otherwise you are doomed.

Follow Graeme on Twitter

Moving To 3D by Mike Daily

Mike is a good friend of mine and I look forward to hanging out with him at the conference each year. His talk was all about showing the developers how easy it actually is to create a 3D game without the use of a game engine. Mike’s demo (show below) was an absolutely incredible space shooter where you used the gyroscope to maneuver around.

Mike will be posting a series on his blog in the near future about how to make his game using GLKit in the near future.

VTM Game Prototype from Michael Daley on Vimeo.

Follow Mike on Twitter

Storyboarding by Erica Sadun

Erica is an OG (original gangster) when it comes to iOS development. She has been in the space since way before the first SDK was published (in fact she had a jailbroken dev book almost ready to go). Her current book, The iPhone Developer’s Cookbook is a beast containing almost 900 pages!!!

Her talk showed how easy it is to use storyboarding and just how powerful the technique can be.

Follow Erica on Twitter

Conclusion

It should be obvious from this post, that the VTM conference was incredible to say the least. If you didn’t attend, I strongly urge you to check out their next one. Hopefully you will get to blog about my talk at it (assuming I get my crap together).

Happy Coding!

Caterpillar-HD Now In The App Store: Tutorial Series To Follow

I have just released the update to my Centipede clone called Caterpillar. For those of you who don’t know, I am doing a 6 part series on how to create this game over at MobileTuts+.

This update adds some interesting functionality on which I will be blogging about in the near future.

I have added iAds to my cocos2D project and when the iAds fail to serve (which is about 75% of the time), I replace them with Admob ads. This was achieved by creating a new Admob ad view inside of the bannerView:didFailToReceiveAdWithError: delegate method.

I will either post a full tutorial about doing this Here or on Mobile Tuts. Either way, I’ll keep you posted.

Also, be sure to download the game, test it out, and lemme know if you have suggestions. Version 1.1 addressed quite a few issues from feedback (namely poor controls).

Happy coding!

WordPress To Jekyll And Back Again

Earlier this year, I jumped ship on WordPress and moved to Jekyll after reading this post on Hacker News. I wanted to be 1337! I wanted to ditch the whale that was WordPress.

Well, it was quite a run, but in the end I decided to revert back to WordPress. Although Jekyll is much faster than WordPress, here were my issues:

Build Times

As my post count grew, so did the time to compile my jekyll site. Jekyll is a static site builder, so naturally it has to rebuild your site any time anything changes. With my blog containing hundreds of posts, my site build times started getting into minutes. I simply don’t want to wait forever to publish a post.

Since it took so long to build my site, it discouraged me from posting. I would only write posts on my specified #iDevBlogADay days, rather than just posting quick info posts.

Too Many Dependancies

Jekyll is a beast to install, especially if you want to support some of the fancier plugins like syntax highlighting. This limited my blogging to only my machines. I couldn’t blog from anywhere anymore. I could have installed Jekyll on my server, but that just seems like a hassle, also see my first point about build times.

No Mobile App

I like to blog on the go, and with Jekyll I just couldn’t find an elegant solution to blog from my iPhone or iPad. I found myself trying to come up with hackish solutions and write custom scripps, but in the end it just wasn’t worth it.

I can now use Markdown with WordPress

I fell in love with Jekyll because I could write in markdown. With this plugin, I can now do just that with WordPress. It stores the Markdown in a separate meta field and generates the post_content html upon publishing the post. So, I’m not married to the plugin in case I decide to ditch it.

I have also hid the disgusting “Visual Editor” that WordPress is unfortunate enough to ship with. This makes my writing experience much more pleasant.

The Future

While Jekyll was a fun experiment, I think I will stick with WordPress for now.

geekCred–;

What’s Your Cruising Speed?

Earlier this year, I launched an application called Smart Lockscreen Creator. It was a pretty simple app that allowed you to add dynamic data (such as weather) to your wallpaper and save it back out to your camera roll. The idea is to improve the functionality of the user’s lockscreen. It did very well on launch (and even made it to #1 in the Israel App Store). At the peak, I was selling about 600 copies per day.

Well, the honeymoon period is over and sales have slowed down quite a bit, however they have completely stabilized around what I’m calling the “cruising speed”. So, what’s my speed? On an average day, I will sell between 10-15 copies of the application per day. This is with no additional marketing, I’m not on any top 500 pages, and honestly I haven’t done much to the application at all. The app even has ~2 star rating. Not because it sucks, but because people don’t read the description and assume it will constantly update their lockscreen.

I have asked a few developers and this seems to be a fairly common cruising speed. So, now I’m asking you.

What’s YOUR cruising speed?

Do you think updating the application will affect this speed?

What dictates the speed?

I’d love to hear your responses in the comments.

This post is part of iDevBlogADay, a group of indie iOS development blogs featuring two posts per day. You can keep up with iDevBlogADay through the web site, RSS feed, or Twitter.

Join Me At The Voices That Matter iOS Conference

In November, I will be attending the Voices That Matter iOS Developers conference. It will be my third time attending, and I can’t recommend it enough. One major change from this year however is, I will be attending as a sponsor. A new company/project (currently in private alpha) will be participating as a sponsor at the conference.

We intend to have a table set up with multiple computers and devices so you can check out our product first hand. Bleh, that sounds kind of spammy. But, we have been working on something incredibly killer and I can’t wait to share it with all of you.

If YOU are planning on attending the conference, please comment on this post, write me on Twitter, or email me. I’d love to set up a one on one time to give you the full demo.

Also, I’m sure many of you already have a discount code, but if not, I have a pretty sweet promo code for $100!

BSTBLOG

Enter that at checkout. Combining that with the “Early Bird Pricing”, you save $300! Not a bad deal.

So, if you do end up coming (you are crazy not to), please communicate with me. At least to say hi, you don’t have to here my super awesome sales spiel if you don’t want to…

Happy Coding!

This post is part of iDevBlogADay, a group of indie iOS development blogs featuring two posts per day. You can keep up with iDevBlogADay through the web site, RSS feed, or Twitter.

Beginning Jailbroken iOS Development – Your First Tweak

This is the 3rd installment of my jailbroken iOS development series. If you haven’t already, make sure you read the following tutorials to get up to speed.

Today I’m going to show you how to patch any internal Apple method that you want. In this demo, we are going to hook into the init method of Springboard and show a UIAlertView upon starting your phone up. It’s not the coolest of applications, but the design pattern and concepts used can be applied to patching any other internal method of any class.

Getting Set Up

In order to create a tweak, you must interface with Saurik’s libsubstrate.dylib dynamic library. This might come packaged with theos, but if not, you need to download a fresh copy. One can be found on this very spammy site. Download libsubstrate.dylib

Once you have downloaded it, copy it to the folder /opt/theos/lib. This is the folder where you will copy any other dynamic libraries that you might need to use in your application.

The iOS Headers

Most likely, theos came with the iOS headers that you need. If not, you need to obtain them by doing a header dump on the device OR Googling around for them. I suggest the latter as someone else has surely done the work for you. Once you have these headers, you need to put them in the folder /opt/theos/include. For this example you should have a folder in there called Springboard containing all of the Springboard headers.

Creating The Project

The process for creating the project is simple. I’m going to assume that you already have all of your environment variables in place that we discussed in the last tutorial. If not, you will get errors.

Open the console, cd into the directory where you want to create your application and type the following command to create a new Tweak application.

<code class=’bash’>$THEOS/bin/nic.pl</code>

Now, when prompted select the number 5 for a tweak. Next, you will enter all of the information about your project. The resulting output should look like this:

<code class=’bash’>NIC 1.0 - New Instance Creator
——————————
  [1.] iphone/application
  [2.] iphone/library
  [3.] iphone/preference_bundle
  [4.] iphone/tool
  [5.] iphone/tweak
Choose a Template (required): 5
Project Name (required): WelcomeWagon 
Package Name [com.yourcompany.welcomewagon]:                 
Author/Maintainer Name [Brandon Trebitowski]: 
MobileSubstrate Bundle filter [com.apple.springboard]: 
Instantiating iphone/tweak in welcomewagon/…
Done.</code>

The Tweaks File

Once your project has been created, you can open in up in your favorite editor. I prefer TextMate. Theos creates a file for you called Tweak.xm. This is a special file that will run through theos’s preprocessor in order to hook into the classes and methods that you specify. So, rather than us having to write tons of boilerplate/crazy hook code, Theos does that all for us with a nice interface.

By default, EVERYTHING in that file is commented out. It took me longer than I care to admit to figure that out when I created my first Jailbroken iOS app.

The Preprocessor commands

There are a few commands that you need to know in order to hook into a class:

%hook and %end

<code class=’objc’>%hook Springboard
// overwrite methods here
%end</code>

The first command is called %hook followed by the name of the class you are hooking in to. You choose the methods to overwrite within the context of %hook className and %end. In the above code, we are saying that we want to hook into some methods in the SpringBoard class.

%orig

When inside a method, the %orig command will call the original method. You can even pass arguments to the command like this %orig(arg1,arg2). One thing to note is, if you don’t call %orig, the original method will never be called. So, if you hook SpringBoard’s init command and fail to call %orig, SpringBoard will never start and your phone will be unusable until you delete your app via ssh.

Hooking Into Springboard

Open up Tweak.xm and add the following code. Don’t worry, I will explain it afterwards.

<code class=’objc’>#import <SpringBoard/SpringBoard.h>

%hook SpringBoard

-(void)applicationDidFinishLaunching:(id)application {
    %orig;
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Welcome" 
        message:@"Welcome to your iPhone Brandon!" 
        delegate:nil 
        cancelButtonTitle:@"Thanks" 
        otherButtonTitles:nil];
    [alert show];
    [alert release];
}

%end</code>

OK, so what’s going on here. First, we import the Springboard.h header. This will allow us access to springboard. Next, we tell the preprocessor to hook into the Springboard class.

The method that we are overriding here is the applicationDidFinishLaunching: method. This will of course fire right when SpringBoard starts up. Notice that we make the %orig call. If we omit this, our phone would never boot up properly as SpringBoard needs it’s initialization method.

Finally, we just throw up a UIAlertView. Again, not too exciting, but you get the point.

Adding Additional Frameworks

If you were to type build to build this project at this point you would see an error like this:

<code class=’bash’>Tweak.xm: In function ‘objc_object* $_ungrouped$SpringBoard$init(SpringBoard*, objc_selector*)’:
Tweak.xm:6: error: declaration of ‘objc_object* self’ shadows a parameter</code>

This is because we depend on the UIKit framework to show alerts. In order to tell theos that we want to link in UIKit, we must create an addition to the Makefile. Add the following line to your Makefile.

<code class=’bash’>WelcomeWagon_FRAMEWORKS = UIKit</code>

This will ensure that UIKit gets linked in.

Building, Packaging, And Installing

In the terminal, cd into your project’s directory. At this point, you can type make to simply build your project. Theos has provided a nice way to automatically install your library on your device. In order for it to work you must have the THEOS_DEVICE_IP environment variable set to your iPhone/iPod’s IP address. This is explained in the previous tutorial.

In the terminal type:

<code class=’bash’>make install</code>

This will build your tweak and install it on your device. When prompted to enter your password, the default is “alpine”. Also, make sure that SSH is installed on your device.

After installation, your device will respring and you will be greeted with your custom message like this:

Jailbroken App Development

Conclusion

You should now have a basic understand of how to patch any method inside of iOS. With this knowledge, you can customize ANYTHING that you don’t like about the device. If you have any questions or comments, feel free to leave them in the comments section of this post.

You can download the source code for this tutorial here.

Happy Jailbreaking!

This post is part of iDevBlogADay, a group of indie iOS development blogs featuring two posts per day. You can keep up with iDevBlogADay through the web site, RSS feed, or Twitter.

10 Great Pixel Art Tutorial And Free Resource Sites For Your Games

I don’t usually create “list” posts, however I wanted to share a grouping of resources I have been collecting over the past few months. As you may have noticed, I’m a bit of a Pixel Art fanatic and wanted to share with you the tutorials that helped to get me started as well as some sites offering some high quality free pixel art.

Keep in mind that some of these sites have similar content, however they all take a slightly different approach in teaching. I found it very helpful to read each of the tutorials and learn from different points of view.

1. Gas 13 – Isometric Pixel Art Tutorial

Pixel House

link

This was my very first pixel art tutorial. I was amazed at how quickly I was able to make a really professional looking pixel art building. I highly recommend all of the tutorials on this guy’s site. Some of them however can be quite complex.

2. Derek Yu – The Pixel Tutorial

Wrestler

link

This was another site that I stumbled upon early on in my pixel art quest. Derek provides a nice story telling approach to teaching the in’s and out’s of pixel art. I really appreciated his tutorial on lines.

3. Mini Wizard Studios – What is ‘Isometric’ pixel art

Sample pixel art

link

This guy offers another dead simple intro to pixel art. Most of it is just explanation, however his examples are quite good. He shows examples of Backgrounds, Characters, objects, tiles, as well as a ton of different UI elements and icons. It’s a great place to go for some inspiration.

4. Hub Pages – How To Start With Pixel Art

Victorian House

link

Again, another great site for the pixel art n00b. This tutorial goes over all of the basics of line, cubes, and texturing. It also links out to other great pixel art tutorials for creating various objects such as a bed, table, and lamp.

5. Bio Rust – Isometric Pixel Art

Pixel Sphere

link

This tutorial is a bit rushed however it provides a great overview for creating other basic shapes besides a cube. In addition to lines and cubes, it demonstrates pyramids, cylinders, and spheres.

6. Oceans Dream – Pixel Art Tutorials

Pixel Character

link

This is the most comprehensive site for pixel art tutorials. While many of them aren’t for the faint of heart, there is some fantastic content here. This site has everything from tips and tricks, to character creation, to breakdowns of existing games. I could spend hours on this site.

7. Pixel Character Tutorial – NekoSoraYagami on Deviant Art

Pixel Character

link

This is a nice in depth tutorial for creating a custom character from start to finish. They start out with a base character (plain, nude, genderless) and turn it into their own creation. Very well written and very fun to follow.

8. City Creator

City Creator

link

The City creator is not so much a tutorial as it is a resource for creating gorgeous pixel cities. It has a nice interface and a huge selection of buildings, objects, roads, signs, and trees to go into your city. I am not sure what their license is on the generated cities, however I didn’t see any clause about not reusing the graphics in your own projects.

9. Has Graphics

Pixel level

link

Has graphics provides tons of free game graphics mostly geared towards tiled games. So, if you are hacking an old school RPG or platformer, I would definitely check out this site.

10. VX Resource Planet

Pixel characters

link

This is the Motherload. I have saved the best for last. This a wordpress blog that contains TONS of free pixel art and tilesets for use in your games. They have endless spritesheets and beautiful tiles that would enable anyone to have a very professional looking game. If you visit one site from this list, visit this one.

Conclusion

If you have any resources of your own, please paste them in the comments. My readers and myself would be very interested in them.

Happy Coding!

This post is part of iDevBlogADay, a group of indie iOS development blogs featuring two posts per day. You can keep up with iDevBlogADay through the web site, RSS feed, or Twitter.

Cocos2D Tutorial – Dynamically Coloring Sprites

Custom Bitizens

Have you ever seen a game (such as Tiny Tower) that contains similar sprites that only vary by certain attributes (coloring, shading, accessories, etc…)? I would often wonder how long it would take the artists to create each permutation of these sprites. After discovering that you can call a method on a CCSprite called setColor, I realized how most of this customization is done in code.

This tutorial will be a continuation of my last post about creating your own Bitizen in Photoshop. So, if you don’t already have a Bitizen character to work with, I suggest you follow that tutorial OR download my template here.

White Out

As I mentioned above, we are going to be using the setColor method of CCSprite to dynamically color each part of our Bitizen. The way it works is each pixel’s color is multiplied by the value passed into setColor giving it a “tint”. So, pixels that are all white will be fully tinted and pixels that are all black will have no change.

So, our first goal is to create an “all white” version of our Bitizen. Don’t worry about shading for now, I will cover that in a moment. I just started with our Bitizen as a base and created new layers for each of the “white” components.

You should end up with 5 new layers:

  • white-head
  • white-skin
  • white-hair
  • white-pants
  • white-shoes

For each layer, trace over the corresponding colored layer. For the “white-skin” layer, make sure to trace over the hands as well as the face. This will ensure that your Bitizen’s color is consistent. When you are done, your Bitizen should look something like this:

White Bitizen

Looks pretty bland… The next step is to add our shading. We will be using only black with varying alpha in order to achieve the desired shading. So, make sure to play with it a bit and get the shading to your liking. Add a new shading layer for each component (or simply draw on top of the current layer with the black pencil).

Your bitizen should look something like this after doing all of the shading:

Shaded Bitzen

Chop It Up

The final thing we need to do with our graphic is chop up the pieces so that they can be individually colored. Convert each of the white-* layers to Smart Objects, copy them to a new document, and save them. You should end up with 5 .png files (head.png,skin.png,hair.png,pants.png,shoes.png).

I increased the size of my Bitizen by 4 before doing this step. You might consider increasing their size as well. Remember that the size increase you choose will change some of the values when we recreate the Bitizen in Cocos2D. So, if you want to follow along, make sure your Bitizen is 60×100 before exporting the various parts.

One thing to note is we are going to bring these into Cocos2D as 5 different sprites. There are some optimizations that you could do using sprite sheets, however I want to make things as clear as possible. So, we are going the long way.

You can download my completed white bitizen here.

Rebuilding The Bitizen In Cocos2D

Once you have imported the 5 Bitizen image files into Cocos2D, you need to reconstruct them in code. This involves adding each sprite to the layer.

Here is the code to display the skin/head+hands in our layer. As a note, I simply created a new Cocos2D project and am using the retina only mode for my display using [director enableRetinaDisplay:YES]. The offsets will change quite a bit if you are choosing to support non-retina.

<code class=’objc’>int spriteX = 240;
int spriteY = 160;

CCSprite *skin = [CCSprite spriteWithFile:@"skin.png"];
[skin setPosition:ccp(spriteX, spriteY)];
[self addChild:skin];</code>

This will draw our white(shaded) head on the screen. That’s pretty boring so let’s draw the rest of the body. Update your code to look like the following:

<code class=’objc’>int spriteX = 240;
int spriteY = 160;

CCSprite *skin = [CCSprite spriteWithFile:@"skin.png"];
[skin setPosition:ccp(spriteX, spriteY)];
[self addChild:skin];

int hairOffset = 11;

CCSprite *hair = [CCSprite spriteWithFile:@"hair.png"];
[hair setPosition:ccp(spriteX, spriteY+hairOffset)];
[self addChild:hair];

int shirtYOffset = -9;
int shirtXOffset = 1;

CCSprite *shirt = [CCSprite spriteWithFile:@"shirt.png"];
[shirt setPosition:ccp(spriteX + shirtXOffset, spriteY+shirtYOffset)];
[self addChild:shirt];

int pantsYOffset = -15;
int pantsXOffset = 1;

CCSprite *pants = [CCSprite spriteWithFile:@"pants.png"];
[pants setPosition:ccp(spriteX + pantsXOffset, spriteY+pantsYOffset)];
[self addChild:pants];

int shoesYOffset = -17;
int shoesXOffset = 1;

CCSprite *shoes = [CCSprite spriteWithFile:@"shoes.png"];
[shoes setPosition:ccp(spriteX + shoesXOffset, spriteY+shoesYOffset)];
[self addChild:shoes];</code>

Now, you should see the lonely ghost of a Bitizen standing in the center of your screen.

Ghost Bitizen

Still boring… Time to spice him up with some color.

Tinting Cocos2D Sprites

As I mentioned before, tinting Cocos2D sprites is very simple. I would recommend keeping all sprites that you wish to tint a shade of white/gray otherwise some crazy things will happen.

The setColor method takes an array of integers from 0-255. This array contains 3 numbers (1st for red, 2nd for green, 3rd for blue). For example, we can pass all Red to the setColor method by sending it {255,0,0}.

Let’s start by tinting our Bitizen’s shirt a random color. Change the code that displays the shirt to look like this:

<code class=’objc’>CCSprite *shirt = [CCSprite spriteWithFile:@"shirt.png"];
[shirt setPosition:ccp(spriteX + shirtXOffset, spriteY+shirtYOffset)];
ccColor3B shirtColor = {arc4random() % 255,arc4random() % 255,arc4random() % 255};
[shirt setColor:shirtColor];
[self addChild:shirt];</code>

Now, every time you run the application, the Bitizen should have a different shirt color. You can apply this principle to each of your sprites to completely customize your Bitizen.

What if you only want to limit certain colors? (you ask). Well, that’s a great question. I solved this by creating an array of ccColor3Bs. Basically an array of arrays. And then I index into this array and set the color accordingly. Here is an example of setting a random skin color to avoid having blue people (unless maybe you are making Smurfs).

<code class=’objc’>ccColor3B skinColors[] = { 
    {247,224,194},
    {255,232,214},
    {136,119,82},
    {245,232,205},
    {144,110,38}
};
CCSprite *skin = [CCSprite spriteWithFile:@"skin.png"];
[skin setPosition:ccp(spriteX, spriteY)];
ccColor3B skinColor = skinColors[arc4random() % 5];
[skin setColor:skinColor];
[self addChild:skin];</code>

I have an array of 5 different arrays and randomly index into it using skinColors[arc4random() % 5]. This will give me a random color within my skin color group.

After running this through a loop and adding random colors to some of the other sprites, I ended up creating the image you see at the top of this post.

Conclusion

I hope that this tutorial has found you well and I have demystified the magic that is dynamic sprites. You may download the source code for this tutorial (include the code to generate the screenshot above) here.

If you have any questions or comments, please feel free to leave them in the comments section of this post. Also, make sure you subscribe to my RSS feed for more great tutorials!

Happy Coding!

This post is part of iDevBlogADay, a group of indie iOS development blogs featuring two posts per day. You can keep up with iDevBlogADay through the web site, RSS feed, or Twitter.

Pixel Art Character Tutorial – Creating And Customizing A Bitizen

This will be a continuation of my last pixel art tutorial about configuring Photoshop for Pixel Art. For the past month or so, both my wife an I have been pretty addicted to this amazing game called Tiny Tower created by Nimble Bits. The biggest draw for me to this game isn’t the fact that it has great simulation style game mechanics, it’s the fact that it was created using Pixel Art.

As I mentioned in my other post, I have a serious passion for pixel art and have been doing everything I can to learn about it and improve my skills. One great thing about it is, anyone can do it. You don’t have to be this amazing artist to be able to create interesting pixel art.

Getting Started

They say that imitation is the best form of flattery, so we are going to flatter the heck out of the Nimble Bits guys are learn how to make our own Bitizen characters from Tiny Tower. I have found that a good starting place for learning pixel art (or anything really), is to start with something that already exists, copy it, then modify it. Once you do that a few times and get comfortable, then you should have the confidence to branch out into creating your own artwork.

When creating a game (or complex piece of pixel artwork) that involves a ton of different characters, it will save a ton of time and energy if you create a “base character”. What I mean by “base character” is one that is very bland and plain. Something that is easily customizable. So, that’s what this tutorial is about, we are going to create a bland white guy for Tiny Tower.

One thing I want to point out before we start is, I have lowered the resolution of the character a bit and am not putting in as much detail as the Nimble Bits team. This is just for simplicity’s sake in order to get my point across and make things easier on you.

New Document

Start out by creating a 15x25px document. I know, it’s very small, but we don’t need much. Make sure you have Photoshop configured for pixel art. At this point, I’d suggest creating all of the layers for your bitizen. Why use layers? you might ask. Great question. Well, in order to quickly modify our base character, we want to have a separate layer for each of his features/body parts. So, create the following layers.

  • Head
  • Mouth
  • Hair
  • Eyes
  • Shirt
  • Pants
  • Feet
  • Arms

Now, you can confidently modify any part of your Bitizen without the risk of destroying the rest. As I reference each part below, make sure you switch to the correct layer when drawing.

Creating The Head

The head is perhaps the most complicated part of the Bitizen due to its odd shape and shading. The shape is due to the fact that the Bitizen is always looking in the forward direction.

Start with a skin tone color (I have used #f7e0c2) and create a 10 x 6 rectangle in the center of your view like this:

Bitizen head

Now, that the base head is in place, it’s time to draw the chin and neck. With the same color, indent one pixel in on the bottom and draw straight across. Finally, indent 3 more pixels in, and draw 4 pixels across. This is what your head should look like at this point.

Head and Chin

Shading

Shading with pixel art is simply a matter of drawing with a darker shade of your main color. With the color chooser in PS and the skin tone still selected, drag the color down to a slightly darker shade and lowlight a 1 pixel line on the right side of the face. In our example the Bitizen is looking to his right, so his left will be shaded.

Then, add some more shading as you see necessary. If you look at mine, I have used a bit of shading to extend the head a little bit.

Head Shading

Hair, Mouth And Eyes

The mouth and eyes are very simple with our Bitizens. The eyes are just single black pixels and the mouth is just a 4 pixel line using a darker shade of the skin tone.

Hair can be whatever you like. I have chosen a very simple hairstyle that you see quite often in the game with a simple shade of brown. I have also applied the same shading technique to the hair that I did to the face and neck. When you are finished, it should really start looking like a person.

Hair and eyes

Creating The Body, Legs and Feet

For the body, start with 6 x 5 rectangle set to the color that you want to make the shirt. I chose #63cfea. For the pants, simply draw a solid line. Finally, the feet are just two 2px lines spread apart by two more pixels. If you notice in the game, to animate the movement of these guys, they simply alternate between this position and a centered 4px line. It just goes to show you how much things can be simplified when you use pixel art.

Body and legs

To finish up our Bitizen, we add single pixel dots for hands and a couple pixels for arms. After that, we add a collar and some simple shading.

Here is what the completed Bitizen looks like:

Completed Bitizen

Conclusion

The one thing to remember when creating pixel art for game is to keep it simple. Simplify everything. Take for example the Toy Story characters I made at the top of this post. They are very simplistic yet you recognize who they are right away. My 2.5 year old son was yelling “Woody! Buzz!” the entire time I was creating them. I think this is one of the largest challenges; sticking to “less is more”.

There are some other fun things we can do to customize these guys. We can even do it in code! Next time, I will show you how to take a “base character” and customize its colors using Cocos 2D. This can save you even more time and energy when trying to make dynamic characters for your game.

If you are feeling lazy and want to simply download my bitizen base, click the following link:

Download my bitizen.psd template

On a final note, don’t just copy these guys for YOUR game! I know it might seem tempting to give em a different shirt and plop them in your super rad fart machine RPG, but these guys are the product of the hard work of the guys at Nimble Bits.

If you have any questions or tips, please feel free to leave them in the comments.

I would also LOVE to see some of the custom bitizens you guys come up with. Please link to them in the comments if you end up creating some.

Happy Coding!

This post is part of iDevBlogADay, a group of indie iOS development blogs featuring two posts per day. You can keep up with iDevBlogADay through the web site, RSS feed, or Twitter.

Configuring Photoshop For Pixel Art

First things first. My wife and I had welcomed a new baby boy into the world on Monday so you guys are going to have to see the obligatory “dad” pics.

Here they are

Jack

Jack

Ok, now that’s past us, let’s chat about pixel art. I have always been a HUGE fan of pixel art both in games and as a form of art. As an aspiring game developer (games coming soon 😉 ), I found pixel art a great fit for me. Not only is is aesthetically pleasing, it also allows developers to create “better” art than developer art. All it takes is a little patience.

Today, I’m going to share with you how I have configured Photoshop to create some pixel art and eventually show you how to make your own Bitizens from Tiny Tower in a follow up post.

Some of you might argue that Photoshop is not the way to go and that there are better tools for Pixel art. I have tried quite a few and keep coming back to PS because of some of it’s great features (shapes, layering, masks, gradients, noise filters, etc…). We can use a lot of these tools to our advantage when creating pixel art, PS just needs to be set up correctly.

Just a heads up before I start, I’m using Adobe Photoshop CS3 for Mac.

Change The Way Photoshop Scales Images

First, we need to change the way PS scales images. This is useful for when you are ready to export your sprites for production. By default, PS uses a Bicubic algorithm when you want to enlarge an image. This generally produces a very blurry effect. It’s quite useful in many cases, but terrible for pixel art. Here, we need to tell PS to use a “Nearest Neighbor” scaling algorithm. This will preserver all of our edges without PS mucking with the blending.

To change this setting, navigate to Photoshop->Preferences->General

Nearest Neighbor

The only setting you need to modify is “Image Interpolation”. Make sure to change it to “Nearest Neighbor”.

Enabling A Grid

When creating pixel art, it is very useful to have a grid in place in order to determine where to place your next pixel. Without it, you are just blindly placing them. To turn on and configure a grid in PS, navigate to Photoshop->Preferences->Guides, Grid, Slices & Count…

1px gridlines

Make sure to set Gridline every to 1 and Subdivisions to 1. This will create a 1px grid on for you to use as a guide.

Once you have configured the grid, click on View->Show->Grid to display it. You might have to do this for every document.

Configuring the Pencil Tool

When creating pixel art in PS, the pencil tool is your best friend. You will use it ~95% of the time when drawing. We need to make sure that the pencil draws single pixel dots without any interpolation. With the pencil tool selected, click the dropdown next to brush, tap the arrow and then select basic brushes. When prompted to replace current brushes, click OK.

Basic Brushes

Next, select the 1 px brush (it should be in the top left). Most of the time, you will want to draw with single pixels.

1 px brush

Creating A New Document

Deciding on a document size can be tricky. You generally want to create your document as small as possible to avoid having to do more work than you need. The size depends on how “pixellated” you want your art to look after scaling. Basically, using the scaling we chose above (nearest neighbor), the “pixels” will just increase in size.

Here is a blown up view of our 15×25 image that we will use in the next tutorial to create a Bitizen from Tiny Tower.

New Document

Since the zoom level isn’t too high, we are seeing grid slices every 2 pixels rather than 1. As you zoom, you will see the grid size increasing.

Multiple Zoom Levels In View

One cool trick with PS is, it allows you to have multiple windows of the same document open. The reason this is handy is you can see various zoom levels for your artwork all at once. While drawing each pixel zoomed in, you can see the result in the desired resolution. This helps out dramatically when you are trying to fine tune your work.

To do this, go to Window->Arrange->New Window for [projectname.psd] Now you can control the zoom level of each window individually.

In the next post, I will go over how to make these Bitizens as well as some tips for customization as an example for creating dynamic characters. We will also go over some of the basic techniques that were used.

If you have any comments, questions, or Photoshop Pixel Art Tips, please feel free to post them in the comments.

Happy coding!

This post is part of iDevBlogADay, a group of indie iOS development blogs featuring two posts per day. You can keep up with iDevBlogADay through the web site, RSS feed, or Twitter.

Announcing iOS 4 In Action + Free Chapter!

Wow, I can’t believe it has been over a year since the release of my book iPhone And iPad In Action. Since then, we have sold over 6,000 copies and have just have released in numerous languages!

As with all iOS (tech books really), my book was almost outdated the moment it hit the shelves due to Apple’s constant SDK release cycle. My book ended with “here is what’s coming in iOS 4…”, and didn’t hit the shelves until after iOS 4 was released.

I was asked last year by Manning Publishing to write the 3rd version of the book to include all of the 4.0 SDK changes. Due to some huge changes in my life, I was unable to accept and they had to find the 4th author to work on the book.

Earlier this month, Jocelyn Harrington released the 3rd version of the book titled “iOS 4 In Action”. Here is a bit about this version from their site.

Written for Xcode 4, iOS 4 in Action guides you from setting up your development environment,
through coding your first app, all the way to selling in the App Store. Work through sample
applications including a chat client, a video game, an interactive map, background audio,
and more as you explore the iOS 4 SDK.

Here are some highlights about what’s inside.

  • Full coverage of iOS SDK 4.3
  • Mastering Xcode 4
  • Multitasking for iPhone and iPad
  • Game Center, iAd, and AirPrint
  • Local and push notification
  • Implementing in-app purchasing

This is a significant update and I’m really excited to get my copies in the mail. As soon as I do so, I’ll do a couple giveaways on my blog. Make sure you stick around or subscribe to the RSS feed so you don’t miss it!

Freebie

Manning is allowing anyone to download the full Chapter 21 on multitasking now for free! Go grab your copy!

Happy Coding!

This post is part of iDevBlogADay, a group of indie iOS development blogs featuring two posts per day. You can keep up with iDevBlogADay through the web site, RSS feed, or Twitter.

Autonomous Steering Behaviors In Corona SDK Games

Wow, it’s already been 5 months since I was last blogging for #iDevBlogADay. The time has flown by!

Recently, I have been dabbling with [Corona SDK][1] and have been getting really excited about the possibilities. For those of you who don’t know, Corona SDK is a multi platform game engine that allows you to write your code in Lua and deploy on iOS and Android devices.

Today I want to chat with you about Autonomous Steering Behaviors and show you how I have implemented a few of them in a small game that I’m working on.

Here is a short demo video of what we will be creating


Boids Demo from Brandon Trebitowski on Vimeo.

</center>

What Are Autonomous Steering Behaviors

The name does sound pretty fancy. At the core they are just behaviors that define how a character interacts with the world around them in a life-like manner. Some of the main behaviors include wandering, path following, flocking, pursing and evading. The theory and algorithms for all of these behaviors and more can be found in a paper published by Craig Reynolds in the 80’s called Steering Behaviors For Autonomous Characters.

While I admit I didn’t quite read all of it, the paper contains some incredible gems in terms of making your character AI seem much more life like.

There are plenty of examples (especially in games) where these behaviors come in handy. Perhaps the easiest behavior to implement is wander. Say for example you have an NPC (non player character) that walks around a village. The wander algorithm is a perfect fit to make it seem like that NPC is actually “thinking” about where he’s going and keeps your animations looking smooth.

The seek and evade is another interesting algorithm. Often times in our games, we want enemies to chase after us without it seeming like they have the exact shortest path to use. It adds a bit of randomness and makes your enemies seem much more realistic.

How Can I Use Them In My Corona SDK Game?

After doing a bit of research, I found this incredible site by daniel shiffman that detailed some of the algorithms using processing. This at least took the words from the paper and made them in to some code. I really suggest that you read up on that page to get a solid understanding of what we are doing here. Rather than simply regurgitating what Daniel wrote, I’m going to focus on showing you how his code can be ported for use in your Corona SDK games.

The first challenge was, the code relies heavily on using 2D vectors. Now, I didn’t see a nice built-in way to do this in Corona or Lua for that matter. So I decided to roll my own Vector2D class. For those Corona SDK veterans reading this, feel free to blast me in the comments if I’m reinventing the wheel with this and just failed to fully read the documentation. Otherwise, enjoy this Vector2D class!

Here is the link to the gist containing that file.

Here is a short snippet of that class just to add to the aesthetics of this post:

<code class=’lua’>function Vector2D:new(x, y)  – The constructor
  local object = { x = x, y = y }
  setmetatable(object, { __index = Vector2D })  – Inheritance
  return object
end

function Vector2D:normalize()
    local temp
    temp = self:magnitude()
    if temp > 0 then
        self.x = self.x / temp
        self.y = self.y / temp
    end
end

function Vector2D:dot(vec)
    return self.x * vec.x + self.y * vec.y
end</code>

Basically it’s a lua “object” that has an x and y with some helper methods for doing vector math. The lower case methods act on the current self object and the upper case methods act as static class level methods meant to return a new vector. The file is a little sloppy but it gets the job done.

Creating A Boid

In the paper, an autonomous character is called a Boid. There are basically 2 actions that we need to implement that are needed in most of the behaviors. They are steer and seek. Steer is the basis for all of the autonomous behaviors. Given a Vector2D as the target, it will return a new Vector2D for the boid’s acceleration in the direction of the target. We simply wrap this call in the seek method. Now, any behavior can call seek in order to direct the boid towards a target.

Here is a link to our Boid on github

A snippet of the wander function

<code class=’lua’>function Boid:wander()
    local wanderR = 16.0
    local wanderD = 60.0
    local change  = 0.5

    local negChange = math.random(2)
    local randomNum = math.random() * change
    if negChange == 2 then
        self.wanderTheta = self.wanderTheta - randomNum
    else 
        self.wanderTheta = self.wanderTheta + randomNum
    end 

    local circleLoc = self.vel:copy()

    circleLoc:normalize() 
    circleLoc:mult(wanderD)
    circleLoc:add(self.loc)

    local circleOffset = Vector2D:new(wanderR*math.cos(self.wanderTheta), 
        wanderR*math.sin(self.wanderTheta))
    local target = circleLoc:copy()
    target:add(circleOffset)

    self.acc:add(self:steer(target))
end</code>

What I have done is taken the code from Daniel Shiffman’s processing project and ported it directly to lua. As of right now, I have only implemented wander, however you can see how easy it is to implement other behaviors using the same techniques. Since Daniel has processing code for each of them, it’s a simple matter of making them work in your lua class.

The way wander works is, it picks random points on a circle to steer towards. These random points only vary by a fraction of a radian (defined by the change variable above) from the current steer point. The larger the change value is, the more your boid will appear jittery. This value must be tweaked to fit the wander style for your game. Based on my testing, .5 seems to generate a pretty smooth wander path.

Putting It All Together

In your own code you might want to build directly on top of my boid class or subclass it for each boid type. In the following example, I’m going to show you how to simply run our boid class and watch some dots wander around (hang on to your hats).

Here is a link to main.lua on github, but I have also pasted it here so we can talk about it.

<code class=’lua’>local Boid = require(‘Boid’)

– Define some limiting constants
MAX_FORCE = 1.75
MAX_SPEED = 2.0

local wanderers = {}

function animate(event) 
    for i=1,#wanderers do
        local wanderer = wanderers[i]
        wanderer:wander()
        wanderer:run()
    end
end

function Main()
    math.randomseed( os.time() )
    
    for i=1,10 do
        local loc = Vector2D:new(display.contentWidth / 2,display.contentWidth / 2)
        local wanderer = Boid:new(loc,MAX_FORCE,MAX_SPEED)
        table.insert(wanderers,wanderer)
    end
    
    Runtime:addEventListener( "enterFrame", animate );
end

Main()</code>

Here we declare an array of wanderers. In the Main() method we initialize each one, insert them into the array, and add a hook to call our animate method for each frame. Inside of the animate method, we simply tell each wanderer to wander and then run itself. The boid class will take care of the rest.

One thing to note is, the boids are unaware of each other at this time. That requires a cohesion method. I have it written and might post it up at a later time; I just want to keep things simple for now. Please feel free to ask me questions in the comments or write me on Twitter.

You can download or fork the full source for this project here.

Happy Coding!

This post is part of iDevBlogADay, a group of indie iOS development blogs featuring two posts per day. You can keep up with iDevBlogADay through the web site, RSS feed, or Twitter.

[1]: http://www.anscamobile.com/corona/

Check Out AutoCorrector + Promo Codes!

So, this blog post might sound like a lame press release, but I actually do want to talk about a cool app some buddies of mine created. Just read it in a cheesy used car salesman voice and it will be a lot less more enjoyable.

The Problem

Have you ever tried to type shorthand text to a friend and it come out completely wrong? For example: AFK -> AFT, AKA -> Aja. Or maybe your friend has an uncommon nickname that auto corrects to something hilarious…

Enter AutoCorrector

@cruffenach , @matt_tuzzolo , and @damian_r just released an app for the iPhone called AutoCorrector! It’s an app that allows you add words to your iPhone’s auto correct dictionary. Once added, the iPhone will stop pestering you to auto correct uncommon/shorthand words that you frequently type.

How It Works

Adding words directly to the dictionary would be against the Apple SDK terms of use as it would require your app to run outside of it’s “sandbox”. However, clever @cruffenach realized that when you add comma separated words to a contact’s nickname in the address book, they get added automatically to the iPhone’s dictionary.

This actually makes a lot of sense when you think about it. If you have a friend with a nickname, chances are you will want to address that person at some point by that nickname. It would get very annoying if you iPhone tried to autocorrect you every time you tried to type that friend’s name.

Auto corrector simply uses the AddressBook framework to maintain a contact with a nickname containing a list of words you have added. When you add a new word, it simply updates this contact.

Why Use Auto Corrector?

Sure you could just do this manually, however it’s a pain and requires too many steps (6 taps vs. 2 taps for AC). Also, auto corrector provides a beautiful interface for entering and managing words you have added.

Word Packs!
Bundled with AC, comes the SMS shorthand word pack with 116 words ready to install instantly. In the near future, the guys plan on creating a ton more word packs as well as provide a portal for community packs.

I’m pretty excited about this app and really think it has a good future.

Download it here

What do you think? Would/did you buy it?

Edit
Here are some promo codes!

4YMPYNFJEWNE
MY6FTY49M4F6
H9KYWH9J4YPY
XW4EXHM67R34
AR6JN3RJYFE6

Beginning Jailbroken iOS Development – Building And Deployment

Welcome to the next installment of my jailbroken iOS development series. If you haven’t already done so, read my previous post to get up to speed.

Beginning Jailbroken iOS Development – Getting The Tools

Now that your environment has been set up, it’s time to start hacking your project, building, and deploying it. This tutorial will be fairly quick and will just demonstrate how to build a .deb file and install it on your device. This will not cover creating a Cydia repository for public access (this is for a later tutorial).

Introduction

Start by creating a simple project. Refer to the previous tutorial to determine how to do this. I will use the example of the #1 iphone/application and will be calling it fooProject.

<code class=’bash’>$/opt/theos/bin/nic.pl
NIC 1.0 - New Instance Creator
——————————
  [1.] iphone/application
  [2.] iphone/library
  [3.] iphone/preference_bundle
  [4.] iphone/tool
  [5.] iphone/tweak
Choose a Template (required): 1
Project Name (required): fooProject
Package Name [com.yourcompany.fooproject]:    
Author/Maintainer Name [Brandon Trebitowski]: 
Instantiating iphone/application in fooproject/…
Done.</code>

This will create a new directory for our project with the following files.

  1. control: Contains information about your application/tweak. This is the info you see when you install something from Cydia (name, author, version, etc…)
  2. [applicationName]Application.mm: This is essentially your appDelegate file. It creates a window, adds your RootViewController and displays it.
  3. main.m : Same main file that you would use in an iPhone project. Just initializes your [applicationName]Application.mm file on launch.
  4. Makefile: contains the necessary build commands to compile your project. I’ll go over this in detail in a bit
  5. Resources: This folder contains your info.plist and is also where you can place all of your images
  6. RootViewController.h/mm: A simple view controller

The Makefile

theos provides some great tools that simplify the build process as much as possible. I know some of you might shudder at the sound of a Makefile, but trust me, it’s very painless.

Let’s first take a look at the anatomy of the Makefile that was generated.

<code class=’bash’>include theos/makefiles/common.mk</code>

This line simply tells theos to include the common make commands in your build script to save you some work.

<code class=’bash’>APPLICATION_NAME = fooProject</code>

The name of the application we are building. The Makefile will use this constant to do a number of things under the hood. Don’t modify this unless your application changes names.

<code class=’bash’>[applicationName]_FILES = main.m fooProjectApplication.mm RootViewController.mm</code>

This is the meat of the Makefile. It’s the list of m (or mm in this case) files that need to be compiled. *Note: you do not add your .h files here. So, whenever you add a new .m file to the project, make sure to append it to this list or it won’t get built.

<code class=’bash’>[applicationName]_FRAMEWORKS = UIKit Foundation QuartzCore AudioToolbox CoreGraphics</code>

This line is not included by default, but is needed if you want to use ANY frameworks; be them Apple’s or h4x0red ones.

<code class=’bash’>include $(THEOS_MAKE_PATH)/application.mk</code>

More defaults to help theos build your project.

Setting up Your Environment

Do you remember in the last tutorial that we had to set an environment variable in order to use theos? Well, we need to set a couple more to build and deploy.

Here are the 3 that you MUST have.

<code class=’bash’>export THEOS=/opt/theos/
export SDKVERSION=4.3
export THEOS_DEVICE_IP=192.168.1.122</code>

The first line, you should have already done. Otherwise you would not have been able to run the nic tool above. The second defines your current SDK version. This will tell theos where to look for your frameworks and whatnot. (ex If you only have 4.2 installed, set this to 4.2). Finally, the last line, tells theos the ip address of your device.

Once theos does the package install, it will sftp the package to your device for installation. One thing to note here is your iPhone MUST be on the same network as the computer you are developing on.

If you don’t know your device’s ip address, it’s in the SBSettings menu. If you don’t have SBSettings, go download it from Cydia and think about why you would have a jailbroken device without this app installed…

 

Building The Project

Building is just as easy as running the make command inside of your project’s root directory.

Here is an example of building my fooProject app using the command:

make.

<code class=’bash’>$ make
Making all for application fooProject…
 Compiling main.m…
 Compiling fooProjectApplication.mm…
 Compiling RootViewController.mm…
 Linking application fooProject…
 Stripping fooProject…
 Signing fooProject…</code>

If your project contains errors, they will be flushed out here. Also, theos treats warnings as errors (as should you) 😉 . So, if you have any warnings you won’t be able to build.

When you are ready to distribute your application, you must build a .deb package. Luckily, theos does this for us with a simple command:

make package.

<code class=’bash’>make package
Making all for application fooProject…
make[2]: Nothing to be done for ‘internal-application-compile’.
Making stage for application fooProject…
 Copying resource directories into the application wrapper…
dpkg-deb: building package ‘com.yourcompany.fooproject’ in ‘/Users/brandontreb/Desktop/fooproject/com.yourcompany.fooproject_0.0.1-1_iphoneos-arm.deb’.</code>

You should now see a file like com.yourcompany.fooproject_0.0.1-1_iphoneos-arm.deb in your project’s root directory. One great feature of theos is it handles versioning automatically. So subsequent builds will increment the build number. If you change your version in the info.plist file, it will start the build counter over (2-1, 2-2, etc…).

At this point, you could sftp this file to your device and run:

<code class=’bash’>dpkg -i com.yourcompany.fooproject_0.0.1-1_iphoneos-arm.deb</code>

as root to test the installation. However, that is quite a bit of a pain. Luckily, theos will do all of this for you by simply using the command:

make package install

<code class=’bash’>$ make package install
Making all for application fooProject…
make[2]: Nothing to be done for `internal-application-compile’.
Making stage for application fooProject…
 Copying resource directories into the application wrapper…
dpkg-deb: building package ‘com.yourcompany.fooproject’ in ‘/Users/brandontreb/Desktop/fooproject/com.yourcompany.fooproject_0.0.1-3_iphoneos-arm.deb’.
install.copyFile "/Users/brandontreb/Desktop/fooproject/com.yourcompany.fooproject_0.0.1-3_iphoneos-arm.deb" "com.yourcompany.fooproject_0.0.1-3_iphoneos-arm.deb"
root@192.168.1.122’s password: 
com.yourcompany.fooproject_0.0.1-3_iphoneos-arm.deb                                                                                                                                                                                                                              100% 4434     4.3KB/s   00:00    
install.exec "dpkg -i com.yourcompany.fooproject_0.0.1-3_iphoneos-arm.deb"
root@192.168.1.122’s password: 
Selecting previously deselected package com.yourcompany.fooproject.
(Reading database … 2006 files and directories currently installed.)
Unpacking com.yourcompany.fooproject (from com.yourcompany.fooproject_0.0.1-3_iphoneos-arm.deb) …
Setting up com.yourcompany.fooproject (0.0.1-3) …</code>

You will have to enter your password several times during the process. The default is alpine.

After this has been run, you will need to restart (or respring) your iPhone. Respringing takes a simple button tap if you have SBSettings installed (have you installed it yet?).

Conclusion

You now have all of the tools needed to start hacking your very first jailbroken iOS application. In the next tutorial, we are going to learn about MobileSubstrate hacks and how to overwrite Apple functionality. I will give a basic example of how to display an alert message every time your device boots up.

Until next time, happy hacking!

Half Off iPhone And Android Books From Manning Publishing Today

Last year I wrote the second edition of [iPhone and iPad In Action][1]. It was published by [Manning Publishing][2] and today they are offering half off all of their mobile software development books!

Simply use the code:

dotd0414

when you check out at [manning.com][3] for a half price discount on the following titles:

    </p>
  • <a style="FONT-STYLE: italic; COLOR: #727272; TEXT-DECORATION: none" href="http://www.manning.com/trebitowski/" shape=rect track="on" linktype="link">iPhone and iPad in Action That’s mine!</a>
  • <a style="FONT-STYLE: italic; COLOR: #727272; TEXT-DECORATION: none" href="http://www.manning.com/jharrington/" shape=rect track="on" linktype="link">iOS 4 in Action</a>
  • <a style="FONT-STYLE: italic; COLOR: #727272; TEXT-DECORATION: none" href="http://www.manning.com/cahill/" shape=rect track="on" linktype="link">iPhone in Practice</a>
  • <a style="FONT-STYLE: italic; COLOR: #727272; TEXT-DECORATION: none" href="http://www.manning.com/collins/" shape=rect track="on" linktype="link">Android in practice</a>
  • <a style="FONT-STYLE: italic; COLOR: #727272; TEXT-DECORATION: none" href="http://www.manning.com/franco/" shape=rect track="on" linktype="link">Hello! iPhone</a>
  • <a style="FONT-STYLE: italic; COLOR: #727272; TEXT-DECORATION: none" href="http://www.manning.com/crawford/" shape=rect track="on" linktype="link">iPad in Practice</a>
  • <a style="FONT-STYLE: italic; COLOR: #727272; TEXT-DECORATION: none" href="http://www.manning.com/harwani/" shape=rect track="on" linktype="link">Quick & Easy iPhone Programming</a>
  • <a style="FONT-STYLE: italic; COLOR: #727272; TEXT-DECORATION: none" href="http://www.manning.com/ableson2/" shape=rect track="on" linktype="link">Android in Action, Second Edition</a>
  • Location-Aware Applications 
  • Objective-C Fundamentals 
  • Sencha Touch in Action 
  • Windows Phone 7 in Action 
  • </span></ul>

    This deal is only available for today April 14th, so go right now…

    [1]: http://manning.com/trebitowski [2]: http://manning.com/ [3]: http://manning.com

My Journey To Create The inPulseNotifier For Jailbroken iPhones – Part 2

This post is a continuation from my previous post found here.

A MobileSubstrate Tweak?

After I completed a basic app that allowed me to send various notification types from my iPhone to my inPulse watch, I quickly realized that this would not work if I wanted to hook into the iPhone’s notification system. A Google search revealed to me that I had to make MobileSubstrate hack to overwrite the default notification functionally.

** What the heck is Mobile Substrate? **

Here is the description according to iPhoneDevWiki.net.

MobileSubstrate is the de facto framework that allows 3rd-party developers to provide run-time
patches (“MobileSubstrate extensions”) to system functions, similar to Application Enhancer on
the OS X. MobileSubstrate consists of 3 major components: MobileHooker, MobileLoader and safe mode.

Basically, it allows you to “hook” into any method of any class on the iPhone. I will talk in a later tutorial about how to see what methods are available. Here is a sample for hooking into the CFShow() method:

<code class=’objc’>static void (*original_CFShow)(CFTypeRef obj);  // a function pointer to store the original CFShow().
void replaced_CFShow(CFTypeRef obj) {           // our replacement of CFShow().
  printf("Calling original CFShow(%p)…", obj);
  original_CFShow(obj);                         // calls the original CFShow.
  printf(" done.\n");
}
…
// hook CFShow to our own implementation.
MSHookFunction(CFShow, replaced_CFShow, &original_CFShow);
// From now on any call to CFShow will pass through replaced_CFShow first.
…
CFShow(CFSTR("test"));</code>

Yeah… this looks pretty intense. Luckily, I found a super helpful tool that greatly simplifies this process called theos. Check out my tutorial on getting started with theos.

What lead me to theos was the incredible work of Peter Hajas. He wrote and open sourced his fantastic notifications app called Mobile Notifier. Without it, I would have been dead in the water. After chatting downloading his code and nagging him on Twitter, he pointed me to theos.

Working With theos

As I mentioned in my tutorial, theos is a great tool to aid in the development of a Mobile Substrate Tweak. Instead of the complexities above to hook into the functionality of classes, you simply do something like this:

<code class=’objc’>%hook SpringBoard

-(void)applicationDidFinishLaunching:(id)application
{    
    %orig;

    INPreferenceManager *preferenceManager = [[[INPreferenceManager alloc] init] autorelease];
    BOOL enabled = [[preferenceManager.preferences valueForKey:@"inpulseEnabled"] boolValue];
    if(enabled) {
        manager = [[INAlertManager alloc] init];
        [manager connectToWatch];
    }
}

- (void) dealloc {
    [manager release];
    manager = nil;
    %orig;
}

%end;</code>

This is a simple hook that allows me to overwrite the functionality of Springboard’s applicationDidFinishLaunching method. DHowett (creator of theos), has done a brilliant job giving devs quite a few commands like %orig (which calls the original method) and %hook (starts a hook).

The reason this works is, the file you code in (called Tweaks.xm) gets run through a preprocessor called Logos (which he also wrote). It replaces these simple commands with the complex stuff you see above before compiling your project. Using this technique, you can hook into anything. I will have a tutorial on this in the very near future, so make sure you subscribe to my RSS feed if you haven’t already.

Copy And Paste

OK, so I copied some of Peter’s code (he’s well cited in the source and I kept his license in the headers too). He had already solved the problem of capturing most of the iPhone’s notifications and this is precisely what I needed. So I Frankensteined my code and his to create the first version of inPulseNotifier.

This current version supports SMS, Push Notifications, Local Notifications, and Calendar Notifications.

Deployment

Even though I open sourced the code for the app, I couldn’t possibly expect users to build the code themselves and install it on their devices. So I had to learn about setting up my own Cydia repository.

A Cydia repository allows users to browse your applications/tweaks through the Cydia application created by Saurik. This is the method of choice for deploying jailbroken iPhone applications.

Saurik has a very detailed tutorial on creating a Cydia repository here.

(In case you are wondering, my Cydia repo is hosted at http://brandontreb.com/cydia )

OK, How Do I Install It?

Great question I assume you might ask. I have written a tutorial about installing it on your iPhone here.

Plans For The Future

Well, at the moment development has slowed as I prepare for a few changes in my life. However, in the coming months, I intend on doing the following updates.

  1. Remove the dependency on Insomnia for preventing the phone from sleeping. I have found a version of their source that I can integrate into my own code.
  2. Add support for phone calls
  3. Add support for emails
  4. Create an SBSettings toggle to allow rapid enabling/disabling
  5. Auto-reconnect after disconnecting from the watch

Conclusion

Hacking for the inPulse watch has been a new and exciting experience. The team over there has really created something special and I can’t wait to see what the future holds for them (hopefully a touchscreen).

I’d love to hear your thoughts in the comments. And stay tuned for some jailbroken dev tutorials based on my experiences.

Happy Coding!

My Journey To Create The inPulseNotifier For Jailbroken iPhones – Part 1

Many of you may have seen my tweets or blog posts regarding my development of a native iOS interface for the inPulse Watch. I just wanted to share a bit with you about the development process and talk about my updates moving forward.

What is the inPulse Watch?

For those of you who don’t know, the inPulse watch is a programmable wristwatch with a bluetooth controller. It can run a single app at a time on top of it’s firmware that is installed on the watch via a bluetooth interface with your computer. People have written all sorts of apps from analog clocks to roguelikes and Connway’s Game of Life. Check out http://inpulsewatch.com/watchapps.asp to see the latest apps.





&nbsp

</p>

It Begins

After waiting about 10 days for my watch (yeah it’s a long waiting period since they have seen quite a bit of recent success), it finally came in the mail. Enthusiastically, I opened it up and followed their getting started guide. Within a few minutes I was running some of the sample applications in the forums.

No iOS Support?

One of the coolest features of the watch is the ability to have your smartphone notifications show up on it. You are able to read SMS, Email, Calendar, etc… for a wide variety of Blackberry and Android phones.

After digging around a bit, I was disappointed to see that there was limited (no) iPhone support. They had some old file that used BTStack at some point to communicate a simple canned message to the iPhone. No documentation, no support, nada.

Building The App

As I had no experience developing for a jailbroken iPhone, I had no idea how to even compile this sample app. So, I used the Google machine and found the Google repository for BTStack (the bluetooth library of choice for jailbroken iOS apps). I was able to download the source and build a sample application that basically connected my iPhone to a bluetooth device.

Well, this got me started. So I did what any curious developer would do and started plugging crap in. I replaced the sample file that was packaged with BTStack with a slightly modified version of inPulse’s sample iPhone file. Sure enough, I was able to build and install it.

We Have Connection

After figuring out how to hardcode my watch’s address into the source, I was able to determine that the iPhone had actually connected to the watch. I monitored the packets and threw up an alert view (No NSLogging available at this point) when a connection was made.

So, now that we are connected, let’s trying sending the sample message…fail! I couldn’t even send the time.

At this point, I decided to move the code I had written into a sample iPhone project so that I could do attached debugging. This showed me that the packets were arriving on the watch since I received an ack packet back. So, the watch sees the messages, but doesn’t consider them notifications.

Time to hit the docs


Knowing that the packets were received gave me quite a bit of hope. I figured that I must have had the protocol incorrect. So, I dug into the inPulse protocol document which outlined what the packet structures should look like. My C skills aren’t the strongest so I had to look up quite a few things.

Sure enough, they had upped the version number of their protocol by 1 and mine was outdated. So, I updated what I could and gave it another shot…fail.

No messages were displaying. At this point I was ready to give up. I read online somewhere that the BT implementation on the watch was not supported by inPulse and felt dead in the water. So I took a break for a couple days.

When I came back to it, I was tapping through my watch and noticed that the calendar appointments had some data in them on the watch. Could it be? Did my notifications arrive? (I was trying to send SMS notifications). So I dug into the docs again…

We have a message!!!

Sure enough, I had some fields declared as * uint16_t * when they should have been * uint8_t * . My headers were the wrong size!!! All of a sudden I was able to send every type of notification to the watch and have it displayed.

It was now time to build out an actual application for release to inPulse. The next hurdle would be hooking into the iPhone’s messaging system and forwarding along the messages. Now the real iPhone hacking begins.

This post is continued here

Beginning Jailbroken iOS Development – Getting The Tools

Developing for jailbroken is actually quite similar to regular iOS development with one addition. More Power! oh oh oh (said in a Tim Taylor voice (sorry for non-Americans that don’t get the reference)). With your device jailbroken, you have the ability to hook in to pretty much every class that Apple writes allowing you quite a bit of control over the iPhone’s functionality.

In today’s tutorial, I will simply be discussing the best way to get up and running with the tools necessary to write a jailbroken iPhone app. We will not be doing any coding, however this tutorial will be necessary for all posts going forward.

Theos

There are many ways to go about writing a jailbroken iOS app. Most of them are quite complex. @DHowett has come up with a brilliant tool called theos which drastically simplifies the process. My tutorial will pretty much be a regurgitation of his tutorial found here with some added cheesy jokes.

Theos is a command line utility that essentially generates a template for creating applications, libraries, preference bundles, tools, and mobile substrate hacks. These cover 99% of the jailbroken apps that you are likely to create.

One thing to note is DHowett talks about doing jailbroken iOS development on both Mac and Linux; my tutorials will be Mac-only.

Step 1: Install the iOS SDK

You will first need to install the official iOS SDK.

http://developer.apple.com/devcenter/ios/index.action

You can register for a free account and download the latest SDK. Once installed reboot your Mac and come back here. I’ll wait…

Step 2: Setting Up The Environment Variables

Start by deciding on a good location to install theos. The suggested location is /opt/theos. The only issue with doing it here is you will need to have administrator permissions as well as have to enter your password when updating files. For teaching purposes, I am going to assume you will install it here too.

Open the terminal and type:

<code class=’bash’>export THEOS=/opt/theos</code>

What we are doing is setting an environment variable. You can always see if this variable is set by typing echo $THEOS in the command line. It will need to be (re)set every time you reopen the terminal to develop a jailbroken app.

Step 3: Getting theos

DHowett uses subversion for version control on theos, so you need to make sure and have it installed. If you followed step one above, it should have been installed by default. We will be checking out theos into the THEOS directory specified in step 2.

In the terminal type:

<code class=’bash’>svn co http://svn.howett.net/svn/theos/trunk $THEOS</code>

You most likely will be asked for your password. You should now see the /opt/theos directory created with theos installed.

Step 4: Getting ldid

We now need to install the ldid tool. ldid is a tool written by Saurik (if you don’t know who he is, stop reading now). Basically, it simulates the signing process for the iPhone, allowing you to install your jailbroken apps/hacks on an actual device.

You can find this tool in many places, however DHowett has generously hosted it for us on his dropbox account.

Now, I had a tricky time getting this to download directly to my /opt/theos folder. So, I downloaded it to my desktop and then moved it in to /opt/theos/bin/ldid

<code class=’bash’>curl -s http://dl.dropbox.com/u/3157793/ldid > ~/Desktop/ldid
chmod +x ~/Desktop/ldid
mv ~/Desktop/ldid $THEOS/bin/ldid</code>

Alternatively, if you can get it to work properly, do it like DHowett suggests and download it directly into place.

<code class=’bash’>curl -s http://dl.dropbox.com/u/3157793/ldid > $THEOS/bin/ldid; chmod +x $THEOS/bin/ldid</code>

Step 5: Install dpkg

Dpkg is a tool to bundle up your app into a Debian package for distribution in a Cydia repository. You can install it through Macports.

<code class=’bash’>sudo port install dpkg</code>

Step 6: Creating A New Project

theos uses a tool called nic (new instance creator) to create a new project. Simply run nic by typing:

<code class=’bash’>$THEOS/bin/nic.pl</code>

and it starts the new instance creator. Here is a sample of making a jailbroken application.

<code class=’bash’>brandon-trebitowskis-macbook-pro:Desktop brandontreb$ $THEOS/bin/nic.pl
NIC 1.0 - New Instance Creator
——————————
  [1.] iphone/application
  [2.] iphone/library
  [3.] iphone/preference_bundle
  [4.] iphone/tool
  [5.] iphone/tweak
Choose a Template (required): 1
Project Name (required): FartLight
Package Name [com.yourcompany.fartlight]: com.brandontreb.fartlight
Author/Maintainer Name [Brandon Trebitowski]: 
Instantiating iphone/application in fartlight/…
Done.</code>

This will create a new folder with a basic template called fartlight (killer project, I know). In addition to the usual files it will contain a Makefile (for building the application) and a control file (information about the application when it’s in a Cydia repository).

This should now give you the basis for creating a jailbroken application/tweak/hack. In the next tutorial we will go over building, signing, and deployment. For now, you can check out the project I created with nic called inPulseNotifier. It’s a combination of a tweak (5) and a preference bundle (3) for the app settings.

Feel free to ask me a question in the comments and check out #theos on IRC.

Update Check out the next tutorial in this series here.

Happy coding!

Jailbroken iPhone Development – Would You Be Into It?

As of recent I have had a ton of interest in doing development for Jailbroken iPhones. I love the power, being able to hack anything on the device. It opens up a whole new world of possibilities.

My most current project (inPulseNotifier) is a Mobile Substrate hack which allows the iPhone to interface with an inPulse watch. It uses BTStack and boots up during the init method of your springboard. I will do a full writeup on this in the near future, but basically it forwards all of your phone’s notifications (SMS, Local, Push, Calendar) to your watch!

Serious Lack Of Resources

InPulseNotifier was a blast to create, however I found it incredibly challenging to find many resources about doing jailbroken development. I finally found theos which was a total lifesaver. Also, I had the code for mobileNotifier to follow along with.

IRC (yeah I’m a true hacker ;)) was also huge help, but there simply aren’t enough tutorials/examples on the web related to jailbroken iPhone dev. My guesses are either 1. it’s quite hard, 2. there’s not enough <font color”green”>$$$</font> in it, or 3. jailbreakers like to stay “underground”.

I haven’t quite figured it out, but I was curious what YOU thought about it as I’m considering doing some jailbroken iOS development tutorials on my blog. Please let me know in the comments. Are you down to “Hack the planet”?

Officially Running On Jekyll

Well, I have finally made the switch from WordPress to Jekyll and couldn’t be happier. Here are some of the bonuses I have seen thus far.

  1. SPEED: Just click around on my site. It is screaming fast now.
  2. Resources: Checking top on my server reveals that I have a TON of extra resources (which makes sense since Jekyll sites are way more lightweight).
  3. Ease of blogging: Ok, WordPress was pretty easy too, however, I was really starting to get sick of the post interface. I switch to Tumblr at some point simply for it’s minimalist interface. WordPress’ is gross and TinyMCE (the WYSIWG editor) is terrible. I love writing in TextMate!
  4. Offline publishing. I can write my posts anywhere since they are just .md (markdown) files. Check out Daring Fireball’s great writeup on this.
  5. Portability: Have you have tried to move your WordPress site? Yeah, it’s about as fun as chewing on tin foil with metal fillings.
  6. Focus on content: WordPress has quite a bit of focus on using rich media in your posts which tends to take away from the content if you are not careful. There is something about writing in a text editor that makes you forget about images/video/etc… unless it’s totally needed. So don’t be surprised if my posts aren’t as “rich”. (Hopefully they will be more clever :) )

I really urge you to see for yourself what it’s like blogging with Jekyll. I will do a writeup on my conversion process in the near future to help aid others in the switch. Until then, you can google around and find tons of great resources.