Which Compute ID for me?

The first time you look at some compute code, you need to work out what each thread is going to do. Since everything is driven from the system IDs passed to the entry point, you need to know what each one means. Then later when you’re writing your own compute code, you need to remember the names and values of those system IDs. And every time I need to open the ID3D11DeviceContext::Dispatch() page to get the pretty/confusing diagram, and then I’m still challenged to work out the one I need. Not any more! Here’s what you need based on what you’re doing:

1D Processing

  • Use uint SV_DispatchThreadID/S_DISPATCH_THREAD_ID to index an element in 1D array.
  • Use uint SV_GroupIndex/S_GROUP_INDEX (and SV_GroupThreadID/S_GROUP_THREAD_ID in the 1D case) to index within the group – maybe not for sharing between threads, but you could use LDS as a per-thread value cache.
  • Use uint SV_GroupID/S_GROUP_ID to know which group of 64 you’re in – if you wanted to do a reduction.

For example, assume we have N elements to process. We’ll handle 64¹ at a time with thread groups defined as numthreads(64,1,1), requiring a group count of (N+63)/64 and a dispatch(groupCount, 1, 1). Here is a visual concept of what that means:

1D Dispatch IDs

2D Processing

  • Use uint SV_GroupIndex/S_GROUP_INDEX to index linearly within the group for LDS access.
  • Use uint2 SV_GroupThreadID/S_GROUP_THREAD_ID to index the pixel in the tile.
  • Use uint2 SV_DispatchThreadID/S_DISPATCH_THREAD_ID to index pixel/texel.
  • Use uint2 SV_GroupID/S_GROUP_ID to index a matching tile in metadata (assuming 8×8).

In this case we’ll consider a case of a 2D array of dimensions W by H. These will be split into 8×8 tiles with numthreads(8,8,1) mean we have (W+7)/8 tiles in X and (H+7)/8 tiles in Y and will be starting the shader with dispatch(tilesX, tilesY, 1). In the case of a 16×16 array (or 2×2 tiles), we get these values:

2D Dispatch IDs

Something to note

One thing to know is that the only values that need to be passed to your shader are SV_GroupID/S_GROUP_ID and SV_GroupThreadID/S_GROUP_THREAD_ID. The other values are calculated based on these combined with the values from numthreads:

SV_DispatchThreadID = SV_GroupID * numthreads
                    + SV_GroupThreadID;

SV_GroupIndex = SV_GroupThreadID.z*numthreads.x*numthreads.y
              + SV_GroupThreadID.y*numthreads.x
              + SV_GroupThreadID.x;

This means there are implicit multiply-adds to calculate these values and on some platforms we can shave a few cycles by manually calculating them and using the 24bit versions of the multiplies rather than the full 32bit that the compiler may select. The minor problem with this is that you need to duplicate the numthreads values into the handwritten version (assuming you have less than 16M (2^24) odd threads). Check your assembly!

¹ 64 – it’s always going to be 64!

How to find missing PS Vita PlayStation®Plus titles

I’m a huge fan of my Vita for gaming and remote play on my PS4 – most likely due to my trophy hunter/gatherer nature. Every couple of months, a great title appears on PlayStation®Plus for Vita and then you go to grab it fresh from the store as soon as you can. However, this isn’t always as simple as you’d hope – this month I had to try a bunch of things before I could download Titan Souls.

Here’s a set of steps you should take once you enter the store.

  1. Open the PlayStation®Plus section. If the game is there, cracking job! Start the download! If it’s not there, go straight to step 2:
  2. Try the Search box (top right). Give it a word from the title of the game and let it go find it. Beware that the title may be quite a way down the list of results. If that doesn’t work:
  3. For Plan C, you need to “purchase” the title elsewhere. You can do this on the PS Store website or on another PlayStation device, such as your PS4 if the title was cross-buy – it may even already be in the PS Plus section of the PS4 Store! Once purchased, you can go back to the PS Store application on your Vita and go to the Download List (lower right under the ellipsis) and near the top of the list should be your recent “purchase”, ready for you to download.

