Mostrando entradas con la etiqueta C#. Mostrar todas las entradas
Mostrando entradas con la etiqueta C#. Mostrar todas las entradas

Manually copying Unity's APK and OBB files to an Android device for testing

When developing an Android game that is meant to be published through the PlayStore, there's a limitation regarding the maximum file size of the APK. It currently can't exceed 100 MB.

The thing is that games usually go beyond that limit. To deal with that, Google offers the so called APK Expansion Files. Every application can include up to 2 of them, with a maximum size of 2 GB each.

If your game goes beyond 100 MB, you can easily instruct Unity to split the game in two by checking the "Split Application Binary" in Edit->Project Settings->Player->Android->Publishing Settings.

Image result for unity split application binary

That will generate two files instead of one:
  • APK: the usual APK file with all the binaries, scripts etc, and the first scene included in the build settings (the scene with build index 0). You need to take care that the first scene is small enough so this APK doesn't go beyond 100 MB. In general, this scene is usually just a loading icon, or a game logo that is displayed while loading. 
  • OBB: A second Expansion File with the OBB, holding everything else. 
Some time ago, it was necessary to use a Unity plugin to deal with OBB loading, but this is no longer necessary. So, first of all, DO NOT USE that plugin. In fact, it hasn't been updated for years, and won't work in current versions of Unity. 

Current versions of Google PlayStore natively support the distribution of OBB files, so you won't need to do anything special besides providing the OBBs along with the APK when you upload your game.

Note: usually, the first time you upload your game to Google Play, it won't ask you for OBB expansion files (I guess that's a bug in the system). If that's your case, simply generate a second version of your game, and re-upload your APK. Then it will ask for Expansion Files properly. 

How to install the game locally, in a test device? 

In normal circumstances, you  just create one big APK, copy it manually to the SD-Card of your phone, and install the game by tapping on the APK file. If you do that now, the game will install fine but it won't be able to find the Expansion OBB files, so the first scene will load fine, but it will probably get stuck there. 

In order to let the game find the OBB files, you need to:

1.- Rename the OBB so it follows the convention:

Unity creates valid OBB files, but their names don't follow the convention Android expects. Your OBB file should have a name like the following: 

main.[VERSION_NUMBER].[PACKAGE_NAME].obb

Where [VERSION_NUMBER] is the highest digit of the version number you can find in the Player Settings:


And [PACKAGE_NAME] is the package name specified in the same screen, right above the version number:


So, in the example depicted in the images, the name of the OBB file would be:

main.1.com.iayucar.TestGame1.obb

2.- Copy the renamed OBB file to an specific location

The game will expect to find that OBB file in a location like:

[INSTALL_LOCATION]\Android\obb\[PACKAGE_NAME]

Where [PACKAGE_NAME] is the same value described above, and INSTALL_LOCATION refers to whether the game is installed in the internal memory or the external SD-Card (this depends on your own settings). 

As our game is configured to be installed in an external SD-Card preferably, the folder where we need to paste the OBB file is:

\\SDCard\Android\obb\com.iayucar.TestGame1\

And that's it. Now you can launch the game, and it will properly find the additional contents included in the OBB Expansion File. 

Custom MainLoop in C# / UWP applications with DirectX (SharpDX) with unlocked frame rates (beyond 60 Hz)

When you want to write a game or a 3D application in C# using SharpDX, and you want it to be UWP, there is little information about how to correctly handle the basics of the main loop.

All examples I found were based on the interop between XAML and DirectX, but if you go that path, you´ll need to rely on the CompositingTarget.Rendering event to handle your updates and renders, which lets all the inner processing to Windows.UI.XAML and limits the frame rate to 60 Hz.

So, how to create your own, unlocked-framerate-ready, main loop?

First things first:

Dude, where's my Main entry point?

Typically, a C# application has a Program static class where the "main" entry point is defined.

When you create a WPF, UWP or Windows Store application though, aparently that code is missing, and the application is started magically by the system.

The truth is that the main entry point is hidden in automatically-generated source code files under the obj\platform\debug folder. If you look there for a file called App.g.i.cs, you'll find something like this:


#if !DISABLE_XAML_GENERATED_MAIN
    /// <summary>
    /// Program class
    /// </summary>
    public static class Program
    {
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        static void Main(string[] args)
        {
            global::Windows.UI.Xaml.Application.Start((p) => new App());
        }
    }
