History: MogreQuickStart
Source of version: 6 (current)
Copy to clipboard
__MogreQuickStart__ is a __.NET__ class written in __Visual Basic__ 2008. It's goal is to provide a quick entry point to easily write ((MOGRE|Mogre)) applications. I developped it for myself to use it in my project (KSEditor), but everyone can use it. It takes in input as an ''OSM'' file to load.
There is also a topic in the Mogre forum to discuss it. This is [http://www.ogre3d.org/phpBB2addons/viewtopic.php?p=47555#47555|the thread].
__Note:__ The old name of MogreQuickStart was ''clOgre''.
----
{maketoc}
!!Introduction
What you need to use this class in your executable path is:
''MogreQuickStart.dll'' (this class)
''Mogre.dll''
''MogreNewt.dll''
''Mois.dll''
''Newton.dll''
''ofusionLoader.dll'' (see forward)
''OgreMain.dll''
''OIS.DLL''
''Plugins.cfg:''
To use video capture system, you will have to download AVIFILEWRAPPER that you can found [http://www.codeproject.com/KB/audio-video/avifilewrapper.aspx|here].
I have modified it so the functions can accept the new parameter _''ChoixDuCodec'' and when codec is choosen, it will be save in registry for later use.
You can download it as a DLL [http://www.trokus.fr/index.php/files/get/YGrmM6DAhr/avifile.dll|here].
For source code, ask me by PM in forum.
The whole VB 2008 solution can be downloaded here (complete with help file in french): [http://www.trokus.fr/index.php/files/get/D06GlwHU77/clogre.rar].
{CODE(wrap="1", colors="ini")}# Defines plugins to load
# Define plugin folder
PluginFolder=.\Plugins
# Define plugins
Plugin=RenderSystem_Direct3D9
Plugin=RenderSystem_GL{CODE}
You also need a folder ''Plugins'' which contains the specified plugins from ''plugins.cfg.''
To compile ''oFusionLoader.dll'' of [[OFusion)), use C# Express 2008. It works fine.
Of course, you also need an OSM scene to load.
Here is the class:
{CODE(wrap="1", colors="vbnet")}Imports Mogre
Imports MOIS
Imports MogreNewt
Imports OFusion
Imports System
Public Class MogreQuickStart
Imports Mogre
Imports MOIS
Imports MogreNewt
Imports OFusion
Imports System
Imports System.Drawing
Imports System.ComponentModel
#Region "Déclarations"
'Cette fonction sert à capturer une image (utilisé pour le système de capture vidéo)
'function to capturing content of a graphic (use to make video capture)
Private Declare Function BitBlt Lib "gdi32" Alias "BitBlt" (ByVal hDestDC As Int32, _
ByVal x As Int32, _
ByVal y As Int32, _
ByVal nWidth As Int32, _
ByVal nHeight As Int32, _
ByVal hSrcDC As Int32, _
ByVal xSrc As Int32, _
ByVal ySrc As Int32, _
ByVal dwRop As Int32) As Boolean
Structure Camera 'Permet de contenir les informations de caméra / contains camera information
Dim Camera As Mogre.Camera
Dim CamNode As Mogre.SceneNode
Dim CamViewNode As Mogre.SceneNode
Dim CamBody As MogreNewt.Body
End Structure
Private _OgreRacine As Mogre.Root 'La racine OGRE / Ogre Root
Private _OgreSceneManager As Mogre.SceneManager 'Le SceneManager OGRE / Ogre Scene Manager
Private _OgreCamera As Mogre.Camera 'La caméra sélectionnée / Currently selected camera
Private _RenderWindow As Mogre.RenderWindow 'la fenêtre de rendu / Render Window
Private _ShowAxesMonde As Boolean = False 'Axe du monde visible ou pas / World axes visible or not
Private _ShowAxesObjet As Boolean = False 'Axe d'un objet sélectioné visible ou pas / Selected object axes visible or not
Private _TrackObjet As Boolean = False 'Autotracking de la caméra actif ou pas / Camera autotracking enable or not
Private _Gravity As Single = -9.81 'Et oui, on aura un poid...(Sur terre = 9.81m/s² / gravity forces
Private _RenderWindowHandle As System.IntPtr 'Le handle du contrôle qui affichera le rendu / handle of the control to render on
Private _TopWindowHandle As System.IntPtr 'Le handle de la fenêtre contenant le contrôle de rendu / handle of main window
Private _CollisionDetection As Boolean = True 'Détection de collision activée ou pas / collision detection enable or not
Private _Application As Object 'Pour permettre de gérer le doevents dans la boucle de rendu / To handle 'doevent' in render loop
Private _init As Boolean = True 'Permettra de savoir si on est en cours d'initialisation de l'application / if we are in initialiastion of the class
Private _showLoad As Boolean = True 'Afficher ou pas la fenêtre d'info au chargement / 'show or not the splash screen
Private _GravityOnOff As Boolean = True 'Gravité active ou pas / gravity on or off
Private _LoadAxe As Boolean = False 'on charge les axex ou pas / axes loaded or not
Private _RenderOn As Boolean = True 'Sert à savoir si on à quitter l'appli pour stopper le rendu / if quitting application, stop render
Private _MoveFactor As Single = 2 'Vitesse de déplacement / speed of move
Private _DebugNewton As Boolean = False 'Permet de demander l'activation du debuger Newton / Init or not Newton Debuger
Private _ShowDebugNewtonInfo As Boolean = False 'Si vraie, montre les infos de debug Newton / If true, show Newton debug Info
Private _OgreMaxFPS As Integer = 1000
Private _MaxFrameSkip As Integer = 5
'La taille du body représentant le corp physique de la caméra Ajuster cette valeur en fonction de la scène.
'Size of body of the camera. Adjust this value depending of the scene.
Private _CamSize As Mogre.Vector3 = New Mogre.Vector3(1, 1.7, 1) 'Taille du body de la caméra / Camera body size
Private _CammMass As Single = 90 'Masse de la caméra / Camera mass
Private _GetPerformanceCounter As Decimal 'Pour le timer (non implémenté) / For high resolution timer (not implemented yet)
Private _GetPerformanceFreqency As Decimal 'Pour le timer (non implémenté) / For high resolution timer (not implemented yet)
Private _SceneType As Mogre.SceneType = SceneType.ST_GENERIC 'Comme son nom l'indique / As name says
Private _StartupPath As String 'Chemin de démarrage de l'application pour l'ajout au Ressources Manager / application startup path for ressources manager
Private _NewtonUpdateFps As Single = 60 'Nombre de FPS à gérer par Newton / Number of FPS to handle by Newton
Private _TimeFactor As Single = 1 'Echelle de temp pour Newton / Time scale for Newton
Private _SuspendRender As Boolean = False 'Permet de suspendre le rendu durant une période / Allows to suspend render for a reason or another
Private _SceneToLoad As String 'Le nom de la scène à charger / Scene'name to load
Private _RessourcesToLoad As ArrayList = New ArrayList 'La liste des ressources à charger / list of ressources needed
Private _moving As Boolean 'vraie si on a cliqué dans le control de rendu (permet le déplacement) / true if render control is clicked (allow to move)
Private _AvgFPS As Single 'Nombre moyen de FPS / average FPS..
Private _CurrentCamBody As MogreNewt.Body 'Le corps physique de la caméra sélectionnée / the body of selected camera
Private _NewtonWorldSizeMin As Mogre.Vector3 = New Mogre.Vector3(-1000, -1000, -1000)
Private _NewtonWorldSizeMax As Mogre.Vector3 = New Mogre.Vector3(1000, 1000, 1000)
Private _mReflectSceneNode As Mogre.SceneNode 'le scene node de l'objet de la scène sur lequel sera basé la réflection / scene node to base reflection on
Private _ReflecionIntensity As Single = 0.35F 'degrée de réflection (1 pour mirroir) / quantity of reflection (1 for a mirror)
Private _UScaleReflect As Single = 0.1F 'pour mise à l'échelle de la texture originale de l'objet de base / for scaling of base object texture
Private _vScaleReflect As Single = 0.1F
Private _SceneBlendingType As Mogre.SceneBlendType = SceneBlendType.SBT_TRANSPARENT_ALPHA 'le type de fondu de la texture de base et de la texture réfléchie / blending type for base and reflected texture
Private _ReflectPlaneNormal As Mogre.Vector3 = Mogre.Vector3.UNIT_Y 'Pour définir l'orientation du plan de réflection / To define reflect plane orientation
Private _myWorld As World = Nothing 'Le monde physique / Newton physical world
Private _Translate As Single = 2 'La valeur de translation pour la gestion sans détection de collisions / movement speed if Newwton is nont used
Private _Rotate As Single = 1 'Pareil mais pour les rotations / same for rotation
Private _FSAA As Integer = 0 'antialiasing
Private _NbCapturedFrameBySecond As Integer = 24 'Nombre d'image à capturer pour la capture vidéo / Numbre of frame to be captured for video
Private ListeCamera As ArrayList = New ArrayList 'La liste des caméra de la scène / camera scene list
Private _InfoMessage As String = "" 'Message à afficher dans la fenêtre d'info
'Variable pour la capture video / variables for video capture
Private _CtrlToCapture As Object 'Le control à capture / control to capture
Private _ChoixDuCodec As Boolean 'true : affichera la fenêtre de choix du codec / true : allow to chow codec window choice
Private _RecordDate As String 'Date de l'enregistrement / record date
Private FilmManager As AviFile.AviManager
Private FilmStream As AviFile.VideoStream
Private bRecordVideo As Boolean = False 'true si capture video en cours / true if capture video is running
Private TimeUpdate As Single = 1 / _NewtonUpdateFps 'Vitesse d'update de Newton / Newton update speed
Private TimeElapsed As Single = 0 'Pour Newton / for Newton
Private TimeSinceLastFrame As Single 'Pour Newton / for Newton
Private NodeAxe As Mogre.SceneNode 'L'axe des objets / Object axes
Private NodeAxeMonde As Mogre.SceneNode 'L'axe du monde / world axes
Private myfrminfo As New frmInfo 'Splash screen
Private Scene As OSMScene 'La variable pour le chargement de la scene oFusion / oFusion scene
'Déclarations pour Newton
Private CurrentCamNode As Mogre.SceneNode 'Le node de la caméra sélectionnée / currently selected camera node
Private CurrentCamViewNode As Mogre.SceneNode 'Le View Node de la caméra sélectionnée / currently selected view node
Private camera_rotation_x As Single
Private camera_rotation_y As Mogre.Degree
Private y_rotation_cont As Degree
Private y_limit_a As Single = 90 'Les limites hautes et basses de rotation de la caméra / movement limitation on Y
Private y_limit_b As Single = -90
Private InitialCamBodyPos As Mogre.Vector3 'Position et orientation de départ de la caméra / initial position and orientation of camera
Private InitialCamBodyOrient As Mogre.Quaternion
'Déclaration pour MOIS / MOIS declaration
Private inputManager As MOIS.InputManager
Private inputKeyboard As MOIS.Keyboard = Nothing
Private inputMouse As MOIS.Mouse = Nothing
'Les déclarations pour le plan de réflection / Reflection plane declaration
Private ReflectionPlane As Mogre.Plane 'Le plan suivant lequel se fera la réflection / Reflection plane
Private mPlaneEnt As Mogre.Entity 'l'entity de plan / Plane entity
Private mPlaneNode As Mogre.SceneNode 'son scene node / It's scene node
Private ReflectOn As Boolean = False 'reflection active ou pas / reflection on or off
Private ReflectInit As Boolean = False 'vraie si les réflection sont actives / true if reflection active
Private texture As Mogre.TexturePtr
Private ReflectPlane As Mogre.MeshPtr
Private rttTex As Mogre.RenderTarget
'Private FrameTime As New System.TimeSpan
'Private LastFrameTime As New System.TimeSpan
'Private TimeSinceLastFrames As New System.TimeSpan
Private FrameTime As UInteger
Private LastFrameTime As UInteger
Private TimeSinceLastFrames As UInteger
Private Counter As Integer
Private OgreTimer As Mogre.Timer = New Mogre.Timer
#End Region
#Region "Définition des API / API definitions"
'Pour le timer haute résolution (non implémenté) / for high resolution timer (not implemented yet)
Declare Function QueryPerformanceCounter Lib "Kernel32" (ByVal X As Decimal) As Boolean
Declare Function QueryPerformanceFrequency Lib "Kernel32" (ByVal X As Decimal) As Boolean
#End Region
#Region "Les propiétés / Property"
'Les actions ci dessous permettent d'affecter ou lire les différentes propriétés exposée. Ce passe de commentaire
'This actions allow to get or set exposed property of the class
ReadOnly Property OgreRacine() As Mogre.Root
Get
Return _OgreRacine
End Get
End Property
ReadOnly Property OgreSceneManager() As Mogre.SceneManager
Get
Return _OgreSceneManager
End Get
End Property
Property OgreCamera() As Mogre.Camera
Get
Return _OgreCamera
End Get
Set(ByVal value As Mogre.Camera)
_OgreCamera = value
End Set
End Property
Property ShowAxesMonde() As Boolean
Get
Return _ShowAxesMonde
End Get
Set(ByVal value As Boolean)
_ShowAxesMonde = value
End Set
End Property
WriteOnly Property osmSceneName() As String
Set(ByVal value As String)
_SceneToLoad = value
End Set
End Property
WriteOnly Property RessourcesToLoad() As String()
Set(ByVal value As String())
For i As Integer = 0 To value.Length - 1
_RessourcesToLoad.Add(value(i))
Next
End Set
End Property
WriteOnly Property RenderWindowHandle() As System.IntPtr
Set(ByVal value As System.IntPtr)
_RenderWindowHandle = value
End Set
End Property
WriteOnly Property TopWindowHandle() As System.IntPtr
Set(ByVal value As System.IntPtr)
_TopWindowHandle = value
_RenderWindowHandle = value
End Set
End Property
Property CollisionDetection() As Boolean
Get
Return _CollisionDetection
End Get
Set(ByVal value As Boolean)
_CollisionDetection = value
End Set
End Property
WriteOnly Property Application()
Set(ByVal value)
_Application = value
End Set
End Property
WriteOnly Property Moving() As Boolean
Set(ByVal value As Boolean)
_moving = value
End Set
End Property
WriteOnly Property Init() As Boolean
Set(ByVal value As Boolean)
_init = value
End Set
End Property
WriteOnly Property ShowInfo() As Boolean
Set(ByVal value As Boolean)
_showLoad = value
End Set
End Property
WriteOnly Property RenderOn() As Boolean
Set(ByVal value As Boolean)
_RenderOn = value
End Set
End Property
WriteOnly Property GravityOn() As Boolean
Set(ByVal value As Boolean)
_GravityOnOff = value
End Set
End Property
Property Gravity() As Single
Get
Return _Gravity
End Get
Set(ByVal value As Single)
_Gravity = value
End Set
End Property
Property MoveFactor() As Single
Get
Return _MoveFactor
End Get
Set(ByVal value As Single)
_MoveFactor = value
End Set
End Property
WriteOnly Property TranslatFactor() As Single
Set(ByVal value As Single)
_Translate = value
End Set
End Property
WriteOnly Property RotateFactor() As Single
Set(ByVal value As Single)
_Rotate = value
End Set
End Property
WriteOnly Property AxeLoaded() As Boolean
Set(ByVal value As Boolean)
_LoadAxe = value
End Set
End Property
WriteOnly Property CameraSize() As Mogre.Vector3
Set(ByVal value As Mogre.Vector3)
_CamSize = value
If Not _CurrentCamBody Is Nothing Then
CurrentCamNode.SetScale(_CamSize)
End If
End Set
End Property
ReadOnly Property GetPerformanceCounter() As Decimal
Get
Return _GetPerformanceCounter
End Get
End Property
ReadOnly Property GetPerformanceFrequency() As Decimal
Get
Return _GetPerformanceFreqency
End Get
End Property
WriteOnly Property AssignSceneType() As Mogre.SceneType
Set(ByVal value As Mogre.SceneType)
_SceneType = value
End Set
End Property
WriteOnly Property StartupPath() As String
Set(ByVal value As String)
_StartupPath = value
End Set
End Property
WriteOnly Property DebugOnOff() As Boolean
Set(ByVal value As Boolean)
If value Then
MogreNewt.Debugger.Instance.ShowLines(_myWorld)
Else
MogreNewt.Debugger.Instance.HideLines()
End If
End Set
End Property
WriteOnly Property NewtonUpdateFps() As Single
Set(ByVal value As Single)
_NewtonUpdateFps = value
If Not _myWorld Is Nothing Then
_myWorld.SetMinimumFrameRate(_NewtonUpdateFps)
TimeUpdate = 1 / _NewtonUpdateFps
End If
End Set
End Property
WriteOnly Property NewtonTimeFactor() As Single
Set(ByVal value As Single)
_TimeFactor = value
End Set
End Property
ReadOnly Property OgreRenderWindow() As Mogre.RenderWindow
Get
Return _RenderWindow
End Get
End Property
WriteOnly Property SuspendRender() As Boolean
Set(ByVal value As Boolean)
_SuspendRender = value
End Set
End Property
WriteOnly Property ShowDebugNewtonInfo() As Boolean
Set(ByVal value As Boolean)
_ShowDebugNewtonInfo = value
End Set
End Property
WriteOnly Property CamMass() As Single
Set(ByVal value As Single)
_CammMass = value
End Set
End Property
ReadOnly Property FPS() As Single
Get
Return OgreRenderWindow.AverageFPS
End Get
End Property
ReadOnly Property CamBody() As MogreNewt.Body
Get
Return _CurrentCamBody
End Get
End Property
ReadOnly Property NewtonWorld() As MogreNewt.World
Get
Return _myWorld
End Get
End Property
WriteOnly Property ReflectSceneNode() As Mogre.SceneNode
Set(ByVal value As Mogre.SceneNode)
_mReflectSceneNode = value
End Set
End Property
WriteOnly Property Reflectionintensity() As Single
Set(ByVal value As Single)
_ReflecionIntensity = value
End Set
End Property
WriteOnly Property uScale() As Single
Set(ByVal value As Single)
_UScaleReflect = value
End Set
End Property
WriteOnly Property vScale() As Single
Set(ByVal value As Single)
_vScaleReflect = value
End Set
End Property
WriteOnly Property SceneBlendingType() As Mogre.SceneBlendType
Set(ByVal value As Mogre.SceneBlendType)
_SceneBlendingType = value
End Set
End Property
WriteOnly Property ReflectPlaneNorma() As Mogre.Vector3
Set(ByVal value As Mogre.Vector3)
_ReflectPlaneNormal = value
End Set
End Property
WriteOnly Property OgreMaxFPS() As Integer
Set(ByVal value As Integer)
_OgreMaxFPS = value
End Set
End Property
WriteOnly Property MaxFrameSkip() As Integer
Set(ByVal value As Integer)
_MaxFrameSkip = value
End Set
End Property
WriteOnly Property NewtonWorldSizeMin() As Mogre.Vector3
Set(ByVal value As Mogre.Vector3)
_NewtonWorldSizeMin = value
End Set
End Property
WriteOnly Property NewtonWorldSizeMax() As Mogre.Vector3
Set(ByVal value As Mogre.Vector3)
_NewtonWorldSizeMax = value
End Set
End Property
WriteOnly Property DebugNewton() As Boolean
Set(ByVal value As Boolean)
_DebugNewton = value
End Set
End Property
WriteOnly Property InfoMessage() As String
Set(ByVal value As String)
_InfoMessage = value
End Set
End Property
WriteOnly Property FSAA() As Integer
Set(ByVal value As Integer)
_FSAA = value
End Set
End Property
'WriteOnly Property ArrayImg()
' Set(ByVal value)
' _tArrayImg.Add(value)
' End Set
'End Property
WriteOnly Property CtrlToCapture()
Set(ByVal value)
_CtrlToCapture = value
End Set
End Property
WriteOnly Property ChoixDuCodec() As Boolean
Set(ByVal value As Boolean)
_ChoixDuCodec = value
End Set
End Property
ReadOnly Property RecordDate() As String
Get
Return _RecordDate
End Get
End Property
WriteOnly Property NbCapturedFrameBySecond() As Integer
Set(ByVal value As Integer)
_NbCapturedFrameBySecond = value
End Set
End Property
#End Region
#Region "Procédures et fonctions / Proc and sub"
#Region "Publics"
Public Sub ChangeMessage()
If _showLoad Then
myfrminfo.lblInfo.Text = _InfoMessage
myfrminfo.Refresh()
End If
End Sub
Public Function Timer() As Single
'Une fonction Timer haute résolution basée sur les performances de l'ordi
'Pour la gestion de l'update de Newton, non encore implémenté
Static Start As Decimal = 0
Static Frequency As Decimal = 0
If Start = 0 Then
'Si premier appel, on initialise les variables statiques
Dim bool As Boolean = QueryPerformanceCounter(Start)
QueryPerformanceFrequency(Frequency)
Return 0.0F
End If
Dim counter As Decimal
QueryPerformanceCounter(counter)
'On renvoi la valeur depuis le premier appel
Return ((counter - Start) / Frequency)
End Function
Public Function InitOgre(ByVal PluginFiles As String, ByVal CfgFile As String, ByVal LogFile As String) As Boolean
'Création de la racine OGRE et du SceneManager.
'Affichage de la fenêtre de paramètres OGRES, le cas échéant
'Ogre root, scenen manager initialisation and showing of ogre configuration window if necessary
_OgreRacine = New Root(PluginFiles, CfgFile, LogFile)
If Not _OgreRacine.RestoreConfig() Then
If Not _OgreRacine.ShowConfigDialog Then
Return False
End If
End If
Try
_OgreSceneManager = _OgreRacine.CreateSceneManager(_SceneType)
Catch ex As System.Runtime.InteropServices.SEHException
'en cas d'erreur..../ if error is raised
If OgreException.IsThrown Then
MsgBox(OgreException.LastException.FullDescription, MsgBoxStyle.Critical, _
"Exeption OGRE!")
Return False
Else
MsgBox(ex.ToString, "Erreur")
Return False
End If
End Try
Try
'On initialise OGRE/ OGRE initialisation
_OgreRacine.Initialise(False)
Catch ex As System.Runtime.InteropServices.SEHException
'en cas d'erreur..../ if error is raised
FileIO.FileSystem.DeleteFile(_StartupPath + "\ogre.cfg")
If Not _OgreRacine.ShowConfigDialog Then
Return False
End If
End Try
Return True
End Function
Public Function InitScene(ByVal Langue As String) As Boolean
If _showLoad Then
Langue = Langue.ToUpper
If Langue = "FR" Then
myfrminfo.lblInfo.Text = "Chargement de la scène en cours....Merci de patienter."
ElseIf Langue = "DE" Then
myfrminfo.lblInfo.Text = "Laden der aktuellen Szene.... Bitte sich gedulden."
ElseIf Langue = "ES" Then
myfrminfo.lblInfo.Text = "Carga de la escena corriente.... Gracias por tener paciencia."
ElseIf Langue = "IT" Then
myfrminfo.lblInfo.Text = "Caricando del palcoscenico in progresso....Grazie essere paziente."
ElseIf Langue = "PO" Then
myfrminfo.lblInfo.Text = "Carregando em desenvolvimento da fase....Lhe agradeça ser paciente."
Else
myfrminfo.lblInfo.Text = "Scene loading in progress....Please wait"
End If
myfrminfo.Show()
myfrminfo.Refresh()
End If
Try
'On initialise OGRE/ OGRE initialisation
'_OgreRacine.Initialise(False)
'On crè la fenêtre, ici ce sera dans un contrôle, une picturebox / OGRE window creation, here in a control
Dim misc As NameValuePairList = New NameValuePairList
misc("externalWindowHandle") = _RenderWindowHandle.ToString
misc("FSAA") = _FSAA
Dim const_list As Const_NameValuePairList = misc.ReadOnlyInstance
_RenderWindow = _OgreRacine.CreateRenderWindow("OgreWieport", 0, 0, False, const_list)
'On crés le ressource manager avec les ressources passées en paramètre dans la liste des ressources.
'Ressource manager creation withe ressources given in parameters in ressources list
'Par défaut, on prend le chemin de la scène / pth of the scene by default
ResourceGroupManager.Singleton.AddResourceLocation(System.IO.Path.GetDirectoryName(_SceneToLoad), "FileSystem", "General")
'On ajoute le répertoires OBJETS de l'application qui contient, entre autre, les axes
'adding objets path that contain such thing as axes for example
ResourceGroupManager.Singleton.AddResourceLocation(_StartupPath + "\Objets", "FileSystem", "General")
'et on parcourt la variable _RessourcesToLoad pour ajouter les ressources supplémentaires (répertoires ou fichiers zip)
'iteration of _RessourceToLoad to add other ressources (Directory or zip files)
Dim SplitRessource() As String
For i As Integer = 0 To _RessourcesToLoad.Count - 1
SplitRessource = _RessourcesToLoad(i).ToString.Split("|")
ResourceGroupManager.Singleton.AddResourceLocation(SplitRessource(0), SplitRessource(1), "General")
Next
'Fini, on initialise toutes les ressources / Initailisation of all ressources
ResourceGroupManager.Singleton.InitialiseAllResourceGroups()
'On charge la scène OSM grâce à la dll oFusion / OSM scene loading with oFusion DLL
Scene = New OSMScene(_OgreSceneManager, _RenderWindow)
Scene.Initialize(_SceneToLoad)
Scene.CreateScene(_OgreSceneManager.RootSceneNode)
'création de la caméra / camera creation
If Scene.CameraList.Count > 0 Then
'Si la scene contient au moins une caméra, on sélectionne la première / if there is at least one cam in scene we select it
_OgreCamera = Scene.CameraList(0)
Else
'sinon, on en crè une par défaut / else we create one
_OgreCamera = Scene.SceneMgr.CreateCamera("CameraDefaut")
_OgreCamera.SetPosition(0, 0, 0)
_OgreCamera.SetDirection(0, 0, 0)
_OgreCamera.FOVy = CType(1, Mogre.Radian)
Dim camNode As SceneNode = _OgreSceneManager.CreateSceneNode("CameraDefaut")
camNode.AttachObject(_OgreCamera)
Dim CameraTarget As Mogre.SceneNode = _OgreSceneManager.CreateSceneNode("CameraDefaut.target")
CameraTarget.SetPosition(1000, 1000, 1000)
CameraTarget.SetDirection(0, 0, 0)
CameraTarget.SetScale(1, 1, 1)
'On crè le viewport / vieport creation
Dim ViewPort As Mogre.Viewport = _RenderWindow.AddViewport(_OgreCamera)
_OgreCamera.AspectRatio = ViewPort.ActualWidth / ViewPort.ActualHeight
End If
_OgreCamera.NearClipDistance = 5
InitialCamBodyOrient = _OgreCamera.Orientation
InitialCamBodyPos = _OgreCamera.Position
'si on a décidé d'activer la gestion des collisions, on initialise Newton / if colision detection enable, Newton init
If _CollisionDetection Then
InitNewton(Langue)
End If
'initialisation de l'inputmanager MOIS / input manager initialisation
InitInputHandler()
If _LoadAxe Then
LoadAxe() 'Chargement et instanciation des axes / axes loading
End If
Catch ex As System.Runtime.InteropServices.SEHException
If _showLoad Then
myfrminfo.Hide()
myfrminfo.Dispose()
End If
'en cas d'erreur..../if error
If OgreException.IsThrown Then
MsgBox(OgreException.LastException.FullDescription, MsgBoxStyle.Critical, _
"Exeption OGRE!")
Return False
Else
MsgBox(ex.ToString, "Erreur")
Return False
End If
End Try
'If _showLoad Then
' myfrminfo.Hide()
' myfrminfo.Dispose()
'End If
Return True
End Function
Public Sub OgreGo()
If _showLoad Then
myfrminfo.Hide()
myfrminfo.Dispose()
End If
While _RenderOn
If _ShowDebugNewtonInfo Then
MogreNewt.Debugger.Instance.ShowLines(_myWorld)
End If
If Not _SuspendRender Then
'et on rend une frame / render of one frame
Try
_OgreRacine.RenderOneFrame()
Catch ex As Exception
End Try
'Update du monde physique / physical worl update
If _CollisionDetection Then
_NewtonUpdateFps = _AvgFPS
UpdateNewton(TimeSinceLastFrame)
End If
If _ShowDebugNewtonInfo Then
MogreNewt.Debugger.Instance.ShowLines(_myWorld)
MogreNewt.Debugger.Instance.HideLines()
End If
End If
_Application.doevents()
If _ShowDebugNewtonInfo Then
MogreNewt.Debugger.Instance.HideLines()
End If
End While
End Sub
Public Sub OgreUpdate()
If _showLoad Then
myfrminfo.Hide()
myfrminfo.Dispose()
End If
'A utiliser dans les fenêtre de dialogue modale à l'aide d'un timer
'To use in a modal window wihtin a timer of that window
If _ShowDebugNewtonInfo Then
MogreNewt.Debugger.Instance.ShowLines(_myWorld)
End If
If Not _SuspendRender Then
'et on rend une frame / render one frame
_OgreRacine.RenderOneFrame()
'Update du monde physique / physical world update
If _CollisionDetection Then
_NewtonUpdateFps = _AvgFPS
UpdateNewton(TimeSinceLastFrame)
End If
If _ShowDebugNewtonInfo Then
MogreNewt.Debugger.Instance.ShowLines(_myWorld)
MogreNewt.Debugger.Instance.HideLines()
End If
End If
If _ShowDebugNewtonInfo Then
MogreNewt.Debugger.Instance.HideLines()
End If
End Sub
Public Sub ReSize(ByVal width As Single, ByVal height As Single)
'Pour redimensionner le vieport de manière correcte quand on redimmensionne la picturebox (du à un resize de la form ou un déplacement des splitter)
'to resize vieport when render control is resized
If Not _init Then
_RenderWindow.WindowMovedOrResized()
_OgreCamera.AspectRatio = width / height
End If
End Sub
Public Sub SelectCamera(ByVal CameraName As String, ByVal GravityOn As Boolean)
'Permet de changer de caméra sur une scène multi caméra / allow to choose camera in a multi camera scene
_OgreCamera = OgreSceneManager.GetCamera(CameraName) 'on récupère le nom de la caméra sélectionnée/ selected camera's name
_RenderWindow.GetViewport(0).Camera = _OgreCamera 'et on change de caméra / affecting camera to vieport
If ReflectOn Then
rttTex.GetViewport(0).Camera = _OgreCamera 'si on affiche les réflecion, on change aussi la caméra / if reflection on, we change camera too
End If
_GravityOnOff = GravityOn
For i As Integer = 0 To ListeCamera.Count - 1
'Important, il faut bien resélectionner les cambody et autre associés à la caméra choisi / and important, getting the good cam body
If ListeCamera.Item(i).Camera.name = CameraName Then
CurrentCamNode = ListeCamera.Item(i).CamNode
_CurrentCamBody = ListeCamera.Item(i).CamBody
CurrentCamViewNode = ListeCamera.Item(i).CamViewNode
Exit For
End If
Next
Dim myViewport As Mogre.Viewport = _RenderWindow.GetViewport(0)
_OgreCamera.AspectRatio = myViewport.ActualWidth / myViewport.ActualHeight
If ReflectOn Then
myViewport = rttTex.GetViewport(0)
_OgreCamera.AspectRatio = myViewport.ActualWidth / myViewport.ActualHeight
End If
End Sub
Public Sub Shutdown()
'On arrête le rendu / render stop
_RenderOn = False
End Sub
Public Sub DisposeOgre()
'Pemet de nettoyer les instances OGRES en cas de rechargement de la scène ou de l'ouverture d'une nouvelle
'Allow to destroy all ogre instances
If ReflectOn Then
texture = Nothing
texture.Dispose()
ReflectPlane = Nothing
ReflectPlane.Dispose()
Mogre.MeshManager.Singleton.RemoveAll()
Mogre.MeshManager.Singleton.Dispose()
Mogre.TextureManager.Singleton.RemoveAll()
Mogre.TextureManager.Singleton.Dispose()
End If
ResourceGroupManager.Singleton.DestroyResourceGroup("General")
ResourceGroupManager.Singleton.Dispose()
_RenderWindow.RemoveAllViewports()
_OgreRacine.DetachRenderTarget(_RenderWindow)
_RenderWindow.Destroy()
_OgreRacine.DestroySceneManager(_OgreSceneManager)
_OgreRacine.DestroyAllRenderQueueInvocationSequences()
_OgreRacine.Shutdown()
_OgreRacine.Dispose()
End Sub
Public Sub DisposeNewton()
'Permet de liberer les instances Newton
'allow to clear newton world
If _CollisionDetection Then
Try
_myWorld.DestroyAllBodies()
_myWorld.Dispose()
Catch ex As Exception
End Try
End If
End Sub
Public Sub ReflectionOff()
'Permet de suspendre la reflection / allow to suspend reflection
mPlaneEnt.Visible = False 'on cache le plan de reflection / hiding reflection plane
_mReflectSceneNode.GetAttachedObject(CType(0, UShort)).Visible = True 'on montre l'objet initial / showing base object
ReflectOn = False 'on ne fait plus de reflection / no reflection
End Sub
Public Sub ReflectionOn()
'Permet d'initialiser les reflections ou de les réactiver si elles avaient été suspendue
'Allow to initialise reflection or reactivat it if the have been suspended
If ReflectInit Then 'si elle ont été suspendus, alors, on les réactive / if suspended, reactivate it
mPlaneEnt.Visible = True 'on montre le plan de réflection / showing reflection plane
_mReflectSceneNode.GetAttachedObject(CType(0, UShort)).Visible = False 'on cache l'objet de base / hiding base object
ReflectOn = True 'on réfléchit / recflection on
Exit Sub
End If
ReflectionPlane.normal = _ReflectPlaneNormal 'par défaut un plan horizontal / horizontal plane
ReflectionPlane.d = 0 '?
'Creation du plan / plane creation
ReflectPlane = Mogre.MeshManager.Singleton.CreatePlane("ReflectPlane", Mogre.ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME, ReflectionPlane, 1024, 1024, 16, 16, True, 1, 1, 1, Mogre.Vector3.UNIT_Z)
'Tou ce qui suit est pour ajouter le plan à la scene / all that follow is to add plane to scene
mPlaneEnt = _OgreSceneManager.CreateEntity("ReflectPlaneEnt", "ReflectPlane")
mPlaneNode = _OgreSceneManager.RootSceneNode.CreateChildSceneNode
mPlaneNode.AttachObject(mPlaneEnt)
'Le plan pend les même taile et position que l'objet de base / plane take same size and position than base object
mPlaneNode.Position = _mReflectSceneNode.Position
mPlaneNode.Orientation = _mReflectSceneNode.Orientation
mPlaneNode.Scale(_mReflectSceneNode.GetScale)
'Creation de la texture pour le calcul des réflections / texture creation for reflection
texture = Mogre.TextureManager.Singleton.CreateManual("RttTex", "General", Mogre.TextureType.TEX_TYPE_2D, CType(512, UInteger), CType(512, UInteger), 0, Mogre.PixelFormat.PF_R8G8B8, Mogre.TextureUsage.TU_RENDERTARGET)
rttTex = texture.GetBuffer.GetRenderTarget()
'Creation du viewport pour calculer les réflections / creation of reflection viewport
Dim v As Mogre.Viewport = rttTex.AddViewport(_OgreCamera)
v.SetClearEveryFrame(True)
v.BackgroundColour = Mogre.ColourValue.Black
'Récupération de la texture de l'objet de base / getting texture from base object
Dim OrigObjet As Mogre.Entity = _mReflectSceneNode.GetAttachedObject(CType(0, UShort))
Dim MatToBlend As Mogre.MaterialPtr = OrigObjet.GetSubEntity(CType(0, UShort)).GetMaterial().Clone("ReflectMat") 'on la clone pour ne pas alterer celle de l'objet / cloning it to not alter base object texture
'on crè une nouvelle technique dans la texture / creation of a new ehcnique in texture
Dim t As Mogre.TextureUnitState = MatToBlend.GetTechnique(CType(0, UShort)).GetPass(CType(0, UShort)).CreateTextureUnitState("RttTex")
'on récupère la première technique de la texture pour permettre sa mise à l'échelle / getting first technique to scaling texture
Dim t1 As Mogre.TextureUnitState = MatToBlend.GetTechnique(CType(0, UShort)).GetPass(CType(0, UShort)).GetTextureUnitState(CType(0, UShort))
'le paramètrage pour le fondu des deux texture / applying param to blend textures
t.SetColourOperationEx(LayerBlendOperationEx.LBX_BLEND_MANUAL, LayerBlendSource.LBS_TEXTURE, LayerBlendSource.LBS_CURRENT, Mogre.ColourValue.White, Mogre.ColourValue.White, _ReflecionIntensity)
t.SetTextureAddressingMode(TextureUnitState.TextureAddressingMode.TAM_CLAMP)
t.SetProjectiveTexturing(True, _OgreCamera)
MatToBlend.SetSceneBlending(_SceneBlendingType)
'mise à l'échelle de la première texture / scaling first texture
t1.TextureUScale = _UScaleReflect
t1.TextureVScale = _vScaleReflect
'on affecte les évènement à faire avant et après rendu du viewport / affecting event in pre and post viewport render
AddHandler rttTex.PostRenderTargetUpdate, AddressOf postRenderTargetUpdate
AddHandler rttTex.PreRenderTargetUpdate, AddressOf preRenderTargetUpdate
'on affecte le materiel au plan / adding material to plan
mPlaneEnt.SetMaterialName(MatToBlend.Name)
OrigObjet.Visible = False 'on cache l'objet de base / hiding base object
ReflectOn = True 'on active les réflections / activate reflection
ReflectInit = True 'les reflection on été initialisées / reflection are initialised
End Sub
Public Sub OpenVideoStream(ByVal CheminFilm As String, ByVal NomFilm As String)
'Permet d'initialiser la capture video / Allow to initialisz video capture
Dim g As Graphics = _CtrlToCapture.CreateGraphics()
Dim newImage As System.Drawing.Image = New Bitmap(_CtrlToCapture.Size.Width, _CtrlToCapture.Size.Height, g)
g = _CtrlToCapture.CreateGraphics()
newImage = New Bitmap(_CtrlToCapture.Size.Width, _CtrlToCapture.Size.Height, g)
_RecordDate = Date.Now.ToString
_RecordDate = RecordDate.Replace("/", "-")
_RecordDate = RecordDate.Replace(":", "-")
FilmManager = New AviFile.AviManager(CheminFilm + "\" + NomFilm + "_" + _RecordDate + ".avi", False)
bRecordVideo = True
FilmStream = FilmManager.AddVideoStream(True, _NbCapturedFrameBySecond, newImage, _ChoixDuCodec)
End Sub
Public Sub CloseVideoStream()
'Arrête la capture vidéo / stop video capture
bRecordVideo = False
FilmManager.Close()
End Sub
#End Region
#Region "Privées"
Private Sub InitNewton(ByVal Langue)
Dim CamNode As ArrayList = New ArrayList 'Le node de la caméra / camera node
Dim CamViewNode As ArrayList = New ArrayList
Dim CamBody As ArrayList = New ArrayList 'Le corps physique de la caméra / physical cam body
Dim CamColl As CollisionPrimitives.Ellipsoid 'Le type de collision / collision type
If Langue = "FR" Then
myfrminfo.lblInfo.Text = "Initialisation du moteur physique....Merci de patienter."
ElseIf Langue = "DE" Then
myfrminfo.lblInfo.Text = "Initialisierung der körperlichen Maschine.... Bitte sich gedulden."
ElseIf Langue = "ES" Then
myfrminfo.lblInfo.Text = "Inicialización del motor fÃsico.... Gracias por tener paciencia."
ElseIf Langue = "IT" Then
myfrminfo.lblInfo.Text = "Inizio del motore fisico....Grazie essere paziente.."
ElseIf Langue = "PO" Then
myfrminfo.lblInfo.Text = "Iniciação do motor fÃsico....Lhe agradeça ser paciente."
Else
myfrminfo.lblInfo.Text = "Initialization of the physics engine.....Please wait"
End If
myfrminfo.Refresh()
'Initialisation de Newton pour la gestion des collision caméras
'Newton init to handle cam colision
If _myWorld Is Nothing Then
_myWorld = New World 'le monde physique / physical world
'et initialisation de sa taille, par défaut elle est de 100 sur chaque axes.
'and init of it's size by default it's 100 on each axes
'myWorld.SetWorldSize(_NewtonWorldSizeMin, _NewtonWorldSizeMax)
_myWorld.SetWorldSize(New Mogre.Vector3(-100000, -100000, -100000), New Mogre.Vector3(100000, 100000, 100000))
End If
_myWorld.SetMinimumFrameRate(_NewtonUpdateFps)
TimeUpdate = 1 / _NewtonUpdateFps
'Création du monde physique pour Newton / creating newton physical world
Dim stat_col As MogreNewt.CollisionPrimitives.TreeCollisionSceneParser = New MogreNewt.CollisionPrimitives.TreeCollisionSceneParser(_myWorld)
stat_col.ParseScene(_OgreSceneManager.RootSceneNode, False) 'Utilisation du parser de scène Newton, attention, à ce jour (juillet 2008), le parmètre true, au mieux, ne fonctionne pas et au pire plante le programme.
'use of newton scene parser. Beware if true is use, physical world is not well initialised
'Création et paramétrage du body pour le monde / creation and initialisation of body world
Dim bod As MogreNewt.Body = New MogreNewt.Body(_myWorld, stat_col)
stat_col.Dispose()
bod.AttachToNode(_OgreSceneManager.RootSceneNode)
bod.SetPositionOrientation(New Mogre.Vector3(0.0, 0.0, 0.0), Quaternion.IDENTITY)
For i As Integer = 0 To Scene.CameraList.Count - 1
_OgreCamera = Scene.CameraList(i)
'Collision de la caméra / camera collision
Dim PosCam As Mogre.Vector3 = _OgreSceneManager.GetSceneNode(_OgreCamera.Name).Position 'on récupère la position de la caméra / cam position
Dim OrientCam As Quaternion = _OgreSceneManager.GetSceneNode(_OgreCamera.Name).Orientation 'on récupère l'orientation de la caméra / cam orientation
Dim localcambody As MogreNewt.Body
CamNode.Add(Nothing)
CamBody.Add(Nothing)
CamViewNode.Add(Nothing)
CamNode(i) = _OgreSceneManager.RootSceneNode.CreateChildSceneNode("N" + _OgreCamera.Name) 'on crè un Scennode / scenenode creation
CamNode(i).SetScale(_CamSize) 'on le met à la taille de la caméra / applying cam size
CamColl = New CollisionPrimitives.Ellipsoid(_myWorld, _CamSize) 'on crè le système de collision / collision system creation
localcambody = New Body(_myWorld, CamColl) 'on l'applique au body représentant la caméra / applying it to cam body
CamColl.Dispose() 'on libère la collision / freeing collision
localcambody.AttachToNode(CamNode(i)) 'et on l'attache au noeud créé précédement / attach it to node
'calcul de l'inertie de la caméra / inertia camera
Dim cam_inertia As Mogre.Vector3 = MomentOfInertia.CalcEllipsoidSolid(_CammMass, _CamSize)
localcambody.SetMassMatrix(_CammMass, cam_inertia)
AddHandler localcambody.ForceCallback, AddressOf camera_force_callback 'la fonction appelée lors de l'update du monde physique / function call at each physical update
localcambody.AutoFreeze = False 'Important, sinon, impossible de déplacer le body... / important else body don't move
CamBody(i) = localcambody
'Création d'un "UP Vector" pour empécher le body de tomber / creation of a "UP Vector" so body can't fall
Dim uv2 As BasicJoints.UpVector = New BasicJoints.UpVector(_myWorld, CamBody(i), Mogre.Vector3.UNIT_Y)
'Création d'un scenenode 1 unités au dessus du camnode pour y mettre la caméra
'Creation of a scene node 1 units above camnode to put camera in
CamViewNode(i) = CamNode(i).CreateChildSceneNode("Newt" + _OgreCamera.Name, New Mogre.Vector3(0, 1, 0)) 'création du scenenode / scene node creation
_OgreSceneManager.RootSceneNode.DetachObject(_OgreCamera) 'on détache la caméra du rootscenenode (créé par OSMLoader) / detaching camera from root scene node (create by OSM Loader)
CamViewNode(i).AttachObject(_OgreCamera) 'et on attache la caméra au viewnode / attachin cam to viewnode
CamBody(i).SetPositionOrientation(PosCam, OrientCam) 'Sert à récupérer la position et orientation initiale de la caméra pour positionner son corp. / Puting body in initial cam position and orientation
InitialCamBodyOrient = get_body_orientation(CamBody(i))
InitialCamBodyPos = get_body_position(CamBody(i))
Dim StructCam As New Camera
StructCam.Camera = _OgreCamera
StructCam.CamNode = CamNode(i)
StructCam.CamViewNode = CamViewNode(i)
StructCam.CamBody = CamBody(i)
ListeCamera.Add(StructCam)
Next
_CurrentCamBody = CamBody(0)
CurrentCamNode = CamNode(0)
CurrentCamViewNode = CamViewNode(0)
_OgreCamera = Scene.CameraList(0)
If _DebugNewton Then
MogreNewt.Debugger.Instance.Init(_OgreSceneManager) 'et on initialise le debugger newton. / newton debugger initialisation
End If
End Sub
Private Sub preRenderTargetUpdate()
'Procedure exécutée avant le render de la texture de réflection
'On cache le plan de réflextion et on active la reflection de la caméra
'Proc executed before reflection render
'we hide reflection plan, and activate camera reflection
If ReflectOn Then 'si la reflection est active/ if reflection on
mPlaneEnt.Visible = False
_OgreCamera.EnableReflection(ReflectionPlane)
End If
End Sub
Private Sub postRenderTargetUpdate()
'Procedure exécutée après le render de la texture de réflection
'On désactive la reflection de la caméra et on réaffiche le plan de réflection
'Proc executed after reflection render
'we show reflection plan, and deactivate camera reflection
If ReflectOn Then 'si la reflection est active / if reflection on
_OgreCamera.DisableReflection()
mPlaneEnt.Visible = True
End If
End Sub
Private Sub InitInputHandler()
Dim param As MOIS.ParamList = New MOIS.ParamList()
'Les 4 premiers paramètres servent à signaler que MOIS ne sera pas le seul à être capable de gérer le clavier et la souris
'ceci permet de disposer du curseur de la souris pour faire autre chose pendant que Ogre rend ses frames
'The first four parameters are to say to MOIs than it's not the only one than can handle keyboard and mouse
'this permit to do other things with mouse and keyboard whne ogre is rendereing
param.Insert("w32_mouse", "DISCL_NONEXCLUSIVE")
param.Insert("w32_mouse", "DISCL_FOREGROUND")
param.Insert("w32_keyboard", "DISCL_NONEXCLUSIVE")
param.Insert("w32_keyboard", "DISCL_FOREGROUND")
param.Insert("WINDOW", _TopWindowHandle.ToString) 'ici, on passe le handle de notre "top level window" (cf. DirectX et DirectInput) / handle of "top level window" (see DirectX and DirectInput)
'Hook de l'input manager à la fenêtre / hook of window input manager
inputManager = MOIS.InputManager.CreateInputSystem(param)
If Not inputManager Is Nothing Then
'Creation des device de capture MOIS / creating device capture
Try
'Le clavier / keyboard
inputKeyboard = CType(inputManager.CreateInputObject(MOIS.Type.OISKeyboard, False), MOIS.Keyboard)
Catch ex As System.Runtime.InteropServices.SEHException
'en cas d'erreur.... / if error
If OISException.IsThrown Then
MsgBox(OISException.LastException.eText, MsgBoxStyle.Critical, _
"Exeption OIS!")
Else
MsgBox(ex.ToString, "Erreur")
End If
End Try
Try
'La souris / mouse
inputMouse = CType(inputManager.CreateInputObject(MOIS.Type.OISMouse, False), MOIS.Mouse)
Catch ex As System.Runtime.InteropServices.SEHException
'en cas d'erreur.... / if error
If OISException.IsThrown Then
MsgBox(OISException.LastException.eText, MsgBoxStyle.Critical, _
"Exeption OIS!")
Else
MsgBox(ex.ToString, "Erreur")
End If
End Try
'A répéter pour d'autre input, joystick par exemple :
'to repeat for another input, joystick for example :
'' ''Try
'' '' inputJoy = CType(inputManager.CreateInputObject(MOIS.Type.OISJoyStick, False), MOIS.JoyStick)
'' ''Catch ex As System.Runtime.InteropServices.SEHException
'' '' 'en cas d'erreur....
'' '' If OISException.IsThrown Then
'' '' MsgBox(OISException.LastException.eText, MsgBoxStyle.Critical, _
'' '' "Exeption OIS!")
'' '' Else
'' '' MsgBox(ex.ToString, "Erreur")
'' '' End If
'' ''End Try
End If
' Et l'évènement qui sera attaché au FrameStarted / and event to attach to framestarded
AddHandler _OgreRacine.FrameStarted, AddressOf FrameStarted
AddHandler _OgreRacine.FrameEnded, AddressOf FrameEnded
End Sub
Private Function FrameStarted(ByVal evt As FrameEvent) As Boolean
'Gère les évènements clavier et souris
'handle mouse and keyboard events
'le test pour annuler le mouvement de la caméra est mis en externe par rapport
'au test de detection de collision car si on relache la souris avant les touches
'la caméra continue à se déplacer, donc, on annule sa vélocité et sa rotation à la fin de la fonction
'test to cancel cam movement is externalise because if we release mouse buton befor keyboard
'cam continue to move, so, we cancel is velocity and rotation at end of function
'Le code du système pour réduire le nombre de FPS est du à Beauty sur le forum MOGRE, merci beaucoup
'FPS reduction system is due to Beauty on MOGRE forum. Thanks a lot.
If FPS = 0 Then
'-- initialize at first run --
'FPSMax = 85 ' set wanted fps 'C'est un paramètre passé à la classe / it's a parameters pass to the class
FrameTime = 1000 / _OgreMaxFPS ' wanted time for one frame
'LastFrameTime = New TimeSpan(DateTime.Now.Ticks)
LastFrameTime = OgreTimer.MillisecondsCPU
End If
'TimeSinceLastFrames = New TimeSpan(DateTime.Now.Ticks - LastFrameTime.Ticks)
'LastFrameTime = New TimeSpan(DateTime.Now.Ticks)
TimeSinceLastFrames = OgreTimer.MillisecondsCPU - LastFrameTime
LastFrameTime = OgreTimer.MillisecondsCPU
If TimeSinceLastFrames < FrameTime Then
'wait if needed
Try
If FrameTime - TimeSinceLastFrame > 0 Then
System.Threading.Thread.Sleep(FrameTime - TimeSinceLastFrame)
End If
Catch ex As Exception
End Try
End If
Dim PasdeMouvement As Boolean = True
CaptureFunction() 'on lance la capture clavier/souris par MOIS / go capture
If inputKeyboard.IsKeyDown(MOIS.KeyCode.KC_SYSRQ) Then 'Capture de l'écran / to capture screen
Dim temp As String() = System.IO.Directory.GetFiles(Environment.CurrentDirectory, "screenshot*.jpg")
Dim fileName As String = _StartupPath + "\" + String.Format("screenshot{0}.jpg", temp.Length + 1)
OgreRenderWindow.WriteContentsToFile(fileName)
ElseIf inputKeyboard.IsKeyDown(MOIS.KeyCode.KC_ESCAPE) Then 'On stop le rendu / stop render
_RenderOn = False
End If
TimeSinceLastFrame = evt.timeSinceLastFrame
If _moving Then 'Si on a cliqué sur le bouton gauche de la souris, on se déplace dans le monde / if mouse button lef clicked, we move
'Il y a 2 systèmes de mouvement, avec ou sans détection de collisions / there is 2 movement systeme one with newton, and the other not
If _CollisionDetection Then
'Avec / with
'Le principe est de récupérer l'orientation du corps de la caméra sur l'axe de déplacement choisi
'et de lui affecter une vitesse de déplacement sur cette axe.
'Lorsque l'on arrête le déplacement, on annule la vitesse.
'we get cam body orientation then applying it a velocity on move axe. When we stop, we cancel velocity
Dim direction As Mogre.Vector3
If inputKeyboard.IsKeyDown(MOIS.KeyCode.KC_UP) Then
direction = get_body_orientation(_CurrentCamBody) * Mogre.Vector3.NEGATIVE_UNIT_Z
_CurrentCamBody.Velocity = _CurrentCamBody.Velocity * New Mogre.Vector3(0, 1, 0) + direction * _MoveFactor
PasdeMouvement = False
End If
If inputKeyboard.IsKeyDown(MOIS.KeyCode.KC_DOWN) Then
direction = get_body_orientation(_CurrentCamBody) * Mogre.Vector3.UNIT_Z
_CurrentCamBody.Velocity = _CurrentCamBody.Velocity * New Mogre.Vector3(0, 1, 0) + direction * _MoveFactor
PasdeMouvement = False
End If
If inputKeyboard.IsKeyDown(MOIS.KeyCode.KC_LEFT) Then
direction = get_body_orientation(_CurrentCamBody) * Mogre.Vector3.NEGATIVE_UNIT_X
_CurrentCamBody.Velocity = _CurrentCamBody.Velocity * New Mogre.Vector3(0, 1, 0) + direction * _MoveFactor
PasdeMouvement = False
End If
If inputKeyboard.IsKeyDown(MOIS.KeyCode.KC_RIGHT) Then
direction = get_body_orientation(_CurrentCamBody) * Mogre.Vector3.UNIT_X
_CurrentCamBody.Velocity = _CurrentCamBody.Velocity * New Mogre.Vector3(0, 1, 0) + direction * _MoveFactor
PasdeMouvement = False
End If
'Pour le déplacement sur Y (vertical) on se déplace sur le Y du monde et pas de la caméra
'Donc, pas besoin de récupérer la direction de la caméra
'For moving on Y (vertical) we move on worl Y and not cam Y so, no needs to get cam orientation
If inputKeyboard.IsKeyDown(MOIS.KeyCode.KC_PGUP) Then
_CurrentCamBody.Velocity = New Mogre.Vector3(0, 1, 0) * _MoveFactor * 2
PasdeMouvement = False
End If
If inputKeyboard.IsKeyDown(MOIS.KeyCode.KC_PGDOWN) Then
_CurrentCamBody.Velocity = New Mogre.Vector3(0, -1, 0) * _MoveFactor
PasdeMouvement = False
End If
'Pour la rotation de la caméra, on récupère le déplacement de la souris sur X et Y
'Fot cam rotation, we get x y mouse movement
Dim mouseState As MOIS.MouseState_NativePtr = inputMouse.MouseState
camera_rotation_x = -mouseState.X.rel * _Rotate
If camera_rotation_x <> 0 Then
PasdeMouvement = False
End If
camera_rotation_y = -mouseState.Y.rel * 0.5F
'On travaille sur le camviewnode pour que l'axe de la caméra soit orienté correctement
'working on cam view node for cam axes well oriented
CurrentCamViewNode.Pitch(camera_rotation_y)
'Si on atteint un angle de rotation maximale vers le haut ou le bas, on annule la rotation
'if we reach max vertical movement, we cancel it
y_rotation_cont += camera_rotation_y
If y_rotation_cont > y_limit_a Or y_rotation_cont < y_limit_b Then
CurrentCamViewNode.Pitch(-camera_rotation_y)
y_rotation_cont -= camera_rotation_y
End If
Else
'Sans / without
'On applique simplement une translation ou une rotation à la caméra
'It's a simpl translation or rotation on camera
Dim myTranslation As Mogre.Vector3 = Mogre.Vector3.ZERO 'Pour le déplacement de la caméra sur ces axes sans détection de collision / for mowing camera without collision detection
myTranslation.z = 0
myTranslation.x = 0
myTranslation.y = 0
If inputKeyboard.IsKeyDown(MOIS.KeyCode.KC_UP) Then
myTranslation.z += -_Translate
End If
If inputKeyboard.IsKeyDown(MOIS.KeyCode.KC_DOWN) Then
myTranslation.z += _Translate
End If
If inputKeyboard.IsKeyDown(MOIS.KeyCode.KC_LEFT) Then
myTranslation.x += -_Translate
End If
If inputKeyboard.IsKeyDown(MOIS.KeyCode.KC_RIGHT) Then
myTranslation.x += _Translate
End If
If inputKeyboard.IsKeyDown(MOIS.KeyCode.KC_PGUP) Then
myTranslation.y += _Translate
End If
If inputKeyboard.IsKeyDown(MOIS.KeyCode.KC_PGDOWN) Then
myTranslation.y += -_Translate
End If
Dim mouseState As MOIS.MouseState_NativePtr = inputMouse.MouseState
camera_rotation_x = mouseState.X.rel * -_Rotate
camera_rotation_y = mouseState.Y.rel * -_Rotate
'Et on déplace la caméra / and move camera
_OgreCamera.Position += _OgreCamera.Orientation * myTranslation * evt.timeSinceLastFrame
_OgreCamera.Yaw(camera_rotation_x * evt.timeSinceLastFrame)
_OgreCamera.Pitch(camera_rotation_y) 'si on multiplie par timesincelastframe, le résultat est plus qu'étrange...A voir. / if multiplying by timesincelastframe, stange result appear...Must see that
End If
End If
'C'est ici que l'on annule la vélocité et la rotation de la caméra. / it's here tha we cancel velocity and camera rotation
If PasdeMouvement And _CollisionDetection Then
_CurrentCamBody.Velocity = New Mogre.Vector3(0, 0, 0)
camera_rotation_x = 0
End If
Return _RenderOn 'tant que l'on ne quitte pas l'appli, on renvoi True. / if not quiting, return true
End Function
Private Function FrameEnded(ByVal evt As FrameEvent) As Boolean
'Fonction exécuté à après le dessin d'une frame. Ici, sert à la capture vidéo
'Function executed after a frame is drawn. Here, it's used to cature a video
If bRecordVideo Then
Dim g As Graphics = _CtrlToCapture.CreateGraphics()
Dim MyImage As System.Drawing.Image = New Bitmap(_CtrlToCapture.Size.Width, _CtrlToCapture.Size.Height, g)
Dim memoryGraphics As Graphics = Graphics.FromImage(MyImage)
'get handle
Dim src As IntPtr = g.GetHdc()
Dim dest As IntPtr = memoryGraphics.GetHdc()
' more information here:
' http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wceui40/html/_celrfternaryrasteroperations.asp
BitBlt(dest, 0, 0, _CtrlToCapture.Size.Width, _CtrlToCapture.Size.Height, src, 0, 0, 13369376)
' release handles
g.ReleaseHdc(dest)
g.Dispose()
memoryGraphics.ReleaseHdc(src)
memoryGraphics.Dispose()
FilmStream.AddFrame(MyImage)
End If
Return True
End Function
Private Sub CaptureFunction()
'Lance la capture du clavier et de la souris / lauch keyboard and mouse capture
inputKeyboard.Capture()
inputMouse.Capture()
End Sub
Private Function get_body_position(ByVal bod As Body) As Mogre.Vector3 'retourne la position du body / return body position
Dim orient As Quaternion
Dim pos As Mogre.Vector3
bod.GetPositionOrientation(pos, orient)
Return pos
End Function
Private Function get_body_orientation(ByVal bod As Body) As Quaternion ' retourne l'orientation du body / return body orientation
Dim orient As Quaternion
Dim pos As Mogre.Vector3
bod.GetPositionOrientation(pos, orient)
Return orient
End Function
Private Sub camera_force_callback(ByVal Corps As Body)
'Cette procédure est appelée à chaque update du monde physique.
'On y applique la gravité ainsi que la rotation sur l'axe des X
'this proc is called by each physical worl update
'we put gravity force and X rotation
If _GravityOnOff Then
Dim masse As Single
Dim inertie As Mogre.Vector3
Dim Force As Mogre.Vector3 = New Mogre.Vector3(0, _Gravity * 10, 0)
'on récupère la position et l'orientation du corp passé en paramètre / gettinf position and orientation of param body
Dim posBody As Mogre.Vector3 = get_body_position(_CurrentCamBody) * Mogre.Vector3.NEGATIVE_UNIT_Z
Dim OrientBody As Quaternion = get_body_orientation(_CurrentCamBody)
Corps.GetMassMatrix(masse, inertie) 'on récupère sa masse et son inertie / getting it's mass and inertia
'on y applique la gravité / applying gravity
Force *= masse
Corps.AddForce(Force) 'on applique la force de gravité / applying forces
End If
Corps.Omega = New Mogre.Vector3(0, camera_rotation_x, 0) 'pour la rotation sur X / rotation on X
End Sub
Private Sub LoadAxe()
'Permet de charger l'objet Axe et de l'ajouter à la scene
'allow to load axe object and adding to scene
Dim Axe01 As Entity 'Sera l'axe afficher sur les objets / object axe
Dim AxeMonde As Entity 'Comme son nom l'indique / world axe
Try
Axe01 = _OgreSceneManager.CreateEntity("Axe01", "Axe.mesh") 'on charge l'objet / loading object
AxeMonde = Axe01.Clone("AxeMonde") 'on le clone pour avoir deux axes séparés / cloning it to have 2 of it
'On crè le node qui contiendra l'axe du monde / world axe node
NodeAxeMonde = _OgreSceneManager.RootSceneNode.CreateChild("AxeMonde")
NodeAxeMonde.AttachObject(AxeMonde)
NodeAxeMonde.SetPosition(0, 0, 0)
NodeAxeMonde.SetScale(1, 1, 1)
NodeAxeMonde.SetVisible(False)
NodeAxeMonde.ResetToInitialState()
'on fait pareil pour l'axe des objets / world axe object
NodeAxe = _OgreSceneManager.RootSceneNode.CreateChild("Axe01")
NodeAxe.AttachObject(Axe01)
NodeAxe.SetPosition(0, 0, 0)
NodeAxe.SetScale(1, 1, 1)
NodeAxe.InheritOrientation = False 'si on ne fait pas ça, l'axe se comporte étrangement lorsque l'objet tourne / to handle correct rotation axe
NodeAxe.InheritScale = False 'Pareil, le scale de l'objet s'ajoute au scale de l'axe / same for scale
NodeAxe.SetVisible(False)
Catch ex As System.Runtime.InteropServices.SEHException
'en cas d'erreur.... / if error
If OgreException.IsThrown Then
MsgBox(OgreException.LastException.FullDescription, MsgBoxStyle.Critical, _
"Exeption OGRE!")
Else
MsgBox(ex.ToString, "Erreur")
End If
End Try
End Sub
Private Sub UpdateNewton(ByVal TimeSinceLastFrame As Single)
'La fonction d'update du monde physique / function to update physical world
If _TimeFactor <> 0 Then
TimeElapsed = 3.5 * TimeSinceLastFrame * _TimeFactor
End If
'If TimeElapsed > TimeUpdate Then 'si le temps passé depuis le dernier update est plus grand que le temp minimum choisi, on se rattrape / if time passed since last update greater than minimum time, running after time
' While TimeElapsed > TimeUpdate
' myWorld.Update(TimeUpdate)
' TimeElapsed -= TimeUpdate
' End While
'Else 'sinons / else...
If TimeElapsed < TimeUpdate Then
'Le temps passé est plus petit que le temps minimum, on ne fait rien / time elapsed smaller than minimum time
Else
_myWorld.Update(TimeUpdate) 'sinon, on update / else updating
End If
'End If
End Sub
#End Region
#End Region
End Class{CODE}
By the way, you need to define object in the form. The most important is the panel to render to, here panRender.
You will need this too, it's the ofusion loader library. I found it somewhere in the wiki. It's not of my own programation, I change only the log system, because it cause crash if I use the class more than one time in soft.
Note: The code is from the wiki page ((MOGRE OSMSceneLoader 2))
{CODE(wrap="1", colors="c#")}/**********************************************************************
*<
oFusion Scene Loader CE (see License.txt)
FILE: OgreOSMScene.cpp
DESCRIPTION: Contains the OE_XMLScene reader (oe_scene)
IMPLEMENTED BY: Andres Carrera
HISTORY:
Original implementation by Lasse Tassing (Channex)
2005 ITE ApS, Lasse Tassing
*> Copyright (c) 2006, All Rights Reserved.
**********************************************************************/
/* Mogre port notes (28/Jan/2007) by smernesto (Ernesto Gutierrez):
* Tested with Mogre 0.1.9 + OGRE 1.2.5
* Changed initilise -> Initialize
* Changed Ogre Exceptions with .Net Exceptions
* I ported the code very similar to the C++ code.
* I used the same event convention as in the old mogre osm loader.
* I used List<> for the created objects because the C++ code also use lists.
* Only one line not ported. mSceneMgr.SetOption("PrimaryCamera", primaryCamera.NativePtr); //unsafe
* The commented code was commented also in the C++ code and is code not used in the oFusion CE version.
* Added StandardisePath() because Mogre doesn´t have a wrapper to the Ogre::StringUtil class.
* */
using System;
using System.Collections.Generic;
using System.Xml;
using System.Globalization;
using Mogre;
namespace OFusion
{
public class OSMScene
{
//For culture independent code
private NumberFormatInfo numberFormat = new NumberFormatInfo();
private const int SceneSkyPlane = 1;
private const int SceneSkyBox = 2;
private const int SceneSkyDome = 3;
// Created objects
private List<Camera> mCameras = new List<Camera>();
private List<Light> mLights = new List<Light>();
private List<Entity> mEntities = new List<Entity>();
// Callback interface (Changed to Events)
public delegate void LoadedSceneObjectEventHandler(Object objectCreated, XmlElement xmlElement);
public event LoadedSceneObjectEventHandler OnCameraCreate;
public event LoadedSceneObjectEventHandler OnNodeCreate;
public event LoadedSceneObjectEventHandler OnLightCreate;
public event LoadedSceneObjectEventHandler OnEntityCreate;
//virtual void OnHelperCreated(Ogre::SceneNode* pHelper, XmlElement pHelperDesc) {};
//virtual void OnShapeLoaded(const Ogre::SimpleSpline& spline)
//virtual bool OnStaticGeometryCreated(Ogre::StaticGeometry* pStatic, const NodeList& nodeList)
// Scene manager
private SceneManager mSceneMgr;
private RenderWindow mWindow;
// Scene XML document
private XmlDocument mXMLDoc;
public OSMScene(SceneManager pSceneMgr, RenderWindow win)
{
numberFormat.CurrencyDecimalSeparator = ".";
mSceneMgr = pSceneMgr;
if (win != null)
mWindow = win;
else
mWindow = Mogre.Root.Singleton.AutoCreatedWindow;
}
// Init overloads - use either of them
public bool Initialize(string pszXMLFile)
{
//LogManager.Singleton.LogMessage("********************************");
//LogManager.Singleton.LogMessage("** oScene Loader Lib **");
//LogManager.Singleton.LogMessage("********************************");
string msg = "oSceneLoader: Loading '";
msg += pszXMLFile;
msg += "' file";
//LogManager.Singleton.LogMessage(msg);
// Create new XML document
mXMLDoc = new XmlDocument();
DataStreamPtr pStream = ResourceGroupManager.Singleton.OpenResource(pszXMLFile);
if (!(pStream.Size() > 0))
{
throw new System.IO.InvalidDataException("oSceneLoader: Empty scene file");
}
string pBuf = pStream.AsString;
pStream = null;
try
{
mXMLDoc.LoadXml(pBuf);
}
catch (XmlException ex)
{
mXMLDoc = null;
throw ex;
}
XmlElement locations = (XmlElement)mXMLDoc.DocumentElement.SelectSingleNode("locations");
if (locations != null)
{
FileInfoListPtr fileInfo = ResourceGroupManager.Singleton.FindResourceFileInfo(ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME, pszXMLFile);
string strPath = fileInfo[0].archive.Name;
strPath = StandardisePath(strPath); //In C++ StringUtil::standardisePath
foreach (XmlElement pLocationElem in locations.ChildNodes)
{
// Ogre could cast an exception, in which case we just try to
// continue reading the other location paths
try
{
string pszName = pLocationElem.GetAttribute("path");
string strDir = strPath + pszName;
ResourceGroupManager.Singleton.AddResourceLocation(strDir, "FileSystem");
}
catch
{
}
}
}
return true;
}
// Declare all resources used in the scene
public void DeclareResources()
{
if (mXMLDoc != null)
{
XmlElement rootElem = mXMLDoc.DocumentElement;
try
{
// Get mesh filename from entities
XmlElement pMeshNode = (XmlElement)rootElem.SelectSingleNode("entities");
if (pMeshNode != null)
{
// Iterate all meshes, creating them.
foreach (XmlElement pMeshElem in pMeshNode.ChildNodes)
{
//Verify the Element is an entity element.
if (pMeshElem.Name != "entity")
continue;
// Declare mesh resource
string pszFileName = pMeshElem.GetAttribute("filename");
ResourceGroupManager.Singleton.DeclareResource(pszFileName, "Mesh");
}
}
}
catch
{
}
}
}
// Create scene, optionally attaching it to a parent node
public bool CreateScene(SceneNode pParent)
{
if (mXMLDoc != null)
{
string msg = "oSceneLoader: Creating scene on '";
msg += pParent != null ? pParent.Name : "Root";
msg += "' node";
//LogManager.Singleton.LogMessage(msg);
bool bHandled = false;
XmlElement rootElem = mXMLDoc.DocumentElement;
if (mSceneMgr == null)
{
if (rootElem.SelectSingleNode("sceneManager") != null)
pParent = CreateSceneManager(rootElem, ref bHandled);
else
mSceneMgr = Root.Singleton.CreateSceneManager(SceneType.ST_GENERIC);
}
if (pParent == null)
pParent = mSceneMgr.RootSceneNode.CreateChildSceneNode();
System.Diagnostics.Debug.Assert(pParent != null);
XmlElement list;
try
{
// Entities
list = (XmlElement)rootElem.SelectSingleNode("entities");
if (list != null)
CreateEntities(list, pParent);
}
catch (Exception ex)
{
//LogManager.Singleton.LogMessage("Error while loading entities");
throw new Exception("oSceneLoader: Error while loading entities. " + ex.Message);
}
try
{
// lights
list = (XmlElement)rootElem.SelectSingleNode("lights");
if (list != null)
CreateLights(list, pParent);
}
catch (Exception ex)
{
//LogManager.Singleton.LogMessage("Error while loading lights");
throw new Exception("oSceneLoader: Error while loading lights. " + ex.Message);
}
if (!bHandled)
{
try
{
// cameras
list = (XmlElement)rootElem.SelectSingleNode("cameras");
if (list != null)
CreateCameras(list, pParent);
}
catch (Exception ex)
{
//LogManager.Singleton.LogMessage("Error while loading cameras");
throw new Exception("oSceneLoader: Error while loading cameras. " + ex.Message);
}
}
/*
try {
// helpers
list = rootElem.SelectSingleNode("helpers");
if(list)
createHelpers(list, pParent);
} catch(...)
{
LogManager.Singleton.LogMessage("Error while loading helpers");
OGRE_EXCEPT(Exception::ERR_RT_ASSERTION_FAILED,
"oSceneLoader: Error while loading helpers",
"OSMScene::createScene");
}
try {
// shapes
list = rootElem.SelectSingleNode("shapes");
if(list)
createShapes(list);
} catch(...)
{
LogManager.Singleton.LogMessage("Error while loading shapes");
OGRE_EXCEPT(Exception::ERR_RT_ASSERTION_FAILED,
"oSceneLoader: Error while loading shapes",
"OSMScene::createScene");
}
try {
// External skeletal animation files
list = rootElem.SelectSingleNode("skeletal_animations");
if(list)
{
SkeletonHandles skelHandles;
loadAnimations(list, skelHandles);
}
}catch(...)
{
LogManager.Singleton.LogMessage("Error while loading external animations");
OGRE_EXCEPT(Exception::ERR_RT_ASSERTION_FAILED,
"oSceneLoader: Error while loading external animations",
"OSMScene::createScene");
}
*/
// Set scene properties
SetSceneProperties(rootElem);
// Static Geometry
list = (XmlElement)rootElem.SelectSingleNode("staticGeometry");
if (list != null)
CreateStaticGeometry(list);
//LogManager.Singleton.LogMessage("********************************");
//LogManager.Singleton.LogMessage("** oSceneLoader: Scene loaded **");
//LogManager.Singleton.LogMessage("********************************");
return true;
}
return false;
}
// Get list of cameras in this scene
public List<Camera> CameraList
{
get { return mCameras; }
}
// Get list of lights in this scene
public List<Light> LightList
{
get { return mLights; }
}
// Get list of entities in this scene
public List<Entity> EntityList
{
get { return mEntities; }
}
public SceneManager SceneMgr
{
get { return mSceneMgr; }
}
private SceneNode CreateNode(XmlElement pElem, SceneNode pSceneRoot)
{
SceneNode pNode = null;
// Try to find the parent node
string pszName = pElem.GetAttribute("name");
if (pszName == string.Empty) return null;
// Check if this node has a parent
string pszParent = pElem.GetAttribute("parent");
if (pszParent == string.Empty)
{
// Check if the scene node has already been created by a child
//DisableLogManager();
try
{
pNode = mSceneMgr.GetSceneNode(pszName);
}
catch
{
pNode = pSceneRoot.CreateChildSceneNode(pszName);
}
//EnableLogManager();
}
else
{
SceneNode pParent = null;
DisableLogManager();
try
{
// Try to find parent scenenode
pParent = mSceneMgr.GetSceneNode(pszParent);
}
catch
{
// We try to create the parent node as child of root node.
// Later when the parent (hopefully) is created, we can adjust it,
// if it is child of another node.
pParent = pSceneRoot.CreateChildSceneNode(pszParent);
}
try
{
// Check if the scene node has already been created by a child
// In this case we would have to change the parent.
pNode = mSceneMgr.GetSceneNode(pszName);
// Get old parent (probably scene root)
SceneNode pOldParent = pNode.ParentSceneNode;
// Remove this node
pOldParent.RemoveChild(pNode);
// Insert us as child on the "real" parent
pParent.AddChild(pNode);
}
catch
{
pNode = pParent.CreateChildSceneNode(pszName);
}
EnableLogManager();
}
// Position
XmlElement posElem = (XmlElement)pElem.SelectSingleNode("position");
if (posElem != null)
{
Vector3 pos = new Vector3();
pos.x = float.Parse(posElem.GetAttribute("x"), numberFormat);
pos.y = float.Parse(posElem.GetAttribute("y"), numberFormat);
pos.z = float.Parse(posElem.GetAttribute("z"), numberFormat);
/*pos.x /= 100;
pos.y /= 100;
pos.z /= 100;*/
pNode.Position = pos;
}
// Rotation
XmlElement rotElem = (XmlElement)pElem.SelectSingleNode("rotation");
if (rotElem != null)
{
pNode.SetOrientation(
float.Parse(rotElem.GetAttribute("w"), numberFormat),
float.Parse(rotElem.GetAttribute("x"), numberFormat),
float.Parse(rotElem.GetAttribute("y"), numberFormat),
float.Parse(rotElem.GetAttribute("z"), numberFormat));
}
// Scale
XmlElement scaleElem = (XmlElement)pElem.SelectSingleNode("scale");
if (scaleElem != null)
{
Vector3 scale;
scale.x = float.Parse(scaleElem.GetAttribute("x"), numberFormat);
scale.y = float.Parse(scaleElem.GetAttribute("y"), numberFormat);
scale.z = float.Parse(scaleElem.GetAttribute("z"), numberFormat);
pNode.SetScale(scale);
}
// Notify
if (OnNodeCreate != null)
OnNodeCreate(pNode, pElem);
// Animation
XmlElement animList = (XmlElement)pElem.SelectSingleNode("animations");
if (animList != null)
{
//
foreach (XmlElement animElem in animList.ChildNodes)
{
if (animElem.Name != "animation")
continue;
// Get name of animation
string pszName1 = animElem.GetAttribute("name");
Animation pAnim = null;
DisableLogManager();
try
{
pAnim = mSceneMgr.GetAnimation(pszName1);
}
catch
{
}
EnableLogManager();
// If this animation has not been created yet, we create it
if (pAnim == null)
{
float fLength = float.Parse(animElem.GetAttribute("length"), numberFormat);
pAnim = mSceneMgr.CreateAnimation(pszName1, fLength);
pAnim.SetInterpolationMode(Animation.InterpolationMode.IM_LINEAR);
}
// Create animation track for this node
NodeAnimationTrack pTrack = pAnim.CreateNodeTrack((ushort)(pAnim.NumNodeTracks + 1), pNode);
// Iterate all keyframes for this node
foreach (XmlElement pKeyframeElem in animElem.ChildNodes)
{
if (pKeyframeElem.Name != "keyframe")
continue;
float fTime = float.Parse(pKeyframeElem.GetAttribute("time"), numberFormat);
TransformKeyFrame pKeyFrame = pTrack.CreateNodeKeyFrame(fTime);
// Position
XmlElement posElem1 = (XmlElement)pKeyframeElem.SelectSingleNode("position");
if (posElem1 != null)
{
Vector3 trans = new Vector3();
trans.x = float.Parse(posElem1.GetAttribute("x"), numberFormat);
trans.y = float.Parse(posElem1.GetAttribute("y"), numberFormat);
trans.z = float.Parse(posElem1.GetAttribute("z"), numberFormat);
pKeyFrame.Translate = trans;
}
// Rotation
XmlElement rotElem1 = (XmlElement)pKeyframeElem.SelectSingleNode("rotation");
if (rotElem1 != null)
{
Quaternion qRot = new Quaternion();
qRot.x = float.Parse(rotElem1.GetAttribute("x"), numberFormat);
qRot.y = float.Parse(rotElem1.GetAttribute("y"), numberFormat);
qRot.z = float.Parse(rotElem1.GetAttribute("z"), numberFormat);
qRot.w = float.Parse(rotElem1.GetAttribute("w"), numberFormat);
pKeyFrame.Rotation = qRot;
}
// Scale
XmlElement scaleElem1 = (XmlElement)pKeyframeElem.SelectSingleNode("scale");
if (scaleElem1 != null)
{
Vector3 scale = new Vector3();
scale.x = float.Parse(scaleElem1.GetAttribute("x"), numberFormat);
scale.y = float.Parse(scaleElem1.GetAttribute("y"), numberFormat);
scale.z = float.Parse(scaleElem1.GetAttribute("z"), numberFormat);
pKeyFrame.Scale = scale;
}
}
}
}
return pNode;
}
// Create SceneManager
private SceneNode CreateSceneManager(XmlElement sceneProp, ref bool bHandled)
{
System.Diagnostics.Debug.Assert(sceneProp != null);
// Scene manager
XmlElement sceneMgrElem = (XmlElement)sceneProp.SelectSingleNode("sceneManager");
int type = int.Parse(sceneMgrElem.GetAttribute("type"));
SceneType sceneType = (SceneType)(1 << (type - 1));
mSceneMgr = Mogre.Root.Singleton.CreateSceneManager(sceneType);
System.Diagnostics.Debug.Assert(mSceneMgr != null);
SceneNode pSceneRoot = mSceneMgr.RootSceneNode.CreateChildSceneNode();
System.Diagnostics.Debug.Assert(pSceneRoot != null);
// Scene shadows
XmlElement shadowsElem = (XmlElement)sceneProp.SelectSingleNode("shadowTechnique");
if (shadowsElem != null)
{
int type1 = int.Parse(shadowsElem.GetAttribute("type"));
ShadowTechnique shadowType = (ShadowTechnique)type1;
mSceneMgr.ShadowTechnique = shadowType;
ushort tex_size = ushort.Parse(shadowsElem.GetAttribute("tex_size"));
ushort tex_count = ushort.Parse(shadowsElem.GetAttribute("tex_count"));
mSceneMgr.SetShadowTextureSettings(tex_size, tex_count);
// Shadow Color
XmlElement colorElem = (XmlElement)shadowsElem.SelectSingleNode("color");
if (colorElem != null)
{
ColourValue color = new ColourValue();
color.r = float.Parse(colorElem.GetAttribute("r"), numberFormat);
color.g = float.Parse(colorElem.GetAttribute("g"), numberFormat);
color.b = float.Parse(colorElem.GetAttribute("b"), numberFormat);
mSceneMgr.ShadowColour = color;
}
}
// Scene fog
XmlElement fogElem = (XmlElement)sceneProp.SelectSingleNode("fogMode");
if (fogElem != null)
{
int type2 = int.Parse(fogElem.GetAttribute("type"));
FogMode mode = (FogMode)type2;
float density = float.Parse(fogElem.GetAttribute("density"), numberFormat);
float linearStart = float.Parse(fogElem.GetAttribute("linearStart"), numberFormat);
float linearEnd = float.Parse(fogElem.GetAttribute("linearEnd"), numberFormat);
ColourValue color = new ColourValue();
// Fog Color
XmlElement colorElem = (XmlElement)fogElem.SelectSingleNode("color");
if (colorElem != null)
{
color.r = float.Parse(colorElem.GetAttribute("r"), numberFormat);
color.g = float.Parse(colorElem.GetAttribute("g"), numberFormat);
color.b = float.Parse(colorElem.GetAttribute("b"), numberFormat);
}
mSceneMgr.SetFog(mode, color, density, linearStart, linearEnd);
}
// World Geometry
string worldGeometry = sceneMgrElem.GetAttribute("worldGeometry");
if (worldGeometry != string.Empty)
{
// Some scene managers need cameras created before the world geometry
try
{
// cameras
XmlElement list = (XmlElement)sceneProp.SelectSingleNode("cameras");
if (list != null)
CreateCameras(list, pSceneRoot);
if (sceneType == SceneType.ST_EXTERIOR_CLOSE)
{
if (mCameras.Count == 0)
{
throw new System.InvalidOperationException("oSceneLoader: Scene dont contain cameras, Terrain Scene Manager needs a camera to initialize");
}
Camera primaryCamera = mCameras[0];
mWindow.GetViewport(0).Camera = primaryCamera;
//mSceneMgr.SetOption("PrimaryCamera", primaryCamera.NativePtr); //unsafe
}
// cameras created, the main scene loader method should not re-parse the list
bHandled = true;
}
catch
{
}
mSceneMgr.SetWorldGeometry(worldGeometry);
}
return pSceneRoot;
}
// Set Scene Properties
private void SetSceneProperties(XmlElement sceneProp)
{
// Ambient light Color
XmlElement colorElem = (XmlElement)sceneProp.SelectSingleNode("lightColor");
if (colorElem != null)
{
ColourValue color = new ColourValue();
color.r = float.Parse(colorElem.GetAttribute("r"), numberFormat);
color.g = float.Parse(colorElem.GetAttribute("g"), numberFormat);
color.b = float.Parse(colorElem.GetAttribute("b"), numberFormat);
mSceneMgr.AmbientLight = color;
}
// Background Color
colorElem = (XmlElement)sceneProp.SelectSingleNode("bkgcolor");
if (colorElem != null && mWindow != null)
{
int numViewports = mWindow.NumViewports;
if (numViewports > 0)
{
ColourValue color = new ColourValue();
color.r = float.Parse(colorElem.GetAttribute("r"), numberFormat);
color.g = float.Parse(colorElem.GetAttribute("g"), numberFormat);
color.b = float.Parse(colorElem.GetAttribute("b"), numberFormat);
for (ushort i = 0; i < numViewports; ++i)
mWindow.GetViewport(i).BackgroundColour = color;
}
}
// Scene sky
XmlElement skyElem = (XmlElement)sceneProp.SelectSingleNode("skyTechnique");
if (skyElem != null)
{
int type = int.Parse(skyElem.GetAttribute("type"));
string materialName = skyElem.GetAttribute("material");
if (materialName != " ")
{
string drawFirstAttribute = skyElem.GetAttribute("drawFirst");
bool drawFirst = drawFirstAttribute == "yes";
float tiling = float.Parse(skyElem.GetAttribute("tiling"), numberFormat);
float scale = float.Parse(skyElem.GetAttribute("scale"), numberFormat);
float dist = float.Parse(skyElem.GetAttribute("dist"), numberFormat);
float bow = float.Parse(skyElem.GetAttribute("bow"), numberFormat);
int xSegments = int.Parse(skyElem.GetAttribute("xSegments"));
int ySegments = int.Parse(skyElem.GetAttribute("ySegments"));
Quaternion quat = Quaternion.IDENTITY;
Plane plane = new Plane();
plane.d = dist;
plane.normal = -(Vector3.UNIT_Y);
switch (type)
{
case SceneSkyPlane:
mSceneMgr.SetSkyPlane(true, plane, materialName, scale,
tiling, drawFirst, bow, xSegments, ySegments);
mSceneMgr.SetSkyBox(false, "");
mSceneMgr.SetSkyDome(false, "");
break;
case SceneSkyBox:
mSceneMgr.SetSkyBox(true, materialName, dist, drawFirst, quat);
mSceneMgr.SetSkyPlane(false, plane, "");
mSceneMgr.SetSkyDome(false, "");
break;
case SceneSkyDome:
mSceneMgr.SetSkyDome(true, materialName, bow, tiling, dist,
drawFirst, quat, xSegments, ySegments);
mSceneMgr.SetSkyPlane(false, plane, "");
mSceneMgr.SetSkyBox(false, "");
break;
}
}
}
}
// Create all entities in scene
private void CreateEntities(XmlElement pEntityNode, SceneNode pSceneRoot)
{
// Iterate all meshes, creating them.
foreach (XmlElement pMeshElem in pEntityNode.ChildNodes)
{
if (pMeshElem.Name != "entity")
continue;
// Ogre could cast an exception, in which case we just try to
// continue reading the other meshes
try
{
string pszName = pMeshElem.GetAttribute("name");
string pszFileName = pMeshElem.GetAttribute("filename");
// try to create the mesh
Entity pEntity = mSceneMgr.CreateEntity(pszName, pszFileName);
if (pEntity == null) continue;
// Check if the object should cast shadows
string pszCastShadows = pMeshElem.GetAttribute("CastShadows");
if (pszCastShadows == "no")
pEntity.CastShadows = false;
else
pEntity.CastShadows = true;
// Create node with full information
SceneNode pObjNode = CreateNode(pMeshElem, pSceneRoot);
// Attach the mesh entity to node
pObjNode.AttachObject(pEntity);
// Notify
if (OnEntityCreate != null)
OnEntityCreate(pEntity, pMeshElem);
// Add to entity list
mEntities.Add(pEntity);
}
catch
{
continue;
}
}
}
// Create all Lights in scene
private void CreateLights(XmlElement pLightNode, SceneNode pSceneRoot)
{
// Iterate all Lights, creating them. We do not attach them yet, since
// we need to make sure all potential parent entities have been created.
foreach (XmlElement pLightElem in pLightNode.ChildNodes)
{
if (pLightElem.Name != "light")
continue;
// Ogre could cast an exception, in which case we just try to
// continue reading the other Lights
try
{
string pszName = pLightElem.GetAttribute("name");
Light pLight = mSceneMgr.CreateLight(pszName);
if (pLight == null) continue;
// Figure out which type of light we are using
string pszType = pLightElem.GetAttribute("type");
if (pszType == "omni")
{
pLight.Type = Light.LightTypes.LT_POINT;
}
else if (pszType == "spot")
{
pLight.Type = Light.LightTypes.LT_SPOTLIGHT;
pLight.SetSpotlightRange(
new Radian(new Degree(float.Parse(pLightElem.GetAttribute("hotspot"), numberFormat))),
new Radian(new Degree(float.Parse(pLightElem.GetAttribute("falloff"), numberFormat))));
pLight.SetDirection(0f, 0f, -1f);
}
else if (pszType == "directional")
{
pLight.Type = Light.LightTypes.LT_DIRECTIONAL;
}
// Check if the light should be on
string pszOn = pLightElem.GetAttribute("on");
if (pszOn == "true")
pLight.Visible = true;
else
pLight.Visible = false;
// Check if the object should cast shadows
string pszCastShadows = pLightElem.GetAttribute("CastShadows");
if (pszCastShadows == "no")
pLight.CastShadows = false;
else
pLight.CastShadows = true;
// Diffuse Color
XmlElement colorElem = (XmlElement)pLightElem.SelectSingleNode("color");
if (colorElem != null)
{
pLight.DiffuseColour = new ColourValue(
float.Parse(colorElem.GetAttribute("r"), numberFormat),
float.Parse(colorElem.GetAttribute("g"), numberFormat),
float.Parse(colorElem.GetAttribute("b"), numberFormat));
}
// Specular Color
XmlElement specularElem = (XmlElement)pLightElem.SelectSingleNode("specular");
if (specularElem != null)
{
pLight.SpecularColour = new ColourValue(
float.Parse(specularElem.GetAttribute("r"), numberFormat),
float.Parse(specularElem.GetAttribute("g"), numberFormat),
float.Parse(specularElem.GetAttribute("b"), numberFormat));
}
// Attenuation
XmlElement attenElem = (XmlElement)pLightElem.SelectSingleNode("attenuation");
if (attenElem != null)
{
pLight.SetAttenuation(
float.Parse(attenElem.GetAttribute("range"), numberFormat),
float.Parse(attenElem.GetAttribute("constant"), numberFormat),
float.Parse(attenElem.GetAttribute("linear"), numberFormat),
float.Parse(attenElem.GetAttribute("quadratic"), numberFormat));
}
// Create node with full information
SceneNode pLightNode1 = CreateNode(pLightElem, pSceneRoot);
// Attach the Light entity to node
pLightNode1.AttachObject(pLight);
// Target
XmlElement targetElem = (XmlElement)pLightElem.SelectSingleNode("target");
if (targetElem != null)
{
// Create node with full information
SceneNode pTargetNode = CreateNode(targetElem, pSceneRoot);
pLightNode1.SetAutoTracking(true, pTargetNode);
}
// Notify
if (OnLightCreate != null)
OnLightCreate(pLight, pLightElem);
// Add to light list
mLights.Add(pLight);
}
catch
{
continue;
}
}
}
// Create all Cameras in scene
private void CreateCameras(XmlElement pCameraNode, SceneNode pSceneRoot)
{
// Iterate all Cameras, creating them. We do not attach them yet, since
// we need to make sure all potential parent entities have been created.
foreach (XmlElement pCameraElem in pCameraNode.ChildNodes)
{
if (pCameraElem.Name != "camera")
continue;
// Ogre could cast an exception, in which case we just try to
// continue reading the other Cameras
try
{
string pszName = pCameraElem.GetAttribute("name");
// Create camera
Camera pCamera = mSceneMgr.CreateCamera(pszName);
if (pCamera == null) continue;
// Set Field of View on camera
pCamera.FOVy = new Radian(float.Parse(pCameraElem.GetAttribute("FOV"), numberFormat));
pCamera.NearClipDistance = 5f;
// Create node with full information
SceneNode pCameraNode1 = CreateNode(pCameraElem, pSceneRoot);
// Attach the Camera entity to node
pCameraNode1.AttachObject(pCamera);
// Target
XmlElement targetElem = (XmlElement)pCameraElem.SelectSingleNode("target");
if (targetElem != null)
{
// Create node with full information
SceneNode pTargetNode = CreateNode(targetElem, pSceneRoot);
pCameraNode1.SetAutoTracking(true, pTargetNode);
}
if (mWindow == null)
{
throw new InvalidOperationException("oSceneLoader: RenderWindow not valid, If the RenderWindow was not auto created you must add it in the OSMScene object contructor");
}
// If viewport(s) are not present, create a default viewport
if (mWindow.NumViewports == 0)
{
Viewport vp = mWindow.AddViewport(pCamera);
// Alter the camera aspect ratio to match the viewport
pCamera.AspectRatio = (float)vp.ActualWidth / (float)vp.ActualHeight;
}
// Notify
if (OnCameraCreate != null)
OnCameraCreate(pCamera, pCameraElem);
// Add to camera list
mCameras.Add(pCamera);
}
catch
{
continue;
}
}
}
// For CE version, helpers, shapes, static geometry
// and external skeleton animation support is not provided
private void CreateHelpers(XmlElement pHelperNode, SceneNode pSceneRoot)
{
}
private void CreateShapes(XmlElement pShapeNode)
{
}
private void CreateStaticGeometry(XmlElement pStaticGeom)
{
}
//void LoadAnimations(XmlElement animationsNode, SkeletonHandles& handles) {
// Iterate all skeletons, adding animations from ".anim" files
//}
private void EnableLogManager()
{
LogManager.Singleton.SetLogDetail(LoggingLevel.LL_NORMAL);
}
private void DisableLogManager()
{
LogManager.Singleton.SetLogDetail(LoggingLevel.LL_LOW);
}
//This method is used because Mogre doesn´t have a wrapper for the Ogre::StringUtil class
//It was ported from the c++ source of Ogre.
private string StandardisePath(string init)
{
string path = init;
path = path.Replace('\\', '/');
if (path[path.Length - 1] != '/')
path += '/';
return path;
}
}
//OSMAnimSerializer::OSMAnimSerializer() {
//}
//void OSMAnimSerializer::addAnimation(Ogre::SkeletonPtr skel, const Ogre::String& filename) {
}{CODE}
---
Alias: (alias(clOgre))