Ported July/2006 oScene loader library

smernesto

29-01-2007 00:15:08

Hi.

I ported the last version of the oScene loader library source code released in July 28, 2006.

The old Mogre osm loader has some bugs and lack support for the archive section and it was based in a loader version before July.

I ported it making it very very similar to the C++ code.

I want that people using oFusion give it a try to this loader and test it before I upload it to the wiki.

This code is not based int the old loader, I ported it from the originally loader in C++, but for convenience I used the same events names that the old used, The name of the class is OSMScene as in the C++ code.

I didn´t use HashTables for the created objets I used List<> as in the c++ code, but if all of you want hashtables I will change it.

One line was not ported: mSceneMgr.SetOption("PrimaryCamera", primaryCamera);. Because SetOption wants a void* pointer, if you have a solution for this without using unsafe code post it here.

Please test shadows, lights, entities, cameras, scene node animations, archives, skybox, ambient light loaded from the osm file.

Post your comments about this code please.


/**********************************************************************
*<
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):
* 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.
* */

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);
//?Tengo Dudas aca
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) {


}

ncazanav

02-02-2007 22:08:10

Hi,

I haven't tested much your port of the OSM loader yet, but i hope to post more interesting comments in the future.

Just a remark for the moment about your transcription of the Initialize method. The line

string pBuf = pStream.AsString;

