brandontreb.com Tips And Resources For Software Consultants

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.

Considering Leaving WordPress For Jekyll

So, after my 6 year relationship with WordPress, I have been having some strong feelings for another (blog engine). Jekyll does everything that I want my wordpress to do.

  1. Not suck at security
  2. Not be bloated
  3. Not have a sucky post editor
  4. Expense – I have a few blogs hosted on Rackspace and my bill has gotten pretty pricey. I’m hoping to host my Jekyll site on App Engine for frizzle (free).

That’s about it. In case you live in a box (which most of us do since most houses are relatively square) and haven’t hear of it, Jekyll is a new blogging engine written in Ruby. Simply put, you write posts, run a command and it spits out static pages. You just upload these pages to your server (how old skool right?) Now you no longer have a dependancies on any server side language, fancy server configs, etc…

Jekyll has no(minimal) features, no comments, track backs etc… and no built-in SEO. It doesn’t even have an admin (since you are serving up static content). Sounds like a blast right? I’ll blog a bit about it as I make the migration and you will see, it’s going to be great!

I just finished reading this post from Hacker News, which was pretty much the nail in the coffin.

Huge Update To Smart Lockscreen Creator + Promo Codes

I have just updated Smart Lockscreen Creator and am giving away 10 copies!

Download It Here

I know you probably aren’t reading this as you race to see if any of the promos aren’t taken but…

Here is what’s new:

Misc

  • Added ability to generate a new image on startup. Just turn Auto-Start on in the settings

Weather

  • Toggle Fahrenheit and Celsius
  • Added missing weather images
  • Updated weather icons
  • Improved performance and stability of retrieving weather

Customization

  • Customize separator color and height
  • Customize which day of the week to highlight for a calendar
  • Ability to customize the background color of each widget

Minor Bug Fixes

The Promo Codes

METL6KNXW6TL
TWFHLKT7RYWK
J6JXJ7JPNJRN
XLP9FF9RAEA9
L74ATPTYXJ4F
A6KJPTLWE97P
HNWP6L7F6JW9
XEHNFKJPMR6Y
MFH3MNHKXF3A
FENRH4M9PAEA

Please leave a 5 star review :)

Download It Here

Free App Idea: Drop Tunes

Perhaps this already exists, if so, please link me to it.

The idea
Drop music into your Dropbox folder on your computer. Then open up the app which presents you with an iPod like interface for this music.

The genius
What’s great about it is, you have all of you music on your iPhone without using up disk space. Of course you may need to upgrade your Dropbox account to something greater than 2GBs to see any real value.

Smart Lockscreen Creator Released + Promo Codes

My latest iOS app, Smart Lockscreen Creator has just released on iPhone for $.99.

Download It Here

The Idea

Currently your lockscreen on your iOS device is nothing more than a pretty watch with a background. Jailbreakers have solved this issue with an incredible application called intelliscreen, which adds lots of interesting information to it. However, you and I are Apple fanboys and won’t violate our precious iPhones with jailbreaking. Enter Smart Lockscreen Creator.

Smart Lockscreen Creator allows you to build a completely custom (and smart) lockscreen image within the application. You then set this image as your lockscreen background. The following items are currently supported by the app.

  • Current weather, condition, high and low for any city/region in the World
  • Weekly forecast for any city/region in the World
  • Monthly calendar
  • Custom text
  • Blank space (useful when customizing the look of your lockscreen)
  • Line separator
  • Many more in the works!

Here are some promo codes. If you fail to grab one and have some interest in reviewing the app on your site, I would be happy to email you one.

FMP9LRW4FP99
MH7XHH3FLH4P
JH9E47JXP9KA
RYRAPRARPAJ3
4FKKW6LN7W9J
If you have any suggestion for lockscreen “widgets”, don’t hesitate to post them here.
Please give some review love as well 😉

Albuquerque Marathon Training

