Yes! YES!! OH GOD, YES!!!

I mean … uhm …

While browsing throught the E3 reports, I was moderately pleased to see the Aliens versus Predator series (of games, not movies) is getting another sequel.


I've always had a soft spot for xenomorphs. This extends to the Aliens versus Predator games that have been released on the PC. The first AVP came out in 1999 and I think this was one of the first PC games I ever bought. While not really as popular or as rich in storyline as, say, HalfLife, I still think it has many redeeming qualities even today. For example …

An Alien on the ceiling watching dinner walk by: I seeee you.

You can play as Human, Alien, or Predator, each with very different styles of play. This was pretty unique back then for FPSs. Actually, I think it still is. The Alien in particular was unusual: very quick, able to walk on walls and ceilings and a strange fish-eye lens point of view. It also had no ranged attack, which meant you had to get up close and personal to attack. Moreover, the alien did not have much in the way of hitpoints, which effectively meant that you had to not only get close, but get close undetected. You had to hide in dark corners and on ceilings waiting for people to walk by and then bite their heads off.

Most games will put you as the Hero Marine against bug-like critters to be slaughtered en-masse. This game gives you the opportunity to see what it looks like from the other side, which is definitely an educational experience. One thing that comes very clear, for example, is why fire and flamethrowers are not your friend. Bullets could often be avoided (except from turrets), but flamethrowers put up an entire wall of fire and one hit would keep burning for quite some time which, for creatures with few hitpoints, would fit nicely into the bad things category.

Playing against the aliens was also a different-than-usual experience. Able to hide anywhere (how many FPSs require you to check the ceilings?), nearly invisible against the background, fast and very, very deadly.

And … oh yeah! They bleed acid. Yeah.

They also had a very peculiar reaction to being shot: exploding and scattering themselves over a wide area. All while bleeding acid. If you remember your physics classes, you should be aware of this thing called inertia: things in motion will continue in the same direction. You know which direction the Aliens will usually be moving towards when you shoot them? You. You know in which direction all the parts and blood will be moving? You!

In other words: even when you kill them, there's a good chance they'll kill you right back.

Acid rain. (click for details)


The game's also quite hard. I'd almost say Nintendo Hard. AVP 1 had no in-level saving. I don't think there's ever been a PC FPS that didn't allow you to save at will. Combined with the fact that the characters were realistically weak (a rocket jump, would only get parts of you to far-off distances or heights; on average you remain in the same spot), the lack of saving increased the tension considerably.

Of course a sizable group of gamers, cowardly pussies that they are, complained and eventually a save feature was added later. Shame, really; the levels are short enough for it to work, and it's actually way more fun to play when you're running for dear life.

And then there's the motion tracker. If you've seen the movie Aliens, you'll know what I'm talking about. Basically, it's a device that measures how deep the shit you're in is. If it emits a low bup, you're safe; if it starts giving off a high-pitched beep (or worse, multiple beeps), you're in trouble.

This truly is the stuff of nightmares. There's actually something worse than darkness: darkness and having a reminder that you're probably going to die in the next few steps if you're not careful. This feeling was enhanced by the night vision goggles which turn off the tracker. So now you only know where something was, roughly, and you have to find it again. The motion tracker is without a doubt the single most evil and mind-screwing feature ever put in a game. For those who want to argue in favor of, say, Resident Evil or Silent Hill or other horror games: No! You're wrong! It really is that simple.

On second thought, there is something worse. It's called a facehugger. The spiderlike critters from the Alien series that jump you from out of nowhere and basically rape your face. The game has those too. To show just how bad these are, here's a little anecdote about my first encounter with one.

Why facehuggers are evil

It's the third Marine mission: Invasion. You have to get to the top of the tower for a rescue. Up to this point I had done what I'd always done in an FPS: make slow but steady progress to avoid any nasty surprises. From this level onward that strategy doesn't work anymore. At all.

The reason for that is that now the aliens start to respawn at semi-random locations. So not only am I a puny hooman faced with very quick aliens that can come from out of nowhere trying to take my head off, now there's an endless supply of them too and only one of me. Oh and did I mention there's no save? Not that it'd matter because they'd spawn at a different location anyway, but still.

