Exemple #1
0
Dragon::Dragon(Ogre::SceneManager* scene_manager, Ogre::SceneNode* parent_node)
	: CollidableObject(parent_node)
{
	//Set up our OGRE scene objects
	Ogre::String num_str = Ogre::StringConverter::toString(parent_node->numChildren());
	Ogre::String node_name = "DragonNode"+num_str;
	mEntity = scene_manager->createEntity("Dragon"+num_str, "Dragon.mesh");
	mSceneNode->attachObject(mEntity);
	mParticleSystem = scene_manager->createParticleSystem("DragonFire"+num_str, "SlayADragon/Fire");
	mParticleNode = mSceneNode->createChildSceneNode("DragonParticleNode"+num_str);
	mParticleNode->attachObject(mParticleSystem);
	mParticleEmitter = (Ogre::PointEmitter*)mParticleSystem->getEmitter(0);
	mParticleEmitter->setDuration(0.5f);
	mParticleEmitter->setEnabled(false);
	//Set up our "pop" animation variables
	mPopHeight = 1.0f;
	mPopSpeed = 3.0f; //World units per second
	mStartHeight = mSceneNode->getPosition().y;
	mTimeWaiting = 0.0f;
	mMaxFireWaitTime = 1.5f;
	mMaxWaitTime = mMaxFireWaitTime + 0.5f;
	//Set up general object state variables
	mDidBreathFire = false;
	isPopping = false;
	//This is an easy way to dynamicaly get an approx. for the dragon mesh's dimensions
	scene_manager->_updateSceneGraph(scene_manager->getCamera("PlayerCam")); //Necessary to get an accurate AABB
	Ogre::AxisAlignedBox boundBox = mSceneNode->_getWorldAABB();
	//Set up our mesh-size dependent variables
	mParticleNode->translate(0.0f,  boundBox.getSize().y * 0.6f, 0.0f);
	SetCollideShapeBox(boundBox.getSize().x, boundBox.getSize().y, boundBox.getSize().z * 0.8f);
	geomOffset = Ogre::Vector3(0.0f, boundBox.getSize().y / 2.0f, 0.0f);
	SetCanCollide(false);
}
void AIRayPathFinderStrategy::Init()
{
	AIPathFinderStrategy::Init();
	//if (Inited)
	//	return;
	Inited=true;
	if (Lines)
		delete [] Lines;
	
	Lines = new Ogre::Ray[LinesNumber];

    IScenable *scen = Parent->GetScenable();
    assert(scen);

	Ogre::AxisAlignedBox OurBox = scen->GetBoundingBox(false);
	Vector3 extent = OurBox.getSize();
	float HalfSide = extent.z/2, Side=HalfSide*2;

	LineOrigins[0]=Vector3(-HalfSide,-HalfSide,0);
	LineOrigins[1]=Vector3(-HalfSide,HalfSide,0);
	LineOrigins[2]=Vector3(HalfSide,HalfSide,0);
	LineOrigins[3]=Vector3(HalfSide,-HalfSide,0);

	LineOrigins[4]=Vector3(0,-HalfSide,0);
	LineOrigins[5]=Vector3(-HalfSide,0,0);
	LineOrigins[6]=Vector3(0,HalfSide,0);
	LineOrigins[7]=Vector3(HalfSide,0,0);
}
Exemple #3
0
	void RenderBoxScene::updateViewport()
	{
		// пр?нуле вылетает
		if ((mCanvas->getWidth() <= 1) || (mCanvas->getHeight() <= 1))
			return;

		if ((nullptr != mEntity) && (nullptr != mCamera))
		{
			// не ¤сн? нужн?ли раст¤гивать камеру, установленну?юзером
			mCamera->setAspectRatio((float)mCanvas->getWidth() / (float)mCanvas->getHeight());

			// вычисл¤ем рассто¤ни? чтоб?бы?виде?весь объект
			Ogre::AxisAlignedBox box;

			box.merge(mEntity->getBoundingBox().getMinimum() + mEntity->getParentSceneNode()->_getDerivedPosition());
			box.merge(mEntity->getBoundingBox().getMaximum() + mEntity->getParentSceneNode()->_getDerivedPosition());

			if (box.isNull()) return;

			Ogre::Vector3 vec = box.getSize();

			float width = sqrt(vec.x*vec.x + vec.z*vec.z); // само?длинно?- диагонал?(если крутит?модель)
			float len2 = width / mCamera->getAspectRatio();
			float height = vec.y;
			float len1 = height;
			if (len1 < len2) len1 = len2;
			len1 /= 0.86; // [sqrt(3)/2] for 60 degrees field of view
			// цент?объект?по вертикал?+ отъехать та? чтоб?влезла ближ?¤ гран?BoundingBox'?+ чуть ввер??ещ?наза?дл¤ красот?
			Ogre::Vector3 result = box.getCenter() + Ogre::Vector3(0, 0, vec.z/2 + len1) + Ogre::Vector3(0, height*0.1, len1*0.2);
			Ogre::Vector3 look = Ogre::Vector3(0, box.getCenter().y /*+ box.getCenter().y * (1-mCurrentScale)*/, 0);

			mCameraNode->setPosition(result);
			mCameraNode->lookAt(look, Ogre::Node::TS_WORLD);
		}
	}