#endif

Et'voila... There's your entry point.

So first thing is to define the DISABLE_XAML_GENERATED_MAIN conditional compilation symbol to prevent Visual Studio from generating the entry point for you.

Next, is to add your own Program class and main entry points, as always, so you have control on the application start procedure. You can simply copy-paste that code anywhere in your project.

The Main Loop

Please note: this implementation is inspired by the C++ equivalent described here.

Now that you have a main entry point, you can replace the invokation of Windows.UI.Xaml.Application.Start (which internally deals with its own main loop) with your own code.

What we want to use instead is: Windows.ApplicationModel.Core.CoreApplication.Run, which is not bound to XAML and allows you to define your own IFrameworkView class, with your custom Run method.

Something like:


public static class Program
{
    static void Main(string[] args)
    {
        MyApp sample = new MyApp();
        var viewProvider = new ViewProvider(sample);
        Windows.ApplicationModel.Core.CoreApplication.Run(viewProvider);            
    }
}

The ViewProvider class

The main purpose of the view provider is to create a IFrameworkView when required, so it could be something like this:


public class ViewProvider : IFrameworkViewSource
    {
        MyApp mSample;

        public ViewProvider(MyApp pSample)
        {
            mSample = pSample;
        }
        //
        // Summary:
        //     A method that returns a view provider object.
        //
        // Returns:
        //     An object that implements a view provider.
        public IFrameworkView CreateView()
        {
            return new View(mSample);
        }
    }

The View Class

The view class implements the IFrameworkView interface, which defines most of the logic we want to implement.

The framework will invoke interface's methods to perform the initialization, uninitialization, resource loading, etc, and will also report us when the application window changes through the SetWindow method.

For the purpose of this article, the most interesting part is the Run method, which we can write to include our own, shiny, new Main Loop:



public void Run()
{
    var applicationView = ApplicationView.GetForCurrentView();
    applicationView.Title = mApp.Title;

    mApp.Initialize();

    while (!mWindowClosed)
    {
        CoreWindow.GetForCurrentThread().Dispatcher.ProcessEvents(
                                   CoreProcessEventsOption.ProcessAllIfPresent);
        mApp.OnFrameMove();
        mApp.OnRender();
    }
    mApp.Dispose();
}

This removes the need to rely on XAML stuff in your game (and its overhead), gives you more control about how the mainloop behaves, and unleashes the possibility of rendering with a variable frame rate in C#.

Please refer to this page for further info about how to initialize a swap chain suitable for unlocked frame rates.

Hope it helps!

[UWP] Unable to activate Windows Store app - The app didn't start


Today, I've been struggling with a Visual Studio 2015 deploy error for a while.

When trying to debug a C# - UWP application, I kept receiving the following error upon application activation:


Places like this have information about other people finding the same error. Some of them even re-installed Windows 10 from scratch with no luck.

In my case, the cause (and solution) was much simpler than that:

I have my all my projects in an external SSD drive. Yesterday I was working in my laptop, and the last compilation I did there was in Release mode. When I brought the external disk back to my main PC today and tried to deploy directly as Debug, the activation failed for some reason.

So, going back to Release mode, rebuild, launch and let Windows activate the app did the trick. After that, I've been able to go back to Debug mode normally. 

Hope it helps.

Steering Wheel Support in Forza Motorsport 6: Apex (and any other UWP application)

Since Turn10 released the Forza Motorsport 6: Apex demo, there has been quite a lot of noise, rumors, and opinions about the lack of support for steering wheels like Logitech G27, G29, Fanatec, and so on.

Sites like this or even the official Forza forums have tough debates about the issue. Some users complain about Microsoft not caring about PC gamers, or even talking about a conspiracy to force us to renew our controllers (or to buy XBox Certified devices). Leaving conspiracies aside, most people wonder why a PC game has no support for steering wheels, when the controller is perfectly detected and configured in Windows.

Truth is there is no conspiracy... The answer is simple: UWP

What is UWP and why should I care? 

UWP stands for Universal Windows Platform.

Apps developed as UWP can run in any device (PCs, XBox, Phones, ...) and can be published in the consolidated Windows Store. You know, the famous convergence:one OS, one Store... So, it has its advantages (big advantages, to be honest).

