Mostrando entradas con la etiqueta Windows 7. Mostrar todas las entradas
Mostrando entradas con la etiqueta Windows 7. Mostrar todas las entradas

New XNA 4 book by Kurt Jaegers [Packt Publishing]

Kurt Jaegers has a new book on XNA 4 Game Development. I´ll review it in a few days, by now, I paste here some word from the author itself:

“This book follows the same style as my previous books on 2D game development with XNA, bringing three different 3D games to life. I cover items such as:
- The basic concepts behind 3D graphics and game design
- Generating geometry with triangles
- Converting height map images into terrain
- An introduction to HLSL, including writing shaders that handle lighting and multi-texturing
- Building a 2D button-based interface to overlay on your 3D action
- Implementing skyboxes for full 3D backgrounds”

More info here and here.

Properly calculating the diffuse contribution of lights in HLSL Shaders

It’s been many years since Vertex and Pixel Shaders came out, and several years too since the Fixed Pipeline is deprecated, but there are still many questions in the forums out there asking about how to properly calculate the diffuse contribution of Lights. This paper has a great tutorial about the issue, and includes a whole Shader that mimics the Fixed Pipeline behavior. However, we will see here how to perform just the basic calculations, just in case you don’t need to emulate the full pipeline.
First thing is to write some D3D9 code that allows you to switch from the old Fixed Pipeline and your own Shaders, using the same parameters. Doing so, you will easily find any behavior differences in light calculations. You can read more about how D3D9 Fixed Pipeline calculates lighting in this page.
When writing shaders, people tend to calculate the diffuse contribution like:
Out.Color = (materialAmbient * lightAmbient) + (materialDiffuse * lightDiffuse * dot(Normal, L));
Where L is the vector from the vertex position (in world coordinates) to the light.
Apart from not doing any specular or emissive calculations (which could not be necessary in many cases, depending on your scenario), there are several mistakes in that approach:
1.- You don’t want the dot to return negative values, because it will black out colors wrongly. So, you need to clamp it to the 0..1 range, using the saturate operator: saturate(dot(Normal, L))
2.- In order to get the same results as the Fixed Pipeline, you should include Attenuation calculations, because they modify the intensity of light with the distance between the point being lit and the light source. Attenuation (as opposed to what its name suggests), not only attenuates light, but also can increase intensity in some circumstances. (See below how to properly calculate attenuation factors)
3.- Once you are calculating attenuation, you should remove the materialDiffuse factor from the previous equation, as you don’t want it to be attenuated too. You will apply it later, when the entire lighting contribution is properly calculated and attenuated.
Keeping those 3 things in mind, the final calculation in a vertex shader would be:
    float4 LightContrib = (0.f, 0.f, 0.f, 0.f);
    float fAtten = 1.f;

    // 1.- First, we store the total ambient light in the scene (multiplication of material_ambient, light_ambient, and any other global ambient component)
    Out.Color = mMaterialAmbient * mLightAmbient;

    // 2.- Calculate vector from point to Light (both normalized and not-normalized versions, as we might need to calculate its length later)
    float pointToLightDif = mLightPos - P;
    float3 pointToLightNormalized = normalize(pointToLightDif);
    
    // 3.- Calculate dot product between world_normal and pointToLightNormalized
    float NDotL = dot(Nw, pointToLightNormalized);        
    if(NDotL > 0)
    {
        LightContrib = mLightDiffuse * NDotL * mLightDivider;     
            
        float LD = length(pointToLightDif);        
        if(LD > mLightRange)
            fAtten = 0.f;
        else
            fAtten = 1.f/(mLightAtt0 + mLightAtt1*LD + mLightAtt2*LD*LD);
        
        LightContrib *= fAtten;
    }
    Out.Color += LightContrib * mMaterialColor;
    Out.Color = saturate(Out.Color);

 

Comparison

First image is the Programmable version. You can slightly tell it by the reflections on the windows.
image
Second image is the Fixed Pipeline version (no real time reflections on windows):
image

Cómo controlar el orden de propiedades o categorías en un PropertyGrid

