Saturday, January 26, 2008

Building a Cocoa Calculator Application with XCode 3 for Mac (Part 1)

As promised, for you avid Mac lovers out there wanting to churn out some software of your own, I present you with my latest screencast showing how to build a calculator very similar to the calculator widget that comes with Mac. This tutorial incorporates the XCode 3 IDE, the Cocoa Framework, Objective-C (well really not until the next part of the series), and Interface Builder 3 (the primary focus of this first screencast).

With some snazzy editing and practice runs, I've managed to condense this large lump of knowledge down to approximately 3 minutes of guns blazing glory. Okay, maybe not guns blazing, but you get the point.



The next part in the series will go over the concepts of actions and outlets and how to set those up for this calculator application. In other words, we'll be setting up event handling to make this lovely interface shine (a.k.a respond).

Saturday, January 19, 2008

Encrypting & Decrypting on the Mac - Video Screencast

I recently picked up some software for producing screencasts for the Mac. I was eager to produce a blog post more "hands on" for my visitors, so pardon the amateur first attempt. As with most things, these will improve with practice!

The following video goes over tools provided by the Gnu Privacy Guard (GPG), namely GPG Drop Thing and GPG File Tool. These tools enable users to encrypt and decrypt information. I wanted to put together this little gem because most of the time whenever I run into someone and start talking about encrypted emails being the "wave of the future" due to privacy concerns (or should I say violations?), most people get the "deer in the headlights" look - I usually try to settle their nerves by exclaiming just how simple encryption can be for the end user, but most of the time I get the "suuuuuuuure" vibe :) On with the show!



Wednesday, January 16, 2008

C# Generics Performance Gain Benchmarks