In any case, at some point you'd clue in to the fact that the only way this is gonna work is to just make a blind run for it and hope pray curse for the best. Amazingly, this worked out pretty well. That is, until I took an elevator down to face this:

An open Alien egg. Initialize panic mode.

An open Alien egg. And I could hear the pitter-patter of tiny feet down the corridor to the right, which also lit up on the tracker. When turning round the corner, the sound became louder. But still, I could not actually see the little bastard yet. “Well. Shit.” is something of an understatement at this point.

But then I hear something above me as well: an Alien was climbing down to the room in the image. “Well. Shit.” has now become completely inappropriate and I headed back to the elevator room to kill it. I basically sprayed the whole room with fire, hoping I'd catch it at some point. And I did. I continued to dance around to avoid it until it burst. And then all was quite again. I didn't even hear the face hugger moving around anymore in the distance. Thinking all was safe, I turned round to hunt down the face hugger again an…


Turns out the reason I didn't hear the facehugger anymore wasn't that I'd killed it or that it had moved too far away, but because it was already in mid-jump. Not only did it get me, it got me completely by surprise and the blood-curdling scream it emitted actually made me fall off my chair. Literally. It scared me so much that I actually leaped out of my chair. It took about a minute before I could even hold the mouse again because my hands were shaking so much. No game has ever had that strong of an effect before or since. This was just awful. And yet awesome at the same time.

Facehuggers are just plain evil. Just hearing one moving in the area is enough to give me hives.

The only really bad thing about the game is that it won't play on current computers – some graphics and sound glitches that made crashed the game or made it unplayable. However, this has actually been remedied recently. People have been tinkering with the source code and fixed the most important issues. See forumplanet.gamespy.com/tech_support/b49029/1049364 for details and links to patches.


Compared to AVP 1, its sequel was, well, ultimately something of a let-down. It's still good playing, but I felt that it could have been so much more. Sure, it had better graphics. Well, more detailed models and textures anyway; unfortunately, the textures also looked really coarse and flat, and decals would often seem to be placed over the polygons, rather than on it, which just looked awful. AVP 1 had destructable light sources – something the Alien could make use of very well – but AVP 2 didn't. It also did not have adjustable gamma settings, which really hurt because often I literally could not see anything. And they took out the cheat modes and skirmish *sigh*.

The Aliens had also changed in some very bad ways. In the original, they were fast and furious, but in AVP 2 it often seemed thay they were just hobbling along on their way too skinny legs. Instead of looking like the vicious and fast killing machines, they came off more as clumsy puppies. Okay, yes, puppies with really sharp claws and teeth, but not the terrors they're supposed to be.

They also didn't explode into parts with that delightful crackling sound anymore, or bleed over everything (mostly you). Mostly they just flopped down. Also, there seemed to be only one or two death poses and I think only a single animation timer for all critters. Often you'd find yourself in a field of dead aliens which lay down in exactly the same way. I know it doesn't sound like a big deal, but little things like this can spoil the mood completely. Worst of all though was what they did with the facehuggers: they took away the scream when they kill you. This completely removed the scare factor :(

Having said that, it also did some things very right. There was one interconnected story line, with the threads of the three playmodes intersecting at several instances. Very nicely done. Also, as the Alien you actually played through the facehugger and chestburster stages. This was also fun.

Ugly texturing (click for details).

Synchonized dying.

Chestburster finding its way out.

Intersecting story line - Alien.

Intersecting story line - Marine.

Intersecting story line - Predator.

And now there's gonna be a third installment. Like in AVP 2, there will be an interwoven story, so that's good. From the pictures I've seen, the graphics are going to be awesome. Textures are crips, motion looks fluid – it just looks right again. It also looks like it's not going to be for the faint of heart, with lovely gratuitous displays of blood and guts and trophy-taking and everything (see here for video).

I was somewhat surprised to see Sega as the publisher for the game. It seemed a little odd at first, but if you take into account that they're a bunch of fucking sadists, I think it is actually quite fitting.


So yeah, I'm looking forward to this one.

new and improved geshi