El control PropertyGrid es fantástico para crear herramientas de prototipado rápido, donde podamos cambiar propiedades de objetos de forma rápida y visual. Como ya sabrás, el espacio de nombres System.ComponentModel contiene multitud de atributos y herramientas para personalizar el modo en que las propiedades se agrupan y configuran dentro de un PropertyGrid.

De forma automática, las propiedades se ordenan alfabéticamente según su DisplayName, o se agrupan por categorías (y se aplica el mismo criterio alfabético dentro de éstas) si así lo selecciona el usuario. Lamentablemente, no existe una forma sencilla de poder controlar manualmente el orden de las propiedades o de las categorías.

Existen muchas formas distintas de lograrlo, pero casi todas implican escribir código. Un workaround sencillo, efectivo, y que no implica utilizar código adicional es el siguiente:

1.- Dentro del atributo DisplayName de cada propiedad, o dentro del nombre de cada categoría (atributo Category),  añadiremos por delante tantos caracteres especiales de tipo \u200B como posiciones queramos “subir” dicha propiedad o categoría hacia arriba. Dicho carácter identifica un espacio vacío de longitud 0, por lo que en la práctica no modificará el texto que se muestra en la propiedad, pero sí afectará al algoritmo de ordenación.

En el siguiente ejemplo, se muestra un objeto con dos propiedades Width y Height. De forma natural (por orden alfabético), Height aparecería antes que Width. Para modificar ese comportamiento y lograr el orden inverso, mucho más natural, solo tendremos que modificar los atributos como sigue:

        [Category("Layout")]
        [DisplayName("\u200B\u200BWidth")]
        public float Width
        {
            get { return mWidth; }
            set { mWidth = value; }
        }
        [Category("Layout")]
        [DisplayName("\u200BHeight")]
        public float Height
        {
            get { return mHeight; }
            set { mHeight = value; }
        }

Así, logramos un PropertyGrid correctamente ordenado, como el de la siguiente ilustración:

image

2.- Debemos asegurarnos de que el PropertyGrid utiliza una fuente que soporte dicho carácter, ya que no todas lo hacen. Por ejemplo, la fuente por defecto Microsoft Sans Serif 8.25 lo soporta perfectamente. No obstante, si queréis aseguraros de forma programática de que la fuente es correcta, podéis utilizar este código:

        public UIEditor()
        {
            InitializeComponent();

            this.propertyGrid1.Font = new Font("Microsoft Sans Serif", 8.25f, FontStyle.Regular);
        }

Developing a MatrixStack in pure managed C# code (ready for XNA)

Some time ago, we already talked about the possibility of creating your own Math library directly in C#, with no native code. If you take enough care, it can be as fast as performing interop with a native one.
Today, we are showing an additional example on this matter, and we are going to develop our own fast MatrixStack class, all in safe C# code, with no COM interop.

Why?

I never understood well why the MatrixStack class remains to be an iDisposable COM object. Don´t know what kind of optimizations it has internally that justify having disposable resources, but it’s annoying to have the iDisposable overhead with no need for it.
Besides that, MatrixStacks are used in most cases as simple matrix helpers, to traverse object hierarchies. So, replacing the API MatrixStack with your own one should be a piece of cake, and will definitely help you if trying to port your code to some other platform.
Last, but not least, XNA does not have a MatrixStack class. So this C# implementation fits perfectly on it for all that want to use it.
I this example, I will be comparing my own class with the SlimDX MatrixStack, which is nothing more than a wrapper over the D3DX Matrix Stack.

The interface

In order to make the SlimDX stack replacement painless, I will keep the exact same interface in my class (except the COM-related stuff, which is no longer necessary). So, it will have to be something like this:
image

How it works

A MatrixStack, basically supplies a mechanism to enable matrices to be pushed onto and popped off of a matrix stack. Implementing a matrix stack is an efficient way to track matrices while traversing a transform hierarchy.
So, we can clear the stack to the Identity or to any other matrix, we can operate with the top of the stack, and we can add (push) or remove (pop) nodes (or levels, if you want) to the stack.
Example: for a robot arm hierarchy, we would go like this:

1.- Initialize the stack, and load the matrix of the first node in the hierarchy (the upper arm, for example). Now you can use the Top matrix to draw the upper arm.
2.- Create another level on the stack (Push) for the lower arm, and multiply the lower arm matrix. Use the Top matrix to draw the lower arm.
3.- Create another level on the stack (Push) for the hand, and multiply the hand matrix. Use the Top matrix to draw the hand.
The stack itself does nothing you cannot do with regular Matrix multiplications, except that it keeps track of the previous levels you have been creating. So you can go back to the upper node whenever you want. After the previous operations, for instance, if we perform a Pop, we would remove the top node of the stack, and go back to the previous. This way, the new Top node would represent the lower arm matrix, instead of the hand matrix.

The code

Here is my implementation of the MatrixStack. Please keep in mind that it has not been intensively tested, and might contain errors. Use it at your own risk:
    public class MatrixStack
    {
        /// <summary>
        /// Retrieves the Top node matrix of the stack
        /// </summary>
        public Matrix Top = Matrix.Identity;        
        public object Tag = null;
        private List<Matrix> mStack = new List<Matrix>();
        
        /// <summary>
        ///
        /// </summary>
        public MatrixStack()
        {
            LoadIdentity();
        }
        /// <summary>
        /// Clears the stack and loads the Identity Matrix in the top of the stack
        /// </summary>
        public void LoadIdentity()
        {
            mStack.Clear();
            Top = Matrix.Identity;
        }
        /// <summary>
        /// Clears the Stack, and loads the matrix in the top of the stack
        /// </summary>
        /// <param name="pMat"></param>
        public void LoadMatrix(Matrix pMat)
        {
            mStack.Clear();
            Top = pMat;
        }
        /// <summary>
        /// Adds a new level to the stack, cloning the current TOP matrix of the stack
        /// </summary>
        public void Push()
        {
            mStack.Add(Top);
        }
        /// <summary>
        /// Removes the current TOP matrix of the stacks, returning back to the previous one
        /// </summary>
        public void Pop()
        {
            if (mStack.Count > 0)
            {
                Top = mStack[mStack.Count - 1];
                mStack.RemoveAt(mStack.Count - 1);                
            }
        }
        /// <summary>
        /// This method right-multiplies the given matrix to the current matrix (transformation is about the current world origin).
        /// This method does not add an item to the stack, it replaces the current matrix with the product of the current matrix and the given matrix.
        /// </summary>
        /// <param name="pMat"></param>
        public void MultiplyMatrix(Matrix pMat)
        {
            Matrix.Multiply(ref Top, ref pMat, out Top);
        }
        /// <summary>
        /// This method left-multiplies the given matrix to the current matrix (transformation is about the local origin of the object).
        /// This method does not add an item to the stack, it replaces the current matrix with the product of the given matrix and the current matrix.
        /// </summary>
        /// <param name="pMat"></param>
        public void MultiplyMatrixLocal(Matrix pMat)
        {
            Matrix.Multiply(ref pMat, ref Top, out Top);            
        }      
        /// <summary>
        /// Rotates (relative to world coordinate space) around an arbitrary axis.
        /// </summary>
        public void RotateAxis(Vector3 pAxis, float pAngle)
        {
            Matrix tmp;
            Matrix.RotationAxisAngle(ref pAxis, pAngle, out tmp);
            Matrix.Multiply(ref Top, ref tmp, out Top);           
        }
        /// <summary>
        /// Rotates (relative to world coordinate space) around an arbitrary axis.
        /// </summary>
        public void RotateAxisLocal(Vector3 pAxis, float pAngle)
        {
            Matrix tmp;
            Matrix.RotationAxisAngle(ref pAxis, pAngle, out tmp);
            Matrix.Multiply(ref tmp, ref Top, out Top);           
        }
        /// <summary>
        /// Rotates (relative to world coordinate space) the specified Euler Angles
        /// </summary>
        public void RotateYawPitchRoll(float pYaw, float pPitch, float pRoll)
        {
            Matrix tmp;
            Matrix.CreateFromYawPitchRoll(pYaw, pPitch, pRoll, out tmp);
            Matrix.Multiply(ref Top, ref tmp, out Top);            
        }
        /// <summary>
        /// Rotates (relative to world coordinate space) the specified Euler Angles
        /// </summary>
        public void RotateYawPitchRollLocal(float pYaw, float pPitch, float pRoll)
        {
            Matrix tmp;
            Matrix.CreateFromYawPitchRoll(pYaw, pPitch, pRoll, out tmp);
            Matrix.Multiply(ref tmp, ref Top, out Top);           
        }
        /// <summary>
        /// Scale the current matrix about the world coordinate origin
        /// </summary>
        public void Scale(float pX, float pY, float pZ)
        {
            Matrix tmp;
            Matrix.CreateScale(pX, pY, pZ, out tmp);
            Matrix.Multiply(ref Top, ref tmp, out Top);
        }
        /// <summary>
        /// Scale the current matrix about the world coordinate origin
        /// </summary>
        public void ScaleLocal(float pX, float pY, float pZ)
        {
            Matrix tmp;
            Matrix.CreateScale(pX, pY, pZ, out tmp);
            Matrix.Multiply(ref tmp, ref Top, out Top);           
        }
        /// <summary>
        /// Determines the product of the current matrix and the computed translation matrix determined by the given factors (x, y, and z).
        /// </summary>
        public void Translate(float pX, float pY, float pZ)
        {
            Matrix tmp;
            Matrix.CreateTranslation(pX, pY, pZ, out tmp);
            Matrix.Multiply(ref Top, ref tmp, out Top);           
        }
        /// <summary>
        /// Determines the product of the current matrix and the computed translation matrix determined by the given factors (x, y, and z).
        /// </summary>
        public void TranslateLocal(float pX, float pY, float pZ)
        {
            Matrix tmp;
            Matrix.CreateTranslation(pX, pY, pZ, out tmp);
            Matrix.Multiply(ref tmp, ref Top, out Top);
        }
    }

