Free Web Hosting Provider - Web Hosting - E-commerce - High Speed Internet - Free Web Page
Search the Web

vbProgramming | Tutorials | Direct3D | Direct3D.Sprite
    vbProgramming 
Tutorials -
Using Direct3D.Sprite
 
     

vbProgramming Home :: vbProgramming Forums :: Tutorials :: Contact :: Links 

 

 

Short tutorial that shows you how to use Direct3D.Sprite

Direct3D.Sprite
You know all that stuff we did in the 'Rendering a Sprite' tutorial? We're going to shorten that to like... 5 lines in this one.
You might be mad "ALL THAT WORK FOR NOTHING?"  - everything has its own purpose. The knowledge you used in 'Rendering A Sprite' will be used for a much more advanced topic - which we'll get to later: Heightmaps.

Well. DirectX comes with its own Sprite class for rendering 2d objects. 
I could say to you "Open the tutorial from the previous project" - but unfortunately I've received emails suggesting me not to do that, because not everyone works through each and every tutorial. Someone could have simply googled and got to this page.

So I'll.paste our existing code. I'm assuming that those who 'googled and got to this page' have at least a basic understanding of DirectX. If not, please read my other tutorials.

Create a new class called GameClass:
 

'If you didn't put this there, then you'd have to write out the variable names
'For example: "Dim D3DDev as Microsoft.DirectX.Direct3D.Device"
'as opposed to: "Dim D3DDev as Device"
Imports Microsoft.DirectX
Imports Microsoft.DirectX.Direct3D
Imports Microsoft.DirectX.Direct3D.D3DX
Public Class GameClass
    'Stores whether game state. If True, then the game will end
    Public GameOver As Boolean

    Private D3Ddev As Device = Nothing

    'Short for PresentationParameters
    Private D3Dpp As PresentParameters = Nothing

    'Stores Display mode
    Private DP As DisplayMode = Nothing

    Public Sub Initialize(ByVal TargetForm As Form, ByVal FullScreen As Boolean)
        If FullScreen Then
            '800x600 Resolution
            DP.Width = 800
            DP.Height = 600
            'R5G6B5 = 24-bit. Visit MSDN to find out what the other ones are.
            DP.Format = Format.R5G6B5
        Else
            'If it's not fullscreen, use the current display mode!
            DP = Manager.Adapters.Default.CurrentDisplayMode
        End If
        D3Dpp = New PresentParameters
        'Initialize some stuff for the Presentation parameters.
        'The backbuffer is what it draws to first. Then the content of the backbuffer
        'is copied to the screen.
        D3Dpp.BackBufferFormat = DP.Format
        D3Dpp.BackBufferWidth = DP.Width
        D3Dpp.BackBufferHeight = DP.Height
        'There's flip, copy, and discard - discard seems to be the slowest but the most 'accurate' 
        'MSDN has more information.
        D3Dpp.SwapEffect = SwapEffect.Discard
        'Gets the most FPS out of your game. Present the scene immediately
        D3Dpp.PresentationInterval = PresentInterval.Immediate
        'Set to Fullscreen or Windowed
        If FullScreen Then
            D3Dpp.Windowed = False
        Else
            D3Dpp.Windowed = True
        End If
        'Instantiate the device
        D3Ddev = New Device(Manager.Adapters.Default.Adapter, DeviceType.Hardware, TargetForm.Handle, CreateFlags.SoftwareVertexProcessing, D3Dpp)
        'Manager.Adapters.Default.Adapter        - Use the current display driver: the one that's displaying your desktop right now
        'DeviceType.Hardware                     - If you've worked with GDI+, you'll know how slow software devices are
        'TargetForm.Handle                       - Draw to the form
        'CreateFlags.SoftwareVertexProcessing    - Processing vertices with Software (Direct3D) is safer than processing it with your hardware
        '                                          This is becuase different graphics cards may process them differently. You want it to be
        '                                          processed the same universally, so you let Direct3D do the work.
        'D3Dpp                                   - Well, use the presentation parameters!
        'Will be discussed in the next tutorial, but in case you're wondering, I've listed the arguments below
        D3Ddev.Transform.View = Matrix.OrthoOffCenterLH(0 - 100, DP.Width - 100, DP.Height - 100, 0 - 100, 1, 10)
        '0              - Left side of the view
        'DP.Width       - Right side of the view. In our case, it's 800
        'DP.Height      - Bottom side of the view. In our case, it's 600.
        '0              - Top side of the view
        '0              - Specifies the ZNear plane: The closest our object can be before it's cut-off from the view
        '0              - Specifies the ZFar plane:  The farthest our object can be before it's cut-off from the view
        'Our object is so close to the screen that the lighting conflicts with its visibility,
        'making it appear black, so we disable lighting.
        D3Ddev.RenderState.Lighting = False
    End Sub
    'A rendering block in D3D looks like this usuallly:
    ' Clear()
    ' BeginScene()
    ' Render()
    ' EndScene()
    ' Present()
    Public Sub RenderScene()
        Do While Not GameOver
            'Try commenting this out :). You'll see what it does. It might hang your app depending on your graphics card.
            'Usually it caueses the screen to flash in multiple colors.
            D3Ddev.Clear(ClearFlags.Target, Color.FromArgb(0, 0, 225), 0, 0)
            'ClearFlags.Target          - Clear the form, our "target"
            'Color.FromArgb(0, 0, 225)  - Clear it with this color (Dark blue)
            '0                          - ZDepth. Our app isn't 3D yet, so don't waste memory on ZDepth
            '0                          - Stencil. I haven't figured out what this is lol.
            D3Ddev.BeginScene()
            D3Ddev.EndScene()
            D3Ddev.Present()
            'In a loop, keyboard events are ignored. This means: let them NOT be ignored!
            Application.DoEvents()
        Loop
        Terminate() 'Exit everything!
    End Sub
    Public Sub Terminate()
        'Free up mem
        DP = Nothing
        D3Dpp = Nothing
        D3Ddev.Dispose()
        D3Ddev = Nothing
        'Exit
        Application.Exit()
        'FORCE an exit if it didnt exit
        System.Environment.Exit(System.Environment.ExitCode)
    End Sub