With Tonc I pretty much did all the syntax highlighting of code manually. As you might expect, this experience was – well, the proper description is something not suitable for anyone under the age of several thousand, so let's keep it at “somewhat less than pleasant”. So the first thing I looked when starting this whole blogging gig for was something that could do that automatically. In my case, that was codesnippet, which was build on the very awesome Geshi. There were some small problems with number formatting and whitespace handling, but overall it's served me well.

The Geshi that came with it was …, I think. In any case, Geshi's is now at, so I figured it was time for an upgrade. Most notable was that the way numbers were parsed has been greatly modified, with different types of representations now being parsed separately – and correctly to boot. Right now, it's almost fully correct, as you can see from the list below:

// Regular int
123ll       // fail
123LL       // fail
123u        // fail
123U        // fail

// Octal

// Hex

// Float

// Inner

Only some of the more special integer literals aren't parsed correctly, specifically the unsigned (-U) and long long (-LL) suffixes aren't accepted. I don't suppose hex floats will work either, but that's a GCC extension anyway.

To fix this, you need to modify geshi a little; specifically the GESHI_NUMBER_INT_CSTYLE regular expression:


… yeah. I'm not sure why it's formulated like that either. I'd have thought '\b' would have worked just as well, but alright. Anyway, notice the single 'l' character in there? That needs to be extended to something that matches a potential single 'u', possibly followed by one or two 'l's. In other words: 'u?l{0,2}'.


HTML in code

An astute readed may have noted the bold in the previous snippet. Normally, you can't do that in Geshi.. One of the things that Geshi does is translate HTML entities like '<' into things like "&lt;" so that it'll turn up right on the resulting page. This, of course, is one of the things Geshi is expected to do. However, in this case it also makes it impossible to add HTML parts in the code snippet, which at times can be very useful.

So what do we do now? Well, we can use escaped HTML tags. Much like "\n" doesn't actually mean backslash + 'n' but a newline character, "\<" can be used for the actual '<'. And to unescape that, a double backslash can be used, much like it is in C.

\\<b\\>BOLD\\</b\\>    becomes     \<b\>BOLD\</b\>

There are several ways to implement this. One would be to modify it in the geshi code. I haven't tried that route yet because I expect it could get messy. That's arguably how it should be done, but it's easier to do it after the fact: when all the conversions have been done. Basically, you need something like this:

// Initialize geshi with the text to convert and language file to use.
$geshi = new GeSHi($text, $lang, $this->geshi_path);

// This does the actual work.
$text= $geshi->parse_code();

// Replace (un)escaped html entities.
$text= str_replace(
        // Normal entities
        '\\\&lt;', '\\\&gt;', '\\\&amp;',
        // In-string escapes get crap added, gaddammittohell >_<.
        '<span class="es0"><</span>',
            '<span class="es0">></span>',
            '<span class="es0">&</span>',
        // Unescaped entities
        '\\\&', '\\\<', '\\\>'),
        '<'     , '>'     , '&',        // Normal entities
        '<'     , '>'     , '&',        // In-string entities.
        '\\\&amp;', '\\\&lt;', '\\\&gt;'    // Unescaped entities

There are three sets of items to search & replace here. The first two are the basic escaped tag delimiters, so that they'll actually result in HTML tags, and unescaped delimiters, so that you can print the combination itself. The third category are for HTML in string literals. Since the backslash has a specific meaning there as well, Geshi puts some highlighting stuff around it that would make the standard search fail. So that whole thing would need to be searched for and destroyedreplaced.

It's ugly, I know, but it seems to work. It'd be nicer if this could be done in the parser itself, but I have a feeling that'd take changes in multiple places. Since I don't know the code that well yet, I'm not touching that one with a ten-foot pole.

Lastly, let's test the ARM asm highlighter:

// Regular int

// Binary

// Octal

// Hex

// Float

// Inner

Still works too. Bitchin'.

DMA vs ARM9 - fight!

DMA, or Direct Memory Access, is a hardware method for transferring data. As it's hardware-driven, it's pretty damn fast(1). As such, it's pretty much the standard method for copying on the NDS. Unfortunately, as many people have noticed, it doesn't always work.