Some of my readers may recall an earlier post I made (http://strainthebrain.blogspot.com/2007/12/c-generics-performance-gain-not-so-fast.html), talking about the lack of performance I was seeing during some testing with generics. Thanks to a reader, the mystery was clarified. When testing out generics, make sure that the data type you're declaring is a value type, not a reference type! If you need clarification on which are which (I can admit I did), refer here for value types and here for reference types.

I have put together some revised code, as well as implemented a better mechanism for benchmarking code execution performance using the diagnostics stopwatch.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace GenericsPerformance
{
    class Program
    {
        static void Main(string[] args)
        {
            int intVal = 0;
            string strVal = "";

            //Generics Test-------------------------------------------------------
            System.Diagnostics.Stopwatch genericSW = new System.Diagnostics.Stopwatch();

            genericSW.Start();
            Stack<int> genStack = new Stack<int>();
            for (int i = 0; i < 1000000; i++)
                genStack.Push(i);
            for (int i = 0; i < 1000000; i++)
                intVal = genStack.Pop();
            genericSW.Stop();

            Console.WriteLine("Generics (using int): {0} ms", genericSW.ElapsedMilliseconds);
            //--------------------------------------------------------------------

            //Non-generics Test---------------------------------------------------
            System.Diagnostics.Stopwatch nongenericSW = new System.Diagnostics.Stopwatch();

            nongenericSW.Start();
            Stack nonGenStack = new Stack();
            for (int i = 0; i < 1000000; i++)
                nonGenStack.Push(i);
            for (int i = 0; i < 1000000; i++)
                intVal = (int)nonGenStack.Pop();
            nongenericSW.Stop();

            Console.WriteLine("Non-Generics (using int): {0} ms", nongenericSW.ElapsedMilliseconds);
            //--------------------------------------------------------------------

            //Generics Test-------------------------------------------------------
            System.Diagnostics.Stopwatch genericSW2 = new System.Diagnostics.Stopwatch();

            genericSW2.Start();
            Stack<string> genStack2 = new Stack<string>();
            for (int i = 0; i < 1000000; i++)
                genStack2.Push(i.ToString());
            for (int i = 0; i < 1000000; i++)
                strVal = genStack2.Pop();
            genericSW2.Stop();

            Console.WriteLine("Generics (using string): {0} ms", genericSW2.ElapsedMilliseconds);
            //--------------------------------------------------------------------

            //Non-generics Test---------------------------------------------------
            System.Diagnostics.Stopwatch nongenericSW2 = new System.Diagnostics.Stopwatch();

            nongenericSW2.Start();
            Stack nonGenStack2 = new Stack();
            for (int i = 0; i < 1000000; i++)
                nonGenStack2.Push(i.ToString());
            for (int i = 0; i < 1000000; i++)
                strVal = (string)nonGenStack2.Pop();
            nongenericSW2.Stop();

            Console.WriteLine("Non-Generics (using string): {0} ms", nongenericSW2.ElapsedMilliseconds);
            //--------------------------------------------------------------------

            Console.ReadLine();
        }
    }
}
While the results varied slightly each run, I will show you 3 separate runs of this program. You'll notice that I first show Generics vs. Non-generics using a value type of int (this SHOULD perform better). I then show Generics vs. Non-generics using a reference type of string (Microsoft makes no claim on performance gain in this instance).

Run 1 Result:
Generics (using int): 49 ms
Non-Generics (using int): 212 ms
Generics (using string): 911 ms
Non-Generics (using string): 912 ms
Run 2 Result:
Generics (using int): 50 ms
Non-Generics (using int): 230 ms
Generics (using string): 935 ms
Non-Generics (using string): 944 ms
Run 3 Result:
Generics (using int): 50 ms
Non-Generics (using int): 212 ms
Generics (using string): 899 ms
Non-Generics (using string): 908 ms
As can be seen, generics using appropriate value types (such as int) show a dramatically improved performance gain, whereas generics using reference types (such as string) only perform slightly better than their non-generic counterpart.

Saturday, January 12, 2008

Objective-C using the Cocoa Framework - Part 1

Having picked up an iMac this past Christmas, I've been eager to dive into the opposing world of Mac development. I spend the majority of my time in the workplace developing using C# with the .NET framework.

I spent some time first poking around the net, looking for the best free integrated development environments (IDE) I could find for the Mac OS X Leopard platform. Before you say it, yes yes, there's always vi(m), emacs, pico, etc. While I am a fairly large proponent of vim, I was still curious what else was out there. I took a look around the XCode IDE and was thoroughly impressed with the apparent plethora of project types that could be crafted, however I soon realized I needed to resort to simpler editors first if I really wanted to "understand" some of the new languages and frameworks before letting an IDE do all the mysterious work for me behind the scenes. After digging around further I came across Smultron. Great little light-weight app that suits my needs just perfectly for coding.

For those coming from the .NET arena, wanting to sample the goods on this side of the fence, let me present you with my little analogy that helped me keep things straight. C# is to .NET as Objective-C is to Cocoa. We are dealing with languages and frameworks containing lots of useful libraries.

While this example isn't completely original, I have made sufficient enough changes and additions to warrant considering this equally informative to that of other beginner examples of the language and framework. I make no claims to be an expert with Objective-C nor the Cocoa framework, so there may be more efficient ways to perform certain tasks.

We're going to deal with a simple "Fractions" example from your most basic element of math. Say we wanted to craft our very own Fraction object.

Fraction.h
#import <Foundation/NSObject.h>

@interface Fraction: NSObject
{
    int numerator;
    int denominator;
}

-(void) print;
-(void) set_Numerator: (int) n Denominator: (int) d;
-(int) get_Numerator;
-(int) get_Denominator;
@end
Fraction.m
#import <stdio.h>
#import "Fraction.h"

@implementation Fraction
// ------------------------------------------------------
-(void) print 
{
    printf("%i/%i%c", numerator, denominator, '\n');
}

// ------------------------------------------------------
-(void) set_Numerator: (int) n Denominator: (int) d
{
    numerator = n;
    denominator = d;
}
// ------------------------------------------------------
-(int) get_Denominator 
{
    return denominator;
}
// ------------------------------------------------------
-(int) get_Numerator 
{
    return numerator;
}
// ------------------------------------------------------
@end
main.m
#import <stdio.h>
#import "Fraction.h"

int main(int argc, const char *argv[]) 
{
    // Allocate and initialize a Fraction object for use
    Fraction *fraction1 = [[Fraction alloc] init];

    // Call our set_Numerator:Denominator function, passing both parameters
    [fraction1 set_Numerator:3 Denominator:4];
    
    // Display our results
    printf("Our Numerator: %i%c", [fraction1 get_Numerator], '\n');
    printf("Our Denominator: %i%c", [fraction1 get_Denominator], '\n');
    printf("Our Complete Fraction: ");
    [fraction1 print];

    // Release all of our claimed memory
    [fraction1 release];
}
The first thing to point out here is that the implementation files for Objective-C end in ".m" rather than ".c", as you might expect. With that being said, if you have a background in C/C++, this basic structure will look very familiar - a header file depicting the API interface, an implementation file depicting the actual code for each method/function for that class, and a main driver file for controlling the flow of our program.

An additional difference I immediately noticed with the language was the numerous instances of "[..]" notation. This is basically the way method/function calls are made in Objective-C, however they are referred to more as "sending messages". You'll notice I provided a couple different examples above, some calling functions without passing any parameters (print) and other calls passing multiple parameters (set_Numerator:Denominator).

You may be asking yourself about now, okay great, I have the complete source to get me started on a simple example, but since you didn't use XCode, how on earth do I compile this thing? Is it just like C/C++? My answer, pretty darn close! After some trial and error, here's the magic command I use for compiling:
gcc -x objective-c -framework Foundation -lobjc main.m Fraction.m
If all goes well, you should see output precisely like this (including the line to execute the program):
$ ./a.out
Our Numerator: 3
Our Denominator: 4
Our Complete Fraction: 3/4
I plan on creating a gradually more complex series of examples over time, so stay tuned!

Saturday, January 5, 2008

Facial Morphing & Animation Using the Free Software - MorphX

I stumbled across this nifty little freeware the other week and finally got around to giving it a try. For those of you who haven't tried morphing software before, the basic concept is to create a before and after photo, and tell the software to morph or tween between the two to make them seamlessly transform.

For this little demo, I took a couple webcam shots with some interesting effects and plopped those down for the before and after shots. I took care to try and keep my head in relatively the same position between the shots. This would likely make the transitions that much more believable.

I took a screenshot of the process of setting up the morph below. You'll notice there is a dotted bright green (and blue where selected) line hovering over my face. The idea is to click near key features on the before image. Once complete, pressing enter would carry over that same line pattern to the after image. From here you would simply adjust the vertices as necessary to maintain the key point landmark positions.



There's a built in preview feature to help you make sure your morphing sequence is looking good. Once you're happy, you can either render the image sequence to several files or you can choose to render to movie (quicktime). In my case, I rendered to quicktime and then took the movie into iMovie to further play with it, including your basic title screens as well as frame reversal effects and slow-motion :)

video

A really cool way of extending my example would be to daisy chain several facial morphs back to back. You could for example take photos from your entire life and morph from one to the next chronologically, showing gradual age progression! The possibilities are abundant and the software is free, so have fun!