More of a programming nerd than is strictly healthy. See also {nevyn.nu, thirdcog.eu, twitter}

Projects

Overooped

Updated my Mac Frameworks page with GLEW 1.5.0.

Properly bundling .frameworks in your application package

Update: My blog post on @rpath supersedes/complements this post (it’s not finished yet, though).



I’m sure you’ve run into it. You build your app and it works fine, but when you distribute it, your users get:

Library not loaded: /Users/Richard/Library/Frameworks/libmng.framework/Versions/A/libmng
  Referenced from: /Users/nevyn/Downloads/Sphere-Mac RC3/SphereEngine.app/Contents/MacOS/SphereEngine
  Reason: image not found

One more time. This subject seems to pop up quite often, but I think I’ve finally gotten it nailed. Before I used to fetch the sources of all the libraries I was using, set up an .xcodeproj and set install_name to “@executable_path/../Frameworks/” (and that I did here). That’s not really necessary, and not possible for non-open source frameworks. So, no matter what framework or library you have, this is how you bundle it anyway, no matter what the install_name is.

  1. Add an extra Copy Files target action in your XCode project (and rename it Copy Frameworks)
  2. Get info on the new terget action, and set its destination to Frameworks.
  3. Then, drag all custom frameworks to this target action, and they will be automatically bundled with the application when you build.
  4. You will now need to gather some information. Run `otool -L on YourApp.app/Contents/MacOS/YourApp` and note its output for each of the lines corresponding to a framework you just bundled.
  5. Next, add a Shell Script target action. This target action will call the install_name_tool to rewrite the linking information in the built binary to reference the bundled frameworks instead, even if the frameworks haven’t been built with an install_name of @executable_path/../Frameworks. Copy and modify as appropriate:
function relocateLibraryInCurrentApp() {
  install_name_tool -change $1$2 @executable_path/../Frameworks/$2 $CONFIGURATION_BUILD_DIR/$EXECUTABLE_PATH
}

relocateLibraryInCurrentApp /usr/local/lib/ libfmodex.dylib #note the space
relocateLibraryInCurrentApp /Library/Frameworks/ Foobar.framework/Versions/A/Foobar #note the space
Note the two different styles for a loose dylib and for a .framework. Just add one relocateLibraryInCurrentApp for each library or framework you’re bundling. Good luck!


Addendum: I realized that making a post that just describes how to do something, not why, is kind of lame.

In Mac OS, each binary contains a list of paths to binaries which it was linked to and which need to be loaded for all code to be available. When you launch an app, the runtime will thus load the app’s code, and for each library it needs to find will try to load it from the path set in the app’s binary. (For frameworks it’ll also look in /System/Library/Frameworks and /Library/Frameworks). What install_name_tool does is simply to rewrite that path inside the binary given as the fourth argument, searching exactly for the string argument #2, and change it to argument #3.

Additional resources:

Weekend Hacking

I had a lot to do this weekend and decided to do none of it, and instead ported sfxr to Cocoa, with a native UI and proper save/load :) My version’s called cfxr (as in “Cocoa sfxr”) and is available at http://thirdcog.eu/apps/cfxr . I’m not saying it’s better than sfxr, only different and more native. If you’ve got a 10.5 Mac, check it out and let me know what you think :) It’s basically just an experiment to learn Core Data and Bindings (Thanks, Scott!), and a reason to make save/load work better on the Mac.

The sfxr code (more specifically, the sdl port), when I first saw it, seemed like the worst mess I’ve ever seen. Sure, it’s a quick hack, but not even keeping state in a struct? OMG. But after working with this code for a weekend, it’s surprisingly good for what it is! “Porting” it to Cocoa was as easy as finding out which globals were properties of the sound (that is, attributes), and adding “sound.” before all accesses to those, and #defining objc syntax as C syntax for the four major playback methods. I guess I could’ve #defined the sound attribute accesses as well, making an upgrade as easy as a copy-paste, but I felt I had already done enough code generation for one day :P (Check out the legacyAccessors.m in the source to see what I mean :P Not very good looking code but it got the job done.)

It’s a rough 0.1 and might need some work. I was also thinking about making the playback part an AudioUnit or VST (just for fun) to make the playback more flexible. It works pretty nice as it is though, so do check it out :)