Why does that affect to Forza? Guess... Forza 6: Apex has been developed as an UWP. Probably as part of a marketing campaign to push the platform forward, or maybe because Turn10 really saw the benefits of UWP. Who knows.

The thing is that UWP-compatible APIs currently offer no single way to do proper controller input, besides Gamepads. And that's probably the main reason why Forza 6 has been released as BETA until now. Because they knew they didn't have a chance to offer support for steering wheels.

See? No conspiracy. It's just a technical limitation.

So, will it be fixed?

Short answer: yes.

Long answer: a bit of history first...

To make your apps compliant with UWP, you cannot use certain old technologies that don't follow some of the current standards. One example of those technologies that are no longer valid is DirectInput.

DirectInput is a quite old piece of technology that hasn't received updates for many many years. And yet it has been the only way to get decent access to certain types of controllers, until now.

Even the Logitech Developer Labs has been using DirectInput to build their SteeringWheel SDK up to date (this screenshot has been taken today):


As a developer that has been working with DirectInput for more than a decade, I have to say that it had its charms: it was extremely open to literally ANY kind of device. But it had its drawbacks too (like a quite difficult learning curve). So I agree it needed a replacement that complies with current development standards.

That's what Microsoft has been trying in the last few years: to find a decent replacement for DirectInput. With no luck, I have to say. They created XInput, which was meant to be that replacement. Or at least that's what they promised, but the truth is that it never received enough attention to become that. It never got any kind of support for game controllers besides Gamepads. So, it never was an option for Joysticks or RacingWheels.

Some time ago, we heard about a new API called Windows.Gaming.Input. And again, it was described as the way to go now.

We (developers) were a bit skeptical about that, because it sounded too familiar after the XInput promises. And things got only worse when we could start testing it out, and again it only offered support for Gamepads.

That has changed now with the release of the Windows 10 Anniversary Update. and the corresponding Windows 10 SDK - build 14393. Both publicly released today.

So, is it fixed yet?

No, but at least the tech bits needed are there.

The Windows.Gaming.Input namespace now includes all the classes necessary to read from a wider selection of devices, including ArcadeSticks, Gamepads, HeadSets and RacingWheels (surprisingly no Joysticks by now).

I´m sure that now that the update has been released, and UWP apps can read from Steering Wheels, Turn10 will release an update to Forza 6 soon. Maybe it even exits the BETA stage, who knows.

What Steering Wheels will Forza Support?

As far as I know, Forza should support the same range of devices supported by the API. And according to the API documentation, the currently supported list of steering wheels is:


Supported Devices

RacingWheel supports any Xbox One certified or Xbox 360 compatible racing wheel without force feedback support.
Force feedback is supported on the following device models:
ManufacturerModel
LogitechG25
G27
G29
G920
MOMO Force Feedback Racing Wheel
ThrustmasterT300RS
T500RS
RGT Force Feedback
T150
TX
TMX
FanatecCSR
HID-mode for the Xbox One
So, the wait should be over soon! 

Be patient, and wait for the Forza update... 

Cheers, 

Cannot find type System.MarshalByRefObject error in UWP app

Playing and learning with UWPs today, I found a strange error when compiling with VS 2015:

Xaml Internal Error error WMC9999: Cannot find type System.MarshalByRefObject

It's a bit misleading, but one can easily see that it's related to DLL references. After dealing with it for a while, I realized some of my Nuget packages were not up to date. Updating them fixed the issue.

More precisely, updating Microsoft.NETCore.UniversalWindowsPlatform to version 5.1.0 fixed the issue.

Hope it helps! 

Advanced text replacements in Visual Studio using RegEx

This is just a quick tip about making advanced text replaments in Visual Studio.

You are probably used to the "Replace in Files" tool accessible through the Ctrl+Shift+H shortcut (see below). As you already know, you can make text replacements in multiple files, entire solutions, etc.


Using Regular Expressions (you can test them first using this site), you can make quite complex replacements that are really handy when refactoring code. Especially when those changes appear in many different places.

For instance, let's say you were accessing attributes of a class all around your code. Something like:

                        nd.Attributes["ATTRIB_NAME"].Value = "ATTRIB_VALUE";                        

And that you want to change that, replacing with a call to a method. Something like:

nd.SetAttributeValue("ATTRIB_NAME", "ATTRIB_VALUE");

