Your first DirectX 11 Metro application using SharpDX

UPDATE: you can learn how to initialize Direct3D in XAML applications in this new article.

Since Microsoft has decided that “XNA is mature enough” and Shawn Hargreaves has moved to Windows Phone, it looks like we won’t see a version 5 that supports Metro-style applications. The only alternative for graphics programming is using pure DirectX 11 now that it has been merged in the Windows core (no more separate DirectX SDK downloads, yay!) and Microsoft is going to actively promote it (Visual Studio 2012 includes a nice node-based shader editor).

So, if you want to target Metro apps with DirectX, the only initial option is to use C++/CX, which in my humble opinion is a total overkill and a huge step back. Sealed classes, no member functions for structures… this is the 21st century, please let me use a modern programming language and not one that has been patched through 30 years of existence. Well, now you can do this, thanks to the SharpDX project. It’s a series of wrappers that let you access the DirectX libraries from your C# code, and since XNA looks like a dead end, it’s what I’ll be writing about from now on.

Begin creating a new Windows Store > Blank App (XAML) (remember that this template is only available if you are running Visual Studio 2012 in Windows 8!)

Create a new Windows Metro Style Blank Application.

Now you can safely delete all the files except the Assets folder (contains the Windows Store icons for your program), the Package.appxmanifest file (has information about your application deployment settings) and the *_TemporaryKey.pfx file (the temporary certificate for signing the app). We will make everything from scratch.

Get yourself a copy of SharpDX’s libraries. You can download the latest stable version (recommended, since DirectX SDK is required for compiling) or get a copy of the source code and build it by yourself. I will be using the stable versions (2.5.0 as of the writing of this tutorial) and updating when necessary. Now, add references to SharpDX.dll, SharpDX.DXGI.dll and SharpDX.Direct3D11.dll.

Window creation for Windows Store applications is a bit different from everything so far. You can’t instance them directly, as they must be created via a proxy class that implements the IFrameworkViewSource interface. The only method that is enforced by this interface is CreateView, that returns a IFrameworkView object. And yes, you guessed it correct, your window class must implement it.

MyViewProviderFactory class
  1. internal class MyViewProviderFactory : IFrameworkViewSource
  2. {
  3.     public IFrameworkView CreateView()
  4.     {
  5.         return new MyViewProvider();
  6.     }
  7. }

This factory must be instantiated in your Main function and passed to the Run method of CoreApplication:

Main function
  1. private static void Main()
  2. {
  3.     // Tell CoreApplication to create a view instance through the factory.
  4.     MyViewProviderFactory factory = new MyViewProviderFactory();
  5.     CoreApplication.Run(factory);
  6. }

The methods enforced by IFrameworkView are the following:

  • Initialize(CoreApplicationView applicationView): this is the first function called when running the application. The applicationView variable has a CoreWindow property, but it’s null for some reason, so we can’t do anything at the moment.
  • SetWindow(CoreWindow window): called immediately after Initialize, with the current window as a parameter. Now we can save it in a member variable for future use.
  • Load(string entryPoint): create all the necessary Direct3D resources. Explained in more detail below.
  • Run(): we must implement here our update and render loop. Explained in more detail below.
  • Uninitialize(): called when the app is closing. We should release here all our non-disposable resources.

Now comes the fun part: creating all the Direct3D/DXGI objects to get a valid backbuffer. Start by instantiating a new Direct3D11.Device and specify DriverType.Hardware in the constructor. If this fails it means that you don’t have any hardware devices capable of using DirectX so you will have to fall back to software or upgrade your GPU!

Default device creation
  1. SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug);

We have to execute a series of queries to retrieve the final object that we will need: a DXGI.Factory2 that will allow us to create a swap chain for our CoreWindow based on the settings we specify in a SwapChainDescription1 instance. Finally, we create a RenderTargetView from said swap chain and save it for future use.

Backbuffer creation
  1. SharpDX.DXGI.Adapter dxgiAdapter = dxgiDevice2.Adapter;
  2. SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent<SharpDX.DXGI.Factory2>();
  3. // Description for our swap chain settings.
  4. SwapChainDescription1 description = new SwapChainDescription1()
  5. {
  6.     // 0 means to use automatic buffer sizing.
  7.     Width = 0,
  8.     Height = 0,
  9.     // 32 bit RGBA color.
  10.     Format = Format.B8G8R8A8_UNorm,
  11.     // No stereo (3D) display.
  12.     Stereo = false,
  13.     // No multisampling.
  14.     SampleDescription = new SampleDescription(1, 0),
  15.     // Use the swap chain as a render target.
  16.     Usage = Usage.RenderTargetOutput,
  17.     // Enable double buffering to prevent flickering.
  18.     BufferCount = 2,
  19.     // No scaling.
  20.     Scaling = Scaling.None,
  21.     // Flip between both buffers.
  22.     SwapEffect = SwapEffect.FlipSequential,
  23. };
  24. // Generate a swap chain for our window based on the specified description.
  25. swapChain = dxgiFactory2.CreateSwapChainForCoreWindow(device, new ComObject(window), ref description, null);
  26. // Create the texture and render target that will hold our backbuffer.
  27. Texture2D backBufferTexture = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
  28. backBuffer = new RenderTargetView(device, backBufferTexture);