If option 3 doesn’t work, it might just be a simple mistake – if it was really meant to be, it may appear by the end of the month – Titan Souls has now appeared on the PS Vita Store.

How You Fail To Implement Skinning

How many cats have you skinned?

Chances are, as a graphics programmer, you’ve spent some time implementing some engine and shader code that does vertex skinning. I don’t mean anything clever, none of your dual or more quaternion methods, just a bunch of weighted matrix * vertex transforms indexing some kind of palette. Like many “simple” graphics tasks, writing skinning from scratch is one of those things that despite its simplicity, is a complete bug factory – see also, writing a GL application from scratch, rendering offscreen the right way up, etc.

In the spirit of OpenGL: Why Is Your Code Producing a Black Window?, I thought it would be good to make a list of possible mistakes and how to recognize them. Even though you may have implemented it before, it’s possible with all of this spare compute power, that you may be re-implementing it again soon.

Personally I don’t think these kinds of mistakes are a sign of a bad graphics programmer – I’m sure it happens to the best. However, I think how you approach investigating the bug and how quickly you are able to fix the mistake is more indicative of experience with the GPU tools available and problem solving. I’d even say that it could make a good interview test (if you’re inclined to do those things) – something like “@InternDept is stuck implementing their own skinning – can you help them?” and before breaking out the tools, you could even show pictures of what the result currently looks like and have the interviewee guess.

The stages of grief skinning

If you’re implementing skinning incrementally, I’d expect you to go through the following stages:

1) In the beginning, you just pass through the bind pose vertex positions. This sounds easy and you’re not likely to cock up the shader code, but this is where you start checking your bindings and make sure your input and output buffers are pointing in the right places. However, if/when you mess this part up, the rendering result can easily be:

  •  Nothing
    • Forgot to set up the input buffer.
    • Reading/writing float rather than float3.
    • In compute, reading from or writing to ByteAddressBuffers and forgetting they take/give ints and you’ve introduced an implicit cast.

2) Next, you move to indexing and weighting against an identity palette. This is the best place to hide fails since all those identity matrices will give you back whatever you put in unless you see:

  • Shrunken skin
    • Your weights don’t add to 1.0.
  • Explodey skin
    • Your indices index outside of your palette.
  • A unit volume of noise
    • Reading weights instead of vertex positions.
  • A non-unit pile of noise
    • Reading indices converted to floats instead of vertex positions.
  • Small ball of noise with spikes
    • Reading the palette instead of vertex positions.
  • Half a skin with an explodey component
    • 1/4 size palette when you pass matrices as float4s and the matrix count as the float4 count.
  • Nothing
    • Reading indices with int data reinterpreted as floats.
    • Zeros and not identity matrices in your palette.
    • Zero sized palette.

3) Then you generate some real animation output and use it to populate your matrix palette. This is where you get what I believe is the most common skinning fail:


  • John Carpenter’s The Thing (another classic example at igetyourfail)
    • A classic image that typically means that you’ve missed a transpose/mixed up the matrix-vector multiply order.
    • A similar effect comes from reskinning the skinned data – possible if you have compute skinning feeding the skinning vertex shader path.
  • A bat like monstrosity
    • This can happen when mismatching indices and weights, e.g. using weight[i] with index[N-i] – possibly due to the endianness of your packing. Similar to The Thing, but typically features like fingers are extruded when skinned by the wrong bones.
  • Not animated
    • Are you still writing the input vertex positions direct to the output, or not actually using the palette?
  • Skin at wrong location
    • Palette includes the world transform and so does the shader after skinning – double world transform.
    • If packing indices as bytes in a 32 bit value, you could find you completely cobbled the decode of the indices – did you mask the index out of the indices or just mask the index to zero?
  • Nothing
    • Same as previous, but the output has moved offscreen – look around!
    • Your palette is full of rubbish.

4) Once you’re happily animating, you want to get the rest of the lighting inputs so you want to skin the normals and maybe some bitangents. At this point you might see:

  • Black sphere of noise
    • Overwrote the input/output vertex positions with either the normals or bitangents.
  • Correct mesh with lighting craziness
    • Transformed the normals or bitangents with a W of 1.0, since you copied from the vertex positions.
    • Used the vertex positions for the normals or bitangents – either bound the wrong view or reading everything from the vertex position view.

