Programming

Asteroid

For making an asteroid game,

I found it hard at first but it’s quite easy.

Asteroid

One of Newton’s law : In the absence of a net external force, a body either is at rest or moves with constant velocity.

We are evolving in space so the last phrase part is our algorithm.

But you might have encountered some problems if you are very new to games programming, like how do I make all these things move ?

It’s simple,

  • When you change the direction of your ship, you need to keep a reference of the angle your ship is pointing at.
  • With this angle, using trigonometry you will get a vector which is what you need.

And math magics will do the rest !

There are a couple of other issues you need to handle like,

  • Limiting velocity of your ship or soon it will go very fast,
  • Wrap your angle,
  • Screen dimensions,
  • etc …

You will soon find out that the core of games is quite short, but the polishing is very long.

Here is the source for controlling the ship : Asteroid

In the next article, I will show you how to implement weapons, monsters and rocks … that in turn involves a couple of other things …

Generic Singleton

Click here for an introduction to the Singleton.

You might wonder the useful-ness of doing this.

Well, I found that by pure accident, I was reviewing some code then I decided to try enhance the original Singleton pattern.

Here are the benefits :

  • You don’t need to have a field or property representing the singleton instance,
  • With its syntax, it becomes somewhat clearer to read, as it focuses much on the singleton provider rather than the targetted class.
  • Last but not least, you won’t have to define anymore a singleton property in each class you want singleton-ed !

Well, if that’s not enough, I am listening to your suggestions and findings !

The syntax is cumbersome for your fingers but I found that the benefits are worth it.

using System;

namespace GenericSingleton
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Singleton<MyClass>.Instance.Text = "Hello";
            Singleton<MyClass>.Instance.Number = 123;

            Singleton<MyClass>.Instance.Text = "Good bye";
            Singleton<MyClass>.Instance.Number = 321;
        }
    }

    /// <summary>
    /// Provides a generic Singleton.
    /// </summary>
    /// <typeparam name="T">A <see cref="Type"/>.</typeparam>
    public abstract class Singleton<T> where T : new()
    {
        /// <summary>
        /// Instance backing-field.
        /// </summary>
        private static readonly T _instance = new T();

        /// <summary>
        /// Not publicly available.
        /// </summary>
        private Singleton()
        {
        }

        /// <summary>
        /// Singleton instance.
        /// </summary>
        public static T Instance
        {
            get { return _instance; }
        }
    }

    internal class MyClass
    {
        public int Number;
        public string Text;

        public void Do()
        {
        }
    }
}

TaskDialog hidden icons.

Before starting, you need to know there’s a small issue on using the API in your project, you can get an Unable to find an entry point name ‘TaskDialogIndirect’ in DLL ‘comctl32.dll’ error.

To get the whole story, see my post Unable to find an entry point name ‘TaskDialogIndirect’ in DLL ‘comctl32.dll’


Thanks to Bart Desmet, you can access all flavors of icons; these are not present in the TaskDialog documentation, I think they have been removed.

Another CancelShutdown ?

TaskDialog

TaskDialog (2)

TaskDialog (3)

TaskDialog (4)

TaskDialog (5)

Replace the TaskDialogStandardIcon definition with the one below.

    /// <summary>
    /// Specifies the icon displayed in a task dialog.
    /// </summary>
    public enum TaskDialogStandardIcon
    {
        /// <summary>
        /// Displays no icons (default).
        /// </summary>
        None = 0,

        /// <summary>
        /// Displays the warning icon.
        /// </summary>
        Warning = 65535,

        /// <summary>
        /// Displays the error icon.
        /// </summary>
        Error = 65534,

        /// <summary>
        /// Displays the Information icon.
        /// </summary>
        Information = 65533,

        /// <summary>
        /// Displays the User Account Control shield.
        /// </summary>
        Shield = 65532,

        SecurityShieldBlue = 65531,

        SecurityWarning = 65530,

        SecurityError = 65529,

        SecuritySuccess = 65528,

        SecurityShieldGray = 65527,
    }

If you are lazy like I am, get the code : TaskDialogHiddenIcons

Too easy,

  • You still have to get the Windows API Code Pack,
  • Point the Core project location to where you extracted it,
  • Update the TaskDialogStandardIcon definition with the one provided above,
  • Enjoy !

If you’re even lazier than I am (I didn’t know this was possible, I have to meet you right now :-), go to bin\Debug and run the application’s .EXE :-)

Unable to find an entry point name 'TaskDialogIndirect' in DLL 'comctl32.dll'

For those of you who tried Windows API Code Pack, particularly the TaskDialog managed wrapper, you’ve probably encountered the following error when trying to run your program.


Too bad,

I was happy when I heard they finally released a managed API for those (not yet managed) APIs …

I have been struggling a lot last year to try get it working with C#, thanks to Chris Dunford’s VistaBridge Considered Harmful; An Alternative which would have otherwise, never happened.

(Credits goes to Kenny Kerr too, for his article and Bart Desmet’s Using Windows Vista’s TaskDialog API in managed code)

The main problem is was the activation context,

Solution is here :