Well, I have finally decided to put my money where my mouth is when it comes to fitness and train up for a half marathon! The marathon I’m training for is the Albuquerque Half Marathon on Saturday, April 16th at 8 am (that logo is such an eyesore).

Two months seems like a relatively short time to prepare, especially for my first “real” run, however I am just aiming to finish rather than being competitive. Right now, I am running about 3-4 miles per day with a longer day of ~5 miles. As the weeks pass, I intend on upping that to ~5 miles/day with a longer run at about 10 miles.

If any of you are training for something similar, I would love any advice, feedback, criticism, encouragement, stories, etc… that you have. Just post em in the comments.

Also, for those of you who are on nike+, please befriend me. My username is (you guessed it) brandontreb.

I’m very excited about this goal and will be blogging along the way (amidst my other coding related posts of course).

It’s a long road ahead 😉

Tweet Press 3.2 Update – Sidebar Widget

I have recently had an overwhelming number of requests for a sidebar widget that displays your recent Tweetpress photos. Well, it’s finally here! The update was actually quite trivial to make. If I had known how simple it would be, I would have made it months ago.

Make sure you update to the latest version: tweetpress 3.2

How to use it
In the WordPress admin, click on Appearance and the Widgets from the sidebar menu. If your theme supports widgets (which is should), you will see a Tweetpress widget in the available widgets list.

Next drag that widget into the sidebar area and modify the settings.

You can configure the title of the widget as well as the number of photos to be displayed. Please comment here or shoot me an email if you experience any issues with it. I’m also open to suggestions.

It’s Elementary My Dear Watson

IBM's Watson on Jeopardy

Last night marked the beginning of the IBM Jeopardy challenge. For those of you who don’t know, IBM has been working for some time on a system (named Watson) that has overcome some amazing challenges. The goal: to build an entirely self-contained system that can beat the World’s best Jeopardy players.

Now, I’m not going to give you a rundown on it as I’m sure that you can (or have already) read it on a website far more popular than mine. I just wanted to publicly geek out for a second…

I was watching the episode of Jeopardy with my wife, and at first glance she was like “duh, of course a computer could win at Jeopardy”. This made me realize that to a non engineer, this seems like a trivial task since computers are magical Facebook boxes.

Now me on the other hand, I was giddy to the point of almost wetting myself. Seeing how far we have come in AI development and language processing is absolutely incredible.

I for one, will be glued to my tv tonight to watch Watson’s next round of Jeopardy.

Case Of The Mondays

Mondays…

The other day, I was faced with an interesting programming challenge and wanted to share my solution. I just submitted a pretty interesting app to the app store that does a number of things (more details soon). Among those things is the ability to generate a calendar.

The Problem

Generating the calendar was the easy part, however when displayed, I wanted it to highlight every Monday of the month. This turned out to be a bit trickier than I imagined.

Really the main challenge here was to determine which day contained the first Monday of the month. After that, we just loop incrementing by 7 and are done.

Looking At The Date Helpers

Looking at what I had to work with in NSDate, NSCalendar, and NSDateComponents, I really found only 2 things that could help me. From NSDateComponents, I could figure out the current day (numeric) and the current day of the week (numeric). Knowing this information was very important.

The Solution

Having the current day and day of the week allowed me to find the date of the Monday on the current week. This was the first challenge as demonstrated below. Assume weekdayComponents is the NSDateComponents generated from the current date.

<code class=’objc’>NSInteger weekday = [weekdayComponents weekday];
NSInteger day         = [weekdayComponents day];

// First, find how many days we are from Monday
int daysAwayFromMonday = weekday - 2;

// Now resolve the monday of this week
int mondayThisWeek = day - daysAwayFromMonday;

// Check if monday this week falls in last month
if(mondayThisWeek <= 0) {
    mondayThisWeek = day + (7 - daysAwayFromMonday);
}</code>

mondayThisWeek will now contain the day number of the Monday of the current week. If that Monday falls on the previous month, mondayThisWeek will be negative. Line 12 resolves that by carrying it into next week.