The point of all this is that you should be able to check everything here in a few minutes with the great graphics debugging tools we have available – praise be to Razor and RenderDoc!



Hello again.

Well it’s been a while. Two and a half years to be almost exact.

As you may have noticed, SIE (yeah, we changed the name – how’s that for you), has several exciting new products (PSVR and PS4(TM) Pro) coming out and they’ve been somewhat consuming of my development time. Meanwhile home time has been mostly taken up with kids; two of them now, one just having turned 2 years old and being too much fun to spend time on much else.

My original plan was to write a post a month. That means I’m about 30 posts behind now. Guess I’d better get on with it.

One Game a Day

In an era of PS Plus, Humble Bundles, GOG.com and Steam sales, the backlog of games is ever growing (as I’ve mentioned before) and it’s very possible that there’s treasure hidden in that pile. Yahtzee’s remark (in his Broken Age review) about Driver being a game he wouldn’t have played if it had been forced on him, made me think about some of the great games I’ve found in unexpected places, such as Renegade Ops, Limbo and Thomas Was Alone. My plan for February was to play one new game a day.

(One thing to note; February was possibly one of the best months to run this experiment due to the quality of the PS Vita line up!)

The Games

1) Saint’s Row IV (PS3) – A Christmas present put on hold by the release of the PS4. Having only experienced the 3rd of the series that I loved every minute of, I followed all of the press for this and couldn’t wait any longer. As games go, I think of Saints Row as the fun cousin of GTA, emphasising fun over authenticity, without losing any quality in the story. I played this all the way through to the end, and I’ll work my way through the DLC when I get through the other games.

2) OlliOlli (PSVita) – OlliOlli is something I first saw a long time ago and it immediately reminded me of the wonder of playing Tony Hawk on the GBA. The game itself has an initial learning bump, mostly due to the controls, that you overcome to run through all of the levels. Each level takes a couple of tries before you complete it (at least on the easiest setting), and with enough challenges on each level to give you some reason go back and keep retrying. The challenge mechanic means that you don’t feel like you’re grinding (sorry – I didn’t want to use that word but I couldn’t think of an alternative) but rather you just keep trying and retrying.

3) Skulls of the Shogun (iPad) – I downloaded this on a weekend when it was £0 with no idea what it actually was and it’s been the untouched icon next to my daily Tapped Out on the iPad since then. A turn-based strategy involving moving your little guys to a location they can hit the enemy and then doing some hitting. Once I started playing, I quickly came to the conclusion that this game wasn’t for me. I’m not a big fan of the anxiety that comes from a little guy riding into the range of the enemy, giving them half a whack and then waiting for the return hit to knock them dead.

4) Tiny Death Star (Nexus 10) – Something that’s been sitting on my Android tablet for a while. It definitely drops you in without too much background or tutorial, but the fundamentals are easy to pick up. Initially I thought it was something I’d go back to from time-to-time (read daily) but the grind of running a lift to new floors eventually got to me to the point where I removed it for good.

5) Monster Hotel – A PlayStation Mobile freebie. Possibly a bit of duplication after Tiny Death Star, but micro managing monsters was definitely more annoying than lifting people to each floor. A well executed plan let down by the scrolling often overshooting the target, especially while carrying a monster to a new destination, and the overlapping thought bubbles complicating knowing what each monster wants.

6) Rock Boshers DX – Another PlayStation Mobile freebie. This gets bonus points for the Spectrum style loading and the 8-bitness of the whole deal. Overall, not a bad game with a proper retro feel; simple controls, escalating difficulty and living on a knife edge defined by the collision detection.

7) Bike Rider DX (PS Vita) – And another PlayStation Mobile freebie. A great start to an idea for a game, but I think the missing component was any form of pressure or fear of loss. I think this could become a much stronger game if the challenge was increased or if you lost more when you died.