Exemple #4
0
QVector3D EC_Mesh::GetWorldSize() const
{
    QVector3D size(0,0,0);
    if (!entity_ || !adjustment_node_ || !placeable_)
        return size;

    // Get mesh bounds and scale it to the scene node
    EC_Placeable* placeable = checked_static_cast<EC_Placeable*>(placeable_.get());
    Ogre::AxisAlignedBox bbox = entity_->getMesh()->getBounds();
    bbox.scale(adjustment_node_->getScale());

    // Get size and take placeable scale into consideration to get real naali inworld size
    const Ogre::Vector3& bbsize = bbox.getSize();
    const Vector3df &placeable_scale = placeable->GetScale();
    // Swap y and z to make it align with other naali vectors
    size = QVector3D(bbsize.x*placeable_scale.x, bbsize.z*placeable_scale.z, bbsize.y*placeable_scale.y);
    return size;
}
Exemple #5
0
QVector3D EC_Mesh::GetWorldSize() const
{
    QVector3D size(0,0,0);
    if (!entity_ || !adjustment_node_ || !placeable_)
        return size;

    // Get mesh bounds and scale it to the scene node
    EC_Placeable* placeable = checked_static_cast<EC_Placeable*>(placeable_.get());
    Ogre::AxisAlignedBox bbox = entity_->getMesh()->getBounds();
    ///\bug Rewrite this code to properly take the world transform into account. -jj.
    bbox.scale(adjustment_node_->getScale());

    // Get size and take placeable scale into consideration to get real in-world size
    const Ogre::Vector3& bbsize = bbox.getSize();
    const float3 &placeable_scale = placeable->WorldScale();
    // Swap y and z to make it align with other vectors
    size = QVector3D(bbsize.x*placeable_scale.x, bbsize.y*placeable_scale.y, bbsize.z*placeable_scale.z);
    return size;
}
Exemple #6
0
	bool CSphereModel::load(){
		
		try{
		
			_entity = _scene->getSceneMgr()->createEntity(_name,Ogre::SceneManager::PrefabType::PT_SPHERE);

		}catch(std::exception e)
		{
			return false;
		}
		
		
		Ogre::AxisAlignedBox auxBBox = _entity->getBoundingBox();

		_entityNode = _scene->getSceneMgr()->getRootSceneNode()->
								createChildSceneNode(_name + "_node");

		_entityNode->attachObject(_entity);
		

		//Añadir el material
		_entity->setMaterialName(_material);

		//Reescalar el prefab 
		Ogre::Node *node = _entity->getParentNode();

		Vector3 vector = auxBBox.getSize();



		_entityNode->scale(_radio / vector.x * 2,
			_radio / vector.y * 2,
			_radio / vector.z * 2);

		//Modificar la posición

		this->setPosition(_position);

		_loaded = true;

		return _loaded;
	}
	bool CPlaneModel::load(){
		
		try{
		
		_entity = _scene->getSceneMgr()->createEntity(_name,Ogre::SceneManager::PrefabType::PT_PLANE);

		}catch(std::exception e)
		{
			return false;
		}
		
		
		Ogre::AxisAlignedBox auxBBox = _entity->getBoundingBox();

		_entityNode = _scene->getSceneMgr()->getRootSceneNode()->
								createChildSceneNode(_name + "_node");

		_entityNode->attachObject(_entity);
		

		//Añadir el material
		_entity->setMaterialName(_material);

		//Reescalar el prefab 
		Vector3 vector = auxBBox.getSize();


		_entityNode->scale(_dimensions.x/vector.x,_dimensions.y / vector.y,1.0);
		//Girarlo 90 grados porque aparece prependicular al mapa
		_entityNode->setOrientation(-90.0,90.0,0.0,0.0);

		//Modificar la posición
		this->setPosition(_position);
		
		_loaded = true;

		return _loaded;
	}