There are two principle reasons for this: cache and TCM. These are two memory regions of the ARM9 that DMA is unaware of, which can lead to incorrect transfers. In this post, I'll discuss the cache, TCM and their interactions (or lack thereof) with DMA.

The majority of the post is actually about cache. Cache basically determines the speed of your app, so it's worth looking into in more detail. Why it and DMA don't like each other much will become clear along the way. I'll also present a number of test cases that show the conflicting areas, and some functions to deal with these problems.

Continue reading
  1. Well, quite fast anyway. In some circumstances CPU-based transfers are faster, but that's a story for another day.

mode 7 addendum

Okay. Apparently, I am an idiot who can't do math.


One of the longer chapters in Tonc is Mode 7 part 2, which covers pretty much all the hairy details of producing mode 7 effects on the GBA. The money shot for in terms of code is the following functions, which calculates the affine parameters of the background for each scanline in section 21.7.3.

IWRAM_CODE void m7_prep_affines(M7_LEVEL *level)
    if(level->horizon >= SCREEN_HEIGHT)

    int ii, ii0= (level->horizon>=0 ? level->horizon : 0);

    M7_CAM *cam= level->camera;
    FIXED xc= cam->pos.x, yc= cam->pos.y, zc=cam->pos.z;

    BG_AFFINE *bga= &level->bgaff[ii0];

    FIXED yb, zb;           // b' = Rx(theta) *  (L, ys, -D)
    FIXED cf, sf, ct, st;   // sines and cosines
    FIXED lam, lcf, lsf;    // scale and scaled (co)sine(phi)
    cf= cam->u.x;      sf= cam->u.z;
    ct= cam->v.y;      st= cam->w.y;
    for(ii= ii0; ii<SCREEN_HEIGHT; ii++)
        yb= (ii-M7_TOP)*ct + M7_D*st;
        lam= DivSafe( yc<<12,  yb);     // .12f    <- OI!!!

        lcf= lam*cf>>8;                 // .12f
        lsf= lam*sf>>8;                 // .12f

        bga->pa= lcf>>4;                // .8f
        bga->pc= lsf>>4;                // .8f

        // lambda·Rx·b
        zb= (ii-M7_TOP)*st - M7_D*ct;   // .8f
        bga->dx= xc + (lcf>>4)*M7_LEFT - (lsf*zb>>12);  // .8f
        bga->dy= zc + (lsf>>4)*M7_LEFT + (lcf*zb>>12);  // .8f

        // hack that I need for fog. pb and pd are unused anyway
        bga->pb= lam;
    level->bgaff[SCREEN_HEIGHT]= level->bgaff[0];

For details on what all the terms mean, go the page in question. For now, just note that call to DivSafe() to calculate the scaling factor λ and recall that division on the GBA is pretty slow. In Mode 7 part 1, I used a LUT, but here I figured that since the yb term can be anything thanks to the pitch you can't do that. After helping Ruben with his mode 7 demo, it turns out that you can.


Fig 1. Sideview of the camera and floor. The camera is tilted slightly down by angle θ.

Fig 1 shows the situation. There is a camera (the black triangle) that is tilted down by pitch angle θ. I've put the origin at the back of the camera because it makes things easier to read. The front of the camera is the projection plane, which is essentially the screen. A ray is cast from the back of the camera on to the floor and this ray intersects the projection plane. The coordinates of this point are xp = (yp, D) in projection plane space, which corresponds to point (yb, zb) in world space. This is simply rotating point xp by θ. The scaling factor is the ratio between the y or z coordinates of the points on the floor and on the projection plane, so that's:

\lambda = y_c / y_b,

and for yb the rotation gives us:

y_b = y_p cos \theta + D sin \theta,

where yc is the camera height, yp is a scanline offset (measured from the center of the screen) and D is the focus length.

Now, the point is that while yb is variable and non-integral when θ ≠ 0, it is still bounded! What's more, you can easily calculate its maximum value, since it's simply the maximum length of xp. Calling this factor R, we get:

R = \sqrt{max(y_p)^2 + D^2}