[Seven / Vista] La classe TaskDialog et l’erreur “Unable to find an entry point named ‘TaskDialogIndirect’ in DLL ‘comctl32.dll’”

Here is the translation in english :

  1. Open your project properties in the Solution Explorer,
  2. On the Security tab, check Enable ClickOnce Security Settings,
  3. Now you can see appearing the app.manifest file in the Properties folder of your solution, open it,
  4. Beneath the </trustInfo> tag, insert the following code :
      <dependency>
        <dependentAssembly>
          <assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*" />
        </dependentAssembly>
      </dependency>
    
  5. If you try to build there’ll be an error, to fix it, uncheck the Enable ClickOnce Security Settings.

The Singleton pattern !

UPDATE : I have created a generic Singleton.

For the first programming related post, it is going to be a simple post.

The Singleton pattern,

What is this ?

If you are familiar with programming, you probably know what this is, if you are new to programming, i’ll try to explain it to you, especially what it can do for you.

The Singleton pattern, as defined in Wikipedia : “In software engineering, the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object.”

That is, when getting more comfortable with programming, you start to shape your own coding style, by creating some kind of architectures. However, there might be some times when you are confronted to some design issues. (e.g. What you coded doesn’t do what exactly what you expected when thinking about it in your brain)

Still here ?

The Singleton Pattern allows to have a unique instance of a class throughout your application.

Why do I need this ?

Here is one example I encountered when developing my DJ-ing software. Beside the business logic of my application, I had to use a library for accessing audio hardware that is inside my computer : program my sound card to fit my needs. We are going to call this thing the audio manager.

From a development perspective, you need to have a unique and instance of that thing because as it is said on the title it is a manager, hence, it manages one or more thing(s). So when you want to access your audio card, you generally want exclusive access to it. There could be some undesired behaviour if two “things” wants to access an audio device. Moreover, you like to have a unique access point for working with your audio card. This is where the Singleton comes in handy, a unique instance of an object, taking care of not creating other (duplicate) instances of it, returning the first instance created. (Just like in real life, there is one instance of a manager and multiple instances of employees :-)

This is a very common pattern in software development.

Talking .NET now, the implementation is as follows :

You declare the class constructor as private or protected, (we are going to use private for now) this is what blocks the process of creating a new (copy) object of it. You declare a static property in this class, which is nothing more than a instance of the class itself. The static field will be initialized inline and declared as readonly.

This way of coding offers you this :

  • By declaring it as static, you don’t have to create an instance of it, you can just call Singleton.Instance, the instance is available without creating a new object because it is declared as static. Now the readonly keyword does not allow you to modify it once your program has initialized.

The readonly shall not be used without creating a new object of the class :


using System;

namespace PatternSingletonApplication
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var instance = Singleton.Instance;
            var instance1 = Singleton.Instance;

            // Test if it is the same instance.
            if (instance == instance1)
                Console.WriteLine("'instance' and 'instance1' are the same instance.");

            Console.WriteLine("Singleton.Instance can also be accessed directly,");
            Console.WriteLine(Singleton.Instance.Test());

            Console.ReadKey();
        }
    }

    public class Singleton
    {
        /// <summary>
        /// Protected because we don't want to expose it except for derived classes.
        /// </summary>
        protected Singleton() { }

        /// <summary>
        /// The unique instance of the class.
        /// </summary>
        public static readonly Singleton Instance = new Singleton();

        /// <summary>
        /// Added methods shall not be static then !
        /// </summary>
        /// <returns></returns>
        public string Test()
        {
            return "Hello from Instance.Test !";
        }
    }
}

Design Patterns beginners should consider Design Patterns in C# and VB.NET – Gang of Four (GOF). I have it and it’s great, there are nearly 70 samples showing the implementation of (all existing ?) design patterns. For about 70€ for all this, that’s cool, no ?

Moreover, this products offers :

  • Structural examples
  • Real-world examples
  • .NET optimized examples

(Note that I have no affiliation with the site mentioned above)

Detect the type of your monitor

UPDATE : Here is the monitor management application !

MonitorConfigurationAPI

Requirements : Vista and a display monitor with Vista drivers.

Usage : Click ‘Probe’ button then wait a few seconds !

Issues

  • Color temperature doesn’t produce expected results
  • During detection, some monitors may change their settings

If you don’t have a Vista-specific driver, you shouldn’t install an old XP driver otherwise it will break a couple of things on your system like monitor management for instance. You may think that you can roll-back to the previous driver, but it’ll be broken anyway ! I have seen some results with monitor that don’t have Vista drivers with the Generic PnP Monitor that is installed by default, though.


For my MAME GUI project,

I needed to detect what is the type of the monitor plugged onto the PC. This then, would allow me to provide custom scanlines PNGs, dependent of the technology used.

CRT ?

CRT

or LCD ?

LCD

Knowing that LCD does blurry stretching when not set at its native resolution, it is critical to know what display we are going to play on, in order to provide The (best possible) visual experience.

Proper arcade games emulation is somewhat sensitive to your display settings, hence, it’s always best to try provide nearest if not exact, display settings (resolution & refresh rate).