void MaterialEditorFrame::OnFileOpen(wxCommandEvent& event)
{
	wxFileDialog * openDialog = new wxFileDialog(this, wxT("Choose a file to open"), wxEmptyString, wxEmptyString,
		wxT("All Ogre Files (*.material;*.mesh;*.program;*.cg;*.vert;*.frag)|*.material;*.mesh;*.program;*.cg;*.vert;*.frag|Material Files (*.material)|*.material|Mesh Files (*.mesh)|*.mesh|Program Files (*.program)|*.program|Cg Files (*.cg)|*.cg|GLSL Files(*.vert; *.frag)|*.vert;*.frag|All Files (*.*)|*.*"));

	if(openDialog->ShowModal() == wxID_OK)
	{
		wxString path = openDialog->GetPath();
		if(path.EndsWith(wxT(".material")) || path.EndsWith(wxT(".program")))
		{
			MaterialScriptEditor* editor = new MaterialScriptEditor(EditorManager::getSingletonPtr()->getEditorNotebook());
			editor->loadFile(path);
			int index = (int)path.find_last_of('\\');
			if(index == -1) index = (int)path.find_last_of('/');
			editor->setName((index != -1) ? path.substr(index + 1, path.Length()) : path);

			EditorManager::getSingletonPtr()->openEditor(editor);
		}
		else if(path.EndsWith(wxT(".cg")))
		{
			CgEditor* editor = new CgEditor(EditorManager::getSingletonPtr()->getEditorNotebook());
			editor->loadFile(path);
			int index = (int)path.find_last_of('\\');
			if(index == -1) index = (int)path.find_last_of('/');
			editor->setName((index != -1) ? path.substr(index + 1, path.Length()) : path);

			EditorManager::getSingletonPtr()->openEditor(editor);
		}
		else if(path.EndsWith(wxT(".mesh")))
		{
			Ogre::SceneManager *sceneMgr = wxOgre::getSingleton().getSceneManager();
			Ogre::Camera *camera = wxOgre::getSingleton().getCamera();

			if(mEntity)
			{
				sceneMgr->getRootSceneNode()->detachObject(mEntity);
				sceneMgr->destroyEntity(mEntity);
				mEntity = 0;
			}
			
			static int meshNumber = 0;
			Ogre::String meshName = Ogre::String("Mesh") + Ogre::StringConverter::toString(meshNumber++);

			int index = (int)path.find_last_of('\\');
			if(index == -1) index = (int)path.find_last_of('/');
			wxString mesh = (index != -1) ? path.substr(index + 1, path.Length()) : path;

			mEntity = sceneMgr->createEntity(meshName, mesh.GetData());
			sceneMgr->getRootSceneNode()->attachObject(mEntity);

			Ogre::AxisAlignedBox box = mEntity->getBoundingBox();
			Ogre::Vector3 minPoint = box.getMinimum();
			Ogre::Vector3 maxPoint = box.getMaximum();
			Ogre::Vector3 size = box.getSize();

			wxOgre::getSingleton().setZoomScale(max(size.x, max(size.y, size.z)));
			wxOgre::getSingleton().resetCamera();

			Ogre::Vector3 camPos;
			camPos.x = minPoint.x + (size.x / 2.0);
			camPos.y = minPoint.y + (size.y / 2.0);
			Ogre::Real width = max(size.x, size.y);
			camPos.z = (width / tan(camera->getFOVy().valueRadians())) + size.z / 2;

			wxOgre::getSingleton().getCamera()->setPosition(camPos);
			wxOgre::getSingleton().getCamera()->lookAt(0,0,0);

			wxOgre::getSingleton().getLight()->setPosition(maxPoint * 2);
		}
	}
}
	void RenderBoxWrap::updateViewport()
	{
		// при нуле вылетает
		if ((mRenderBox->getWidth() <= 1) || (mRenderBox->getHeight() <= 1) ) return;

		if ((nullptr != mEntity) && (nullptr != mRttCam)) {
			// не ¤сно, нужно ли раст¤гивать камеру, установленную юзером
			mRttCam->setAspectRatio((float)mRenderBox->getWidth() / (float)mRenderBox->getHeight());

			//System::Console::WriteLine("Width {0}, Height {1}", getWidth(), getHeight());

			// вычисл¤ем рассто¤ние, чтобы был виден весь объект
			Ogre::AxisAlignedBox box;// = mNode->_getWorldAABB();//mEntity->getBoundingBox();

			VectorEntity::iterator iter = mVectorEntity.begin();

			while (iter != mVectorEntity.end())
			{
				box.merge((*iter)->getBoundingBox().getMinimum() + (*iter)->getParentSceneNode()->_getDerivedPosition());
				box.merge((*iter)->getBoundingBox().getMaximum() + (*iter)->getParentSceneNode()->_getDerivedPosition());
				iter++;
			}

			if (box.isNull()) return;

			//box.scale(Ogre::Vector3(1.41f,1.41f,1.41f));

			//System::Console::WriteLine("Minimum({0}), Maximum({1})",
			//	gcnew System::String(Ogre::StringConverter::toString(box.getMinimum()).c_str()),
			//	gcnew System::String(Ogre::StringConverter::toString(box.getMaximum()).c_str()));

			//box.getCenter();
			Ogre::Vector3 vec = box.getSize();

			// коррекци¤ под левосторонюю систему координат с осью Z направленную вверх
			#ifdef LEFT_HANDED_CS_UP_Z

				float width = sqrt(vec.x*vec.x + vec.y*vec.y); // самое длинное - диагональ (если крутить модель)
				float len2 = width; // mRttCam->getAspectRatio();
				float height = vec.z;
				float len1 = height;
				if (len1 < len2) len1 = len2;
				len1 /= 0.86; // [sqrt(3)/2] for 60 degrees field of view
				// центр объекта по вертикали + отъехать так, чтобы влезла ближн¤¤ грань BoundingBox'а + чуть вверх и еще назад дл¤ красоты
				Ogre::Vector3 result = box.getCenter() - Ogre::Vector3(vec.y/2 + len1, 0, 0) - Ogre::Vector3(len1*0.2, 0, -height*0.1);
				result.x *= mCurrentScale;
				mCamNode->setPosition(result);

				Ogre::Vector3 x = Ogre::Vector3(0, 0, box.getCenter().z + box.getCenter().z * (1-mCurrentScale)) - mCamNode->getPosition();
				Ogre::Vector3 y = Ogre::Vector3(Ogre::Vector3::UNIT_Z).crossProduct(x);
				Ogre::Vector3 z = x.crossProduct(y);
				mCamNode->setOrientation(Ogre::Quaternion(
					x.normalisedCopy(),
					y.normalisedCopy(),
					z.normalisedCopy()));

			#else

				float width = sqrt(vec.x*vec.x + vec.z*vec.z); // самое длинное - диагональ (если крутить модель)
				float len2 = width / mRttCam->getAspectRatio();
				float height = vec.y;
				float len1 = height;
				if (len1 < len2) len1 = len2;
				len1 /= 0.86; // [sqrt(3)/2] for 60 degrees field of view
				// центр объекта по вертикали + отъехать так, чтобы влезла ближн¤¤ грань BoundingBox'а + чуть вверх и еще назад дл¤ красоты
				Ogre::Vector3 result = box.getCenter() + Ogre::Vector3(0, 0, vec.z/2 + len1) + Ogre::Vector3(0, height*0.1, len1*0.2);
				result.z *= mCurrentScale;
				Ogre::Vector3 look = Ogre::Vector3(0, box.getCenter().y /*+ box.getCenter().y * (1-mCurrentScale)*/, 0);

				mCamNode->setPosition(result);
				mCamNode->lookAt(look, Ogre::Node::TS_WORLD);

			#endif
		}
	}