8) Quiet Please (PS Vita) – The last of the PlayStation Mobile freebies I played and I’m glad I left it until last. A classic “adventure” style game where you have to silence all the noises in and around the house by finding and using items scattered about. Simple pixel graphics mixed with a difficult to define charm make this one of the gems I was hoping to find. I did get stuck on the first playthrough, but stubbornly I gave it another go, believing I’d just get stuck again and managed to finish it. Really worth a go, especially for the charisma of the little brother, and something I’d love to share with more casual gamers as an entry level adventure game.

9) Crazy Market (PS Vita) – A F2P game I grabbed from the PS Store a while back but didn’t try. Basically you get the chance to be a check out operator (although I have strong ranty feelings about the self-service tills that are appearing in stores) and you have to scan products, type product codes and return dogs and babies to their owners/parents. The game fits the classic F2P mould with an in-game coin based currency, boosts you can buy, and a limited number of lives that refresh (30 minutes per life to a maximum of 3) to limit your playing without extra spend. I actually found the game to be quite enjoyable and it fitted in at the time when I only had time to play during tea breaks amidst swathes of DIY.

10) Flappy Bird (iPad) – Based on a tweet from Tim Moss, and a background buzz of mentions at that time in the month, I thought I’d give Flappy Bird a try. The most accurate description I’ve heard is “crushing”. I got a high score of 3 after 10 goes, then deleted it. In the days following that, it really become a burning topic in the game industry, but I’d already left it behind.

11) QWOP (Nexus 10) – I first saw this in a GDC Experimental Games Workshop session and thought how hard could it be!? Then it popped up in a Android Humble Bundle and I thought I’d grab it and give it a go (try the online version here). It’s basically a game where you control a runners thighs and calves by using the Q, W, O and P keys to race along – I was already wondering how the control scheme would move from keys to screen? The fact is, the original was damn hard but still quite hilarious to play and the Android port is a much more polished but just as devilish version. Using the touchscreen to control the legs means it’s much more challenging on a tablet than a phone, just due to the reach for your thumbs. And I’m awful at it. I got better with practice, but better means getting 4 metres along rather than 1 – I’m unlikely to complete the 100 metres and very unlikely to ever be ready for the hurdles.

12) Rage HD (iPad) – A freebie downloaded long ago and left unplayed, but considered for deletion every time I need to find some space on the iPad. A simple on rails shooter, the gameplay is mostly smooth and easy to pick up. Having played the PS3 version, the visuals match my memory and despite the on rails nature, I found it a really enjoyable game. The money scoring mechanic initially confused me, as I expected an end of level shop to upgrade my weapons, but it’s just a score. And I really want better guns.

13) Surge Deluxe (PS Vita) – A colourful join the dots game with a lot of pressure. One of the few games I can think of that I’ve bought based on the studio’s previous work, without it being the next in the series. Quite good fun, but the music reminded me of Velocity, while I’m still awaiting the arrival of Velocity 2X.

14) TxK  (PS Vita) – The definitive version of the Tempest games from Jeff Minter, heavily hyped and with a cult following even before launch. I’d only played Llamatron on the Amiga before, and I think it was before my time. I think it was the Genesis blog post that really got me interested. My initial play sucked until I trained my left thumb to only go left and right, but I still had issues on following the path on levels where the lines overlap. (The beginner’s guide also helps!) One of the features I love is the Restart Best option where the game tracks your best ever life count at the start of the level so you can start anywhere you’ve already played and play on, and if it’s too hard, skip back a few levels and then play it forward, trying not to die even more than usual, so that you have more lives on your future retries.

15) Ben there, Dan that (Steam) – I discovered Dan Marshall’s Gibbage blog almost 2 years ago and I’ve been following @danthat on Twitter ever since. I like his style of comedy and I’ve wanted to try his adventure games for a long time. With regular price drops on Steam, I thought I’d try Ben there, Dan that. During the first full scene in the apartment I laughed out loud 3 times which is a rarity in most games. As with most adventure games, there’s still a lot left to do on this one.