Not sure why Core Audio isn’t an Objective C API

It’s for performance, right? It’s the only good reason I can think of. And, you know, it sounds sensible. I mean, ultra-low latency and all that, you probably don’t want that objc dispatch overhead.

I just did an experiment, however. I dislike working with C APIs, so I’m writing Cocoa wrappers for Core Audio, just exposing those pesky Component properties that take five lines to set or get, with simple methods. Suddenly I thought, “Wait, what if I try to use an objc method as a render callback? Those require very low latency and are called often. So I should be seeing some of that objc overhead.”.

Very unscientific comparison, comparing a simple sine renderer in c and objc, on an MBP 1.83x2 (source available on request):

This isn’t, by far, any compelling evidence that Core Audio should be Objective C; I’m just saying it seems more feasible than I originally thought it’d be. Also, actually thinking about the problem, I realize that the callback’s only called 44100/512 ≈ 86 times a second and has about 10 ms to complete (astronomically long in computer terms).

But NeXT did it that way, didn’t they? I want to remember that NeXT had basically /everything/ in objc, including drivers and audio and such things. So, why not Mac OS X? NeXT was hardly known for being a slow OS. Tell me what I’m missing in the comments.

These are my children. They join me on all my journeys.

So I use a lot of small utility classes that just jump between projects. Not enough to warrant a library, but still code I can’t live without. For example, ary(id first, …) instead of [NSArray arrayWithObjects:…], dict(id key, id value, …) for a dictionary, sf(NSString *format, …) instead of [NSString stringWithFormat:…], a zooming and delta-scrollable CALayer, vector class with most linear algebra, line class, simple macros to turn of CoreAnimation animations… You get the point.

Anyways, from my last blog entry you might have gathered that NSOperationQueue, CoreAnimation and garbage collection don’t really work well together. It seems to be a problem with ensuring that only a single is committing changes/transactions at a time (hence a crash in CALayerEnsureTransaction). NSOperationQueue sets up a full thread with a run loop for every single operation. I have no idea why they chose this wasteful approach; personally, I’d reuse a set of threads. And since NSOperationQueue isn’t working, and my entire acoustic modeling simulation is built around NSOperations, I decided to do just that. Thus, FakeOperationQueue joins my army of utility classes. It has the exact same interface as NSOperationQueue (almost, I only covered what I use), and works on NSOperations. Note that it doesn’t consider dependencies! It’s a very simple class, only a hundred lines of code.

Rentzsch seemed somewhat interested in my fake queue. Thus, I decided I might as well put my stuff online.

Pullsar: Starting up.

Pull Stars from Mario Galaxy is just way too much fun, don’t you think? So do I. So I set out to make a game based on that very concept.

I’m doing it in the same vein of openness as Warren Marshall over at Wanton Hubris, where he documented every step of making his Quake 1 editor ToeTag. Okay, maybe I’m taking it a step further and yet another step too far; I recorded the full hour of development I put into this first prototype. In it you might find some neat Core Animation tricks, or at least get you started on your own CA apps. Note though that I’m using a View as a Controller and doing some generally bad design, just to get started quickly. Also, I’ll try to cut it down to the essentials in maybe a five min vid when I have time.

Check out the project site with all the material at http://thirdcog.eu/apps/pullsar.

Three Points On Error Handling

I’ve been ranting on Twitter lately about how to do error checking the wrong way. Coincidentally, the latest topic on Mac Developer Roundtable was about just that, error handling.

I don’t think this episode of MDR was very interesting. It was essentially an overview of the three common error handling strategies (exceptions, enum returns, pass-by-ref error object), and some general C++/Java likeage from Uli (which is not a compliment :P). However, it got me writing a real blog entry, which is a good thing :)

So: Three things kept repeating in my head while I listened to MDR#3, hoping that someone’d mention it so that we can rid the world of more bad code.


First off, stay far far away from nested ifs. I don’t remember which Mac dev blog I read it on, maybe Wil Shipley’s or ridiculous_fish, but whoever it was recommended to always try to keep the code as far to the left as possible. Use the outermost block for the common, correct case, and use inner blocks for error cases. What I mean by this is, check for the error condition and treat it in-place, don’t check for the not-error case and treat the error in an else far far away. An example is in order…