First, you need a way to find all appearances of something similar, no matter what's inside those strings (ATTRIB_NAME, ATTRIB_VALUE). That can be easily achieved with the following "Find What" argument:

.Attributes\["(.*)"\].InnerText = (.*);

It includes the (.*) RegEx, which basically matches any string. By using the brackets (), it will also instruct Visual Studio to tag whatever it matches the RegEx in each find-and-replace operation. That way, we can use that values in the "Replace With" argument:

.SetAttributeValue("$1", $2);

By using $1..$n, we specify found strings tagged in the "Find What" parameter. That way, the resulting replacement will include what we want, and re-use whatever was found in the original string. 

This page includes more information about using RegEx in Visual Studio.

C# Intellisense making wrong suggestions inside foreach statements

There’s a bug in Visual Studio that has been annoying me for quite a long time: sometimes, Intellisense doesn’t work well inside “foreach” statements in C#. It makes suggestions, but the wrong ones.

For example, if I start writing “foreach (System.Xm….)” with the intention to write “System.Xml.XmlNode”, Intellisense only offers stupid options like System.FromXml that make no sense.

I’ve realized that this only happens if the parenthesis are closed. So, if you delete the closing parenthesis before start typing, Intellisense works as expected. 


I´m sure there are other ways to fix this, but for now unchecking the “Automatic brace completion” option (see below) will suffice. 

In fact, it’s an option I never liked, so two birds with one stone… J


Inyectando TypeEditors dinámicamente

Muchas aplicaciones de edición todavía utilizan Windows Forms. Y muchas de ellas (sobre todo si son prototipos rápidos o herramientas internas) utilizan el PropertyGrid como método rápido y eficiente para editar propiedades de objetos.

Una de las funcionalidades más utiles de los PropertyGrids, es la posibilidad de definir TypeEditors para las propiedades de un objeto, de forma que el sistema escogerá automáticamente un interfaz de usuario específico para editar su valor. .Net incluye por defecto algunos de ellos, como el ColorPicker o el DateTimePicker:

Cuando los TypeEditors por defecto no son suficiente, es una gran idea desarrollar tus propios editores, para hacer tus editores lo más eficientes posible. Por ejemplo, el selector de colores por defecto de .Net no permite escoger valores para el canal Alpha (transparencia). La solución es sencilla y fácil: podemos implementar nuestro propio editor que sí lo permita.

Ahora bien, ¿qué ocurre si queremos aplicar ese TypeEditor a todas las propiedades de un tipo definido en otra DLL?

Es un caso bastante frecuente. En mi entorno, por ejemplo, tengo mi propia clase para almacenar colores, llamada Color4, pero está definida en una DLL específica para operaciones matemáticas. Es una DLL muy básica que quiero mantener con el menor número de referencias posible, para evitar dependencias todo lo que pueda. Por este motivo, es imposible definir el TypeEditor en dicha DLL, ya que eso implicaría referenciar System.Windows.Forms, System.Drawing, y unas cuantas cosas más que no tienen que estar ahí. A fin de cuentas, es mi editor visual el que debe depender de Windows Forms, y no mi DLL de operaciones matemáticas. ¿La solución?

Inyección dinámica de editores de tipo

La solución es asignar el TypeEditor dinámicamente, programaticamente, o como queráis decirlo. En lugar de incluirlo en tiempo de compilación, con clásico código…

 [EditorAttribute("Color4Editor", typeof(System.Drawing.Design.UITypeEditor))]

…lo añadiremos en tiempo de ejecución, algo posible gracias a la clase TypeDescriptor y su método AddAttributes.

Basta con invocar algo como lo siguiente el el inicio del programa:

TypeDescriptor.AddAttributes(typeof(Color4), new EditorAttribute(typeof(Color4Editor), typeof(UITypeEditor)));

De esta forma, mantenemos las DLLs limpias de referencias innecesarias, y solo dependeremos de Windows Forms y similares donde realmente se necesita: en el editor.

Listo ! Smile

Massive hard drive activity when opening the Visual Studio 2013 XAML designer

This has been happening to me since last Wednesday. Honestly, I have no idea why wasn't happening before and why it started to happen now...

I have a pretty big C# Visual Studio solution, with references to native DLLs. Part of the UI is WPF, so it involves using XAML user controls. Now, when I open one of those XAML files and the designer kicks in (you can see a new process in the task manager called XDesProc.exe), my PC almost freezes.