Exemple #10
0
void Objects::insertMesh (const MWWorld::Ptr& ptr, const std::string& mesh)
{
    Ogre::SceneNode* insert = ptr.getRefData().getBaseNode();
    assert(insert);

    Ogre::AxisAlignedBox bounds = Ogre::AxisAlignedBox::BOX_NULL;
    NifOgre::EntityList entities = NifOgre::NIFLoader::createEntities(insert, NULL, mesh);
    for(size_t i = 0;i < entities.mEntities.size();i++)
    {
        const Ogre::AxisAlignedBox &tmp = entities.mEntities[i]->getBoundingBox();
        bounds.merge(Ogre::AxisAlignedBox(insert->_getDerivedPosition() + tmp.getMinimum(),
                                          insert->_getDerivedPosition() + tmp.getMaximum())
        );
    }
    Ogre::Vector3 extents = bounds.getSize();
    extents *= insert->getScale();
    float size = std::max(std::max(extents.x, extents.y), extents.z);

    bool small = (size < Settings::Manager::getInt("small object size", "Viewing distance")) && Settings::Manager::getBool("limit small object distance", "Viewing distance");

    // do not fade out doors. that will cause holes and look stupid
    if (ptr.getTypeName().find("Door") != std::string::npos)
        small = false;

    if (mBounds.find(ptr.getCell()) == mBounds.end())
        mBounds[ptr.getCell()] = Ogre::AxisAlignedBox::BOX_NULL;
    mBounds[ptr.getCell()].merge(bounds);

    bool transparent = false;
    for(size_t i = 0;i < entities.mEntities.size();i++)
    {
        Ogre::Entity *ent = entities.mEntities[i];
        for (unsigned int i=0; i<ent->getNumSubEntities(); ++i)
        {
            Ogre::MaterialPtr mat = ent->getSubEntity(i)->getMaterial();
            Ogre::Material::TechniqueIterator techIt = mat->getTechniqueIterator();
            while (techIt.hasMoreElements())
            {
                Ogre::Technique* tech = techIt.getNext();
                Ogre::Technique::PassIterator passIt = tech->getPassIterator();
                while (passIt.hasMoreElements())
                {
                    Ogre::Pass* pass = passIt.getNext();

                    if (pass->getDepthWriteEnabled() == false)
                        transparent = true;
                }
            }
        }
    }

    if(!mIsStatic || !Settings::Manager::getBool("use static geometry", "Objects") || transparent)
    {
        for(size_t i = 0;i < entities.mEntities.size();i++)
        {
            Ogre::Entity *ent = entities.mEntities[i];

            ent->setRenderingDistance(small ? Settings::Manager::getInt("small object distance", "Viewing distance") : 0);
            ent->setVisibilityFlags(mIsStatic ? (small ? RV_StaticsSmall : RV_Statics) : RV_Misc);
            ent->setRenderQueueGroup(transparent ? RQG_Alpha : RQG_Main);
        }
    }
    else
    {
        Ogre::StaticGeometry* sg = 0;

        if (small)
        {
            if( mStaticGeometrySmall.find(ptr.getCell()) == mStaticGeometrySmall.end())
            {
                uniqueID = uniqueID +1;
                sg = mRenderer.getScene()->createStaticGeometry( "sg" + Ogre::StringConverter::toString(uniqueID));
                mStaticGeometrySmall[ptr.getCell()] = sg;

                sg->setRenderingDistance(Settings::Manager::getInt("small object distance", "Viewing distance"));
            }
            else
                sg = mStaticGeometrySmall[ptr.getCell()];
        }
        else
        {
            if( mStaticGeometry.find(ptr.getCell()) == mStaticGeometry.end())
            {

                uniqueID = uniqueID +1;
                sg = mRenderer.getScene()->createStaticGeometry( "sg" + Ogre::StringConverter::toString(uniqueID));
                mStaticGeometry[ptr.getCell()] = sg;
            }
            else
                sg = mStaticGeometry[ptr.getCell()];
        }

        // This specifies the size of a single batch region.
        // If it is set too high:
        //  - there will be problems choosing the correct lights
        //  - the culling will be more inefficient
        // If it is set too low:
        //  - there will be too many batches.
        sg->setRegionDimensions(Ogre::Vector3(2500,2500,2500));

        sg->setVisibilityFlags(small ? RV_StaticsSmall : RV_Statics);

        sg->setCastShadows(true);

        sg->setRenderQueueGroup(transparent ? RQG_Alpha : RQG_Main);

        for(size_t i = 0;i < entities.mEntities.size();i++)
        {
            Ogre::Entity *ent = entities.mEntities[i];
            insert->detachObject(ent);
            sg->addEntity(ent,insert->_getDerivedPosition(),insert->_getDerivedOrientation(),insert->_getDerivedScale());

            mRenderer.getScene()->destroyEntity(ent);
        }
    }
}
Exemple #11
0
void Objects::insertMesh (const MWWorld::Ptr& ptr, const std::string& mesh, bool light)
{
    Ogre::SceneNode* insert = ptr.getRefData().getBaseNode();
    assert(insert);

    Ogre::AxisAlignedBox bounds = Ogre::AxisAlignedBox::BOX_NULL;
    NifOgre::ObjectList objects = NifOgre::Loader::createObjects(insert, mesh);
    for(size_t i = 0;i < objects.mEntities.size();i++)
        bounds.merge(objects.mEntities[i]->getWorldBoundingBox(true));

    Ogre::Vector3 extents = bounds.getSize();
    extents *= insert->getScale();
    float size = std::max(std::max(extents.x, extents.y), extents.z);

    bool small = (size < Settings::Manager::getInt("small object size", "Viewing distance")) && Settings::Manager::getBool("limit small object distance", "Viewing distance");

    // do not fade out doors. that will cause holes and look stupid
    if (ptr.getTypeName().find("Door") != std::string::npos)
        small = false;

    if (mBounds.find(ptr.getCell()) == mBounds.end())
        mBounds[ptr.getCell()] = Ogre::AxisAlignedBox::BOX_NULL;
    mBounds[ptr.getCell()].merge(bounds);

    bool anyTransparency = false;
    for(size_t i = 0;!anyTransparency && i < objects.mEntities.size();i++)
    {
        Ogre::Entity *ent = objects.mEntities[i];
        for(unsigned int i=0;!anyTransparency && i < ent->getNumSubEntities(); ++i)
        {
            anyTransparency = ent->getSubEntity(i)->getMaterial()->isTransparent();
        }
    }

    if(!mIsStatic || !Settings::Manager::getBool("use static geometry", "Objects") ||
       anyTransparency || objects.mParticles.size() > 0)
    {
        for(size_t i = 0;i < objects.mEntities.size();i++)
        {
            Ogre::Entity *ent = objects.mEntities[i];
            for(unsigned int i=0; i < ent->getNumSubEntities(); ++i)
            {
                Ogre::SubEntity* subEnt = ent->getSubEntity(i);
                subEnt->setRenderQueueGroup(subEnt->getMaterial()->isTransparent() ? RQG_Alpha : RQG_Main);
            }
            ent->setRenderingDistance(small ? Settings::Manager::getInt("small object distance", "Viewing distance") : 0);
            ent->setVisibilityFlags(mIsStatic ? (small ? RV_StaticsSmall : RV_Statics) : RV_Misc);
        }
        for(size_t i = 0;i < objects.mParticles.size();i++)
        {
            Ogre::ParticleSystem *part = objects.mParticles[i];
            // TODO: Check the particle system's material for actual transparency
            part->setRenderQueueGroup(RQG_Alpha);
            part->setRenderingDistance(small ? Settings::Manager::getInt("small object distance", "Viewing distance") : 0);
            part->setVisibilityFlags(mIsStatic ? (small ? RV_StaticsSmall : RV_Statics) : RV_Misc);
        }
    }
    else
    {
        Ogre::StaticGeometry* sg = 0;

        if (small)
        {
            if( mStaticGeometrySmall.find(ptr.getCell()) == mStaticGeometrySmall.end())
            {
                uniqueID = uniqueID +1;
                sg = mRenderer.getScene()->createStaticGeometry( "sg" + Ogre::StringConverter::toString(uniqueID));
                mStaticGeometrySmall[ptr.getCell()] = sg;

                sg->setRenderingDistance(Settings::Manager::getInt("small object distance", "Viewing distance"));
            }
            else
                sg = mStaticGeometrySmall[ptr.getCell()];
        }
        else
        {
            if( mStaticGeometry.find(ptr.getCell()) == mStaticGeometry.end())
            {

                uniqueID = uniqueID +1;
                sg = mRenderer.getScene()->createStaticGeometry( "sg" + Ogre::StringConverter::toString(uniqueID));
                mStaticGeometry[ptr.getCell()] = sg;
            }
            else
                sg = mStaticGeometry[ptr.getCell()];
        }

        // This specifies the size of a single batch region.
        // If it is set too high:
        //  - there will be problems choosing the correct lights
        //  - the culling will be more inefficient
        // If it is set too low:
        //  - there will be too many batches.
        sg->setRegionDimensions(Ogre::Vector3(2500,2500,2500));

        sg->setVisibilityFlags(small ? RV_StaticsSmall : RV_Statics);

        sg->setCastShadows(true);

        sg->setRenderQueueGroup(RQG_Main);

        std::vector<Ogre::Entity*>::reverse_iterator iter = objects.mEntities.rbegin();
        while(iter != objects.mEntities.rend())
        {
            Ogre::Node *node = (*iter)->getParentNode();
            sg->addEntity(*iter, node->_getDerivedPosition(), node->_getDerivedOrientation(), node->_getDerivedScale());

            (*iter)->detachFromParent();
            mRenderer.getScene()->destroyEntity(*iter);
            iter++;
        }
    }

    if (light)
    {
        insertLight(ptr, objects.mSkelBase, bounds.getCenter() - insert->_getDerivedPosition());
    }
}
void CViewManagerView::On3dViews()
{
	int ViewIndex = CMFCRibbonGallery::GetLastSelectedItem(ID_3DVIEWS);
	CEngine *Engine = ((CViewManagerApp*)AfxGetApp())->m_Engine;
	Ogre::Root *Root = Engine->GetRoot();
	m_SceneManager->_updateSceneGraph(m_Camera);
	Ogre::SceneNode *CubeNode = m_SceneManager->getSceneNode("Cube");

	Ogre::AxisAlignedBox Box = m_SceneManager->getRootSceneNode()->_getWorldAABB();
	Ogre::Vector3 Center = Box.getCenter();
	Ogre::Vector3 Position;
	Ogre::Vector3 Destination;

	switch (ViewIndex)
	{
		case 0: //top

			Position = Center;
			Position.y += 4.0 * Box.getSize().y;
			Destination = Center;

		break;
		case 1://bottom
			
			Position = Center;
			Position.y -= 4.0 * Box.getSize().y;
			Destination = Center;

		break;
		case 2:

			Position = Center;
			Position.x += 4.0 * Box.getSize().x;
			Destination = Center;

		break;
		case 3:

			Position = Center;
			Position.x -= 4.0 * Box.getSize().x;
			Destination = Center;

		break;
		case 4:

			Position = Center;
			Position.z -= 4.0 * Box.getSize().z;
			Destination = Center;

		break;
		case 5:

			Position = Center;
			Position.z += 4.0 * Box.getSize().z;
			Destination = Center;

		break;

		case 9:

			CubeNode->roll(Ogre::Radian(-atan(sin(Ogre::Math::PI/4.0))));
			CubeNode->yaw(Ogre::Radian(Ogre::Math::PI/4.0));
			Destination = Center;
			Position = m_Camera->getPosition();

		break;
	}

	m_Camera->setPosition(Position);
	m_Camera->lookAt(Destination);
	Root->renderOneFrame();
}
void CTerrainWalkingView::EngineSetup(void)
{
	Ogre::Root *Root = ((CTerrainWalkingApp*)AfxGetApp())->m_Engine->GetRoot();
	Ogre::SceneManager *SceneManager = NULL;
	SceneManager = Root->createSceneManager(Ogre::ST_GENERIC, "Walking");
 
    //
    // Create a render window
    // This window should be the current ChildView window using the externalWindowHandle
    // value pair option.
    //

    Ogre::NameValuePairList parms;
    parms["externalWindowHandle"] = Ogre::StringConverter::toString((long)m_hWnd);
    parms["vsync"] = "true";

	CRect   rect;
    GetClientRect(&rect);
	Ogre::RenderTarget *RenderWindow = Root->getRenderTarget("Walking");

	if (RenderWindow == NULL)
	{
	try
	{
		m_RenderWindow = Root->createRenderWindow("Walking", rect.Width(), rect.Height(), false, &parms);
	}
    catch(...)
	{
		MessageBox("Cannot initialize\nCheck that graphic-card driver is up-to-date", "Initialize Render System", MB_OK | MB_ICONSTOP);
		exit(EXIT_SUCCESS);
	}
	}
// Load resources
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

    // Create the camera
    m_Camera = SceneManager->createCamera("Camera");
    m_Camera->setNearClipDistance(10);
	m_Camera->setFarClipDistance(10000); 
	m_Camera->setCastShadows(false);
	m_Camera->setUseRenderingDistance(true);

	Ogre::SceneNode *CameraNode = NULL;
	CameraNode = SceneManager->getRootSceneNode()->createChildSceneNode("CameraNode");

	Ogre::Viewport* Viewport = NULL;
	
	if (0 == m_RenderWindow->getNumViewports())
	{
		Viewport = m_RenderWindow->addViewport(m_Camera);
		Viewport->setBackgroundColour(Ogre::ColourValue(0.8f, 0.8f, 0.8f));
	}

    // Alter the camera aspect ratio to match the viewport
    m_Camera->setAspectRatio(Ogre::Real(rect.Width()) / Ogre::Real(rect.Height()));

	Ogre::SceneNode *TopographyNode = SceneManager->getRootSceneNode()->createChildSceneNode("Topography");
	Ogre::Entity *TopographyEntity = SceneManager->createEntity("Topography", "Topography.mesh");
	TopographyNode->attachObject(TopographyEntity);
	
	Ogre::AxisAlignedBox TopographyBox = TopographyEntity->getBoundingBox();
	
	Ogre::Vector3 Minimum = TopographyBox.getMinimum();
	Ogre::Vector3 Center = TopographyBox.getCenter();

	Ogre::SceneNode *RobotNode = SceneManager->getRootSceneNode()->createChildSceneNode("Robot");
	Ogre::Entity *RobotEntity = SceneManager->createEntity("Robot", "robot.mesh");
	RobotNode->attachObject(RobotEntity);
	RobotEntity->getParentNode()->scale(10,10,10);
	Ogre::AxisAlignedBox RobotBox = RobotEntity->getBoundingBox();

	RobotNode->setPosition(Ogre::Vector3(Minimum[0], Minimum[1] + RobotBox.getSize()[1], Minimum[2]));

	m_Camera->setPosition(Ogre::Vector3(Minimum[0], Minimum[1] + 5000, Minimum[2]));
	m_Camera->lookAt(Center);
	
	m_Camera->setPolygonMode(Ogre::PolygonMode::PM_WIREFRAME);

	m_Animation = RobotEntity->getAnimationState("Walk");
	m_Animation->setEnabled(true);
	
	m_CollisionTools = new MOC::CollisionTools(SceneManager);

	Root->renderOneFrame();
}
void CTerrainWalkingView::OnTimer(UINT_PTR nIDEvent)
{
	Ogre::Quaternion Quaternion;
	CEngine *Engine = ((CTerrainWalkingApp*)AfxGetApp())->m_Engine;		
	Ogre::Root *Root = Engine->GetRoot();
	Ogre::SceneNode *RobotNode = Root->getSceneManager("Walking")->getSceneNode("Robot");
	Ogre::Entity *RobotEntity = Root->getSceneManager("Walking")->getEntity("Robot");
	Ogre::AxisAlignedBox RobotBox = RobotEntity->getBoundingBox();

	Ogre::Entity *TopographyEntity = Root->getSceneManager("Walking")->getEntity("Topography");

	Ogre::AxisAlignedBox TopographyBox = TopographyEntity->getBoundingBox();
		
	Ogre::Vector3 Start = TopographyBox.getMinimum();
	Ogre::Vector3 Finish = TopographyBox.getMaximum();

	double x = Start[0] + (Finish[0] - Start[0]) * m_RelativeDistance;
	double y = Start[1] + (Finish[1] - Start[1]) * m_RelativeDistance;
	double z = Start[2] + (Finish[2] - Start[2]) * m_RelativeDistance;
	
	Ogre::Vector3 Elevation(x, y, z);
	Ogre::Vector3 CameraMove;

	switch (nIDEvent)
	{
		case 1:

			m_Animation->addTime(0.01);
			m_RelativeDistance += 0.01;

			if (m_CollisionTools->collidesWithEntity(Elevation, Ogre::Vector3(x,y - 1,z), Ogre::Vector3(x,y + 1,z), 100.0f, 0.0f, 4294967295))
			{
				x = Elevation[0];
				y = Elevation[1] + RobotBox.getSize()[1];
				z = Elevation[2];
			}

			RobotNode->setPosition(x, y, z);
			m_Camera->lookAt(x, y, z);
			
			if (m_RelativeDistance > 1.0)
			  KillTimer(1);

		break;

		case 2:

			CameraMove[0] = -100;
			CameraMove[1] = 0;
			CameraMove[2] = 0;
			m_Camera->moveRelative(CameraMove);

		break;

		case 3:

			CameraMove[0] = 0;
			CameraMove[1] = 100;
			CameraMove[2] = 0;
			m_Camera->moveRelative(CameraMove);

			break;

		case 4:

			CameraMove[0] = 100;
			CameraMove[1] = 0;
			CameraMove[2] = 0;
			m_Camera->moveRelative(CameraMove);

			break;

		case 5:

			CameraMove[0] = 0;
			CameraMove[1] = -100;
			CameraMove[2] = 0;
			m_Camera->moveRelative(CameraMove);

			break;
	}

	Root->renderOneFrame();
	CView::OnTimer(nIDEvent);
}