It has to be fast

When you start coding your own MatrixStack, you will soon realize that .Net includes a Generic Collection called Stack. You can use it, although I didn’t. Why?
Because I have separated the management of the Top Matrix of the stack to a member variable, and for the rest I just preferred to use a simple list to keep track of the previous nodes.
The Top Matrix is stored as a member variable to be able to pass it By Reference to the Matrix Multiplication methods. The speed increase avoiding to pass a whole matrix by value is significant. In the example below, it was around a 40% faster.

Test 1 – Reliability

I just made several random operations with the matrix stack, trying to test some of its features by comparing the end Top Matrix, both with a SlimDX MatrixStack and my own. The test operations are:
matrixStack.LoadIdentity();
matrixStack.MultiplyMatrix(Matrix.PerspectiveFovLH(0.8f, 1.6f, 0.1f, 999f));
matrixStack.Translate(10, 10, 10);
matrixStack.Scale(2, 2, 2);
matrixStack.RotateYawPitchRoll(1f, 0f, 0f);
matrixStack.RotateAxis(Vector3.UnitY, 0.75f);
matrixStack.Push();
matrixStack.TranslateLocal(-5, -5, -5);
matrixStack.ScaleLocal(0.1f, 0.1f, 0.1f);
matrixStack.Pop();
matrixStack.MultiplyMatrixLocal(Matrix.RotationZ(1.45f));
The resulting top matrix is:
SlimDX MatrixStack:
  1. [M11:-0.06350367 M12:4.695973 M13:-0.3505643 M14:0]
  2. [M21:0.5231493 M22:0.5700315 M23:2.887983 M24:0]
  3. [M31:18.08297 M32:20 M33:-23.60117 M34:1]
  4. [M41:-0.1968169 M42:0 M43:0.03565279 M44:0]
MyMatrixStack:
  1. {M11:-0.06350368 M12:4.695973 M13:-0.3505643 M14:0}
  2. {M21:0.5231493 M22:0.5700315 M23:2.887982 M24:0}
  3. {M31:18.08297 M32:20 M33:-23.60117 M34:1}
  4. {M41:-0.1968169 M42:0 M43:0.0356528 M44:0}
As you can see, the result is exactly the same.

Test 2 - Speed

