Posts
53
Comments
108
Trackbacks
0
Saturday, March 24, 2012
Guncraft on Kickstarter - Last Chance this weekend!

Andy Dunn, known far and wide as The Zman (accept no substitutes) has been a strong supporter of the XNA community for many years now (and the Managed DirectX community before that). This coming Sunday at 9:41 pm EDT (UTC + 4) the Kickstarter project for the game, Guncraft, (on which he is the Lead Programmer) comes to a close. They’ve garnered pledges in the amount of $15,375 at the time I’m writing this. The project must meet a funding target of $16,000 by the aforementioned deadline.

I think this is going to be a really fun game. I’ve pledged $65 towards it (and would pledge more if it weren’t tax season). If you have some spare loot and think it’d be a fun game, or if you just want to say thanks to him for everything he’s done over the years (and everything he’s likely to do in the years still to come), consider visiting that Kickstarter link above and making a pledge. If they don’t reach $16,000 then none of the donations take effect.

Anyway, I’ll be keeping my fingers crossed that it meets the goal. I’ve spent money on many stupid things over the years; it’s nice when the chance to spend some money on something worthwhile comes along.

Here’s a trailer for it, for those wondering what it is that I’m so excited over:

(Presumably) Copyright © 2012 Exato Games (Sorry, retired lawyer-itis kicks in on stuff like this.)

Ganbatte Exato!

And good luck to everyone participating in Dream.Build.Play 2012 – just a little more than 80.5 days left until the submission period closes!

Update: They made it! Congratulations to everyone at Exato!

As an update, here’s a gameplay video that Andy pointed me to:

(Presumably) Copyright © 2012 Exato Games (Sorry, retired lawyer-itis kicks in on stuff like this.)
Posted On Saturday, March 24, 2012 12:51 AM | Feedback (0)
Monday, March 05, 2012
Dream.Build.Play 2012 Registration Now Open!

Registration for this year’s Dream.Build.Play competition is now open! Head over to https://www.dreambuildplay.com/Main/Default.aspx for more information and to register.

This year’s DBP includes not only Xbox 360 games but also Windows Phone games as well. So you can develop for either or both! Like last year, I’ve created an unofficial countdown clock for the end of the submission period. Check it out here: http://www.bobtacoindustries.com/Misc/DBP . But don’t wait until the last minute to submit your game; you can update your submission when needed and if you wait until the last minute, you might not make it in time. Optimally, you’ll be done and have everything submitted at least a day before the submission period closes.

There’s just over 98 days and 22 hours (as I’m writing this) until the submission period closes, so get busy creating awesome games! And don’t forget to register: it’s free and the registration period closes on May 15th (before the submission period opens). Good luck!

Posted On Monday, March 05, 2012 3:24 PM | Feedback (0)
Tuesday, February 14, 2012
C# to C++–A Somewhat Short Guide (Update 1)

Last updated: 2012-02-14

This is a big post – over 12200 16600 words – and so I’ve decided to make it available as a PDF download, which you can get here:

http://www.bobtacoindustries.com/Content/Devs/CsToCpp-ASomewhatShortGuide.pdf

It has bookmarks for easier navigation along with a Table of Contents and page numbers.

I expect that I will revise this from time to time and welcome any suggestions, feedback, and (especially) corrections. If so I will update the Last updated field at the top and will create a revised PDF as well. I hope this proves useful.

Update: I realized when looking at stats the other day that this post was so big that it wasn’t going through to many people’s RSS feeds (including my own!). So I stripped out the text and have decided just to keep it as a PDF link.

Updates and Changes:

2012-02-14

New sections:

  • Namespaces
  • enums subheading under Fundamental types
  • Functions
  • A brief word on the volatile keyword
  • Casting values
  • nullptr subheading under Pointers
  • Lambda expressions

Significant changes:

  • Added discussion of cstdint header to Fundamental types
  • Touched up some language and added a brief note on “mixins” to Multiple inheritance
  • Added subheadings to C++ constructors; also revised its code sample
  • Added a note about non-string uses of the ‘char’ type to Strings

There were many other miscellaneous edits made. I incorporated much of the great feedback I’ve received in the comments. I did not end up moving the Pointers section this time but have not ruled it out either. I’m on the fence about it because, to me, modern C++ is all about clean, safe code with automatic storage duration objects and C++ Standard Library container types. Pointers are still a part of C++ and likely always will be. But I’m not convinced that they belong right up front. I need to re-read the document through from beginning to end before I make a decision on that, I guess.

Most of the things I wanted to add this time around are in the document now. I’m considering a section on multi-threading but that will have to wait for another update. Once VS11’s ranged for loop support is released, I’ll be adding a section on that. I would like to make the templates discussion a lot more in depth at some point but that’s something for another time.

The link above has not changed; the new version is there now and has subsumed the old one. I’ll be posting this as a new blog post as well so if you see it twice, that’s why.

Posted On Tuesday, February 14, 2012 1:52 PM | Feedback (0)
Tuesday, February 07, 2012
Going Native 2012 sessions available for download and streaming

If you missed it, you can now download or stream (whichever you prefer) the sessions from the Going Native 2012 conference. I watched the whole thing and it was fascinating. If you’re new to C++, then some of the sessions are likely to be at a higher level than you may be ready for (though you can certainly watch them if you like). But there are some sessions I think any C++ developer would profit from watching. These are they:

Day 1:

Bjarne Stroustrup - C++11 Style

Stephan T. Lavavej - STL11 – Magic && Secrets

Panel - The Importance of Being Native

Day 2:

Herb Sutter - C++11, VC++11 and Beyond

Chandler Carruth - Clang - Defending C++ from Murphy's Million Monkeys

Panel- Ask Us Anything!