Let’s finish this up by creating our main loop. Since CoreWindow doesn’t do it by default, you have to create your own loop and check when to exit the application (key pressed, focus lost, etc.). So just slap a while (true) in the Run() function and exit it with a return when you want (in this tutorial we check for the Escape key being pressed with window.GetAsyncKeyState(VirtualKey.Escape) == CoreVirtualKeyStates.Down). For now, the only Direct3D operations that we will be performing is to set the backbuffer and clear it with the color red, and then presenting it:

Clear screen/present
  1. context.OutputMerger.SetTargets(backBuffer);
  2. context.ClearRenderTargetView(backBuffer, Color.Red);
  3. // Present the current buffer to the screen.
  4. swapChain.Present(1, PresentFlags.None);

That’s it. You can grab the entire source code from the GitHub repo. Stay tuned for more articles!

How to compile a static library as a DLL using VC++

So you have the source code for an old, static library lying around and you want to compile it as a dynamically linked one for whatever reason. Well, it’s as easy as going to the project properties > Configuration Properties > General and change Configuration Type to Dynamic Link Library (.dll).

image

See? Now you can hit F6 and have VC++ compile it into your new, shiny DLL. Grab it from the output directory, link it at your pleasure and start usi- wait, it doesn’t work.

If you examine the DLL with a tool like dumpbin.exe and ask it to show you the exported symbols, you will see something like this:

image

What does this mean? Yes, your DLL is still full of code, like function and class definitions, but not a single one of them is being exported. How can we solve it? Navigate to the header files and stick a __declspec(dllexport) before each function/variable/class definition you want to export. Now recompile and watch magic happen:

image

Now your DLL has the necessary info for linking. And if you are going to import it via GetProcAddress/DllImport, you are good to go. But if you want to do things the best way, continue reading.

Okay, so our library now exports symbols via the header files, and to use it, you must load it at runtime, get the handle to the function pointers… We can alleviate the programmer’s task by defining a small macro in the root header:

    1 #ifndef EXPORTS

    2 #define DECLSPEC_ACTION __declspec(dllimport)

    3 #else

    4 #define DECLSPEC_ACTION __declspec(dllexport)

    5 #endif

and changing all our previous __declspec(dllexport) with the new DECLSPEC_ACTION macro. In the DLL project, go to project properties > Configuration Properties > C/C++ > Preprocessor and add the EXPORTS keyword to the Preprocessor Definitions field. Now you can distribute your compiled DLL along with the header files containing all your definitions, and the compiler will know that it can ignore the missing function bodies because they are implemented in a external library that will be resolved at runtime.

Finally, maybe you are wondering why the function names shown by dumpbin.exe are so funny. They are called decorated names, and each compiler has its own way of generating them. Why are they so strange? Because C++ has some features like classes and operator overloading, and standard C used to name functions only by their name, without taking into account their parameters (and that’s why you can’t have two functions with the same name); this way the compiler can generate unique names that will be correctly resolved when linking.

So, if you want to have your perfectly enginereed DLL, rewrite all your function definitions so there aren’t two of them with the same name, and put an extern “C” when defining them. When compiled, the DLL will be generated with standard C symbols and you will ensure that it will work the same across ALL compilers and platforms, and will make the use of GetProcAddress/DllImport easier:

image

That’s it. Now you have successfully created a DLL from a static library that can be called from standard C/C++ code via the header files or loaded at runtime. What’s coming next? Creating a managed wrapper for it, so stay tuned!

XNB plugin for Paint.NET

Today I have released the first (read: very alpha) version of a plugin I’m making for Paint.NET. It allows you to load XNBs containing compiled Texture2D resources and edit them at your pleasure. Current supported data format is uncompressed assets compiled for Windows or Windows Phone (Xbox 360 uses a different endian and is on the works), with pixel formats Color, Bgr565, Bgra4444 and Bgra5551.

Future additions will include the ability to load the full mipmap chain, DXT-compressed textures, Xbox assets and resaving your work in a new XNB. So, if you want to try it, go to the project’s Downloads page at CodePlex, or browse the lastest changesets.