Finally, we just loop subtracting 7 from that Monday until mondayThisWeek is less than 7 to get the first Monday of the month.

<code class=’objc’>while(mondayThisWeek > 7) {
    mondayThisWeek -= 7;
}</code>

And there you have it. mondayThisWeek (improperly named at this point) will contain the day number of the first Monday for the current month.

So, this was quite a round-a-bout way to find this value. If you have a better solution, please feel free to trash on mine in the comments 😉 .

Farewell (For Now) iDevBlogADay

Hey guys,

I wanted to thank everyone for letting me be a part of the iDevBlogADay community. You guys have been super supportive and I really appreciate all of the commenting, retweeting, and upvoting of my iDevBlogADay articles.

I have found myself in a position with life (work + family) where I may no longer be able to consistently write a post per week. So, after 2 months of writing, it is time for me to pass the torch to the next blogger on the list.

I will still continue to blog (and continue my Twitter For Mac Series), so I really encourage you to subscribe to my RSS feed (or Twitter feed).

Thanks again and Happy Coding!

AppBlogger: A Tool For iOS App Developers And Bloggers

Imagine that you have just found the coolest app in the world and just can’t wait to tell all of your followers about it. So, you head to the admin panel of your blogging engine (hopefully WordPress) and begin to write your review. Now, you want to insert some screenshots, icons, descriptions, app store links, etc… So, what do you do? You head on over to Bing and type in google.com. Next, you search your app name and hopefully find the iTunes URL so that you can slowly grab some information about the app. #Fail

Dum duh dum duh (trumpet noises)!

Enter AppBlogger. AppBlogger is a little tool that I have been working on that uses “Instant Search” technology (jquery fanciness) to allow you to instantly search the app store and quickly get the information you need.

How Does It Work? (you say)

As you start typing, AppBlogger makes an asynchronous request to the iTunes web service and pulls a list of applications that match your search terms. This list is presented as a bunch of icons. You will then click on one of these icons to pull of the details page of that application.

The details page (see above screenshot) then contains everything you need to write a stellar blog post about that application. It provides text fields (for easy copy and paste) with icon URLs, download URL, and screenshot URLs.

I have some plans to integrate this in the near future with my Link Share tool to auto generate shortened URLs that contain your affiliate code (so you can make $). If you have any other suggestions for it, I would love to hear them.

I know many of you are heartbroken and were expecting the next iteration of my Twitter Client For Mac series. I want you to know, you are not forgotten and I will continue the series next Thursday. So Stay Tuned!

Check out AppBlogger!

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.

Image Manipulation: Retrieving And Updating Pixel Values For A UIImage

Grayscale Jobs

With the recent success of cool photo manipulation apps such as Camera+ and Instagram, it got me wondering. How do these photo apps modify the pixel data of the image.

After doing a bit of research on the subject, I found countless posts on Stack Overflow and the Developer forums about various methods to get and set the pixel values of a UIImage. Most of them unanswered or partially answered. I tested out many solutions and banged my head on my computer into the whee hours of the morning with no success. Every solution I tried seemed to completely destroy the image.

It wasn’t until this morning, I had an “aha” moment, changed one line of code and was able to produce a grayscale version of a UIImage.

Having the ability to get and set pixel values of a UIImage is super important if you want to create a photo related app that has “Filters”. Once you know the basics, you can apply your ninja math skillz to implement cool filter algorithms on the pixels. Below, I will show you onc such algorithm for converting an image to grayscale (it’s not that clever).

I should note, that a good majority of my code comes from Olie’s solution on this Stack Overflow post. His example simply returns and array of UIColor objects for a given image. Mine will modify those colors and write them back to a UIImage.

Converting A UIImage Into A Pixel Array

Here is the first part of our grayscale method. It is creating a char array from a global UIImage property named workingImage.