returns a string beginning with strange characters (namely "<oe_scene>....." instead of simply "<oe_scene>....." and so the code throw an error the line after.

I changed the loading of the XMLFile by simply calling mXMLDoc.Load(pszXMLFile); instead of mXMLDoc.LoadXml(pBuf); and i was wondering if this was due to a bug from the DataStreamPtr object or the Resource Group Manager?

smernesto

03-02-2007 00:16:16

Hi.

MM, I don´t know why are you getting those characters, I tried the code with various scenes and I didn´t get strange characters.

The C++ loader code use: pStream->read(pBuf, iSize);
But this code use a pointer in C# also, then I used .AsString property.

If you use the mXMLDoc.Load() method you will not load the osm escene through the Resource Manager, but directly.

Can you provide me the scene that throws that exception, or it is with all scenes?. Are you modifying the scene file manually?

ncazanav

04-02-2007 09:41:11

Hi,

Ok I've understood the origin of the problem : it was due to the coding of the OSM file : i was using UTF-8 coding, instead of ANSI coding, and this leads to strange characters when doing
string pBuf = pStream.AsString;

This little issue aside, everything seems to be ok

Thx

feanor91

16-07-2008 13:20:16

Hello

I begin to use OGRE and MOGRE, and I have tested all the solution to load scene in VB.net.

I try with OgreMax, but did'nt find any loader to work with, so I found your loader for oFusion, I donwload it, and export my scene from Max. I installed Visual C# to build a dll with your OSM loader. Apparently it works, I have created a project based on mogre tutorial 2 on wiki to try to load a scene and it did not work. I get a message about ogre exeception file not found, it did'nt found my osm file, if I understand well...the error occured at OgreResourceGroupManager.cpp line 604 ....

here my code :

Try


'Initialization of Ogre Root and RenderWindow
Dim myRoot As Root = New Root("Plugins.cfg", "ogre.cfg", "ogre.log")
Dim mySceneManager As SceneManager = myRoot.CreateSceneManager(SceneType.ST_GENERIC)

'Show Ogre Rendering Subsystem setup dialog box
If Not myRoot.RestoreConfig Then
If Not myRoot.ShowConfigDialog Then
Exit Sub
End If
End If

'Create an Ogre render window
Dim myWindow As RenderWindow = myRoot.Initialise(True, "Application")

'Loading of OSM scene

Dim Scene As OSMScene = New OSMScene(mySceneManager, myWindow)
Scene.Initialize("c:\OgreSDK\media\Scene\Gymnase.osm")
Scene.CreateScene(mySceneManager.RootSceneNode)

'Start rendering
myRoot.StartRendering()

Catch ex As System.Runtime.InteropServices.SEHException
If OgreException.IsThrown Then
MsgBox(OgreException.LastException.FullDescription, MsgBoxStyle.Critical, _
"An Ogre exception has occured!")
Else
MsgBox(ex.ToString, "An error has occured")
End If
End Try


I did not understand. I put file path in ressource.cfg but it does'nt work too....Someone can help me?

Thanks.

feanor91

16-07-2008 13:59:58

So, I found why it didn't load my scene, it's because I doesn't init ressource manager...What a shame....But now, my application crash without any message....In max if I try to go to oFusion viewport, max crash too. I think things are linked....

I try to buil a little scene with only a box, a sphere, a cam and a spot, under max it work in ofusion viewport, under my appli, it loads....so hopeness is always living....I just have to found why oFusion viewport crash on my scenes.

Here, al little exerpt from ogrelog :


14:59:00: Mesh: Loading PignoHaut2.mesh.
14:59:00: WARNING: PignoHaut2.mesh is an older format ([MeshSerializer_v1.30]); you should upgrade it as soon as possible using the OgreMeshUpgrade tool.
14:59:00: OGRE EXCEPTION(5:ItemIdentityException): SceneNode 'PignoHaut2' not found. in SceneManager::getSceneNode at ..\src\OgreSceneManager.cpp (line 784)
14:59:00: Mesh: Loading MurEntree3.mesh.
14:59:00: WARNING: MurEntree3.mesh is an older format ([MeshSerializer_v1.30]); you should upgrade it as soon as possible using the OgreMeshUpgrade tool.
14:59:00: OGRE EXCEPTION(5:ItemIdentityException): SceneNode 'MurEntree3' not found. in SceneManager::getSceneNode at ..\src\OgreSceneManager.cpp (line 784)
14:59:00: Mesh: Loading MurEntree1.mesh.
14:59:00: WARNING: MurEntree1.mesh is an older format ([MeshSerializer_v1.30]); you should upgrade it as soon as possible using the OgreMeshUpgrade tool.
14:59:00: OGRE EXCEPTION(5:ItemIdentityException): SceneNode 'MurEntree1' not found. in SceneManager::getSceneNode at ..\src\OgreSceneManager.cpp (line 784)
14:59:00: Mesh: Loading ToitEntree.mesh.
14:59:00: WARNING: ToitEntree.mesh is an older format ([MeshSerializer_v1.30]); you should upgrade it as soon as possible using the OgreMeshUpgrade tool.
14:59:00: OGRE EXCEPTION(5:ItemIdentityException): SceneNode 'ToitEntree' not found. in SceneManager::getSceneNode at ..\src\OgreSceneManager.cpp (line 784)
14:59:00: Mesh: Loading Box25.mesh.
14:59:00: WARNING: Box25.mesh is an older format ([MeshSerializer_v1.30]); you should upgrade it as soon as possible using the OgreMeshUpgrade tool.
14:59:00: OGRE EXCEPTION(5:ItemIdentityException): SceneNode 'Box25' not found. in SceneManager::getSceneNode at ..\src\OgreSceneManager.cpp (line 784)
14:59:00: Mesh: Loading Box117.mesh.
14:59:00: WARNING: Box117.mesh is an older format ([MeshSerializer_v1.30]); you should upgrade it as soon as possible using the OgreMeshUpgrade tool.
14:59:00: OGRE EXCEPTION(5:ItemIdentityException): SceneNode 'Box117' not found. in SceneManager::getSceneNode at ..\src\OgreSceneManager.cpp (line 784)
14:59:00: Mesh: Loading Box116.mesh.
14:59:00: WARNING: Box116.mesh is an older format ([MeshSerializer_v1.30]); you should upgrade it as soon as possible using the OgreMeshUpgrade tool.
14:59:00: OGRE EXCEPTION(5:ItemIdentityException): SceneNode 'Box116' not found. in SceneManager::getSceneNode at ..\src\OgreSceneManager.cpp (line 784)
14:59:00: Mesh: Loading Box115.mesh.
14:59:00: WARNING: Box115.mesh is an older format ([MeshSerializer_v1.30]); you should upgrade it as soon as possible using the OgreMeshUpgrade tool.
14:59:00: OGRE EXCEPTION(5:ItemIdentityException): SceneNode 'Box115' not found. in SceneManager::getSceneNode at ..\src\OgreSceneManager.cpp (line 784)
14:59:00: Mesh: Loading Box114.mesh.
14:59:00: WARNING: Box114.mesh is an older format ([MeshSerializer_v1.30]); you should upgrade it as soon as possible using the OgreMeshUpgrade tool.
14:59:00: OGRE EXCEPTION(5:ItemIdentityException): SceneNode 'Box114' not found. in SceneManager::getSceneNode at ..\src\OgreSceneManager.cpp (line 784)
14:59:00: Mesh: Loading PignonHaut1.mesh.
14:59:00: WARNING: PignonHaut1.mesh is an older format ([MeshSerializer_v1.30]); you should upgrade it as soon as possible using the OgreMeshUpgrade tool.
14:59:00: OGRE EXCEPTION(5:ItemIdentityException): SceneNode 'PignonHaut1' not found. in SceneManager::getSceneNode at ..\src\OgreSceneManager.cpp (line 784)