16) Dead Nation (PS3) – A Housemarque classic that was frequently mentioned in a lot of the press around Resogun, and which I’d put to one side (my PS3 says I downloaded it in 2011). However the Trophy Advisor on psnprofiles.com highlighted that there were quite a few of the easier trophies available there. That said, I started on the Grim setting and found an incredibly difficult game that felt very tense while still initially achievable. It feels different to my previous experiences with Housemarque games like Super Stardust and Resogun, since they’re more classic shooters that you restart from the start, whereas Dead Nation is a more linear experience where you continue from your furthest point.

17) Skylanders Swapforce (PS4) – I considered this as a Christmas present for my 5 year old son, versus the similarly toy oriented Disney Infinity, but I skipped both due to the cost. However a recent price drop at one toy store gave me a second chance. The PS4 version is non-stop gorgeous and at the start I thought it a bit too easy but since then the complexity level has massively increased and the increasing number of battle arenas is taking its toll on the small army of figures I also bought, since you need a new character when one dies off. I think we’ll be playing this for a long time yet.

18) Uplink (Steam) – From the Introversion Humble Bundle. I’ve been a long time follower of Introversions development, most recently Prison Architect, and when the Humble Bundle appeared, there was no need to think. Uplink was the first game that I unlocked on my Steam account that has remained dormant since HalfLife 2. An interesting hacking game, starting slightly complicated on the laptop due to high resolution and low mouse speed, but after a while I managed to start getting the hang of it. This is one that I think would play even better on a tablet, which is great because there’s an Android (which I also have via a Humble Bundle – yay) and iOS version – one for the plane on the way to GDC.

19) Threes! (iPad) – This one suggested by Alex Evans on twitter (@mmalex) and further pushed by the wonderful gameplay gif (as seen here at toucharcade.com). A simple concept, well presented but I’ve not yet learnt the trick. I’m averaging a score of 1000 per go, which I was quite proud to maintain, but having seen @kazhiraiceo, a parody twitter account, scoring 67,000, leads me to believe I can do a lot better.

20) Antichamber (Steam) – Included in the Humble Bundle (#11) that overlapped this month of trying games. Antichamber was something I’d previously seen but didn’t quite understand when I first saw it. It’s a long time since I played an FPS with mouse and keyboard so it took a few minutes to get back into it, and straight away I was dropped into a surreal black and white world with flashes of over-saturated colour. The puzzles are engaging and each is telegraphed in a different way with a clue somewhere nearby. The mapping and logo system help give a sense of the level of completion but the counting down timer means that you feel you need to keep moving forwards and exploring new places.

21) Space Marine (PS3) – Big white guy running around with big guns shooting big orks? I’d heard this was a bit of an unexpected gem which is why I chose it from my PS Plus backlog. There’s a lot of elements that hark back to the Warhammer universe in the characters and races, dialogue and details. The environments are full of all of these amongst the epic scenery. There’s a couple of minor negative things, like a big flashing save indicator prior to every large encounter, and the clunkiness of a character in a space suit that looks heavier than a family car. Overall though, it felt like a futuristic God of War depending a little more on guns than melee, and I continued playing until I completed it.

22) The Room (Nexus 10) – From one of the Humble Mobile Bundles. I managed to get through the first box while making and drinking a cup of tea, before getting pretty quickly stuck on the next one. A very beautiful game with incredible detail, but somewhat infuriating when you hit a brick wall.

23) Fuel Tiracas (PSVita) – One of the free PSM games from last year that I must have overlooked. It’s a simple tap-the-right-place-at-the-right-time-to-fill-the-gauges game, very well polished with a well designed difficulty scale. This was great fun until I hit my natural speed limit and it felt like I was fighting just to stand still.

24) Shadow Blade (iPad) – I think this was another Tim Moss recommendation. The gameplay is quite fluid as long as you can keep the ninja moving, which I found challenging, yet again due to the distance from the edge of the screen of the iPad case that my thumbs had to travel. I gave it half an hour, cleared the first section, but quickly lost interest when it got overly complex due to the controls.