End Class

Now add the following code in form1:

Form1 Globals:
 Dim game As New GameClass

Form1_Load:
 Me.Show()
 game.Initialize(Me, True)
 game.RenderScene()

Form1_Keydown:
 
If e.KeyCode = Keys.Escape Then game.GameOver = True

And you should get a blank screen when you run this.

Warning
For those of you with earlier versions of DirectX - you will not be able to follow along with this tutorial, the code will vary. Please upgrade to the latest version: Directx 9.0c (Latest as of 5/06/05. Please let me know if any future updates change the code)

The Code
Now create a bitmap in Paint, 32x32, with the background color as Lime. If you're not sure how - just download the source code here and the bitmap will be included.

In GameClass's globals:
 'Sprite to be rendered
 Private Alex As Direct3D.Sprite
 'Texture for the sprite
 Private AlexTexture As Texture
 'Background Transparent Color
 Private ColorKeyVal As Color

At the end of GameClass.Initialize:
Alex = New Direct3D.Sprite(D3Ddev)
ColorKeyVal = Color.FromArgb(255, 0, 255, 0) 'LimeGreen
AlexTexture = TextureLoader.FromFile(D3Ddev, "down1.bmp", 32, 32, D3DX.Default, Usage.None, Format.Unknown, Pool.Default, Filter.Point, Filter.Point, ColorKeyVal.ToArgb)

Note one thing. See those arguments for TextureLoader.FromFile? I remember giving an explanation of the arguments in that tutorial.

D3Ddev                          - The device which will take care of the rendering
"down1.bmp"
                 - The bitmap which the texture will hold
32, 32
                              - Size of the bitmap
D3DX.Default
                - MipMapping levels - this will be covered later, so for now use Default.
Usage.None
                    - We're only going to read from this texture, we're not going to manipulate it.
Format.Unknown
            - We're not too sure whether this image is 24-bit/16-bit..etc, so we put Unknown and let Direct3D do the guessing!
Pool.Default
                   - Pool stands for Memory Pool - we don't want to mess with this, as improper usage will cause problems. Use default.
Filter.Point, Filter.Point
  - Filter.Point means our image is as clear as possible. Filter.Triangle "blurries" the image if you don't want it so pixilated.
ColorKeyVal.ToArgb
     - The color to be made transparent

And that's pretty much it for that.

Now in GameClass.RenderScene, right after BeginScene and before EndScene:

Alex.Begin(SpriteFlags.AlphaBlend)
Alex.Draw2D(AlexTexture, New Point(0, 0), 0, New Point(0, 0), Color.White)
Alex.End()

This is where the people with earlier versions of DirectX will get errors. You'll have to adapt - some of the arguments and overloaded methods have changed.

Time to explain a bit,
AlexTexture      - The Texture. Duh
New Point(0,0)  - The rotation center.
0                         - Rotation Angle, in radians
New Point(0,0)  - The sprite position
Color.White      - This is the 'base' color. It won't affect anything. Change it to green, and the bitmap will start being more green. White has no effect.

The rotation center and the rotation angle are pretty simple. The rotation center tells you from where in the sprtie do you want to rotate from - it's like the pivot point. The sprite will rotate around that point. The rotation angle is pretty simple - just the rotation in radians.

Declare a Single called Rotation Angle.
And change your code as follows:
RotationAngle -= 0.0001
Alex.Draw2D(AlexTexture, New Point(0, 0), RotationAngle, New Point(200, 300), Color.White)

Run the program.
You should see the sprite rotating around the point(0,0). It might go slow, but for me it went kind of fast - it depends on the speed of your computer.

That's it for this tutorial. We'll get to 3D next!


The Source Code for this tutorial is located here: You can also locate this by logging in to vbProgramming Forums and going to:
Tutorials > Tutorial Source Code > Source Code