After checking for a while, I realized that the VStudio's designer is filling the Shadow Cache folder like crazy (in my PC it's C:\Users\XXX\AppData\Local\Microsoft\VisualStudio\12.0\Designer\ShadowCache). And when I say "crazy", believe me... I mean it... It filled like 8 GB of data in a few moments...

There are many people out there with similar problems (some say to have cleaned from that folder more than 50 GB of data). You can find more examples here, here and here

If any of you have any clue about why this is happening, please let me know. By now, I managed to workaround it by completely disabling the XAML visual editor by:

1.- In Visual Studio solution explorer, right-click in a xaml file and select "Open With"...
2.- Choose XML (Text) Editor
3.- Click on "Set as default".
4.- Click Ok.


Please note: I found several websites suggesting a similar change, but saying the the Source Code (Text) Editor would work as well. It didn't work in my case. The designer didn't open, but the disk activity was surprisingly the same. The only choice that worked for me was XML (Text) Editor.

Next time you open an xaml file, the visual editor won't kick in, and you won't have the problem. However, it'd good to find the cause for this... Maybe I´ll try to re-install VStudio 2013 when I have a minute...

Hope it helps !! :)

Fast casting of C# Structs with no unsafe code (but still kind of "unsafe")

C++ allows us to perform any casting between memory pointers. It's basically up to you to ensure the correct types are casted to prevent memory problems.

C# however doesn't allow to do this out of the box, unless you go into using unsafe code and perform the pointer conversion yourself, pretty much like in C++.

Problem is that unsafe code is not supported in all platforms, and generally it's a good idea to avoid using it as long as you can.

So, imagine we have two structs like this:


    public struct STA
    {
        public int CustomerID;
        public float CustomerRate;
    }
    public struct STB
    {
        public int CustomerID;
        public float CustomerRate;
    }

One of them is yours, and the other one comes from an APIs or legacy software you don't have access to. Now, imagine you need to convert one into another. How would you face that?

Obviously, if you try to simply assign them, it just won't work:



Of course, the most evident (ans safest) solution is to create a new struct of the type STB and copy the contents from STA to STB:

struct_a = new STA(struct_b.CustomerID, struct_b.CustomerRate);

The drawback is that this approach is slow and implies a memory overhead, what might not be an option sometimes.

If performance is a critical issue, you are sure that both structs are 100% compatible and share the exact same memory layout, and that both come from compatible platforms... Why not fooling the compiler and make it just assume that they are compatible types? 

As we mentioned, in unsafe C# code this can be simply achieved by casting pointers, just like in C++. But if you mark your C# code as unsafe, it can be rejected in some platforms. Is there a way to do that without using unsafe code? Yes, there is.

C# StructLayout to the rescue

Perfectly safe C# code allows you to explicitly define the offset of struct members, using attributes from System.Runtime.InteropServices, just like this:


    [StructLayout(LayoutKind.Explicit)]
    public struct STA
    {
        [FieldOffset(0)]
        public int CustomerID;
        [FieldOffset(4)]
        public float CustomerRate;
    }

This allows you to do tricky things like settings two different members of the struct at the same offset, creating something similar to C++ Unions:


    [StructLayout(LayoutKind.Explicit)]
    public struct Union
    {
        [FieldOffset(0)]
        public STA StructA;
        [FieldOffset(0)]
        public STB StructB;
    }

Note that both StructA and StructB are at the same field offset, and therefore will occupy the exact same location in memory. As both share the same memory layout, the result is that you have ONE single object in memory, and two different references (kind of pointers) to them, each one using a different type. 

Now, we can do the following:


            STA struct_a;
            STB struct_b;
            ...
            Union stu = new Union();
            stu.StructB = struct_b;
            struct_a = stu.StructA;

As you can see, no new STA has been created in memory, and we have saved all the process of copying data from one struct to another.

However, please be aware that this is kind of cheating... You are fooling the compiler to accept that, but in practice you are performing a classical pointer conversion, even if you are using purely safe code.

PLEASE BE AWARE that this approach doesn't take into account endianness. Different platforms, with different byte endianness, may store bytes in the opposite way. For example, if STA comes from a big-endian platform, and STB works in a little-endian platform (or just the opposite), bytes will be reversed when doing this operation. It doesn't take into account differences in data types either, so you must be very careful to ensure that all types have the same size in one struct and the other.

