Imports System
Imports Microsoft.DirectX
Imports Microsoft.DirectX.Direct3D
Imports Microsoft.Samples.DirectX.UtilityToolkit
Imports MidRange
Imports BV.Math
Imports System.ComponentModel
Public Class FullD3DControl2
Implements IFrameworkCallback
Implements IDeviceCreation
' Constants
' Private Shared ClearColor As Integer
' Variables
Private drawingFont As Font
' Font for drawing text
Private textSprite As Sprite
' Sprite for batching text calls
Private isHelpShowing, isStatShowing, isShowButtons As Boolean
' If true, show the help ui
Private camera As New ModelViewerCamera()
' A model viewing camera
Private hud As Dialog
' dialog for standard controls
Public d3dObj As Visor3D
#Region "contructor"
Public Sub New()
MyBase.New()
' Llamada necesaria para el Dise�ador de Windows Forms.
InitializeComponent()
' Agregue cualquier inicializaci�n despu�s de la llamada a InitializeComponent().
Initialize()
End Sub
Public Sub New(ByVal f As Framework)
MyBase.New(f)
Me.InitializeComponent()
' Create dialogs
hud = New Dialog(MyBase.frameWork)
Initialize()
End Sub
Public Sub Initialize()
d3dObj = New Visor3D
End Sub
#End Region
'public property Show
Public Property ShowStats() As Boolean
Get
Return isStatShowing
End Get
Set(ByVal value As Boolean)
isStatShowing = value
End Set
End Property
'Public Overrides Property BackColor() As Color
' Get
' Return MyBase.BackColor
' End Get
' Set(ByVal value As Color)
' MyBase.BackColor = value
' ClearColor = value.ToArgb
' End Set
'End Property
<Browsable(False)> _
Public Overrides Property frameWork() As Microsoft.Samples.DirectX.UtilityToolkit.Framework
Get
Return MyBase.frameWork
End Get
Set(ByVal value As Microsoft.Samples.DirectX.UtilityToolkit.Framework)
MyBase.frameWork = value
hud = New Dialog(MyBase.frameWork)
End Set
End Property
' Called during device initialization, this code checks the device for some
' minimum set of capabilities, and rejects those that don't pass by returning false.
Public Function IsDeviceAcceptable(ByVal caps As Caps, ByVal adapterFormat As Format, ByVal backBufferFormat As Format, ByVal windowed As Boolean) As Boolean Implements IDeviceCreation.IsDeviceAcceptable
' Skip back buffer formats that don't support alpha blending
If Not Manager.CheckDeviceFormat(caps.AdapterOrdinal, caps.DeviceType, adapterFormat, Usage.QueryPostPixelShaderBlending, ResourceType.Textures, backBufferFormat) Then
Return False
End If
Return True
End Function
' This callback function is called immediately before a device is created to allow the
' application to modify the device settings. The supplied settings parameter
' contains the settings that the framework has selected for the new device, and the
' application can make any desired changes directly to this structure. Note however that
' the sample framework will not correct invalid device settings so care must be taken
' to return valid device settings, otherwise creating the Device will fail.
Public Sub ModifyDeviceSettings(ByVal settings As DeviceSettings, ByVal caps As Caps) Implements IDeviceCreation.ModifyDeviceSettings
' If device doesn't support HW T&L or doesn't support 1.1 vertex shaders in HW
' then switch to SWVP.
If (Not caps.DeviceCaps.SupportsHardwareTransformAndLight) OrElse (caps.VertexShaderVersion < New Version(1, 1)) Then
settings.BehaviorFlags = CreateFlags.SoftwareVertexProcessing
Else
settings.BehaviorFlags = CreateFlags.HardwareVertexProcessing
End If
' This application is designed to work on a pure device by not using
' any get methods, so create a pure device if supported and using HWVP.
If (caps.DeviceCaps.SupportsPureDevice) AndAlso ((settings.BehaviorFlags And CreateFlags.HardwareVertexProcessing) <> 0) Then
settings.BehaviorFlags = settings.BehaviorFlags Or CreateFlags.PureDevice
End If
' Debugging vertex shaders requires either REF or software vertex processing
' and debugging pixel shaders requires REF.
#If (DEBUG_VS) Then
If settings.DeviceType <> DeviceType.Reference Then
settings.BehaviorFlags = settings.BehaviorFlags And Not CreateFlags.HardwareVertexProcessing
settings.BehaviorFlags = settings.BehaviorFlags Or CreateFlags.SoftwareVertexProcessing
End If
#End If
#If (DEBUG_PS) Then
settings.DeviceType = DeviceType.Reference
#End If
' For the first device created if its a REF device, optionally display a warning dialog box
If settings.DeviceType = DeviceType.Reference Then
Utility.DisplaySwitchingToRefWarning(frameWork, "HLSLwithoutEffects")
End If
End Sub
' This event will be fired immediately after the Direct3D device has been
' created, which will happen during application initialization and windowed/full screen
' toggles. This is the best location to create Pool.Managed resources since these
' resources need to be reloaded whenever the device is destroyed. Resources created
' here should be released in the Disposing event.
Private Sub OnCreateDevice(ByVal sender As Object, ByVal e As DeviceEventArgs)
' Initialize the font
drawingFont = ResourceCache.GetGlobalInstance().CreateFont(e.Device, 15, 0, FontWeight.Bold, 1, False, _
CharacterSet.[Default], Precision.[Default], FontQuality.[Default], PitchAndFamily.FamilyDoNotCare Or PitchAndFamily.DefaultPitch, "Arial")
' Create the vertex shader and declaration
'new VertexElement(0, 0, DeclarationType.Float2, DeclarationMethod.Default,
d3dObj.Initilize(e.Device)
' Setup the camera's view parameters
camera.SetViewQuat(New Quaternion(-0.275F, 0.3F, 0.0F, 0.7F))
End Sub
' This event will be fired immediately after the Direct3D device has been
' reset, which will happen after a lost device scenario. This is the best location to
' create Pool.Default resources since these resources need to be reloaded whenever
' the device is lost. Resources created here should be released in the OnLostDevice
' event.
Private Sub OnResetDevice(ByVal sender As Object, ByVal e As DeviceEventArgs)
Dim desc As SurfaceDescription = e.BackBufferDescription
' Create a sprite to help batch calls when drawing many lines of text
textSprite = New Sprite(e.Device)
' Setup render states
e.Device.RenderState.Lighting = False
e.Device.RenderState.CullMode = Cull.None
'Parece no funcionars
'' Restore the states
'e.Device.TextureState(0).ColorArgument1 = TextureArgument.TextureColor
'e.Device.TextureState(0).ColorArgument2 = TextureArgument.Diffuse
'e.Device.TextureState(0).ColorOperation = TextureOperation.Modulate
'e.Device.SamplerState(0).MinFilter = TextureFilter.Linear
'e.Device.SamplerState(0).MagFilter = TextureFilter.Linear
'e.Device.RenderState.ZBufferEnable = True
'e.Device.RenderState.DitherEnable = True
'e.Device.RenderState.SpecularEnable = True
'e.Device.RenderState.Lighting = True
''e.Device.RenderState.AmbientColor = 0x80808080
'' Create a light
'Dim lightDirection As Vector3 = New Vector3(10, -10, 10)
'e.Device.Lights(0).Type = LightType.Directional
'e.Device.Lights(0).DiffuseColor = New ColorValue(1.0F, 1.0F, 1.0F, 1.0F)
'e.Device.Lights(0).Direction = Vector3.Normalize(lightDirection)
'e.Device.Lights(0).Enabled = True
d3dObj.Reset(e.Device)
' Setup the camera's projection parameters
Dim aspectRatio As Single = CType(desc.Width, Single) / CType(desc.Height, Single)
camera.SetProjectionParameters(CType(System.Math.PI, Single) / 4.0F, aspectRatio, 0.1F, 1000.0F)
camera.SetWindow(desc.Width, desc.Height)
camera.MaximumRadius = 30.0F
' Resize the hud
hud.SetLocation(desc.Width - 170, 0)
hud.SetSize(170, 170)
End Sub
' This event function will be called fired after the Direct3D device has
' entered a lost state and before Device.Reset() is called. Resources created
' in the OnResetDevice callback should be released here, which generally includes all
' Pool.Default resources. See the "Lost Devices" section of the documentation for
' information about lost devices.
Private Sub OnLostDevice(ByVal sender As Object, ByVal e As EventArgs)
d3dObj.Close()
If textSprite IsNot Nothing Then
textSprite.Dispose()
End If
End Sub
' This event will be fired immediately after the Direct3D device has
' been destroyed, which generally happens as a result of application termination or
' windowed/full screen toggles. Resources created in the OnCreateDevice event
' should be released here, which generally includes all Pool.Managed resources.
Private Sub OnDestroyDevice(ByVal sender As Object, ByVal e As EventArgs)
d3dObj.DestroyDevice()
End Sub
' This callback function will be called once at the beginning of every frame. This is the
' best location for your application to handle updates to the scene, but is not
' intended to contain actual rendering calls, which should instead be placed in the
' OnFrameRender callback.
Public Sub OnFrameMove(ByVal device As Device, ByVal appTime As Double, ByVal elapsedTime As Single) Implements IFrameworkCallback.OnFrameMove
' Update the camera's position based on user input
camera.FrameMove(elapsedTime)
Me.d3dObj.UpdateScreen(device, camera)
End Sub
' This callback function will be called at the end of every frame to perform all the
' rendering calls for the scene, and it will also be called if the window needs to be
' repainted. After this function has returned, the sample framework will call
' Device.Present to display the contents of the next buffer in the swap chain
Public Sub OnFrameRender(ByVal device As Device, ByVal appTime As Double, ByVal elapsedTime As Single) Implements IFrameworkCallback.OnFrameRender
Dim beginSceneCalled As Boolean = False
'device.Transform.View = camera.ViewMatrix
'device.Transform.Projection = camera.ProjectionMatrix
' Clear the render target and the zbuffer
Try
device.Clear(ClearFlags.ZBuffer Or ClearFlags.Target, Me.BackColor, 1.0F, 0)
device.BeginScene()
beginSceneCalled = True
Me.d3dObj.Draw(device, camera)
RenderText()
' Render the HUD
hud.OnRender(elapsedTime)
Finally
If beginSceneCalled Then
device.EndScene()
End If
End Try
End Sub
' Render the help and statistics text. This function uses the Font object for
' efficient text rendering.
Private Sub RenderText()
'If shader Is Nothing Then
' Exit Sub
'End If
If Me.isStatShowing OrElse Me.isHelpShowing Then
Dim txtHelper As New TextHelper(drawingFont, textSprite, 15)
' Output statistics
txtHelper.Begin()
txtHelper.SetInsertionPoint(5, 5)
txtHelper.SetForegroundColor(New ColorValue(1.0F, 1.0F, 0.0F, 1.0F).ToArgb())
If Me.isStatShowing Then
txtHelper.DrawTextLine(MyBase.frameWork.FrameStats)
txtHelper.DrawTextLine(MyBase.frameWork.DeviceStats)
End If
' Draw help
If isHelpShowing Then
txtHelper.SetInsertionPoint(10, MyBase.frameWork.BackBufferSurfaceDescription.Height - 15 * 6)
txtHelper.SetForegroundColor(New ColorValue(1.0F, 0.75F, 0.0F, 1.0F).ToArgb())
txtHelper.DrawTextLine("Controls (F1 to hide):")
txtHelper.SetInsertionPoint(40, MyBase.frameWork.BackBufferSurfaceDescription.Height - 15 * 5)
txtHelper.DrawTextLine("Rotate model: Left mouse button")
txtHelper.DrawTextLine("Rotate camera: Right mouse button")
txtHelper.DrawTextLine("Zoom camera: Mouse wheel scroll")
txtHelper.DrawTextLine("Hide help: F1")
Else
txtHelper.SetForegroundColor(New ColorValue(1.0F, 1.0F, 1.0F, 1.0F).ToArgb())
txtHelper.DrawTextLine("Press F1 for help")
End If
txtHelper.[End]()
End If
End Sub
' Before handling window messages, the sample framework passes incoming windows
' messages to the application through this callback function. If the application sets
' noFurtherProcessing to true, the sample framework will not process the message
Public Function OnMsgProc(ByVal hWnd As IntPtr, ByVal msg As NativeMethods.WindowMessage, ByVal wParam As IntPtr, ByVal lParam As IntPtr, ByRef noFurtherProcessing As Boolean) As IntPtr
' Give the dialog a chance to handle the message first
If Not hud.MessageProc(hWnd, msg, wParam, lParam) Then
' Pass all remaining windows messages to camera so it can respond to user input
camera.HandleMessages(hWnd, msg, wParam, lParam)
End If
Return IntPtr.Zero
End Function
' Adds the guid stuff to the application
Public Sub InitializeApplication()
If isShowButtons Then
Dim y As Integer = 10
' Create the buttons
Dim fullScreen As Button = hud.AddButton(2, "Toggle full screen", 35, y, 125, 22)
y += 24
Dim toggleRef As Button = hud.AddButton(3, "Toggle reference (F3)", 35, y, 125, 22)
'y += 24
'Dim changeDevice As Button = hud.AddButton(4, "Change Device (F2)", 35, y, 125, 22)
AddHandler fullScreen.Click, AddressOf OnFullscreenClicked
AddHandler toggleRef.Click, AddressOf OnRefClicked
End If
' Set the callback functions. These functions allow the sample framework to notify
' the application about device changes, user input, and windows messages. The
' callbacks are optional so you need only set callbacks for events you're interested
' in. However, if you don't handle the device reset/lost callbacks then the sample
' framework won't be able to reset your device since the application must first
' release all device resources before resetting. Likewise, if you don't handle the
' device created/destroyed callbacks then the sample framework won't be able to
' recreate your device resources.
AddHandler MyBase.frameWork.Disposing, AddressOf OnDestroyDevice
AddHandler MyBase.frameWork.DeviceLost, AddressOf OnLostDevice
AddHandler MyBase.frameWork.DeviceCreated, AddressOf OnCreateDevice
AddHandler MyBase.frameWork.DeviceReset, AddressOf OnResetDevice
MyBase.frameWork.SetWndProcCallback(New WndProcCallback(AddressOf OnMsgProc))
MyBase.frameWork.SetCallbackInterface(Me)
Try
' Show the cursor and clip it when in full screen
MyBase.frameWork.SetCursorSettings(True, True)
' Initialize the sample framework and create the desired window and Direct3D
' device for the application. Calling each of these functions is optional, but they
' allow you to set several options which control the behavior of the MyBase.frameWork.
MyBase.frameWork.Initialize(True, True, True)
' Parse the command line, handle the default hotkeys, and show msgboxes
MyBase.frameWork.CreateWindowInControl(Me)
' Hook the keyboard event
AddHandler MyBase.frameWork.Window.KeyDown, AddressOf OnKeyEvent
MyBase.frameWork.CreateDevice(0, True, Microsoft.Samples.DirectX.UtilityToolkit.Framework.DefaultSizeWidth, Microsoft.Samples.DirectX.UtilityToolkit.Framework.DefaultSizeHeight, Me)
'AddHandler changeDevice.Click, AddressOf OnChangeDevicClicked
' Hook the button events for when these items are clicked
Catch e As Exception
'#if(DEBUG)
' In debug mode show this error (maybe - depending on settings)
'#else
' catch
' {
' // In release mode fail silently
'#endif
' // Ignore any exceptions here, they would have been handled by other areas
' return (MyBase.frameWork.ExitCode == 0) ? 1 : MyBase.frameWork.ExitCode; // Return an error code here
MyBase.frameWork.DisplayErrorMessage(e)
End Try
End Sub
' As a convenience, the sample framework inspects the incoming windows messages for
' keystroke messages and decodes the message parameters to pass relevant keyboard
' messages to the application. The framework does not remove the underlying keystroke
' messages, which are still passed to the application's MsgProc callback.
Private Sub OnKeyEvent(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
Select Case e.KeyCode
Case System.Windows.Forms.Keys.F1
isHelpShowing = Not isHelpShowing
Exit Select
End Select
End Sub
#Region "Captura de botones"
'Called when the change device button is clicked
Private Sub OnChangeDevicClicked(ByVal sender As Object, ByVal e As EventArgs)
MyBase.frameWork.ShowSettingsDialog(Not MyBase.frameWork.IsD3DSettingsDialogShowing)
End Sub
'Called when the full screen button is clicked
Private Sub OnFullscreenClicked(ByVal sender As Object, ByVal e As EventArgs)
MyBase.frameWork.ToggleFullscreen()
End Sub
'Called when the ref button is clicked
Private Sub OnRefClicked(ByVal sender As Object, ByVal e As EventArgs)
MyBase.frameWork.ToggleReference()
End Sub
#End Region
'Protected Overrides Sub Finalize()
' 'frameWork.CloseWindow()
' frameWork.Dispose()
' MyBase.Finalize()
'End Sub
End Class