This factor R, rounded up, is the size of the required LUT. In my particular case, I've used yp= scanline−80 and D = 256, which gives R = sqrt((160−80)² + 256²) = 268.2. In other words, I need a division LUT with 269 entries. Using .16 fixed point numbers for this LUT, the replacement code is essentially:

// The new division LUT. For 1/0 and 1/1, 0xFFFF is used.
u16 m7_div_lut[270]=
    0xFFFF, 0xFFFF, 0x8000, 0x5556, ...

// Inside the function
    for(ii= ii0; ii<SCREEN_HEIGHT; ii++)
        yb= (ii-M7_TOP)*ct + M7_D*st;           // .8
        lam= (yc*m7_div_lut[yb>>8])>>12;        // .8*.16/.12 = .12
        ... // business as usual

At this point, several questions may arise.

  • What about negative yb? The beauty here is that while yb may be negative in principle, such values would correspond to lines above the horizon and we don't calculate those anyway.
  • Won't non-integral yb cause inaccurate look-ups? True, yb will have a fractional part that is simply cut off during a simple look-up and some sort of interpolation would be better. However, in testing there were no noticeable differences between direct look-up, lerped look-up or using Div(), so the simplest method suffices.
  • Are .16 fixed point numbers enough?. Yes, apparently so.
  • ZOMG OVERFLOW! Are .16 fixed point numbers too high? Technically, yes, there is a risk of overflow when the camera height gets too high. However, at high altitudes the map is going to look like crap anyway due to the low resolution of the screen. Furthermore, the hardware only uses 8.8 fixeds, so scales above 256.0 wouldn't work anyway.

And finally:

  • What do I win? With Div() m7_prep_affines() takes about 51k cycles. With the direct look-up this reduces to about 13k: a speed increase by a factor of 4.

So yeah, this is what I should have figured out years ago, but somehow kept overlooking it. I'm not sure if I'll add this whole thing to Tonc's text and code, but I'll at least put up a link to here. Thanks Ruben, for showing me how to do this properly.

Some interesting numbers on NDS code size

Even though the total size of code is usually small compared to assets, there are still some concerns about a number of systems. Most notably among these are stdio, iostream and several STL components like vectors and strings. I've seen people voice concerns about these items, but I don't think I've ever seen any measurements of them. So here are some.

Table 1 : Memory footprint of some C/C++ components in bytes. Items may not be strictly cumulative.
Barebones: just VBlank code14516

The sizes in Table 1 are for a bare source file with just the VBlank initialization and swiWaitForVBlank() plus whatever's necessary to use a particular component. For the IO parts this means a call to consoleDemoInit(); for vectors and strings, it means defining a variable.


Even an empty project is already 15k in size. Almost all of this is FIFO code, which is required for the ARM9 and ARM7 to communicate. Adding consoleDemoInit() and a printf() call adds roughly 71k. Printf has a lot of bagage: you have to have basic IO hooks, character type functions, allocations, decimal and floating point routines and more.

Because printf() uses the usually unnecessary floating point routines for float conversions, it is often suggested to use the integer-only variant iprintf(). In that case, it comes down to 55k. The difference is mostly due to two functions: _vfprintf_r() and _dtoa_r(), for 5.8k and 3.6k, respectively. The rest is made up of dozens of smaller functions. While the difference is relatively large, considering the footprint of the other components, the extra 16k is probably not that big of a deal. For the record, there is no difference in speed between the two. Well, almost: if the format string doesn't contain formatting parts, printf() is actually considerably faster. Another point of note is that the 55k for iprintf() is actually already added just by using consoleDemoInit().

And now the big one. People have said that C++ iostream was heavy, and indeed it is. 266k! That's a quite a lot, especially since the benefits of using iostream over stdio is rather slim if not actually negative(1). Don't use iostream in NDS projects. Don't even #include <iostream>, as that seems enough to link the whole thing in.

Related to iosteam is fstream. This also is about a quarter MB. I haven't checked too carefully, but I think the brunt of these parts are shared, so it won't combine to half a Meg if you use both. Something similar is true for the stdio file routines.