So, remember:
if(same endiannes & same data types) 
                              you are good to go !

Functional improvements

The Union struct we have created can be made much more comfortable to use if you add operators to it.

For example, comparison operators like this:

 public static bool operator ==(STA left, Union right)
        {
            return left == right.StructA;
        }
        public static bool operator ==(STB left, Union right)
        {
            return left == right.StructB;
        }

Will allow you to simply compare Unions with the original types:

if(union == struct_a)

And even more comfortable, adding implicit operators like this:

        public static implicit operator Union(STA value)
        {
            Union ret = new Union();
            ret.StructA = value;
            return ret;
        }

Will allow you to simply assign one type to the other like this:

            STA struct_a;
            ...
            Union union = struct_a;

Memory footprint improvements

One small drawback of this approach is the need to create structs of the type Union, each time you want to perform a conversion of this kind. A simple solution is to perform the operation in a static Union object. It's a bit messy, but it works. For instance, if you declare the class like this:

    [StructLayout(LayoutKind.Explicit)]
    public struct Union
    {
        [FieldOffset(0)]
        public STA StructA;
        [FieldOffset(0)]
        public STB StructB;

        public static Union StaticRef = new Union();

        public static STA ToSTA(STB pStructB)
        {
            StaticRef.StructB = pStructB;
            return StaticRef.StructA;
        }
        public static STB ToSTB(STA pStructA)
        {
            StaticRef.StructA = pStructA;
            return StaticRef.StructB;
        }
    }

You can now re-use the same static object over and over again, doing things like:

            STA struct_a;
            STB struct_b;
            ...
            struct_a = Union.ToSTA(struct_b);

Hope it helps!! Cheers...

HLSL code editing in Notepad ++

There are several HLSL syntax highlight add-ins for Visual Studio out there, but if you prefer to use the great NotePad++ to author or edit your shaders, my fellow DirectX MVP Matt Pettineo has written a Notepad++ add-in to allow doing this.

You just need to download the HLSL.xml file from his GoogleDrive account, and in Notepad ++ click Language->Define Your Language->Import and then select the downloaded file. After restarting notepad++, you´ll find a new entry in the Language menu item like this:


By clicking in that new item when you load an HLSL file, you´ll get the following result:


According to him, it supports even SM 5.0 profiles.

Great job Matt !!! :)

DirectX Control Panel and D3D Debug Output in D3D 9.x/10.x/11.x for Windows 7, 8 and 8.1

Debugging D3D applications can be a pain, but it´s completely necessary sometimes if you want to know what´s going on in your D3D application (error codes don´t give much information without the debug output).
However, things have changed quite a bit recently in the latest versions of Windows (8.1), Visual Studio (2013) and DirectX (11.2). The following video explains some of the changes related to D3D Debugging, the DirectX Control Panel, and how all the new infrastructure works:

You can also access the content in the form of slides.
Keep in mind that some of the DirectX features are no longer distributed with the DirectX SDK, but with the Windows SDK. So, we will try to cover all the possible cases you could face when trying to activate the Debug Output in D3D, no matter if you work in Windows 7 with the old version of DirectX SDK (June 2010), if you are in Windows 7 or Windows 8 and use the new Windows SDK, or if you are in the latest Windows 8.1 with its own Windows SDK.

The New DirectX Control Panel

We will need to deal with it to enable D3D debug and to manage other stuff, so first thing is to learn to differentiate between the old one (June 2010 DirectX SDK) and the new ones (Windows SDK). It´s easy: the new ones only include one tab (Direct3D 10.x/11.x):
Old Control Panel (DirectX SDK June 2010)
New DX Control Panel (Windows SDK)
image image
Location:
C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Utilities\bin\x64 (or x86)
Location:
C:\Windows\System32

So, if you are developing for D3D 10.x or 11.x, use the new one as the old one won´t have any effect. If you are still using D3D9 and the old DX SDK 2010, grab the one on your left.
Note: See the above video to learn about new features in the panel like the “Feature level limit”.

Windows 7

D3D 9.x