Speed is important, so I decided to run the above mentioned operation 10 million times, to se how long it takes to complete both using SlimDX and my own code.
Obviously, if we run in Debug mode (disabling optimizations), there will be a huge performance difference, as the SlimDX dll is already compiled with optimizations. But what happens if we turn all optimizations on when compiling our code?
Here is the result of a small test application:
image
As you can see, the .Net Framework alone is faster than SlimDX, thanks to its optimizations and to the absence of the interop layer.
What happens if we increase the number of iterations to 60 million? The difference is obviously bigger (1.36 seconds faster):
image
Note: This test has been done on an intel i7 CPU at 3.8 Ghz, running on Windows 7 x64 with .Net Framework 4.0.
Note2: SlimDX MatrixStack uses its own Matrix class and operations. My implementation uses my own Matrix implementation, also written in pure C# code.
Conclusion: .Net Rocks. A purely native C++ code would be even faster of course, but if you put in the equation the huge amount of benefits .Net will give you, I really think it’s worth it. Don’t you think?
Cheers !

New XNA 4.0 book by Packt Publishing

Packt has released a new book on XNA 4.0 development: XNA 4.0 Game Development by Example: Beginner's Guide – Visual Basic Edition.

2403EXP_XNA%204_0%20Game%20Developement%20by%20Example

I think I will have the chance to review the book, so I’ll tell you more when I’ve read it, but it looks promising. Seems to be a must for anyone that is facing XNA 4.0 development in Visual Basic.

Cheers !

Finding the external IP Address of your machine, with a timeout, in C#

If you try to find the IP Address your machine is using, you can follow two paths. The most obvious one is:
 string host = System.Net.Dns.GetHostName();
System.Net.IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(host);
System.Net.IPAddress[] addr = ipEntry.AddressList;
 for (int i = 0; i < addr.Length; i++)
{
      if (addr[i].AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork)
          continue;
      return addr[i].ToString();
}
 
 return "";
Unfortunately, in most cases people are connected to the internet through a router, and therefore each machine is assigned with an internal IP Address of the private LAN network, assigning the external IP Address to the router only, not to each machine. Finding this external address directly is not trivial, as you would need to deal with the router itself, with different router models, etc.
The easiest way to find the external IP Address is to do a web request to one of the several websites out there specially designed to provide you with that address, like whatismyipaddress.com, www.whatismyip.com, etc. In this case, we will use the last one.
Of course, doing a web request can take time, specially if there is no internet connection available, as the default timeout can take several seconds. This function will do the job for you, and accept a custom timeout.
/// <summary>
/// This function uses a Web request to find the external IP Address your machine is using
/// </summary>
/// <param name="pTimeOutMiliSeconds">Number of miliseconds to wait for a response</param>
/// <returns></returns>
public static string GetExternalIP(int pTimeOutMiliSeconds)
{
   string whatIsMyIp = "http://automation.whatismyip.com/n09230945.asp";
   WebClient wc = new WebClient();
   UTF8Encoding utf8 = new UTF8Encoding();
   try
   {
      string ipaddr = null;
      bool done = false;
 
      wc.DownloadDataCompleted += new
      DownloadDataCompletedEventHandler((object sender, DownloadDataCompletedEventArgs e) =>
      {
         ipaddr = utf8.GetString(e.Result);
         done = true;
      });
 
      wc.DownloadDataAsync(new Uri(whatIsMyIp));
      System.DateTime startTime = System.DateTime.Now;
      while (!done)
      {
         System.TimeSpan sp = System.DateTime.Now - startTime;
 
         // We should get a response in less than timeout. If not, we cancel all and return the internal IP Address
         if (sp.TotalMilliseconds > pTimeOutMiliSeconds)
         {
            done = true;
            wc.CancelAsync();
         }
      }
      return ipaddr;
   }
   catch
   {
      return null;
   }
   finally
   {
      if (wc != null)
      {
         wc.Dispose();
         wc = null;
      }               
   }
}

It works pretty obviously. It just uses the DownloadDataAsync method, instead of the synchronous DownloadData, and waits for a certain amount of time. If no response is received in that time, cancels the async method and returns null.
Hope it helps!

Ramblings about the excellent Windows Media Center

Today, I was trying to setup a Windows Media Center Extender, to be able to see my movies (stored in my PC) through my XBox in the living room. In theory, it´s easy, but you can get into some troubles I´d like to point, just in case that might help you…

