Objective-C Blocks

Lately, I have been playing with Objective-C blocks.

These are easy to use constructs that enable defining functions “on the fly” when programming in Objective-C and are very similar to Python’s lambdas.

The syntax might look a little weird at first, but it is not that different from working with function pointers in C.

Here’s a simple example of a function f that receives a block b as a parameter and calls it. The only restriction imposed on b by f is that it must be a block that takes an int argument and returns an int.

#include <stdio.h>

// f is a function that receives a block:
void f(int (^b)(int))
{
	b(0); //call the block
}

int main(int argc, char* argv[])
{
	// Define and pass a block to f():
	f(^(int p){ printf("%d\n", p); return 0; });

	return 0;
}

The output of this program is just the int supplied by f to the block b.

Let’s try a more interesting example. Here, as inspired by this post, we use blocks to define a general-purpose for_each function that receives a list of objects and a block and then applies the block on each element of the list.

In order to define a general-purpose for_each function, we take advantage of Objective-C’s dynamic typing and name our types id.

void for_each(NSArray* array, void (^b)(id))
{
	for (id obj in array)
	{
		b(obj);
	}
}

Now, let’s develop a short program to test the for_each. This program creates a list of strings and uses the for_each function to output all of its contents.

int main(int argc, char* argv[])
{
	// Default autorelease pool:
	NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
	
	// Create an array. The contents could be anything,
	// as long as the block can handle them:
	NSArray* array = 
	[NSArray arrayWithObjects:@"a", @"b", @"c", @"d", @"e", nil];

	// Print every string instance:
	for_each(array, 
		^(id str){ printf("%s\n", [str UTF8String]); });

	[pool release];
	
	return 0;
}

Suppose now that we wanted to print out strings in uppercase. No problem, we can keep all the same structure, we just need to change the block:

	for_each(array, 
		^(id str){ 
			printf("%s\n", [[str uppercaseString] UTF8String]); 
		});

So, what happens if we place an object of a type different from a NSString instance in the array? Well, the for_each is very general and doesn’t know anything about the array’s elements or the block’s internals. Thus, if there is a problem, it will be triggered inside the block code.

Imagine we attempt to send uppercaseString to an object that does not recognize that message. If this happens, an error will be triggered at runtime and abort() will be called, canceling our program.

As we move into dynamic coding, the code becomes more flexible, but we must be more careful not to trigger runtime errors in our programs. It’s important that we develop our blocks to be consistent with our data structures.

Exploring the Android NDK

I have been testing the Android development tools. From what I have learned, the tools are separated into two main products: the Android Software Development Kit (SDK) and the Android Native Development Kit (NDK).

The SDK was the first development toolkit for Android, and it only allowed applications to be written using the Java programming language. The NDK was released some time later as a toolchain to enable developers to write parts of their applications using native programming languages (C and C++).

One of the first programs I developed to get a feeling of what the Android SDK looked like was an OpenGL ES App that painted the background using a color degrade. I wrote it a couple of months ago, but today was the first time I ran it on a real Android device.

The resulting image can be seen in the following picture:

Android OpenGL ES Test

Other than trying the SDK, what I really wanted to do was to experience how hard it would be to rewrite part of the App in C and then having both integrated. It turns out adding components built using the NDK is not very hard (for pure C code), so I decided to try moving all the rendering code to a plain C function.

I started a new project and coded all the rendering logic in a C function that I called “render“. Then, the NDK was used to compile the C code into a JNI-compliant shared library and, finally, I wrote a simple Java wrapper that calls into the shared library’s render function to do all the drawing.

The wrapper is responsible for creating the Android “Activity”, setting up an OpenGL ES context, and calling the native C function. The native C function clears the background and does all the drawing.

Getting all the JNI requirements in place in order to have the Java runtime recognize the native library and call a native method was not too hard, but it was not trivial either. It is definitely much more complicated that calling native libraries from Objective-C or even Python. After a few tries, the bond was made:

Android OpenGL ES rendering from C code.

Clearly this is a very simple example where the C code could be tailored to fit JNI’s requirements from the start. I expect porting an existing C++ codebase to be much more difficult. However, I am looking forward to continue delving into Android’s development tools.

An Angel with Generated Normals

Sometimes the 3D models we have to display provide no information other than vertex data for the triangles they define.

This might be enough to approximate the shape of the object, but having no normal data, we are severely limited if we want to apply realistic lighting on the object’s surface. Without lighting and textures, it’s very hard to depict the 3D shape of objects.

Angel without Normals

An Angel Model lit but with no Normal Data.

To help solve this problem, Vortex now provides a simple Normal generation algorithm that “deduces” smooth per-vertex normals from the geometric configuration of the 3D model. The results are nothing short of astonishing.

Angel with Generated Normals

The same Angel Model lit after Normal data was generated automatically by Vortex.

Normal generation does come at a cost, however. The 3D model depicted in the figures above is composed of 237,018 vertices shared among 474,048 triangles.

In order to produce smooth normals, the generation algorithm must study the triangle adjacency for every vertex and produce exactly one normal for every one.

On the machine the algorithm was developed, a Core 2 Duo @ 2.66 GHz with 4GB of RAM and for the Angel model, this process takes about 841.334 seconds, that is about 14 minutes!

The good news is that given a model, its Normals only need to be generated once. Once the application has the normal data, it can cache it and reuse it every time the model is to be added to a scene, avoiding the computation time altogether.

This gives the developer the opportunity to generate all Normal data offline and then having it attached to the model at runtime.

The Angel model was downloaded from: http://www.cc.gatech.edu/projects/large_models/angel.html

Brief Introduction to Objective-C

Objective-C is a superset of the C programming language that adds object-oriented constructs. Unlike C++, which was influenced by Simula, Objective-C was influenced by Smalltalk, something we can definitely see in its braces syntax.

Just like C, Objective-C keeps the tradition of separating the source code in two files: a header that defines an interface (.h) and a source file that provides the implementation of said interfaces (.m).

Contrary to popular belief, you do not need a computer running Mac OS X to develop Objective-C programs. The GNUstep project is an open source implementation of the OpenStep reference that provides a basic runtime environment and an implementation of part of the library, including Strings, Arrays and Dictionaries. GNUstep is available for Linux, other UNIX-based OSs and even Windows.

Here’s a short example that defines a 2D point structure with two operations: initialize from a given pair of (x,y) coordinates and printing to stdout.

#import <Foundation/Foundation.h>

@interface Point2D : NSObject
{
	float x;
	float y;
}

- (id) initWithX:(float)xval andY:(float)yval;
- (void) print;

@end

Now, we implement this interface in its own file:


#import "point2d.h"
#include <stdio.h>

@implementation Point2D

- (id) initWithX:(float)xval andY:(float)yval;
{
	self = [super init];
	if (self)
	{
		x = xval;
		y = yval;
	}
	return self;
}

- (void) print
{
	printf("(%.2f, %.2f)\n", x, y);
}

@end

Finally, let me show you how to instantiate and send messages to a Point2D object.

#import "point2d.h"
int main()
{
	NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

	Point2D* p = [[Point2D alloc] initWithX:1.0f andY:2.0f];

	[p print];
	[p release];

	[pool release];
	return 0;
}

Although the Autorelease pool was not really necessary, it is a good practice to have one in place.

If you are trying this example on a Mac, then it’s relatively simple to get it to compile and run. Using GNUstep it gets a little harder however. Here’s a simple Makefile for building this application:

CC=gcc -x objective-c

CFLAGS=-I$(GNUSTEP_HOME)/Local/Library/Headers/ -Wall
LDFLAGS=-L$(GNUSTEP_HOME)/Local/Library/Libraries/ -lgnustep-base

all:
	$(CC) $(CFLAGS) $(LDFLAGS) main.m