25) Dead Trigger 2 (iPad) – This was at the forefront of the store when I was browsing through for ideas and I thought since I’d missed the first, and it was used as a poster child for rendering quality, I’d give it a go. I had more thumb on iPad issues, although the controls are quite simple, if a little sensitive. The gameplay is kind of fun, but I spent too much time twitching and looking at the floor or ceiling.

26) Device 6 (iPad) – The third in a row of games from the same engine, but a very different proposition. With an intro similar to a British 60’s TV show, the style is established early. I don’t want to give too many spoilers since it’s a game about discovery, but it’s a new way to approach an adventure game. I’m definitely going to go back to this, but next time, with a piece of paper by my side for my notes.

27) Battle of Puppets (PS Vita) – A PlayStation Mobile title that I grabbed based on this blog post. A simple opera-inspired strategy game where you build attackers for your army and they march directly towards the enemy, scrapping with anyone they meet on the way. Once I found enemy archers stall the motion of whoever they hit, I pretty much ruined the game for myself by just using archer rushes.

28) Gunhouse (PS Vita) – Another PS Mobile title grabbed based on a blog post. And like Battle of Puppets, there’s a very strongly defined art style. For the first few attempts , the tile matching game was confusing – it’s nothing like the Tetris or Match-3 games that my brain is wired for, but it’s really enjoyable ending up with weapons that you can use to assault the approaching attackers, before getting another go.

So what did I learn?

Well first, I did manage to find some gems; something new, OlliOlli, something very old, Ben there, Dan that and something unexpected, Quiet Please.

I also discovered that thumb based tablet gaming mostly aggravates me, mostly due to the lack of control feedback. I’ve been a big Vita fan and the fact is, I’ve always preferred playing with a controller. This has lead me to look at stand alone Android controllers or possibly a NVIDIA SHIELD™ as a future option.

I also know there’s still more games I’ve heard about that I want to try: FTL, Papers Please, Gone Home, Brothers – so maybe I’ll give this a go another month later this year.

Adding Precompiled Headers to vs-android – Part 2

Following on Adding Precompiled Headers to vs-android

No plan of operations extends with certainty beyond the first encounter with the enemy’s main strength – Helmuth von Moltke the Elder

With my PCH-support hammer in hand, I went to find anything I could that uses a PCH. With this further testing I managed to uncover a few more issues that really need to be resolved before support for PCHs could be considered for adding to vs-android.

Missing Directory Fail

The first thing I found was that if the PCH output directory (remember that we put all the different PCH outputs in one directory for GCC to check) was missing, the build would fail at the PCH creation stage. To handle this, we need to add a new MSBuild target before the ClCompile target that performs the PCH and C/C++ compilation. For this target we need to make a list of all of the possible output directory names for PCH files and then invoke the Makedir task to create the directories. In MSBuild language, you need to add this to the Microsoft.Cpp.Android.targets* file:

<Target Name="CreatePCHDirs"
     <GchDirsToMake Include="%(ClCompile.Identity).gch\" Condition="'%(ClCompile.CompileAs)' == 'CompileAsCHeader' or '%(ClCompile.CompileAs)' == 'CompileAsCppHeader'"/>
   <Makedir Directories="@(GchDirsToMake->DirectoryName()->Distinct())" />

Gotta Link ’em All

One other issue I found after applying PCH support to all the libraries I could find, when I updated an application to build with a PCH. This then failed to build when the linker thought it should helpfully link in the PCH output, and then fail. Looking at the log, I found there’s a LinkCompiled property of ClCompile elements which we could clear to tell the linker we don’t want it. To do this, go back to the Microsoft.Cpp.Android.targets* file, and after the  ObjectFileName override from last time, add the following in the same group of elements:

 <LinkCompiled Condition="'%(ClCompile.CompileAs)' == 'CompileAsCHeader' or '%(ClCompile.CompileAs)' == 'CompileAsCppHeader'">false</LinkCompiled>

Are we done yet?

Hopefully so. I’m much happier with this and it now works with everything that I could apply it to.

*Note again that there’s 2 copies of each file once vs-android has been deployed – one under C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Platforms\Android\ (for VS 2010) and the other under C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V110\Platforms\Android\ (for VS 2012). You can make these changes prior to deployment, but that’s harder to test.