If you are still developing with D3D9, honestly you should seriously consider moving forward. But if you can´t, and you need to enable debug in your app, you just need to use the OLD Control Panel described above, and navigate to the Direct3D 9 tab to make sure you select “Use Debug Version of Direct3D 9”, and turn the Debug Output Level to “More”, just like depicted in the following image:
image
That should force your DirectX applications to use the Debug version of the DirectX libraries, so you should immediately start to see debug output in Visual Studio.

Managed D3D9 applications (SlimDX, SharpDX and similar wrappers)

If you are developing in C#, keep in mind that you will also need to activate the flag “Enable native code debugging” under the Debug tab of your main project properties in Visual Studio. If not, the native debug output cannot get through to the output window.
image

D3D 10.x / 11.x

Important None: The necessary components for debugging D3D 10.x and 11.x are no longer installed with the old DirectX SDK (June 2010). In order to have them you need to install the Windows 8 SDK (even if you are in Win7). If you don´t have the necessary components, the creation of the device with the "debug" flag will fail (see below for more info). One easy way to check if you have the components is to check the existance of the NEW DX Control Panel, in C:\Windows\System32.

Activating the debug output in D3D 10.x / 11.x is a bit different, as settings are handled per application (you need to add your exe to a list in the control panel, and set an specific configuration for it in there). To do so, please follow these steps:
  1. 1.- Open the NEW DirectX Control Panel and navigate to the Direct3D 10.x / 11 tab
  2. 2.- Click on “Edit List” to add your exe to the list of applications controlled by the DX panel
  3. 3.- In the window that will pop up (below), click on the dots “…” and navigate to your exe file. Then click “Ok”.
image
  1. 4.- Back in the main tab, choose the configuration you want (probably want to set “Force On” to force debug output), and mute all the message types you don´t want to see (if any)
Once your exe is on the list of apps the Control Panel manages, next step is to make sure your D3D device connects to the Debug Layer of DirectX.
You can find more info here, but basically what you need to do is create your Device with Creation Flags including the D3D11_CREATE_DEVICE_DEBUG flag.

Managed D3D 10.x /11.x applications (SlimDX, SharpDX and similar wrappers)

Just like with D3D 9, when developing in C# you should remember to activate the flag “Enable native code debugging” under the Debug tab of your main project properties in Visual Studio. If not, the native debug output cannot get through to the output window (see above in this post for more info).

Windows 8.x + Windows SDK

This part covers the case when working in Windows 8.x with the newer versions of the Windows SDK.

D3D 9.x

Debugging D3D 9 applications in Windows 8 should work exactly the same as we did in Windows 7. Of course, the new Windows SDK doesn’t include tools to configure D3D9, so you should install the June 2010 DX SDK to get access to the OLD control panel. I couldn’t make sure this works as all my machines are updated to Windows 8.1, so any feedback here will be really welcome.
What I can tell you is that, unfortunately, D3D9 debugging seems to be disabled in Windows 8.1. If you open the OLD DX Control Panel, you will see that all the debug parts of the D3D 9 tab are grayed out. I tried by all means to bring it back with no luck, so if you manage to enable it, please let me know.

D3D 10.x / 11.x

Enabling debug output for D3D 10.x and 11.x is pretty much the same as in the case of Windows 7, unless this time you will need to use the NEW version of the DX Control Panel, located in C:\Windows\System32 instead of the usual DXSDK folders.
Also, remember to create your devices specifying the D3D11_CREATE_DEVICE_DEBUG creation flag (as described above), and in the case of developing in C#, remember to activate the “Enable native code debugging” option in your main project.

Troubleshooting

  • The application works but I get no debug output: If you are in D3D9, make sure you activated the Debug libraries in the old DX Control Panel. Also, if you work in C#, ensure to activate the “Enable native code debugging” option. If you work in D3D 10/11, make sure you created the device with the D3D11_CREATE_DEVICE_DEBUG flag, and don´t forget to add your app to the list of programs managed by the DX Control Panel. In all cases, always use the appropriate DX Control Panel (see above to learn about this).
  • In D3D 10.x / 11.x, the application fails while trying to create the device with the DEBUG creation flag: This usually happens if you don´t have the correct SDK installed. If you are in Windows 7 or in Windows 8, make sure you install the Windows 8 SDK. If you are in the latest Windows 8.1 you should install its own Windows 8.1 SDK, as it´s not compatible with the 8.0 SDK version. One easy way to check if you have the components is to check the existance of the NEW DX Control Panel, in C:\Windows\System32.