You can get some basic knowledge about Media Center extenders here.

First, try to connect your XBox with the PC, through Settings->Network->Connection to computer. If the connection is established successfully, you probably won´t have any problem configuring the Media Center Extender. But if you have problems, check:

1.- That your router supports Multicast Filtering, as some routers, like the Cisco EPC3825 (the one I was trying first), seem to have problems with that. In fact, in the settings dialogs of that router, you won´t find any option about Multicast Filtering. I can tell you that I tried every single possibility for a couple of hours with that router, and no luck. I switched to a different one (from Linksys), and everything worked like a charm…

2.- If your router is supposed to work with this feature, make sure you have enabled the mentioned “Filter Multicast” option (probably available in the Security settings tab of the router), and also that you have enabled the uPnP (probably in the Management settings tab of the router).

3.- If still have problems, you can check your Firewall settings to search for the needed open ports and so on… You can read more here.

One you have properly linked your PC and XBox 360, you can start the Windows Media Center on your PC, to choose what folders you will be sharing.

Some tips about folder structures, in order to see the covers of the movies, and additional info:

1.- Put each movie in a separate folder, as WMC will look this way for additional info for each movie

2.- If you want to manually download a cover for a movie or video, you just need to put the picture in the movie folder, with the name “folder.jpg”. WMC will load it automatically.

3.- If you want to put additional information, like movie specs, genre, etc, you should add some DVDID XML files with a certain format that will help WMC identifying the movie. You can download those files from http://dvdxml.com or even better, use one of the available metadata managers out there. I have tried YAMMM and works pretty well.

4.- If your XBox is downloading the movie covers and info again and again, each time you enter the Windows Media Center, or if it takes long to recover the covers, etc, that´s probably because you don´t have indexed the shared folders on your PC. Just make sure that the Indexing Service is installed and enabled (Start->Control Panel->Programs and Features->Turn on/off Windows features->Indexing Service), and also make sure that the shared folders for the movies are added to the index (Rightclick->properties->advanced->allow to add this folder to the index).

Some tips about YAMMM

1.- It´s a Windows Service, so don´t expect any User Interface, except for setting up the application. It’s run in background, monitoring the folders you tell it to for changes, and downloading automatically the info and covers.

2.- It expects movies to be in separate folders, and users folder’s name (not file’s name) to identify what movie you are talking about. If it doesn´t identify what movie it is, it won´t download anything. If it does, it can automatically rename the folder and movie files (with a more standard name, if you indicate it to do so), and will start downloading.

3.- YAMMM won´t find the correct movie if you don´t use the original movie name for the folder name. So forget any any translated version.

4.- To help YAMMM finding it, you can include the year of the movie, like this: “American Gangster (2007)”. That will help, a lot…

5.- If your movie is divided into several files (part 1, part 2, etc), YAMMM will automatically create a playlist for them, so WMC will identify them as a single movie. By default, after doing this you will see that WMC adds multiple entries for your movie: one for the playlist, and one for each part your AVI or DVD is divided into. In order to hide the parts, and live only the playlist, you can rename the AVI parts like: “video 1.avi” to “video 1.avi2”. This way, WMC won´t identify that part as a movie, and the reference file (playlist) will still work. (You should make sure that the playlist has modified the reference names too, by simply opening it with the WordPad).

Outlook Error. Could not open Outlook Window

Today, I suddenly started receiving the above error. Among the many fixes for this situations depicted here, what worked for me was Method 3: Resetting the Navigation pane.

To do so, just select Start->Run and then type “outlook /RESETNAVPANE”. It worked for me.

Read the instructions on the above link about what side effects can have resetting the navigation pane.

Cheers!

Oriented Button in Windows Forms

imageThe following class is a button which can be oriented both horizontally and vertically (like in the picture of your left). Text and image react properly to this orientation and so do their Alignments. The control also includes customizable margins for the text and image inside the button and a SizePercent property for the Image. Please keep in mind that if Orientation is set to “Horizontal”, the normal Draw methods from the base class are called, so all of this properties are ignored. However, you can change this behavior or add any other property very easily if you need it.
The whole thing has been designed to use as less resources as possible (accept suggestions on this of course ;), but you can very easily add other features, like a PictureBox for the image rendering (re-using all the PictureBox features as: BorderStyle, SizeMode, etc).
You can just copy-paste the following parts of code into a class which inherits from Button, and you´ll have it. Something like this:
public class OrientedButton : Button
Hope it helps:

Declaration of variables and props

        private Orientation mOrientation = Orientation.Horizontal;
        private int mTextMargin = 5;
        private int mImageMargin = 5;
        private int mImageScalingPercent = 100;
        private System.Windows.Forms.VisualStyles.PushButtonState mState = System.Windows.Forms.VisualStyles.PushButtonState.Normal;
 
        #region Props
        [Category("Appearance")]
        [DefaultValue(5)]
        public int TextMargin
        {
            get { return mTextMargin; }
            set { mTextMargin = value; }
        }
        [Category("Appearance")]
        [DefaultValue(5)]
        public int ImageMargin
        {
            get { return mImageMargin; }
            set { mImageMargin = value; }
        }    
        [Category("Appearance")]
        [DefaultValue(Orientation.Horizontal)]
        public Orientation Orientation
        {
            get { return mOrientation; }
            set { mOrientation = value; }
        }
        [Category("Appearance")]
        [DefaultValue(100)]      
        public int ImageScalingPercent
        {
            get { return mImageScalingPercent; }
            set { mImageScalingPercent = value; }
        }
        #endregion

Mouse Events Handling

       #region Mouse Events
        /// <summary>
        ///
        /// </summary>
        /// <param name="mevent"></param>
        protected override void OnMouseDown(MouseEventArgs mevent)
        {
            base.OnMouseDown(mevent);
            mState = System.Windows.Forms.VisualStyles.PushButtonState.Pressed;
            Invalidate();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="mevent"></param>
        protected override void OnMouseUp(MouseEventArgs mevent)
        {
            base.OnMouseUp(mevent);
            mState = System.Windows.Forms.VisualStyles.PushButtonState.Hot;
            Invalidate();
        }       
        /// <summary>
        ///
        /// </summary>
        /// <param name="e"></param>
        protected override void OnMouseLeave(EventArgs e)
        {
            base.OnMouseLeave(e);
            mState = System.Windows.Forms.VisualStyles.PushButtonState.Normal;
            Invalidate();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="e"></param>
        protected override void OnMouseEnter(EventArgs e)
        {
            base.OnMouseEnter(e);
            mState = System.Windows.Forms.VisualStyles.PushButtonState.Hot;
            Invalidate();
        }
        #endregion

OnPaint Method

        /// <summary>
        /// Some code parts were taken from here: http://msdn.microsoft.com/es-es/library/f0ys5025.aspx
        /// </summary>
        /// <param name="pevent"></param>
        protected override void OnPaint(PaintEventArgs pevent)
        {
            base.OnPaint(pevent);
 
            if (mOrientation == Orientation.Horizontal)
                return;
 
            // Base Button Draw
            if (mState == System.Windows.Forms.VisualStyles.PushButtonState.Pressed)
            {
                // Set the background color to the parent if visual styles 
                // are disabled, because DrawParentBackground will only paint 
                // over the control background if visual styles are enabled.
                this.BackColor = Application.RenderWithVisualStyles ?
                    Color.Azure : this.Parent.BackColor;
 
                // If you comment out the call to DrawParentBackground,
                // the background of the control will still be visible
                // outside the pressed button, if visual styles are enabled.
                ButtonRenderer.DrawParentBackground(pevent.Graphics,
                    ClientRectangle, this);
                ButtonRenderer.DrawButton(pevent.Graphics, this.ClientRectangle,
                    "", this.Font, true, mState);
            }
            else
            {
                // Draw the bigger unpressed button image.
                ButtonRenderer.DrawButton(pevent.Graphics, ClientRectangle,
                    "", this.Font, false, mState);
            }
 
            // Draw Text
            if (this.Text != "")
                this.DrawText(pevent.Graphics);
 
            // Draw Image
            if (this.Image != null)
                this.DrawImage(pevent.Graphics);
        }

The DrawText method

        /// <summary>
        ///
        /// </summary>
        private void DrawText(System.Drawing.Graphics pGraphics)
        {
            // Calc size of text (la func devuelve el size horizontal)
            SizeF sizeOfText = pGraphics.MeasureString(this.Text, this.Font);
            float temp = sizeOfText.Width;
            sizeOfText.Width = sizeOfText.Height;
            sizeOfText.Height = temp;
 
            // Calc X coord of Text           
            float x = mTextMargin;
            switch (this.TextAlign)
            {
                case ContentAlignment.MiddleCenter:
                case ContentAlignment.TopCenter:
                case ContentAlignment.BottomCenter:
                    x = (this.Width / 2) - (sizeOfText.Width / 2);
                    break;
                case ContentAlignment.MiddleRight:
                case ContentAlignment.BottomRight:
                case ContentAlignment.TopRight:
                    x = this.Width - mTextMargin - sizeOfText.Width;
                    break;
            }
 
            // Calc Y coord of Text
            float y = mTextMargin;
            switch (this.TextAlign)
            {
                case ContentAlignment.BottomCenter:
                case ContentAlignment.BottomLeft:
                case ContentAlignment.BottomRight:
                    y = this.Height - mTextMargin - sizeOfText.Height;
                    break;
                case ContentAlignment.MiddleCenter:
                case ContentAlignment.MiddleLeft:
                case ContentAlignment.MiddleRight:
                    y = (this.Height / 2) - (sizeOfText.Height / 2);
                    break;
            }
 
            // Draw text
            System.Drawing.SolidBrush drawBrush = new System.Drawing.SolidBrush(this.ForeColor);
            System.Drawing.StringFormat drawFormat = new System.Drawing.StringFormat();
            drawFormat.FormatFlags = StringFormatFlags.DirectionVertical;
            pGraphics.DrawString(this.Text, this.Font, drawBrush, x, y, drawFormat);
            drawBrush.Dispose();
        }

The DrawImage Method

        /// <summary>
        ///
        /// </summary>
        /// <param name="pGraphics"></param>
        private void DrawImage(System.Drawing.Graphics pGraphics)
        {
            float imageScaling = (float)mImageScalingPercent / 100f;
            float finalWidth = (float)this.Image.Width * imageScaling;
            float finalHeight = (float)this.Image.Height * imageScaling;
            float halfFinalWidth = finalWidth / 2f;
            float halfFinalHeight = finalHeight / 2f;
 
            float x = mImageMargin;
            float y = mImageMargin;
            switch (this.ImageAlign)
            {
                case ContentAlignment.MiddleCenter:
                case ContentAlignment.TopCenter:
                case ContentAlignment.BottomCenter:
                    x = (this.Width / 2f) - halfFinalWidth;
                    break;
                case ContentAlignment.MiddleRight:
                case ContentAlignment.BottomRight:
                case ContentAlignment.TopRight:
                    x = this.Width - mImageMargin - finalWidth;
                    break;
            }
            switch (this.ImageAlign)
            {
                case ContentAlignment.BottomCenter:
                case ContentAlignment.BottomLeft:
                case ContentAlignment.BottomRight:
                    y = this.Height - mImageMargin - finalHeight;
                    break;
                case ContentAlignment.MiddleCenter:
                case ContentAlignment.MiddleLeft:
                case ContentAlignment.MiddleRight:
                    y = (this.Height / 2f) - halfFinalHeight;
                    break;
            }
            System.Drawing.Drawing2D.Matrix rotMat = new System.Drawing.Drawing2D.Matrix();
            PointF rotationCenter = new PointF(x + halfFinalWidth, y + halfFinalHeight);           
            rotMat.RotateAt(90, rotationCenter);
            pGraphics.Transform = rotMat;
 
            System.Drawing.Rectangle destRect = new Rectangle((int)x, (int)y, (int)finalWidth, (int)finalHeight);
            System.Drawing.Rectangle srcRect = new Rectangle(0, 0, this.Image.Width, this.Image.Height);
            pGraphics.DrawImage(this.Image, destRect, srcRect, GraphicsUnit.Pixel);
        }

References

http://msdn.microsoft.com/es-es/library/f0ys5025.aspx