Why are the C++ streams so large? Well, lots of reasons, apparently. One of which is actually its potential for extensibility. Because it doesn't work via formatting flags, none of those can be excluded like in iprintf()'s case. Then there's exceptions, which adds a good deal of code as well. There also seems to be tons of stuff for character traits, numerical traits, money traits (wtf?!?) and iosbase stuff. These items seem small, say 4 to 40 bytes, but when there are over a thousand it adds up. Then there's all the stuff from STL strings and allocators, type info, more exception stuff, error messages for the exceptions, date/time routines, locale settings and more. I tell you, looking at the mapfile for this is enough to give me a headache. And worst of all, you'll probably use next to none of it, but it's all linked in anyway.

Finally, some STL. This is also said to be somewhat big-boned, and yes it isn't light. Doing anything non-trivial with either a vector or string seems to add about 60k. Fortunately, though, this is mostly the same 60k, so there are not bad effects from using both. Unfortunately, I can't really tell where it's all going. About 10k is spent on several d_*() routines like d_print(), which is I assume debug code. Another 10k is exceptions, type info and error messages and 10 more for. But after that it gets a little murky. In any case, even though adding STL strings and vectors includes more that necessary, 60k is a fair price for what these components give you.



The smallest size for an NDS binary is about 14k. While printf() is larger than iprintf(), it's probably not enough to worry about, so just use printf() until it becomes a pressing matter (and even then you could probably shrink down another part more easily anyway). There is no speed difference between the two. The C++ iostream and fstream components are not worth it. Their added value over printf and FILE routines are small when it comes to basic IO functionality. STL containers do cost a bit, but are probably worth the effort. If you need more than simple text handling or dynamic arrays and lists, I'd say go for it. But that's just my opinion.

Please note, the tests I did for this were fairly roughly. Your mileage may vary.


Lastly. The nm tool (or arm-eabi-nm for DKA) is my new best friend for executable analysis. Unlike the linker's mapfile, nm can sort addresses and show symbol sizes, and doesn't include tons of crap used for glue.

  1. Yes, I said negative. Even though it has the benefit of being typesafe and extensible, the value of these advantages are somewhat exaggerated, especially since it has several drawback as well (see FQA:ch 15 for details). For one thing, try finding the iostream equivalent of "%08X", or formatted anything for that matter. For early grit code I was actually using iostream until I got to actually writing the export code. I couldn't move back to stdio fast enough.

On arctangent.

The arctangent is one of the more interesting trigonometry functions – and by “interesting” I of course mean a bitch to get right. I've been meaning to write something about the various methods of calculating it for a while now and finally got round to it recently.

I, ah, uhm, may have gotten a little carried away with it though ... but that's okay,! At least now I while one to recommend.

Aaaand, 0.8.3

Well that was fast.

Dovoto discovered some quirks in the way names were used under shared data runs and had a nice suggestion to allow images to be added via grit files as well. There was also some other small niggly bits that needed straightening out. So yeah, grit v0.8.3.

grit 0.8.2 / usenti 1.7.10

Apparently, the GRF format didn't quite follow the official RIFF specs, so I had to fix it (thanks for pointing it out, Daniel). While I was at it, I also changed the names of the meta-tile arrays if a meta-map was asked for. In stead of the -Map affix, it now uses the more logical -MetaTiles. Yes, this probably will break something, but in the long run it's better this way and it's a compiler error, so it's easy to fix.

Usenti's been updated to match.


NDS register overview

libnds 1.3.1 updates

libnds has fixed the datatypes of pretty much all registers and have moved to the GBATek nomenclature for the BG-related registers. The list has been updated to match the libnds v1.3.1. of

The state of register names for NDS homebrew is a bit of a mess. First, there are the GBATek names. Since GBATek is considered the source of GBA/NDS information, it would make sense to adhere to those names pretty closely. But, of course, that's not how actually is in the de facto library for NDS homebrew, libnds.

libnds has two sets of names. This probably is a result of serving different masters in its early days. One set uses Mappy's nomenclature. That's the one without the REG_ in front of it, and uses things like _CR, and _SR. This is one you're most likely to see in the current NDS tutorials. The second set uses GBATek's names (mostly) plus a REG_ prefix. If you've done GBA programming, these should feel quite familiar.

Continue reading