If you are planning to do any multi-threading, then I’d definitely recommend watching Hans Boehm - Threads and Shared Variables in C++11 . For Metro style development, I’d generally recommend using the Parallel Patterns Library (PPL) and the Concurrent Runtime (ConcRT) as they mesh nicely with WinRT’s asynchrony.

Andrei Alexandrescu is a great speaker and his sessions are really entertaining and informative. But it’s likely to be a little while before variadic templates appear in VC++11 (post-RTM but likely in an out-of-band release rather than waiting for VS11 SP1) and they are a pretty tricky topic and the concept of “static if” is a proposal for a future version of the C++ language (but an interesting one and so I’d definitely say go watch it if you have time). They are interesting sessions but not really things for beginners.

Bjarne Stroustrup and Andrew Sutton’s session entitled “A Concept Design for C++” is also interesting but is something that’s still in the research phase of development. It had been proposed for C++11 but was dropped because (as I understand it) they didn’t feel that it was ready to be included in the standard just yet. (This is an area where I personally think C++ could take a lesson from C#. I think C++ would benefit a lot from a purely abstract type (something similar to if not the same as C#’s interface type) with its own keyword designating it as such (thereby adding developer-friendly guarantees that the type was abstract and thus removing the need to use multiple class inheritance for such reasons). This in turn would open the door to a mechanism for templates that would be similar to C#’s constraint system for C# generics. Maybe there are good reasons not to do this; I’m not a language designer. But from an outsider’s perspective, I think C# got this one right.)

Posted On Tuesday, February 07, 2012 10:27 PM | Feedback (0)
Thursday, February 02, 2012
C# to C++ – A Somewhat Short Guide

Last updated: 2012-02-14

This is a big post – over 12200 16600 words – and so I’ve decided to make it available as a PDF download, which you can get here:

http://www.bobtacoindustries.com/Content/Devs/CsToCpp-ASomewhatShortGuide.pdf

It has bookmarks for easier navigation along with a Table of Contents and page numbers.

I expect that I will revise this from time to time and welcome any suggestions, feedback, and (especially) corrections. If so I will update the Last updated field at the top and will create a revised PDF as well. I hope this proves useful.

Update: I realized when looking at stats the other day that this post was so big that it wasn’t going through to many people’s RSS feeds (including my own!). So I stripped out the text and have decided just to keep it as a PDF link.

Updates and Changes:

2012-02-14

New sections:

  • Namespaces
  • enums subheading under Fundamental types
  • Functions
  • A brief word on the volatile keyword
  • Casting values
  • nullptr subheading under Pointers
  • Lambda expressions

Significant changes:

  • Added discussion of cstdint header to Fundamental types
  • Touched up some language and added a brief note on “mixins” to Multiple inheritance
  • Added subheadings to C++ constructors; also revised its code sample
  • Added a note about non-string uses of the ‘char’ type to Strings

There were many other miscellaneous edits made. I incorporated much of the great feedback I’ve received in the comments. I did not end up moving the Pointers section this time but have not ruled it out either. I’m on the fence about it because, to me, modern C++ is all about clean, safe code with automatic storage duration objects and C++ Standard Library container types. Pointers are still a part of C++ and likely always will be. But I’m not convinced that they belong right up front. I need to re-read the document through from beginning to end before I make a decision on that, I guess.

Most of the things I wanted to add this time around are in the document now. I’m considering a section on multi-threading but that will have to wait for another update. Once VS11’s ranged for loop support is released, I’ll be adding a section on that. I would like to make the templates discussion a lot more in depth at some point but that’s something for another time.

The link above has not changed; the new version is there now and has subsumed the old one. I’ll be posting this as a new blog post as well so if you see it twice, that’s why.

Posted On Thursday, February 02, 2012 8:45 AM | Feedback (10)
Monday, January 30, 2012
DMARC – A new anti-spam effort that looks promising

While doing my usual rounds of reading the news I came across an interesting post in the New York Times Bits blog: http://bits.blogs.nytimes.com/2012/01/30/technology-companies-pair-up-to-confront-the-scourge-of-internet/ .

It seems that most of the big players in the internet mail world (Microsoft, Google, Yahoo, Facebook, AOL, LinkedIn, PayPal, and more) have been working together in an attempt to formulate a new way of better identifying not-spam (and thereby more easily identifying spam) by using existing technologies in a consistent way. The group has come up with DMARC (Domain-based Message Authentication, Reporting & Conformance), “a technical specification […] to help reduce the potential for email-based abuse by solving a couple of long-standing operational, deployment, and reporting issues related to email authentication protocols.” (See: http://dmarc.org/index.html ).

Ultimately the goal is to package it up and submit it to the IETF for consideration to become an RFC (i.e. an internet standard). I do very little mailing from my own domains currently but that may change in the future. It is nice that there is now a way that I can potentially show that I am me; the fear of winding up in spam folders is part of the reason why I have not used my domains for many email activities. I’ve glanced through it, but I need to do more research before I can figure out whether this is something I can do directly or if it’s something I need to talk to my hosting company about. Either way, it’s definitely something on my to-do list and is something that all small developers should have a look at as a way of facilitating communication with opt-in customers and with prospective customers, clients, and business partners who send you email.

--------

On an unrelated note, I’m making good progress on my next post in the XNA to DirectX series. It’s already coming in at over 4100 words and I expect it to grow a fair bit longer still. The reason for the length is that it’s a post about modern C++ for C# programmers who either haven’t used C++ ever or haven’t used it for several years at any rate. C++11, the latest standard, is a huge improvement over the previous C++03 standard and really makes C++ a very different language than what it was a decade ago. I had initially been planning out a whole series on it (and even had two posts well along the road to completion) but I decided that it was more feasible and practical for me to create a brief guide of key topics. (The prospect that Shawn Hargreaves may be writing about C++ soon did factor into that decision; he undoubtedly knows more about the topic than I do, especially when it comes to writing games and game engines, so I’m looking forward to his posts as and when they come.)

I want to have something covering key C++ topics in order to set a baseline of knowledge and so that’s what I’m working on. Once that’s done, I’ll know that I can dive into DirectX technologies without needing to worry about writing up ad hoc explanations of the C++ constructs in each bit of code. I’ll also have a central place where I can add new topics and tweak existing topics whenever the need arises. So keep an eye out for that post (hopefully within the next few days). After that we dive into DirectX, likely starting with basic D3D11, with coverage on various other technologies (XAudio2 and Media Foundation, XInput, D2D, DirectWrite, DirectXMath, etc.) in subsequent posts. I’m considering writing with the goal of creating the components needed for a good, basic framework for 2D games (perhaps loosely patterned on XNA’s Game State Management sample, though I haven’t had the opportunity to prototype that yet to see whether it would make sense). We’ll see. For now I need to finish up the C++ post.

Posted On Monday, January 30, 2012 3:45 PM | Feedback (1)
Saturday, December 31, 2011
Getting started with Metro style DirectX

A little more than three months ago, Microsoft hosted the //build/ conference at which they unveiled the upcoming version of Windows (commonly called Windows 8, though I don’t know if the marketing folks have accepted the fact that that is the name most of us are expecting for it yet). They released to the developer world a build of it called the Windows Developer Preview (and Windows Server Developer Preview) along with various tools for creating the new “Metro style” apps. I wasn’t able to make it to //build/ but I’ve watched a lot of the sessions in the past few months (53h43m04s and counting) and I’ve been running the developer preview a lot both on a developer machine and on a Samsung Series 7 Slate that I bought for testing and development.

So far I’m very impressed. As far as UI, there are some small changes I’d like to see. I wish the mouse would work more like touch input; having mouse and touch be different isn’t intuitive (for me) and the touch scheme has a very well-designed flow so I really don’t think it makes sense to keep the mouse in a bizarro legacy interaction style (scroll bars were always a kludge and the metro system bar should be on the right for all input interfaces in my opinion; let people who want the current Metro mouse style select it as a legacy option in Control Panel or at least give those of us who want the mouse to work like touch the option to enable that in Control Panel). But it’s a “developer preview” (i.e. pre-Beta) so such things may change in the beta (expected in late February) and/or in subsequent pre-RTM releases.

I really like the new Metro programming model (with one exception*). And since that’s what this post is about, let me explain it a bit. I want to clear up some misconceptions to begin with.

First, Metro style apps share some design elements (e.g. active tiles rather than dead icons) with Windows Phone but are an evolution from Windows Phone and differ in certain areas, sometimes significantly. If you think it’s all just colored boxes and black backgrounds, then I encourage you to watch Sam Moreau’s talk, Designing Metro style: principles and personality (and also to revisit Windows Phone since it’s evolved quite a bit from its RTM release). I am by no means a designer, but I found it fascinating. I also highly recommend watching Jensen Harris’ talk, 8 traits of great Metro style apps.

Second, Metro style apps don’t replace .NET (or Win32 or Web Applications). You can continue writing .NET apps (including XNA games) and expect them to run without any compatibility problems in Windows 8 Desktop style. Right now it’s not clear whether Desktop style apps will be supported on ARM-based tablets, but if you’re looking to create tablet apps, you really should be using Metro style, not Desktop style, since design of the Windows Runtime (more about that shortly) makes creating touch-friendly apps really easy. If you do any XAML development (WPF, Silverlight) then your XAML skills and even much of your XAML markup will translate directly into the world of Metro style apps. Much of your .NET code will translate directly as well, though there are some differences (and if you’re looking to create WinRT components that can be used in other languages/runtimes then there are some significant differences in order to meet ABI-compatibility requirements that will allow your component to be projected into those other languages in a way that meets the expectations of developers who use those languages. One thing you’ll notice is that .NET 4.5 maintains the same 4.0.30319 version number as .NET 4.0. This is intentional, not an oversight. .NET 4.5 is a superset of .NET 4.0 and the .NET teams at Microsoft have spent a lot of time and effort to make it so that existing .NET 4.0 apps can take advantage of the (in some places huge) performance increases in .NET 4.5 without any changes. There are new APIs (including new APIs for WPF) but backwards compatibility was one of the design goals so you should expect your existing Desktop apps to just work. If you’ve looked at anything about Metro, you’ve undoubtedly seen the (infamous) chart which was designed to highlight aspects of the Windows Runtime and wound up confusing people into thinking that Microsoft lost its mind and threw away decades of work and compatibility. Remember that Microsoft is a company that has built its reputation on backwards compatibility (to the point where they’re still maintaining bug-level compatibility for old 16-bit Windows 3.1 and earlier APIs (with due consideration given to security issues, of course) in order to let companies continue using applications they rely on in the latest versions of Windows.

Ok, so that gets us to Metro style and the Windows Runtime (“WinRT”). Metro style apps use the Windows Runtime (and a small number of Win32 APIs (mostly DirectX)) as their interface to the OS. The Windows Runtime is projected into various languages in ways that are natural and familiar for their developers. So there’s the WinJS library that exposes WinRT as a collection of JavaScript objects (all found within the Windows object, thereby mimicking namespaces) and even does things like project event handlers using both the on_______ function syntax as well as the addEventListener and removeEventListener functions (allowing multi-cast delegates) and adjust the casing of method names to match the conventional JavaScript function syntax where only objects that can be newed start with a capital letter while methods (functions) of objects use camel casing with the initial letter being lower case. Similarly it projects into C++ via the C++/CX syntax (C++ Component Extensions) which looks like C++/CLI but is entirely native rather than .NET (C++ developers can also use WRL to bypass C++/CX if they want to, but it’s not pretty and so most WRL stuff is there really just the implementers C++/CX itself with exceptions like ComPtr that you’ll find used in DirectX programming). Lastly, WinRT is projected into .NET using a combination of BCL classes (e.g. System.String is a projection of WinRT’s HSTRING type) along with the new Windows.* namespaces.

The takeaway from the above is that WinRT is an OS interface (under the hood it’s design is based on COM with a lot of improvements and advances), just like .NET and Win32. It’s projected into different languages in ways that are natural for that language. Where it makes sense, those projections are done via existing things such as .NET classes. But it doesn’t eliminate the Desktop style version of those models. Just provides a new, clean, modern OS interface that will likely supplant Win32 and .NET within the next 10-15 years for most use cases.

Which gets us to Metro style presentation layers. As of the developer preview, your Microsoft provided options are:

  • HTML5/CSS3 with JavaScript;
  • XAML with C#/VB/C++ (native, not the .NET CLI version); or
  • Raw Direct3D (including Direct2D and DirectWrite) with C++.

For high performance game development, Microsoft recommends using Direct3D (and other DirectX APIs) with C++. This gets me to my * above. They haven’t announced a new version of XNA for Metro style apps and the existing XNA, being based on DirectX 9, can’t be used for Metro style apps. This has been a difficult thing to come to terms with. XNA completely changed my life. I’m a better, happier person than I was before I found it. XNA is still the way to go for XBLIG and Windows Phone game development. And you can continue using it to create Desktop style games (it’ll run just like it was Windows 7). But I’m quite sad that they haven’t announced a Metro style version of XNA, though it would certainly be a massive undertaking due to the sea change between DirectX 9 and DirectX 10 (continued in DirectX 11). For those looking for .NET solutions that’ll work in Metro style apps, have a look at SharpDX, (possibly) SlimDX (I believe a Metro-style port is in the works but am not sure), and (possibly) projects like ANX.Framework (not currently targeting Metro style but may in the future).

---------

And thus we arrive at getting started with Metro style DirectX. I’m really excited about the new Windows and about Metro style and the Windows Runtime. I’ve been learning DirectX programming for a while, but it’s taken on a new urgency so the last few months have been a bit of an unexpected cram course for me. But I do believe that I grok it now (or much of it anyway). And I’ve decided to help those of you who are, like myself, XNA/.NET developers who have decided to take the plunge into the world of Metro DX with C++.

Some good news first. If the last time you looked at C++ was around the turn of the millennium, it has become much better. The C++11 (formerly called C++0x) additions make it a much nicer language and the new Windows Runtime stuff that replaces the old C-style Win32 core APIs (no more WndProc and other dark incantations; it’s real objects with events and everything now) is a huge improvement. The improvements to C++ IntelliSense in VS11 are huge and Visual C++ now supports code snippets and other productivity features.

None of this changes the fact that it’s still C++ though. It still has separate header files and code files which makes for a lot of minor annoyances. It still requires you to tell it which libraries to link against (which you do by viewing the project’s properties and then under “Configuration Properties” in “Linking” under “Input” adding them to the “Additional Dependencies” property) and throws compilation hissy fits with horrifying error messages if you make some minor mistake like try to call a static method via, e.g., ThreadPoolTimer.CreatePeriodicTimer(…) rather than ThreadPoolTimer::CreatePeriodicTimer(…) (a thousand apologies oh great compiler for daring to offend you with syntax that you clearly understand but nonetheless consider an abomination). (Yes, me and C++ have a long, at times ugly, history, but with age I’ve learned to mostly just accept it for what it is rather than pointlessly cast aspersions upon it.) Personally, I’d say that I’m now about 75% as efficient in C++ as I am in C# and I don’t really expect that to ever improve since C++ is just more verbose and demanding than C# is and improving it would require changes that would break the language and cause its diehard fans to rise up with torches and pitchforks.

This isn’t a one-off post. I’m planning a series of articles to help relate DirectX 11 to XNA and the C++ Standard Library to the .NET Framework. I can’t commit to a particular schedule but I’m hoping for a cadence of approximately a post a week.

Though I still haven’t actually told you how to get started so I can’t quite wrap up this post. You need a copy of the Windows Developer Preview and VS11 Express for Windows Metro style or VS11 Ultimate. The preview versions of VS11 won’t install on earlier versions of Windows. Note that installing the Windows Developer Preview is a one-way operation; you have to pave and reinstall if you want to go back to Windows 7/Vista/XP. I bought a separate hard drive and installed it to that. Others have used Virtual Machines. Search around; there’s a lot of good advice. For the developer tools version of WDP, you’ll need either a dual layer DVD+/-R or a thumb drive that is at least 8 GB.

Once you have everything installed, you’re ready to begin. I recommend reading Chuck Walbourn’s Getting Started with Direct3D 11 and the materials he links to. I especially recommend reading “Introduction to Direct3D 10” (SIGGRAPH 2007) since Direct3D 11 builds on the huge changes that were introduced in Direct3D 10. One of those changes was to scrap the old caps (capabilities) system that D3D 9 used and replace it with a bucketing system that is now known as feature levels. D3D10 hardware has to implement almost the entire spec (there are only 2-3 things that are optional); the same is true for D3D11 hardware and the D3D11 spec (which is, itself, a superset of D3D10, which is a superset of the capabilities in D3D9). The feature levels allow you to use D3D11 to target most D3D9 GPUs in code (along with D3D10 and 11 GPUs, of course). Rather than build a completely separate rendering pipeline for older cards, you can now just build one base rendering pipeline that works for all hardware and add in more advanced features (like geometry shaders and tessellation) to your graphics pipeline based on the feature level you get back when creating the device along with some performance checks to account for different hardware levels. (An entry level DX11 card may implement all the same things as a high end DX11 card, but it has less ALUs, fewer shader units, a lower clock speed, and slower RAM, all of which combine to produce a distinct difference in performance (and power usage, which is important for laptops and tablets)). The other big change in D3D10 was to change how resources (e.g. textures and vertex buffers) are created such that they are now validated at creation time rather than every time they are bound to the pipeline (as in D3D9). This creates a big performance gain.

The big change in Direct3D 11 was the separation of the graphics device into a device and one (or more) device contexts in order to make multithreading much better. A game will still have one ID3D11Device which is used for things like resource creation (including shaders) but it now will have one ID3D11DeviceContext which serves as the immediate context (i.e. it renders to the back buffer) and zero or more device contexts which are deferred contexts (they render to a command list that the immediate context can then take and execute exceedingly fast). On multicore machines, it can make sense to split off certain rendering operations onto a separate thread in order to perform the CPU side of rendering in parallel (one example being a particle system).

The big change in Metro style DirectX is that D3DX is gone. Desktop apps can still make use of it, but Metro style apps need to use other APIs (e.g. the D3DCompiler_xx.DLL APIs - http://blogs.msdn.com/b/chuckw/archive/2010/04/22/what-s-up-with-d3dcompiler-xx-dll.aspx).

One of the best ways to learn DirectX is with code samples. The samples provided for the Windows Developer Preview are all pretty good and this explanation of the Marble Maze sample does a particularly good job of explaining how a simple 3D game comes together. Much of the code can easily be reused with little-to-no modification for your own games. There’s code that simplifies loading everything from textures to audio to 3D models. I also strongly recommend the //build/ videos about DirectX. They demonstrate a lot of the really neat features that have been added to DirectX and to Visual Studio (PIX is now integrated into Visual Studio, for instance, and you can now do code analysis for C++ (even in the Express version!).

Happy new year to all!

Posted On Saturday, December 31, 2011 4:06 AM | Feedback (1)
Tuesday, September 06, 2011
Leveraging MSBuild for Ruthless Productivity

(Warning: This is semi-advanced stuff. It’s not hard, per se, but it involves editing important project files manually, which, if done wrong, can render them useless making it so that your code won’t compile (and may not even load into Visual Studio). So back up everything or (better still) commit it to your source control repository before doing anything so that in case you mess something up, you can easily recover! You have been warned.)

I’ve been steadily becoming more familiar with MSBuild over the past weeks and months. As my familiarity has grown, so too has my conviction grown firm that MSBuild is the unsung hero of the programming world.

MSBuild, also known as the Microsoft Build Engine, is a program that parses XML files and executes various commands (known as “Tasks” ) contained within them based on the target ( “Targets” ) or targets that are specified. You’ve undoubtedly looked through your project directories over the years and seen files with extensions like .csproj , .vbproj , .vcxproj , .fsproj , and so on. You may even have opened one up in a text editor before and seen a whole large jumble of XML tags with names like <PropertyGroup> and <ItemGroup>. These files are your project files; they’re what tells Visual Studio what files are part of your project, what assembly references your project depends on, and so forth. They also, in part, define what happens when you choose to build your project or solution via the Build menu or via a shortcut key such as F6.

(n.b. Native C++ projects, i.e. .vcxproj files, have their own targets defined in its own special MSBuild files. The rest of this is going to be discussing managed projects, so while it may make interesting reading, remember that Native C++ does its own thing, with its own properties, item groups, and targets that are designed for dealing with the target platform-specific nature of native code).

One thing that’s important to understand is that simply looking at a .csproj (or other .*proj) file will not tell you what is going on. The reason for that is the <Import> tag, which is used to import various other files. One file that’s imported in almost all projects is Microsoft.Common.targets. This file is quite long and consists of more MSBuild XML. What’s important about it is that this is where the default build pipeline is set forth. It defines a number of targets, chief among them being Build, BeforeBuild, CoreBuild, and AfterBuild. It also sets the <Project> tag’s DefaultTargets parameter to be the Build target.

Build itself calls the BeforeBuild, CoreBuild, and AfterBuild targets in that order. CoreBuild is what does all the reference locating, compiling, and linking stuff. It has a number of targets that it runs, but we aren’t going to concern ourselves with that other than to say that the PreBuildEvent and PostBuildEvent targets run within CoreBuild at appropriate times. If you’ve ever viewed your project’s “Properties” in Visual Studio, you may have noticed the “Build Events” tab in which you can specify command line commands to run pre-build and post-build. That’s how these are hooked up, so know that the BeforeBuild target runs before PreBuildEvent and that PostBuildEvent runs before AfterBuild.

Well, so far this has been a dry walkthrough of arcane XML. Where’s the “ruthless productivity” part? It has arrived. We simply needed the dry walkthrough to get to it (and understand it, more importantly). When you build a project, it runs the Build target because that’s what the project (via importing Microsoft.Common.targets) has been setup to do. By default the BeforeBuild and AfterBuild targets do nothing. You, however, can change that. If you edit your .csproj or .vbproj file (Visual Studio’s XML editor works great, but note that the project needs to be closed before you can edit its project file), you’ll find that you can either uncomment the existing, commented out BeforeBuild and AfterBuild targets or else (if they aren’t there or if you feel like making your own tags instead) you can write your own. Do you have anything that you need to do before you build a project? Perhaps for an XNA game you want to copy the latest art assets out of some other directory and move them to the content directory so that your game builds the latest assets. Perhaps you have some files that need to run through a tool or maybe after the build finished you want to copy the new build to a network drive so that you (and other members of your team) can access and run the latest build.

This is where MSBuild shines. Simply open up your .csproj or .vbproj file (or even a .contentproj file) and add some tasks to the BeforeBuild and/or AfterBuild targets. There are many predefined tasks to choose from and, if none fit your needs, you can always write your own custom task. When MSBuild runs a project file, the working directory is generally the directory in which that project file is located; this is handy for when you’re running a Copy task since you can use relative paths (rather than hard-coded ones) so that someone else on a different machine with a different directory structure can still build the project correctly. If you want to run some program, you can make use of the Exec task. You can even check various conditions and abort the build with an Error task if a check fails.

So where does this leave us? Now, rather than have to manually perform various tasks that are necessary to your build process or that you want to perform after the build, you can instead automate them with a few simple lines of XML. Even complex tasks are not outside the read of MSBuild; you just may need to write a custom task for it or perhaps run several different tasks back-to-back (with some error checking thrown in for good measure, of course).

Some final notes. I didn’t really talk much about the ItemGroup and PropertyGroup tags. These are container tags into which you can add various tags with your own unique names. An ItemGroup is normally used to specify one or more files whereas a PropertyGroup is normally used to specify and store values and for evaluating conditions.

A member of an ItemGroup is normally dereferenced via the @(SomeItemTag) syntax, which will by default produce a semicolon separated list of things that are specified in tags in the project’s ItemGroup(s). The above would pull out all items within an ItemGroup that were stored inside <SomeItemTag Include=”text here”></SomeItemTag> pairs. Note that all items must have an Include attribute and that multiple elements within the same Include attribute should be separated with a semicolon. With ItemGroups, you can have the same tag multiple times (and within multiple ItemGroup tag pairs) and it will concatenate them all (provided that you properly escape any special characters using %xx syntax, where xx is the hex code of the ASCII value of the special character ).

Members of a PropertyGroup on the other hand are dereferenced via the $(SomeProperty) syntax. Unlike with ItemGroup, you can only have one instance of a specific tag for PropertyGroup. To the extent that you use the same tag multiple times, only the value of the last instance of the tag will be used. Properties don’t require an Include attribute and normally are specified by including the value within a tag.

As a brief example, here’s a simple MSBuild file that shows some usage of a target, a task type (the Message task), and various ItemGroup and PropertyGroup groups.

<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Hello" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Target Name="Hello">
    <Message Importance="high" Text="@(SomeItemTag)" />
    <Message Importance="high" Text="$(SomeProperty), $(SomeOtherProperty)" />
  </Target>

  <PropertyGroup>
    <HelloWorld>Hello world</HelloWorld>
    <SomeProperty>$(HelloWorld)</SomeProperty>
  </PropertyGroup>
  <PropertyGroup>
    <SomeOtherProperty>how's it going</SomeOtherProperty>
  </PropertyGroup>
  <ItemGroup>
    <VariousFileNames Include="Shiver.bmp;Me.tif;Timbers.xcf"></VariousFileNames>
    <SomeItemTag Include="Ahoy.png;Arg.jpg;@(VariousFileNames)"></SomeItemTag>
  </ItemGroup>
  <ItemGroup>
    <SomeItemTag Include="*.msbuild"></SomeItemTag>
  </ItemGroup>
</Project>

 

If you run a Visual Studio Command Prompt (to setup the environment variables and paths), you can save this to a text file named, e.g. “test.msbuild” and then run it from the command line via:

msbuild test.msbuild

The file name extension doesn’t matter, btw. I used it just for easy knowledge of the file’s contents. Another thing to know is that MSBuild predefines a large number of properties. If you want to see what all they are, do the same as above only this time run it as:

msbuild /v:diag test.msbuild

That tells msbuild to use a verbosity of diagnostic. To find out other command line parameters, just type:

msbuild /?

and it will show you. You can do things like specify properties (and their values) and set a different target than the DefaultTargets target. Say we added a target above called “Goodbye”. Just running MSBuild as is would run the Hello target (and only the Hello target). If you instead used the command line switch, you could tell it to run the Goodbye target or even both targets (in whichever order you specify).

This only scratches the surface of what MSBuild can do. I left out quite a bit that the links do a good job of explaining, so make sure to read them. If you find this post interesting, you might want to bookmark it. I wrote it in part so that I would have something to refer back to whenever I needed, It’s not the kind of thing you’re likely to use every single day or even every week. You might only modify your .csproj file once or twice in the course of an entire project development cycle. So it’s easy to forget quite a bit of this as time passes. If you have any questions, leave comments and I’ll respond to the extent that I can. I may return to this topic again in the future, but for now this should be a good, quick intro to MSBuild.

Posted On Tuesday, September 06, 2011 8:26 AM | Feedback (0)
Friday, August 26, 2011
SmartAssembly 6.1 Review

It’s been quite a while since I’ve done a GeeksWithBlogs.net Influencers review. This time, I had the opportunity to check out Red Gate’s SmartAssembly 6.1, which is a integrated collection of tools for modifying and manipulating assemblies. Now that phrase, while accurate, is quite a mouthful. So what all does it actually do?

SmartAssembly has the ability to:

  1. Do strong name signing;
  2. Add automated error reporting;
  3. Add feature usage reporting;
  4. Merge dependencies (e.g. libraries) into the main assembly (which lets you then apply obfuscation, etc., to them as well);
  5. Embed dependencies into the main assembly (letting you compress and encrypt them in the process, making deployment faster and maintenance nicer);
  6. Automatically prune unneeded metadata like the names of events, properties, and methods (making the assembly smaller such that it’ll run faster and also be much harder to understand if decompiled);
  7. Obfuscate the names of classes, methods (including properties), and fields, with varying levels of configurability;
  8. Obfuscate control flow (modifying the order that code runs in (without messing up how it works) such that the logic becomes very hard to understand;
  9. Have a proxy created at runtime for accessing methods, properties, and fields in external assemblies, which makes any attempts to modify the assembly render it non-working;
  10. Compress and encrypt resources;
  11. Encode non-constant strings, which is useful if you need to store sensitive information such as passwords, SQL queries, etc., in your code;
  12. Apply several other protections and optimizations (e.g. sealing classes that aren’t inherited from);
  13. Generate debugging information which will let you debug your modified assembly in your IDE; and
  14. Integrate into your build process.

Which of these you can use depends on the type of assembly you’re working with; various features aren’t available due to technology limitations, e.g. the automated error reporting and feature usage aren’t available on Xbox 360 XNA games since there’s no external internet access. For a list of feature compatibility, go to the Release notes - version 6.xx and scroll down to “Known limitations”, which includes a helpful chart of what is available in what.

Well, the first thing I expect many people will notice is that it does obfuscation. But I don’t want to talk about that first, since SmartAssembly does a lot of other really neat stuff that probably gets overlooked. One thing I found really interesting was the Automated Error Reporting functionality. You just check a box and it automatically adds a wrapper for unhandled exceptions that lets your users send in anonymous error reports either to the free service that Red Gate operates or, if you have SmartAssembly Pro, to your own server using the web service software they provide: Setting up a custom web server for reporting . The thing I really liked about it is that it works with Windows Phone 7 (both Silverlight and XNA), which is my primary development target these days. You get a full stack trace, including the values of various variables (try saying that five times fast :) ), along with a lot of in-depth information, such as the version of the app, the OS (including version), the CLR version, and a hash of the UserHostAddress (which should help you to sort out which reports come from which users). You can set flags on them, save the reports for browsing later, and mark your progress. This is an example of a saved report:

SmartAssemblyExceptionReport

As you can see, it provides a lot of helpful information, including the exception message (in my case, the fact that I haven’t implemented the “Open” button yet, which is something I knew). The other thing Automated Error Reporting will do is try to recover from the exception if possible. In the case of my unimplemented “Open” button, it popped up the little notification message box telling me there was a problem, asking me if I’d like to send details about it in to help improve the software, and then continued on as though I hadn’t pressed the problematic button. This is one of those features that I know I’d normally overlook or pay little attention to, which is why I’m making a big deal about it. The quality of its implementation, the ease of applying it (as simple as just checking a box), and the value that it adds to a .NET application makes SmartAssembly worth its price on this feature alone in my opinion. Have a look at some of the walkthroughs and videos for more information; they’re short and interesting.

On to obfuscation. If you don’t know what obfuscation is, it’s basically the application of various techniques in order to make it very hard if not impossible for someone to take your .NET program and see its source code using a disassembly tool like ildasm.exe or .NET Reflector. I did several tests of its obfuscation capabilities based on projects I’ve completed, that I’m actively working on, and that I just use for testing. My experiences were mostly good.

I struggled a bit getting my WP7 Silverlight app to obfuscate properly and still work correctly. The obfuscated version was having issues with parsing XAML, which is not surprising given that XAML data binding relies on reflection to work properly and obfuscation messes around with all sorts of things.

It turned out that my problem was event handler methods. Specifically, in various places in my XAML, I was handling events with methods in my code-behind class for the Page that weren’t marked public. For Silverlight projects, SmartAssembly automatically excludes anything marked public from name mangling; anything else gets mangled by default. The solution in this case was to either mark those methods public and let SmartAssembly automatically exclude them, to go and mark them manually (when you put a check next to an assembly in the Obfuscation area, a link called “Exclusions” appears next to it, letting you go in and exclude any namespaces, class names, methods (including custom property getters and setters), and fields that you want from having their names mangled), or to apply custom attributes to them. The last solution is probably the best to go with since once it’s all setup, it’ll just work no matter what you change or refactor in your code.

Once I fixed that issue, almost everything worked. I also had an issue with a third-party control that I was using. I was hoping to be able to merge it and obfuscate it (either name mangling, control flow obfuscation, or both), but it was not meant to be. SmartAssembly recommends against trying to merge third party libraries, suggesting that you embed them instead. Embedding isn’t an option for WP7 though, so I had to modify how I was using the control. Initially I had it as a project within my solution and was including it as a reference as a project. What I did instead was build it as a separate DLL and apply obfuscation to it with a separate SmartAssembly project. I then included a reference to the obfuscated, pre-built DLL and it worked like a charm. Many would consider that a ‘best practice’ way of doing such a thing anyway (seeing as you’re rarely, if ever, going to be changing that third party code so rebuilding it all the time makes no sense), so it was a double benefit in that regard. With that issue resolved, everything worked great.

Next I tested a WP7 XNA app that I’m working on. Once I set up the SmartAssembly project, it worked perfectly the very first time. The error reporting was very simple to integrate and a really pleasant surprise (I created an intentional exception, which you can see in the screen shot above, just to test it). It’s something I will definitely be making use of and something I highly recommend to everyone. Do note that if you setup the automated error reporting to email you for every error report, it will indeed do this. If you publish something and a lot of people get errors in one particular place (which might be very common when doing a beta test, for example), you can expect to get a lot of emails as a result. So I recommend dedicating a special email address for that feature, if you choose to use it, so that you don’t wake up to find your personal inbox chock full of messages. :) (This did not happen to me, but I could easily see it happening by accident, especially for something that you’re just doing a private beta for such that you might not think to use a special email address for it.)

The last thing I tested was my PC XNA sandbox app. I have over half a dozen “sandbox” apps that I use to test out various things in different languages and technologies. I most recently used my PC XNA sandbox app to do some stress testing on SpriteBatch draw calls. So it was already setup to not run particularly well, making it a good measuring platform for how SmartAssembly’s various components affect performance. I modified the project to use a WeakReference to track when GC collections occurred, added in a pointless allocation of 5000 bytes every frame, then used a StreamWriter to write out GC data every time a collection occurred; specifically: the current count of collections, current total game time, the time difference (delta) from the last GC collection, and the average time delta between collections. It was already setup to display the current frame rate. For the SmartAssembly-modified version, I initially set it to use Automated Error Reporting, Obfuscation (Types/Methods Name Mangling set to “I want to obfuscate using only Unicode unprintable characters.” and Fields Name Mangling set to “I want to use standard renaming, so that all the fields in a class have a different name.”), Control Flow Obfuscation, and to seal all classes that are not inherited (under Other Optimizations).

The results? The original Release build (run as a standalone program outside of Visual Studio) and the SmartAssembly-modified version of that Release build ran virtually identically. Both maintained the same frame rate hovering between 34 and 35 fps. I stopped both after they hit a GC count of 21 (I didn’t track any GCs that occurred during the LoadContent phase, just during gameplay). The original Release build hit its 21st GC at 61.950 seconds in with an average delta of 2.950 seconds. The SA version hit its 21st GC at 62.067 seconds in with an average delta of 2.956 seconds. Yep, the SA version actually won (though just barely; it could easily be due to my computer doing stuff in the background). Since the test was to see if it hurt performance, and (with several runs of each just to avoid obvious anomalies) they both ran virtually the same, it seemed clear to me that it didn’t.

Just for kicks, I created another SmartAssembly version, this time with everything enabled except for Generate Debugging Information, Strings Encoding, and Strong Name Signing. I also turned up obfuscation to its maximum levels. I also ran this one several times just to confirm the results weren’t anomalous. This build runs an initial GC much earlier than the other tests (after ~1.7 seconds versus ~2.7 seconds for the previous two builds), but then runs virtually the same as the others. An example run hit its 21st GC at 61.065 seconds in with an average delta of 2.908 seconds. But if you exclude the first collection and average the other 20, you wind up with an average delta of 2.969 seconds. The other builds also showed a slightly early first GC so I’m willing to call them functionally identical. What all these tests told me is that this is a great way to protect my programs without any noticeable performance hits.

The last thing I want to talk about is the ability to automatically integrate a SmartAssembly project into your build pipeline. You can add SmartAssembly in to the MSBuild process or into a ClickOnce deployment. I’ve done this for a couple of projects already and it’s quite easy and very smooth. Some projects (e.g. XNA games) generate extra content that needs to be copied into the output directory (for XNA games, any of your content folders along with their XNB files). You can either configure an MSBuild Copy Task to do that for you (just add it in with the SmartAssembly Task into the AfterBuild target) or you can do it by hand or some other way. So just take note that SmartAssembly (when integrated into MSBuild at least; I haven’t tested ClickOnce) only creates the assembly or assemblies that it is operating on at its destination and that it’s up to you to setup a mechanism for copying any other content files that your assembly depends on.

Just as with ANTS Memory Profiler, I found I really liked SmartAssembly. It’s easy to work with, the help materials and learning videos are really good, and it makes a variety of otherwise complicated tasks very easy to do. There’s a 14-day, fully functional free trial for it, so if you’re on the fence, go check it out and see what you think.

(n.b. While I was finishing up this review, version 6.2 was released. The release notes indicate that the changes are very small and shouldn’t have an impact on anything I discussed above. They do mention the provision of sample error reports, which I think is a great addition since it lets you see what you’ll be getting from error reports without having to spend time creating your own.)

Posted On Friday, August 26, 2011 5:57 PM | Feedback (0)
Saturday, August 06, 2011
Interpolation Sample for XNA

One thing I’ve always enjoyed in Silverlight/WPF are the easing functions ( http://msdn.microsoft.com/en-us/library/ee308751.aspx ). The easing functions are commonly used to provide interesting looking animations via key frame-based interpolation.

XNA has a few, limited bits of interpolation built in (primarily Lerp (i.e. linear interpolation) and SmoothStep (i.e. cubic interpolation)). For a sprite animation project that I’ve since set aside (it’s not dead, but it’s been back-burnered for a while now), I replicated most of the Silverlight/WPF easing function (I never got around to figuring out BounceEase and ElasticEase) so that I could use them in XNA. I decided I’d make them available to all of you to use as well. They’re great for spicing up menus and other animations.

The important part of the sample is the Interpolation.cs/Interpolation.vb file; that contains the static class and the two enums that combine together to provide the interpolation. There are two solutions: Interpolation Sample and Interpolation Visualizer. Sample is a basic demonstration of how to use some of the functionality within an XNA game to do things like animate a sprite’s tint color, scale, and position. Visualizer is a WPF app that lets you see what the different enum values produce (and for a few, what the “formula value” does). The code is dual licensed under the MIT License and the Microsoft Public License. You can get it here: C# - Interpolation_SampleCS.zip VB - Interpolation_SampleVB.zip. The zip files contain both the Interpolation Sample and the Interpolation Visualizer despite the names. Note that the Interpolation Visualizer will need to be built once before you MainWindow.xaml will display properly in the designer due to its use of data binding. Until you build it, it’ll probably tell you that there are errors since it can’t use reflection to find things in an assembly that doesn’t exist yet.

Enjoy!

Posted On Saturday, August 06, 2011 3:23 PM | Feedback (0)
Bob Taco Industries is an ISV focused on game and app development for Microsoft platforms headed up by Michael B. McLaughlin. Mike is a Microsoft XNA/DirectX MVP, a developer, a writer, a consultant, and a retired lawyer. If you're a developer who is just getting started, consider checking out the BTI website's section for developers for links to code samples and other helpful sites.
Tag Cloud