<code class=’objc’>- (IBAction) grayscale:(id) sender {
    CGContextRef ctx;
    CGImageRef imageRef = [self.workingImage CGImage];
    NSUInteger width = CGImageGetWidth(imageRef);
    NSUInteger height = CGImageGetHeight(imageRef);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    unsigned char *rawData = malloc(height * width * 4);
    NSUInteger bytesPerPixel = 4;
    NSUInteger bytesPerRow = bytesPerPixel * width;
    NSUInteger bitsPerComponent = 8;
    CGContextRef context = CGBitmapContextCreate(rawData, width, height,
    bitsPerComponent, bytesPerRow, colorSpace,
    kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(colorSpace);

    CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
    CGContextRelease(context);
    .
    .
    .</code>

This is a lot of Core Graphics fanciness that isn’t super important to understand. It’s just getting the RGBA values from the image and writing them into the rawData char array. There are 4 bytes per pixel (red, green, blue, alpha), so this array contains 4 * height * width elements.

Modifying The Pixels of a UIImage

Here is where the magic happens. You can replace this code with the logic necessary to apply the filter you are making. Another clever way to approach this would be to pass this code in as a block into the method (I’ll leave that as an exercise for the reader :)).

<code class=’objc’>.
.
.
    int byteIndex = 0;
    for (int ii = 0 ; ii < width * height ; ++ii)
    {
    int outputColor = (rawData[byteIndex] + rawData[byteIndex+1] +
        rawData[byteIndex+2]) / 3;

    rawData[byteIndex] = (char) (outputColor);
    rawData[byteIndex+1] = (char) (outputColor);
    rawData[byteIndex+2] = (char) (outputColor);

        byteIndex += 4;
    }

.
.
.</code>

The first part is pretty straight forward, we have a for loop that goes from 0 to width * height. We index into the rawData array using a counter that we increment by 4 each time (remember 4 bytes per pixel). As you can imagine, the first pixel (rawData[byteIndex]) represents the red pixel, then green for +1, blue for +2, and finally alpha for +3. Note that the alpha byte is last because kCGImageAlphaPremultipliedLast flag above.

In order to do grayscale, we simple set all of the color values to the average color value. So, for example the color [218,232,244] (which is the light blue color of the WordPress editor’s toolbar) would be converted to [231,231,231] which is a fairly light gray color.

The most important step that everyone in the forums seemed to miss was casting the new value to a char. Remember we are using a char array, setting ints as values will generally screw up your image. (This was my “aha” moment that I mentioned above)

Writing The Pixels Back To a UIImage

The final step is to write the pixel data back to a UIImage. Again, I borrowed some of this code from somewhere else and unfortunately lost the link. If I find it, I will update the post.

<code class=’objc’>.
.
.
    ctx = CGBitmapContextCreate(rawData,
        CGImageGetWidth( imageRef ),
        CGImageGetHeight( imageRef ),
        8,
        CGImageGetBytesPerRow( imageRef ),
        CGImageGetColorSpace( imageRef ),
        kCGImageAlphaPremultipliedLast ); 

    imageRef = CGBitmapContextCreateImage (ctx);
    UIImage* rawImage = [UIImage imageWithCGImage:imageRef];  

    CGContextRelease(ctx);  

    self.workingImage = rawImage;  

    free(rawData);
}</code>

All we are doing here is creating a new Bitmap Context, writing it to our CGImageRef and constructing a new UIImage from that CGImageRef. Finally, we just update our workingImage with the modified one. Fancy, I know…

Now, much of this code is to work with my example (download below), but it could easily be tweaked to fit within your super awesome photo app. If you have any questions or comments PLEASE leave them here or send them to me on Twitter (but probably leave them here 😉 ).

Download The Sample Source Project

  • Note on the sample code: Before you give me crap about doing this in the main thread, I know. Don’t do these operation on the main thread. The example is meant to be quick and dirty and by no means is ready for production. Enjoy!

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.