// Don't:
void collectPhazon() {
  PhazonDetector *detector = findNearestPhazonDetector();
  if(detector) {
    Phazon *nearestPhazon = detector->scanForPhazon();
    if(nearestPhazon) {
      sendPhazonCollectorDrone(nearestPhazon->position());
    } else {
      beep(kNoPhazonFoundBeep);
    }
  } else {
    beep(kMajorlyCatastrophicErrorBeep);
  }
}

// Do:
void collectPhazon() {
  PhazonDetector *detector = findNearestPhazonDetector();
  if(!detector) { beep(kMajorlyCatastrophicErrorBeep); return; }
  
  Phazon *nearestPhazon = detector->scanForPhazon();
  if(!nearestPhazon) { beep(kNoPhazonFoundBeep); return; }
  
  sendPhazonCollectorDrone(nearestPhazon->position());
}

This also applies to smaller scopes, such as for and while loops. Instead of having a big if block inside the loop, say if(error_condition) continue;. Feel free to use gotos as well, eg:


  Baz *a() {
    ...
    if(error) goto a_cleanup;

    return myBaz;
  a_cleanup:
    free(myBaz);
    fclose(bazHandle);
    return NULL;
  }

The same effect can be achieved with try-catch-finally, so use whichever makes your code the easiest to understand.


Secondly, never use just a boolean NO or a nil return value as an error return for a method or function that can fail in more than one way. If you do, the user of your library (or yourself, if it’s in your app!) can’t know what actually went wrong.

This leads to error dialogs such as “Couldn’t connect to iPod” — why not? Because one isn’t connected? Because it’s the wrong model? Because I hit it with a hammer? The sentence is lacking a ‘because’ because the reason is hidden behind bad abstractions.

This is where NSError is your friend, and I think that this is the answer to Scotty’s burning question: ‘When should I use NSError’? The answer is simple: whenver there’s more than one way to fail; whenver a NO/nil can mean more than one kind of failure.


Third, and this was actually mentioned, if you’re checking for errors, make sure you understand /why/ you’re checking for that error, and what the logical response is.

This snippet from Apple’s sample “ComplexPlayThru” is a perfect example of how not to do it (ComplexPlayThru.cpp, line 353-354):


  comp = FindNextComponent(NULL, &desc);
  if (comp == NULL) exit (-1);

Nice! My app suddenly disappeared with no explanation whatsoever! And I’m sure no other part of the app uses the error code ‘-1’! Awesome. Also, the component that they’re looking for is an Apple default, must-be-there-or-any-sound-app-will-crash component. It’s safe to assume that it will always be there, and just skip the error check.

This also goes against Gus’ advice: please don’t just copy any sample code you find, even if it’s from Apple.

NSURLConnection, rails, apache, spaces in URLs and “Your browser sent a request that this server could not understand”

My Rails application uses redirect_to at one point in my code where it redirects to a pdf document on an apache server. The URL that it redirects to contains spaces. URLs may not contain spaces. redirect_to does not escape these spaces, but issues a ‘302 Found’ redirect response with the unescaped URL.

When my Cocoa application receives this redirect request through the currently running NSURLConnection, it follows the new url. In 10.4, it escaped the URL before sending the GET request. In 10.5, this is no longer the case, and apache (correctly) barfs on the request with

Bad Request

Your browser sent a request that this server could not understand.

The request line contained invalid characters following the protocol string.

The solution is simple: URI::escape the URL before redirecting to it. The big question however, is: Is this a bug in my code, in Rails, or in Cocoa?

I’m guessing first or second; I’m supposing there’s a very good reason why Apple chose to change the behaviour of NSURLConnection. Also, the Rails documentation does say, String starting with protocol:// (like http://): Is passed straight through as the target for redirection, which would put the responsibility square on me. However, Rails is generating an invalid response, so I’ll go with blaming rails.

Mac frameworks for common game libraries - GLEW

I’ve added GLEW to my list of Frameworkified game libraries.

FreeImage is now Frameworkified.

I’ve updated my Mac frameworks for common game libraries page with instructions and binaries for the FreeImage library.