MOGRE OSMSceneLoader 2        

A port of the oFusion Scene Loader CE (Community Edition) ported by Ernesto Gutiérrez (smernesto).

Ported from the oScene loader library source code released in July 28, 2006 by OFusion.
If you have some questions, want to add something or you have some bug fixes please post at this Mogre forum topic

Some people says that this loaders works better that the another port MOGRE OSMSceneLoader in the wiki.

Note: The empty catch blocks were originally empty also in the C++ code. The original author use this for test if some entities, lights etc. already are in the scene.

/**********************************************************************
 *<
    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);
                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) {

}