This all came out when I decided to try MAME, seriously (this time) on my LCD screen.
I got the following conclusion : it is possible to have a very good display experience even on LCDs, compared to using PowerStrip with my CRT.

While I have a great P1130 which is nothing more than a repainted G520 from Sony and is very good, if not one of the best CRTs to play your arcade games on, I like to play MAME quickly on my desktop PC (which in fact is a laptop) who is connected to the LCD screen. This is because since I got a new PC, the old Precision 360 workstation has been converted to a gaming-only PC. Too lazy to stand up and play just like in a real arcade game …

I thought : “This should be simple to get, I only need to know what is the type of screen, nothing more. (So it’s gonna be easy, yeah ?)”

But life was different,

In fact this post is kind of, the tip of the iceberg I’ve been sitting on and didn’t even know there was an iceberg under my feets until recently … So I decided to write this post, because now I got it working and other people can benefit from it.

I knew that display monitors have a protocol so the PC can speak with them, DDC/CI.

But here the problems comes,

  • The protocol is using nothing more than I²C
  • This is something low-level, not addressable with C# directly

And the list grows with time, why such simple request be so complicated to code ?

Now here are the possible solutions,

  • Get EDID string from Windows registry
    (Nice try but the string is in its raw form, decode it ? the specifications are not free …)
  • Use a software like softMCCS, or better, an SDK like WinI2C/DDC,
    (Nice try again but these analysis softwares are stand-alone application, and while WinI2C is exactly what is needed, it’s pricey and not to consider because of the target project : Another free MAME GUI (already claiming it’s the best).

While I’ve spent some time on WinI2C, the time-bombed samples always crashed for me, though the compiled demo ran … so I haven’t even been able to use it !

Now I don’t really need it because i have the same thing I coded myself but this wouldn’t happen without help right from Microsoft :-) considering you have Vista or better.

Monitor Configuration

You can use the monitor configuration functions to get information from a monitor and to change a monitor’s settings. You can use these functions to :

* Change a monitor’s geometry settings, such as the width and height of the display.
* Change image settings, such as brightness and contrast.
* Reset a monitor’s settings to their factory defaults.
* Degauss the monitor.

Internally, the monitor configuration functions use the Display Data Channel Command Interface (DDC/CI) to send commands to the monitor.
Now while this kicks ass, again, it’s for C++ …

Okay it does 99% of the job, all you have to do is call the functions you need, in fact it is even handier for my project as I am even able to change the colors of the monitor (if supported), great for monochrome emulation !

Now the only thing we need is a C# wrapper. (But some of it ran into trouble)

It got stuck when trying to get the physical monitors from the monitor, the pointer pointing to 0 was indeed correct (a pointer of pointer ?). While I hate pointers I find them working great when they are tamed.

But you still have to do a lot of things even with this API to get your Graal.

Monitor Detect API

In the next part I will unveil a complete monitor configuration wrapper for C# :-)

Monitor Detect Class Diagram
This is longer than expected as I decided to fully document it, and it’s tedious !
(I am already considering another project that creates P/Invoke declarations fully documented from MSDN site but here comes dirty HTML and Regular Expressions …)

Block system shutdown

UPDATE : Here is a sample code for Vista only.

ShutdownBlockReasonCreate

Running the program then initiating a shutdown will display the Windows feature.

As things seems to have changed a little in Windows 7, it doesn’t work with it. I will post an updated version of it, when the documentation is available.

Sometimes you need to handle a shutdown that has been accidentally initiated …

(Yes it can happen, at least for me).

For example in XP, when you have an application running and initiate a shutdown, a small window appears, saying that the application is not responding :

XP shutdown

By simply pressing Cancel you were able to abort the shutdown process.

Now on Vista, things have a changed a little, there is a new more user-friendly interface that appears when you try to shutdown while other applications are running :

Vista's new shutdown UI

There’s an API in Windows that you have to use, though.

In fact that API is more subtile than it looks, because of lack of examples and that you have to place these functions in a precise place in your code.

(Note that while the two provided links are unknown to each other, there are complementary informations on them !)

You have to request that you need to block the shutdown process, probably because the application is doing whatever you think, is a critical operation.

However, according to Microsoft, it is not recommended practice.

Your application shall never block a shutdown process, especially if it’s a critical shutdown (one initiated by the user, from the shutdown button present on the Start menu).

A better practice, would be to save your application’s data and shut it down.

I needed this, so I started using the API but ran onto some issues …

Numerous examples on the web didn’t work for me, when not C++ at best I could see the new UI for 5 seconds only.

Now what I wanted is, just like in Outlook, when you shut down while it is running, the system waits for it to finish Send/Receive then it continues the shutdown process.

On the documentation it seems that the content has not been verified, there are duplicate paragraphs and actually, we can make Vista wait more than 30 + 5 seconds (just as Outlook does or seems to), even in a critical shutdown !

There is also an obscure function, so obscure that Microsoft removed its documentation, CancelShutdown. It does what it says even under Vista and 7, it is able to (need to confirm that) cancel shutdown on these platforms.

We’ll look at all the coding needed for that, on part 2 …