Adding Precompiled Headers to vs-android

I love vs-android – a Visual Studio extension that allows you to develop for Android from the comfort of VS.

Out of the box it works really well and you can start deploying to your own device from the beginning. In fact there’s very few things wrong with it. However when you’re talking about building something big, the build times can really mount up. There’s 2 options here:

  1. Multithreaded compile. Basically running a separate instance of the compiler for each source file in parallel, rather than serially processing files.
  2. Precompiled headers. A standard way of processing a common header file ahead of time, that amortizes the cost of preprocessing the header over all the sources that use it.

Both of these issues already have suggested implementations, but the multithreading fix is an involved set of changes to the C# code that manages the building and has already been accepted by the vs-android developer for a later fix. However the suggested PCH fix involves quite a few project file changes, whereas I’d expect it to be something to be handled by vs-android with minimum effort for the user.

Precompiled Headers

Precompiled headers are really easy to use with GCC. Basically precompile the header and then the compiler will go looking for the precompiled version before the actual header. All we need to do is mark up the header as needing precompilation. To do this we add a new file type to Props\android_gcc_compile.xml* Basically scroll down to the EnumProperty element for the CompileAs type and add the following values:

<!-- Advanced -->
<EnumProperty Name="CompileAs" DisplayName="Compile As" Category="Advanced">
<EnumValue Name="CompileAsCHeader" DisplayName="Compile as C Compiled Header" Switch="x c-header">
<EnumValue Name="CompileAsCppHeader" DisplayName="Compile as C++ Compiled Header" Switch="x c++-header">

Once that’s added you can open the Properties window in Visual Studio for the precompiled header and change the Compile As setting as needed.

The next step is to tell the GCC compiler to compile the files with this markup before all of the other files. The compilation is handled by the GCCCompile element in Microsoft.Cpp.Android.targets* We need to duplicate what’s there and predicate the first one to only build headers, then the second to build everything else. To do this for C++ headers, we need to duplicate the <GCCCompile> block and change the header on one to:

<GCCCompile Condition="'%(ClCompile.ExcludedFromBuild)'!='true' and '%(ClCompile.CompileAs)'=='CompileAsCppHeader'"

and the header on the other <GCCCompile> block to have !=’CompileAsCppHeader’. This change precompiles the header to the intermediate directory which isn’t one of the places that GCC will search, so this needs redirection.

The last step is to redirect the output for these header files to somewhere for GCC to find them. This means modifying Microsoft.Cpp.Android.targets* again to override the default output file name for the precompiled files.

<ObjectFileName Condition="('%(ClCompile.CompileAs)' == 'CompileAsCppHeader')">%(Identity).gch\$(ProjectName)_$(PlatformName)_$(ConfigurationName)%(Extension).gch</ObjectFileName>

There’s some important features of this output filename based on the GCC support for Precompiled Headers:

  1. The file is output to a subdirectory with the same name as the PCH plus the .gch suffix. This is supported by GCC to allow searching through multiple possible PCH outputs. See the “If you need to precompile the same header file for different languages…” paragraph in the GCC documentation.
  2. The output file has a name that incorporates the ConfigurationName property to ensure that you have a unique version per configuration as well as the PlatformName property to avoid conflicts with gch files from other platforms.

With all of these changes in place, a clean and build should have improved your build time. I’ve seen halving of build times already!

What’s Next?

I’ve already passed this on to Gavin Pugh who maintains the vs-android project so hopefully it should appear in a future version.

There’s also the question of Clang, which handles precompiled headers differently. The creation of the precompiled output is the same, but the compiler won’t use the precompiled version unless you explicitly pass it on the command line, which needs some extra more complex modifications.

(Updated 15/01/2014 – make sure you also check out Adding Precompiled Headers to vs-android – Part 2)

*Note that there’s 2 copies of each file once vs-android has been deployed – one under C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Platforms\Android\ (for VS 2010) and the other under C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V110\Platforms\Android\ (for VS 2012). You can make these changes prior to deployment, but that’s harder test.