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) {

}

<HR>
Creative Commons Copyright -- Some rights reserved.


THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.

BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.

1. Definitions

  • "Collective Work" means a work, such as a periodical issue, anthology or encyclopedia, in which the Work in its entirety in unmodified form, along with a number of other contributions, constituting separate and independent works in themselves, are assembled into a collective whole. A work that constitutes a Collective Work will not be considered a Derivative Work (as defined below) for the purposes of this License.
  • "Derivative Work" means a work based upon the Work or upon the Work and other pre-existing works, such as a translation, musical arrangement, dramatization, fictionalization, motion picture version, sound recording, art reproduction, abridgment, condensation, or any other form in which the Work may be recast, transformed, or adapted, except that a work that constitutes a Collective Work will not be considered a Derivative Work for the purpose of this License. For the avoidance of doubt, where the Work is a musical composition or sound recording, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered a Derivative Work for the purpose of this License.
  • "Licensor" means the individual or entity that offers the Work under the terms of this License.
  • "Original Author" means the individual or entity who created the Work.
  • "Work" means the copyrightable work of authorship offered under the terms of this License.
  • "You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation.
  • "License Elements" means the following high-level license attributes as selected by Licensor and indicated in the title of this License: Attribution, ShareAlike.

2. Fair Use Rights

Nothing in this license is intended to reduce, limit, or restrict any rights arising from fair use, first sale or other limitations on the exclusive rights of the copyright owner under copyright law or other applicable laws.

3. License Grant

Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below:

  • to reproduce the Work, to incorporate the Work into one or more Collective Works, and to reproduce the Work as incorporated in the Collective Works;
  • to create and reproduce Derivative Works;
  • to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission the Work including as incorporated in Collective Works;
  • to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission Derivative Works.
  • For the avoidance of doubt, where the work is a musical composition:
    • Performance Royalties Under Blanket Licenses. Licensor waives the exclusive right to collect, whether individually or via a performance rights society (e.g. ASCAP, BMI, SESAC), royalties for the public performance or public digital performance (e.g. webcast) of the Work.
    • Mechanical Rights and Statutory Royalties. Licensor waives the exclusive right to collect, whether individually or via a music rights society or designated agent (e.g. Harry Fox Agency), royalties for any phonorecord You create from the Work ("cover version") and distribute, subject to the compulsory license created by 17 USC Section 115 of the US Copyright Act (or the equivalent in other jurisdictions).
    • Webcasting Rights and Statutory Royalties. For the avoidance of doubt, where the Work is a sound recording, Licensor waives the exclusive right to collect, whether individually or via a performance-rights society (e.g. SoundExchange), royalties for the public digital performance (e.g. webcast) of the Work, subject to the compulsory license created by 17 USC Section 114 of the US Copyright Act (or the equivalent in other jurisdictions).


The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. All rights not expressly granted by Licensor are hereby reserved.

4. Restrictions

The license granted in Section 3 above is expressly made subject to and limited by the following restrictions:

  • You may distribute, publicly display, publicly perform, or publicly digitally perform the Work only under the terms of this License, and You must include a copy of, or the Uniform Resource Identifier for, this License with every copy or phonorecord of the Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Work that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute, publicly display, publicly perform, or publicly digitally perform the Work with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License Agreement. The above applies to the Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Work itself to be made subject to the terms of this License. If You create a Collective Work, upon notice from any Licensor You must, to the extent practicable, remove from the Collective Work any credit as required by clause 4(c), as requested. If You create a Derivative Work, upon notice from any Licensor You must, to the extent practicable, remove from the Derivative Work any credit as required by clause 4(c), as requested.
  • You may distribute, publicly display, publicly perform, or publicly digitally perform a Derivative Work only under the terms of this License, a later version of this License with the same License Elements as this License, or a Creative Commons iCommons license that contains the same License Elements as this License (e.g. Attribution-ShareAlike 2.5 Japan). You must include a copy of, or the Uniform Resource Identifier for, this License or other license specified in the previous sentence with every copy or phonorecord of each Derivative Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Derivative Works that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder, and You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute, publicly display, publicly perform, or publicly digitally perform the Derivative Work with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License Agreement. The above applies to the Derivative Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Derivative Work itself to be made subject to the terms of this License.
  • If you distribute, publicly display, publicly perform, or publicly digitally perform the Work or any Derivative Works or Collective Works, You must keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or (ii) if the Original Author and/or Licensor designate another party or parties (e.g. a sponsor institute, publishing entity, journal) for attribution in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; the title of the Work if supplied; to the extent reasonably practicable, the Uniform Resource Identifier, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and in the case of a Derivative Work, a credit identifying the use of the Work in the Derivative Work (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). Such credit may be implemented in any reasonable manner; provided, however, that in the case of a Derivative Work or Collective Work, at a minimum such credit will appear where any other comparable authorship credit appears and in a manner at least as prominent as such other comparable authorship credit.

5. Representations, Warranties and Disclaimer

UNLESS OTHERWISE AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE MATERIALS, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.

6. Limitation on Liability.

EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

7. Termination

  • This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Derivative Works or Collective Works from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License.
  • Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above.

8. Miscellaneous

  • Each time You distribute or publicly digitally perform the Work or a Collective Work, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License.
  • Each time You distribute or publicly digitally perform a Derivative Work, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License.
  • If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
  • No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent.
  • This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You.