const Ogre::MaterialPtr& MaterialGenerator::GetMaterial(Perm permutation)
{
    // Check if material/shader permutation already was generated
    MaterialMap::iterator i = mMaterials.find(permutation);
    if (i != mMaterials.end())
    {
        return i->second;
    }
    else
    {
        // Create it
        Ogre::MaterialPtr templ = GetTemplateMaterial(permutation & mMatMask);
        Ogre::GpuProgramPtr vs = GetVertexShader(permutation & mVsMask);
        Ogre::GpuProgramPtr fs = GetFragmentShader(permutation & mFsMask);

        // Create material name
        string name = mMaterialBaseName + Ogre::StringConverter::toString(permutation);

        // Create material from template, and set shaders
        Ogre::MaterialPtr mat = templ->clone(name);
        Ogre::Technique* tech = mat->getTechnique(0);
        Ogre::Pass* pass = tech->getPass(0);
        pass->setFragmentProgram(fs->getName());
        pass->setVertexProgram(vs->getName());

        // And store it
        mMaterials[permutation] = mat;
        return mMaterials[permutation];
    }
}
示例#2
0
Ogre::MaterialPtr Renderer::GetMaterialCopy(const String& originalName, const String& newName)
{
    Ogre::MaterialPtr material = GetMaterial(originalName);
    if (material.isNull())
        return material;
    return material->clone(newName);
}
示例#3
0
        Ogre::Pass *getPass(const string &matName, size_t t, const string &passName, bool clone)
        {
            if (!Ogre::MaterialManager::getSingleton().resourceExists(matName))
            {
                log("could not find \"" + matName + "\" material");
                return NULL;
            }

            Ogre::MaterialPtr mat = (Ogre::MaterialPtr)Ogre::MaterialManager::getSingleton().load(
                matName, Ogre::ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME);
            assert(mat.get());

            static idGen id;

            if (clone)
                mat = mat->clone(id(matName));

            try
            {
                Ogre::Pass *ret = mat->getTechnique(t)->getPass(passName);
                return ret;
            }
            catch (...)
            {
                log("Could not find pass \"" + passName + "\" in material \"" + matName + "\"");
            }
            return NULL;
        }
示例#4
0
    void DynamicLines::init(Ogre::String const &resourceGroup,
                            Ogre::RenderOperation::OperationType opType /*= Ogre::RenderOperation::OT_LINE_STRIP*/,
                            bool use2d /*= false*/)
    {
        mPoints.clear();
        mColors.clear();
        //dynamic renderable
        initialize(opType, false);

        {
            Ogre::MaterialPtr const whiteNoLignthing = Ogre::MaterialManager::getSingleton().getByName("BaseWhiteNoLighting");
            Ogre::String const resName = "DynamicLines_" + Ogre::StringConverter::toString(mId) + "_BaseWhiteNoLighting_" + resourceGroup;
            mMaterial = Ogre::MaterialManager::getSingleton().getByName(resName);

            if(mMaterial.isNull())
            {
                mMaterial = whiteNoLignthing->clone(resName, true, resourceGroup);
                mMaterial->load();
            }

            mMaterial->setDepthCheckEnabled(!use2d);
        }
        setMaterial(mMaterial->getName());

        setUse2D(use2d);
        mDirty = false;
    }
Ogre::SceneNode* ParticleFactory::CreateParticleEntity(Ogre::String object_name, Ogre::String material_name,Ogre::SceneNode* parent, Ogre::Vector3 size){

		/* Create one instance of the torus (one entity) */
		/* The same object can have multiple instances or entities */

		/* Create entity */
		Ogre::String name = parent->getName() + object_name;
        //Ogre::Entity* entity = scene_manager->createEntity(object_name);
		Ogre::Entity* entity = scene_manager->createEntity(object_name);

		Ogre::MaterialPtr mat = static_cast<Ogre::MaterialPtr>(Ogre::MaterialManager::getSingleton().getByName(material_name));
		//mat = mat->clone(object_name.append("_" +material_name.append("_" + Ogre::StringConverter::toString(materialCounter))));
		mat = mat->clone(name.append("_" +material_name.append("_" + Ogre::StringConverter::toString(materialCounter))));

		//std::cout << "NAME: " << name << std::endl;
		//mat = mat->clone(object_name.append(material_name));
		/* Apply a material to the entity */
		entity->setMaterialName(mat->getName());
		//materialArray[numMaterials] = mat->getName();
		materialArray.push_back(mat->getName());
		

		/* Create a scene node for the entity */
		/* The scene node keeps track of the entity's position */
        Ogre::SceneNode* scene_node = parent->createChildSceneNode(mat->getName());
        scene_node->attachObject(entity);
		//scene_node->translate(0.5,0.5,-1);
		incrementCounter();
		/* Scale the entity */
		scene_node->scale(size);
		return scene_node;
}
void EC_OgreMovableTextOverlay::SetMaterial(const std::string& new_base_material)
{
    ///\todo Make this work for other materials!
    // Clone own copy of the material for this overlay.
    Ogre::MaterialManager &mm = Ogre::MaterialManager::getSingleton();
    Ogre::MaterialPtr material = mm.getByName(new_base_material);
    if (material.get())
    {
        baseMaterialName_ = new_base_material;
        Ogre::MaterialPtr baseMaterial = mm.getByName(baseMaterialName_);
        materialName_ = renderer_.lock()->GetUniqueObjectName();
        material = baseMaterial->clone(materialName_);

        //todo Check that the the material alpha channel?
        const Ogre::LayerBlendModeEx &blend = baseMaterial->getTechnique(0)->getPass(0)->getTextureUnitState(0)->getAlphaBlendMode();
        if (blend.alphaArg1 > 0)
            materialHasAlpha_ = true;
        else
            materialHasAlpha_ = false;

        // Set the max alpha for the material.
        materialMaxAlpha_ = blend.alphaArg1;

        container_->setMaterialName(materialName_);
    }
    else
        OgreRenderingModule::LogError("Invalid material name!");
}
示例#7
0
文件: Axis3d.cpp 项目: gitrider/wxsj2
   AxisRenderable::AxisRenderable(int lineCount,Ogre::Camera* camera,Ogre::Viewport* viewport) 
   {
        // Disable cast shadows by default
        mCastShadows = false;

      mPrevAxisGizmoSelAxis = -1;
      mCamera = camera;
      mViewport = viewport;

      m_max_line_count = m_line_count  = lineCount;
      m_line_count = 0;

      mLength = 200;
      mProjectDistance = mCamera->getFarClipDistance();
      m_local = false;
      m_locked_data = 0;
      //m_locked_buffer = 0;
      mRenderOp.vertexData = new Ogre::VertexData();
      m_radius = 0;

      mRenderOp.indexData = 0;
      mRenderOp.vertexData->vertexCount = m_line_count*2;
      mRenderOp.vertexData->vertexStart = 0;

      mRenderOp.operationType = Ogre::RenderOperation::OT_LINE_LIST; 
      mRenderOp.useIndexes = false; 

      Ogre::VertexDeclaration* decl = mRenderOp.vertexData->vertexDeclaration;
      Ogre::VertexBufferBinding* bind = mRenderOp.vertexData->vertexBufferBinding;

      decl->addElement(0, 0, Ogre::VET_FLOAT3, Ogre::VES_POSITION);
      decl->addElement(0, 3*sizeof(Ogre::Real), Ogre::VET_COLOUR, Ogre::VES_DIFFUSE);

      Ogre::HardwareVertexBufferSharedPtr vbuf = 
         Ogre::HardwareBufferManager::getSingleton().createVertexBuffer(
         decl->getVertexSize(0),
         2*m_max_line_count,
         Ogre::HardwareBuffer::HBU_WRITE_ONLY);

      bind->setBinding(0, vbuf);

      // Obtain the pure colour material
      Ogre::MaterialPtr pureColourMaterial = createPureColourMaterial(Ogre::ColourValue(1,1,0));

      Ogre::String realName = pureColourMaterial->getName() + "_NoDepthBuffer";
      Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().getByName(realName);
      if (material.isNull())
      {
          // Clone to avoid confuse somewhere else that using the same material
          material = pureColourMaterial->clone(realName);
          material->setDepthCheckEnabled(false);
          material->setDepthWriteEnabled(false);
      }

      setMaterial(material->getName());

      mBox.setExtents(-10,-10,-10,10,10,10);
      setQueryFlags(0);
   }
示例#8
0
void                            Worms::setColor(Ogre::ColourValue &color)
{
  Ogre::MaterialPtr new_mat;
  Ogre::MaterialPtr mat = _ent->getSubEntity(2)->getMaterial();
  new_mat = mat->clone(_name);
  //new_mat->getTechnique(0)->getPass("Skin")->setSpecular(color);
  new_mat->getTechnique(0)->getPass("Skin")->setDiffuse(color);
  this->_ent->getSubEntity(2)->setMaterialName(_name);
}
示例#9
0
void RenderedCompassImpl::_setCompass(Compass* compass)
{
	Ogre::MaterialPtr originalMaterial = static_cast<Ogre::MaterialPtr>(Ogre::MaterialManager::getSingleton().getByName(mMaterialName));
	if (originalMaterial) {
		originalMaterial->load();
		mCompassMaterial = originalMaterial->clone(OgreInfo::createUniqueResourceName(originalMaterial->getName()));
		if (Ogre::Technique* tech = mCompassMaterial->getBestTechnique()) {
			Ogre::Pass* pass = nullptr;
			if (tech->getNumPasses() && (pass = tech->getPass(0))) {
				mCompassMaterialMapTUS = pass->getTextureUnitState("Background");
				if (mCompassMaterialMapTUS) {
					//Make sure that the compass material is using the map texture for the base rendering
					mCompassMaterialMapTUS->setTexture(mMap->getTexture());

					mTexture = Ogre::TextureManager::getSingleton().createManual("RenderedCompass", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D, 128, 128, 1, Ogre::PF_A8R8G8B8, Ogre::TU_RENDERTARGET);
					mRenderTexture = mTexture->getBuffer()->getRenderTarget();
					mRenderTexture->removeAllViewports();
					mRenderTexture->setAutoUpdated(false);
					mRenderTexture->setActive(true);

					mCamera = mSceneManager->createCamera("RenderedCompassCamera");
					mViewport = mRenderTexture->addViewport(mCamera);
					mViewport->setOverlaysEnabled(false);
					mViewport->setShadowsEnabled(false);
					mViewport->setSkiesEnabled(false);
					mViewport->setClearEveryFrame(true);
					mViewport->setBackgroundColour(Ogre::ColourValue::ZERO);

					mMapRectangle = OGRE_NEW Ogre::Rectangle2D(true);
					auto mapMaterialPtr = Ogre::MaterialManager::getSingleton().getByName(mCompassMaterial->getName(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
					if (mapMaterialPtr) {
						mMapRectangle->setMaterial(mapMaterialPtr);
					}

					//We need to maximise the rendered texture to cover the whole screen
					Ogre::RenderSystem* rs = Ogre::Root::getSingleton().getRenderSystem();
					Ogre::Real hOffset = rs->getHorizontalTexelOffset() / (0.5 * mViewport->getActualWidth());
					Ogre::Real vOffset = rs->getVerticalTexelOffset() / (0.5 * mViewport->getActualHeight());
					mMapRectangle->setCorners(-1 + hOffset, 1 - vOffset, 1 + hOffset, -1 - vOffset);

					//Since a Rectangle2D instance is a moveable object it won't be rendered unless it's in the frustrum. If we set the axis aligned box to be "infinite" it will always be rendered.
					Ogre::AxisAlignedBox aabInf;
					aabInf.setInfinite();
					mMapRectangle->setBoundingBox(aabInf);

					//We can't attach something to the root node, so we'll attach it to a newly created node. We won't keep a reference to this node since it will be destroyed along with the scene manager when we ourselves are destroyed.
					mSceneManager->getRootSceneNode()->createChildSceneNode()->attachObject(mMapRectangle);

					//Return early since everything is good.
					return;
				}
			}
		}
	}
	S_LOG_WARNING("Could not load material '" << mMaterialName << "' for the compass.");
}
示例#10
0
    Ogre::MaterialPtr CloneMaterial(const std::string& sourceMaterialName, const std::string &newName)
    {
        Ogre::MaterialManager &mm = Ogre::MaterialManager::getSingleton();
        Ogre::MaterialPtr material = mm.getByName(sourceMaterialName);

        material = material->clone(newName);

        assert(material.get());
        return material;
    }
Ogre::MaterialPtr EmberTerrainProfile::getOrCreateMaterialClone(Ogre::MaterialPtr templateMaterial, const std::string& suffix)
{
    std::string name = templateMaterial->getName() + suffix;

    Ogre::MaterialPtr mat = Ogre::MaterialManager::getSingleton().getByName(name);
    if (!mat.isNull()) {
        return mat;
    }

    return templateMaterial->clone(name);
}
示例#12
0
//---------------------------------------------------------------------
std::list<Ogre::MaterialPtr> MapBlock::cloneMaterials(void) {
	std::list<Ogre::MaterialPtr> clones;
	for(unsigned int i=0; i < mEntity->getNumSubEntities(); i++) {
		Ogre::MaterialPtr realMaterial = mEntity->getSubEntity(i)->getMaterial();
		std::stringstream nameStream;
		nameStream << realMaterial->getName() << " " << mStaticPosition[0] << ":" << mStaticPosition[1];
		Ogre::MaterialPtr newMaterial = realMaterial->clone(nameStream.str());
		newMaterial->load();
		mEntity->getSubEntity(i)->setMaterial(newMaterial);
		clones.push_back(newMaterial);
	}
	return clones;
}
示例#13
0
static void
SubEntity_tintColour(
    SubEntity* self,
    const String& groupName,
    const String& materialName,
    const Ogre::ColourValue& colour
) {
    Ogre::MaterialPtr baseMaterial = Ogre::MaterialManager::getSingleton().getByName(materialName);
    Ogre::MaterialPtr materialPtr = baseMaterial->clone(groupName);
    materialPtr->compile();
    Ogre::TextureUnitState* ptus = materialPtr->getTechnique(0)->getPass(0)->getTextureUnitState(0);
    ptus->setColourOperationEx(Ogre::LBX_MODULATE, Ogre::LBS_MANUAL, Ogre::LBS_TEXTURE, colour);
    self->setMaterial(materialPtr);
}
//-------------------------------------------------------------------------------
Ogre::MaterialPtr CSceneManagerEditor::buildDepthShadowMaterial(Ogre::MaterialPtr cpyMat)
{
    if(mShadowsTechnique->get() >= (int)Ogre::SHADOWTYPE_TEXTURE_ADDITIVE && mShadowsTechnique->get() <= (int)Ogre::SHADOWTYPE_TEXTURE_MODULATIVE_INTEGRATED)
    {
        Ogre::String matName = "DepthShadows/" + cpyMat->getName();

        Ogre::MaterialPtr ret = Ogre::MaterialManager::getSingleton().getByName(matName);
        if (ret.isNull())
        {
            ret = cpyMat->clone(matName);

            Ogre::Technique *t = ret->getTechnique(0);
            t->setShadowCasterMaterial("Ogre/shadow/depth/caster");
            Ogre::Pass *p = t->getPass(0);
            p->setVertexProgram("Ogre/shadow/receiver/depth/pssm3/vp");
            p->setFragmentProgram("Ogre/shadow/receiver/depth/pssm3/fp");

            Ogre::TextureUnitState *tu = p->createTextureUnitState();
            tu->setName("shadow0");
            tu->setContentType(Ogre::TextureUnitState::CONTENT_SHADOW);
            tu->setTextureAddressingMode(Ogre::TextureUnitState::TAM_BORDER);
            tu->setTextureBorderColour(Ogre::ColourValue(1,1,1,1));
            
            tu = p->createTextureUnitState();
            tu->setName("shadow1");
            tu->setContentType(Ogre::TextureUnitState::CONTENT_SHADOW);
            tu->setTextureAddressingMode(Ogre::TextureUnitState::TAM_BORDER);
            tu->setTextureBorderColour(Ogre::ColourValue(1,1,1,1));
            
            tu = p->createTextureUnitState();
            tu->setName("shadow2");
            tu->setContentType(Ogre::TextureUnitState::CONTENT_SHADOW);
            tu->setTextureAddressingMode(Ogre::TextureUnitState::TAM_BORDER);
            tu->setTextureBorderColour(Ogre::ColourValue(1,1,1,1));

            Ogre::Vector4 splitPoints;
            const Ogre::PSSMShadowCameraSetup::SplitPointList& splitPointList = 
                static_cast<Ogre::PSSMShadowCameraSetup*>(mPSSMSetup.get())->getSplitPoints();
            for (int i = 0; i < 3; ++i)
            {
                splitPoints[i] = splitPointList[i];
            }
            p->getFragmentProgramParameters()->setNamedConstant("pssmSplitPoints", splitPoints);
        }
        
        return ret;
    }
    else
        return cpyMat;
}
示例#15
0
    void DebugCreateAmbientColorMaterial(const std::string &materialName, float r, float g, float b)
    {
        Ogre::MaterialManager &mm = Ogre::MaterialManager::getSingleton();
        Ogre::MaterialPtr material = mm.getByName(materialName);
        if (material.get()) // The given material already exists, so no need to create it again.
            return;

        material = mm.getByName("SolidAmbient");
        if (!material.get())
            return;

        Ogre::MaterialPtr newMaterial = material->clone(materialName);
        newMaterial->setAmbient(r, g, b);
    }
示例#16
0
    Ogre::MaterialPtr GetOrCreateLitTexturedMaterial(const std::string& materialName)
    {
        const char baseMaterialName[] = "LitTextured";

        Ogre::MaterialManager &mm = Ogre::MaterialManager::getSingleton();
        Ogre::MaterialPtr material = mm.getByName(materialName);

        if (!material.get())
        {
            Ogre::MaterialPtr baseMaterial = mm.getByName(baseMaterialName);
            material = baseMaterial->clone(materialName);
        }

        assert(material.get());
        return material;
    }
//-----------------------------------------------------------------------
void MaterialTab::OnChangeName(wxCommandEvent& event)
{
	wxString newName = mTxtMaterialName->GetValue();
	wxString oldName = mMaterialListBox->GetStringSelection();
	Ogre::String newMaterialName = wx2ogre(newName);
	Ogre::String oldMaterialName = wx2ogre(oldName);
	Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().getByName(oldMaterialName);
	if (!material.isNull())
	{
		Ogre::MaterialPtr clonedMaterial = material->clone(newMaterialName);
		if (!clonedMaterial.isNull())
		{
			// Load the new resource, unload the old one, remove it from the list and set the new material as the selected
			clonedMaterial->load();
			Ogre::MaterialManager* materialManager = Ogre::MaterialManager::getSingletonPtr();
			materialManager->remove(oldMaterialName);
			mMaterialListBox->Delete(mMaterialListBox->GetSelection());
			mMaterialListBox->addMaterialName(newName);
			selectMaterial(newName);
		}
	}
}
示例#18
0
    SelectionBox::SelectionBox(const Ogre::String name, Engine *engine):
        Ogre::ManualObject(name),
        mEngine(engine),
        mLeft(.0f), mTop(.0f), mRight(.0f), mBottom(.0f),
        mVolQuery(nullptr)
    {
        /*The first function sets the render queue for the object to be the Overlay queue.
         The next two functions set the projection and view matrices to be the identity. Projection and
         view matrices are used by many rendering systems (such as OpenGL and DirectX) to define where
         objects go in the world. Since Ogre abstracts this away for us, we won't go into detail about
         what these matrices actually are or what they do. Instead what you need to know is that if you
         set the projection and view matrix to be the identity, as we have here, we will basically create a
         2D object. When defining this object, the coordinate system changes a bit. We no longer deal with
         the Z axis (if you are asked for the Z axis, set the value to -1). Instead we have a new coordinate
         system with X and Y running from -1 to 1 inclusive. Lastly, we will set the query flags for the object
         to be 0, which will prevent the selection rectangle from being included in the query results.*/
        setRenderQueueGroup(Ogre::RENDER_QUEUE_OVERLAY); // when using this, ensure Depth Check is Off in the material
        setUseIdentityProjection(true);
        setUseIdentityView(true);
        setQueryFlags(0);

        {
            Ogre::MaterialPtr const whiteNoLignthing = Ogre::MaterialManager::getSingleton().getByName("BaseWhiteNoLighting");
            Ogre::String const resName = "DynamicLines_BaseWhiteNoLighting_"+mEngine->level()->name();
            mMaterial = Ogre::MaterialManager::getSingleton().getByName(resName);
            if(mMaterial.isNull())
            {
                mMaterial = whiteNoLignthing->clone(resName, true, mEngine->level()->name());
                mMaterial->load();
            }
            mMaterial->setDepthCheckEnabled(false);
        }

        if(nullptr != mEngine->level())
        {
            mEngine->level()->levelRoot()->createChildSceneNode()->attachObject(this);
            mVolQuery = mEngine->level()->sceneManager()->createPlaneBoundedVolumeQuery(Ogre::PlaneBoundedVolumeList());
        }
    }
示例#19
0
RigidObject::RigidObject(std::string file_name,
                         Ogre::SceneManager *scene_manager, int segment_ind)
    : segment_ind_{ segment_ind }, scene_manager_{ scene_manager } {
  Ogre::MeshPtr object_mesh = render::loadMeshFromResource(file_name);
  entity_ = scene_manager_->createEntity(file_name);
  Ogre::MaterialPtr mat =
      Ogre::MaterialManager::getSingleton().getByName("textured");
  std::stringstream ss;
  ss << "textured_" << segment_ind_;
  Ogre::MaterialPtr cloned_mat = mat->clone(ss.str());
  Ogre::Pass *pass = cloned_mat->getTechnique(0)->getPass(0);
  Ogre::TextureUnitState *tex_unit = pass->createTextureUnitState();
  Ogre::MaterialPtr tmp = Ogre::MaterialManager::getSingleton().getByName(
      object_mesh->getSubMesh(0)->getMaterialName());
  tex_unit->setTextureName(tmp->getTechnique(0)
                               ->getPass(0)
                               ->getTextureUnitState(0)
                               ->getTextureName());
  entity_->setMaterial(cloned_mat);

  texture_name_ = tex_unit->getTextureName();
  file_name_ = file_name;

  Ogre::SubEntity *pSub = entity_->getSubEntity(0);
  // mark segment index for vertex shader
  pSub->setCustomParameter(1, Ogre::Vector4(segment_ind_, 0, 0, 0));

  visual_node_ = scene_manager_->getRootSceneNode()->createChildSceneNode();
  visual_node_->attachObject(entity_);

  // store the vertex positions
  extractMeshPositions(object_mesh.get());
  //  std::cout << "extracted " << positions_.size() << " vertices\n";

  // compute the bounding box
  computeBoundingBox();
}
void LIRenAttachmentEntity::replace_texture_now (const Ogre::String& name, Ogre::TexturePtr& texture)
{
	if (mesh.isNull () || entity == NULL)
		return;

	// Translate the name if already replaced before.
	std::map<Ogre::String, Ogre::String>::const_iterator iter;
	iter = applied_texture_replaces.find(name);
	Ogre::String real_name;
	if (iter != applied_texture_replaces.end())
		real_name = iter->second;
	else
		real_name = name;

	// Save the replaced name for future translations.
	applied_texture_replaces[name] = texture->getName ();

	// Replace in each submesh.
	for (size_t subent_idx = 0 ; subent_idx < entity->getNumSubEntities () ; ++subent_idx)
	{
		// Get the material of the subent.
		Ogre::SubEntity* subent = entity->getSubEntity (subent_idx);
		Ogre::MaterialPtr submat = subent->getMaterial ();
		if (submat.isNull ())
			continue;

		// Check if there are replaceable textures.
		if (!render->material_utils->has_overridable_texture (submat, real_name))
			continue;

		// Create a modified version of the material.
		Ogre::String new_name = render->id.next ();
		Ogre::MaterialPtr material = submat->clone (new_name, true, LIREN_RESOURCES_TEMPORARY);
		render->material_utils->replace_texture (material, real_name, texture->getName ());
		subent->setMaterial (material);
	}
}
//-------------------------------------------------------------------------------
Ogre::MaterialPtr CSceneManagerEditor::buildDepthShadowMaterial(const Ogre::String& textureName)
{
    Ogre::String matName = "DepthShadows/" + textureName;

    Ogre::MaterialPtr ret = Ogre::MaterialManager::getSingleton().getByName(matName);
    if (ret.isNull())
    {
        Ogre::MaterialPtr baseMat = Ogre::MaterialManager::getSingleton().getByName("Ogre/shadow/depth/integrated/pssm");
        ret = baseMat->clone(matName);
        Ogre::Pass* p = ret->getTechnique(0)->getPass(0);
        p->getTextureUnitState("diffuse")->setTextureName(textureName);

        Ogre::Vector4 splitPoints;
        const Ogre::PSSMShadowCameraSetup::SplitPointList& splitPointList = 
            static_cast<Ogre::PSSMShadowCameraSetup*>(mPSSMSetup.get())->getSplitPoints();
        for (int i = 0; i < 3; ++i)
        {
            splitPoints[i] = splitPointList[i];
        }
        p->getFragmentProgramParameters()->setNamedConstant("pssmSplitPoints", splitPoints);
    }

    return ret;
}
示例#22
0
    void TerrainWeightEditor::SetUseWeights(bool val)
    {
        if(!GetSceneManager())
            return;

        Scene::EntityList list = scene_manager_->GetEntitiesWithComponent("EC_Terrain");
        Scene::EntityList::const_iterator it = list.begin();

        //Quick fix, we will clone a new material copy for each terrain and assume there does not exist previous material clones
        int i = 0;
        Ogre::String mat_name;
        while(it!= list.end())
        {
            boost::shared_ptr<EC_Terrain> ptr = (*it)->GetComponent<EC_Terrain>();
            if (val)
                ptr->material.Set(AssetReference("Rex/TerrainPCF_weighted"/*, "OgreMaterial"*/), AttributeChange::Disconnected);
            else
                ptr->material.Set(AssetReference("Rex/TerrainPCF"/*, "OgreMaterial"*/), AttributeChange::Disconnected);

            Ogre::MaterialPtr mat = Ogre::MaterialManager::getSingleton().getByName(mat_name);
            if(mat.get())
            {
                if(i>0)
                    //So we have several terrains, need to create more materials
                    mat_name += Ogre::StringConverter::toString(i);

                Ogre::MaterialPtr new_mat =Ogre::MaterialManager::getSingleton().getByName(mat_name);
                if(!new_mat.get())
                    new_mat =  mat->clone(mat_name);
                if(new_mat.get())
                    ptr->material.Set(QString(new_mat->getName().c_str()),AttributeChange::Default);
            }
            it++;
            i++;
        }
    }
//---------------------------------------------------------------------------------------
bool DigitalForensicsVisualisation::visualise(const CEGUI::EventArgs &e)
{
	try
	{
		mSceneMgr->getRootSceneNode()->removeAndDestroyChild("FilesNode");
		mSceneMgr->destroyAllMovableObjects(); //does not destroy movable texts, they are needed to be destroyed manually
		mSceneMgr->destroyAllManualObjects();
		cubeCount = pyramidCount = cylinderCount = 0;

		for (unsigned long int i = 0; i < textArrIndex; ++i)
		{
			textArr[textArrIndex]->~MovableText();
			
			textArr[textArrIndex] = NULL;
		}

		textArrIndex = 0;
	}
	catch(std::exception& e)
	{
		//do nothing
		OutputDebugString("DID NOTHING\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\nnREALLYDIDNOTHING\nn");
	}

	beginProgress();

	const float radius = 1000;
	const float thickness = radius - 45;
	

	try
	{

		MYSQL_RES *res_set; /* Create a pointer to recieve the return value.*/
		MYSQL_ROW row;  /* Assign variable for rows. */
 
		OutputDebugString(buildQuery().c_str());
		res_set = mysqlExecute(buildQuery().c_str());
		unsigned long long int numrows = mysql_num_rows(res_set); /* Create the count to print all rows */
 

		float distFromCentre = radius - thickness;
		unsigned long long int itemIndex = 0;
		char containerName[50]; //for container
		char fileName[50]; //for fileName
		char fontName[50]; //for fontName

		filesNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("FilesNode");
		filesNode->setPosition (0, -300, -500);

		srand(time(NULL));

		

		for (float y = radius - thickness; y <= radius; y += Ogre::Math::PI * 6)
		{

			//progress_bar->setProgress(progress_bar->getProgress() + ( 1/ (Ogre::Math::PI / (thickness * thickness))));

			for (float theta = 0; theta <= Ogre::Math::PI * 1.8; theta += Ogre::Math::PI / (distFromCentre / 6)) 
			{
				if ((row = mysql_fetch_row(res_set)) == NULL)
					goto exit;

			
				try
				{	

					app.e.name = row[0];
					app.e.directory = row[1];
					app.e.size = std::stoull(row[2]); //for unsigned long long
					
					app.e.setExtension();
					std::string ext = app.e.extension;
			
					for (unsigned int i = 0; i < ext.length(); ++i)
					{
						ext[i] = std::toupper(ext[i]);
					}

					app.e.extension = ext;

					app.e.write_permission = std::stoi(row[4]);
					app.e.access_permission = std::stoi(row[5]);
					app.e.creation_time = row[6];
					app.e.access_time = row[7];
					app.e.modification_time = row[8];
					app.e.c = std::stoi(row[9]);
					app.e.a = std::stoi(row[10]);
					app.e.m = std::stoi(row[11]);
			
				}
				catch(std::exception& e)
				{	
					OutputDebugString(e.what());
					OutputDebugString("SIZEEXCEPTIONNN\nn\n\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\n\nn\nn\nn\nn\nnn\nn\nSIZEEXCEPTIONNN\nn\n");
					app.e.creation_time = app.e.modification_time = app.e.access_time = app.e.name = "exception occured";
				
				}

				sprintf(containerName,"container_%d",itemIndex);
				sprintf(fontName,"font_%d", itemIndex);
				sprintf(fileName, "file_%d", itemIndex++);

				Ogre::SceneNode* container = filesNode->createChildSceneNode(containerName);
				Ogre::SceneNode* fsn = container->createChildSceneNode(fileName);
				Ogre::SceneNode* fontNode = container->createChildSceneNode(fontName);
				Ogre::SceneNode* textureNode;
				bool isTexture = app.e.isTextureFile();
				if (isTexture)
				{
					try
					{
					
						char textureName[50];
						sprintf(textureName,"texture_%d",itemIndex-1);
						std::stringstream ss;
						ss << app.e.directory << "/" << app.e.name;
						//loads and adds the image to the resources/////
						
						Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().getByName("MyMaterial2");
						Ogre::MaterialPtr matClone = material->clone(textureName);
						loadImageFile(textureName,ss.str());
						matClone->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setTextureName(textureName);
						
						textureNode = container->createChildSceneNode(textureName);
						textureNode->attachObject(rectangle(textureName));
						textureNode->setPosition(y * cos(theta), 0, y * sin(theta));
						textureNode->scale(.09,((float) app.e.size / 20000000 + 0.1),.09);
					}
					catch(std::exception e)
					{
						
						OutputDebugStringA("\nm\nm\nm\nm\nm\nm\nm\nm");
						OutputDebugStringA(e.what());
					};


					


				}

				ColorMap cm(app.e.extension);
			

				if (colorTree.search(cm) == NULL)
					colorTree.insert(cm);
				else
					cm = colorTree.search(cm)->data;
				

		

			
				
				if ((app.e.write_permission == 1) && (app.e.access_permission == 1))
					fsn ->attachObject(cube(true, cm));
				else if ((app.e.write_permission == 1) && (app.e.access_permission == 0))
					fsn->attachObject(cube(false, cm));
				else if ((app.e.write_permission == 0) && (app.e.access_permission == 1))
				{
					fsn -> attachObject(pyramid(cm));
					fsn -> scale (1.3, 1.3, 1.3);
				}
				else
				{
					fsn->attachObject(cylinder(cm));
					fsn->pitch((Ogre::Radian) Ogre::Math::PI);
					if (isTexture)
						textureNode->scale(.8,1,.8);
					
				}
				std::stringstream ss;
				ss << "file name: " << app.e.name << "\n\nlast access time: " << app.e.access_time << "\nmodification time: " 
					<< app.e.modification_time << "\ncreation time: " << app.e.creation_time;
				std::string s = ss.str();
			
				textArr[textArrIndex] = new Ogre::MovableText("tayyar", (s));
				textArr[textArrIndex] ->setTextAlignment(Ogre::MovableText::H_CENTER, Ogre::MovableText::V_CENTER); // Center horizontally and display above the node	
				textArr[textArrIndex] ->setColor(Ogre::ColourValue(1,1,1,.65));

				fontNode->attachObject(textArr[textArrIndex++]);

				fsn->setPosition(y * cos(theta), 0, y * sin(theta));
				fontNode->setPosition(fsn->getPosition().x + 6, fsn->getPosition().y, fsn->getPosition().z + 3.75);
			

				fsn->scale(.09,((float) app.e.size / 20000000 + 0.1),.09);

		

				OutputDebugString(fileName);
				OutputDebugString("\n");
			
			}

			distFromCentre += Ogre::Math::PI * 6;
		
		}

	
	}
	catch(std::exception& e)
	{
		OutputDebugString(e.what());
		OutputDebugString("EXCEPTIONNN\nn\n\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\n\nn\nn\nn\nn\nnn\nn\nEXCEPTIONNN\nn\n");
					
	}
	
	exit:
	endProgress();
	return true;
}
示例#24
0
// 设置选中的外观颜色.
void CEditDobject_NT::SetSelectLook(Ogre::ColourValue color)
{

	if(0 == m_materialSelVector.size())
	{
		// 选中材质的名字.
		Ogre::String strCloneName;
		int iCount = m_EntityList.size();
		Ogre::Entity* pEntity = NULL;

		for(int i = 0; i < iCount; i++)
		{
			pEntity = m_EntityList[i].pEntity;
			if(pEntity)
			{
				Ogre::SubEntity* pSubEntiy = pEntity->getSubEntity(0);
				if(pSubEntiy)
				{
					
					Ogre::MaterialPtr pMaterial = pSubEntiy->getMaterial();
					
					if(pMaterial.isNull())
					{
						return;
					}//

					const Ogre::String& strName = pMaterial->getName();

					if("BaseWhite" == strName)
					{
						continue;
					}

					strCloneName = strName;
					strCloneName += "_select";
					
					Ogre::MaterialManager* pMaterialManager = (Ogre::MaterialManager*)(pMaterial->getCreator());

					if(NULL == pMaterialManager)
					{
						return;
					}

					Ogre::MaterialPtr pMaterialClone = pMaterialManager->getByName(strCloneName); 
						
					if(pMaterialClone.isNull())
					{
						pMaterialClone = pMaterial->clone(strCloneName);
					}
					//if(!pMaterialClone)
					//{
					//	return;
					//}//

					Ogre::Technique* pTechnique = pMaterialClone->getBestTechnique();
					Ogre::Pass* pPass = pTechnique->getPass(0);

					//pPass->setSceneBlending(SBT_ADD);
					//pPass->setSceneBlending(SBF_SOURCE_ALPHA , SBF_ONE_MINUS_SOURCE_ALPHA );
					//pTextureState->setAlphaOperation(LBX_MODULATE, LBS_TEXTURE, LBS_MANUAL, 1, Transparence, 1);//
				
					Ogre::TextureUnitState* pTextureState = pPass->getTextureUnitState(0);
					pTextureState->setColourOperationEx(Ogre::LBX_ADD , Ogre::LBS_TEXTURE , Ogre::LBS_MANUAL, color, color );
					pSubEntiy->setMaterialName(strCloneName);
					m_materialSelVector.push_back(pMaterialClone);
					m_materilaOldVector.push_back(pMaterial);
					
				}

			}
		}
	}
	else
	{
		int iIndex = 0;

		int iCount = m_EntityList.size();
		Ogre::Entity* pEntity = NULL;

		for(int i = 0; i < iCount; i++)
		{
			pEntity = m_EntityList[i].pEntity;
			if(pEntity)
			{
				Ogre::SubEntity* pSubEntiy = pEntity->getSubEntity(0);
				
				if(pSubEntiy)
				{
					if(iIndex >= (int)m_materialSelVector.size())
					{
						continue;
					}

					std::string strMaterialName = m_materialSelVector[iIndex]->getName();
					pSubEntiy->setMaterialName(strMaterialName);	
					iIndex++;
				}

			}
		}
	}
}
//-----------------------------------------------------------------------------
///
MaterialPtr StaticBillboardSet::getFadeMaterial(const Ogre::MaterialPtr &protoMaterial,
                                                Real visibleDist_, Real invisibleDist_)
{
   assert(!protoMaterial.isNull());

   StringUtil::StrStreamType materialSignature;
   materialSignature << mEntityName << "|";
   materialSignature << visibleDist_ << "|";
   materialSignature << invisibleDist_ << "|";
   materialSignature << protoMaterial->getTechnique(0)->getPass(0)->getTextureUnitState(0)->getTextureUScroll() << "|";
   materialSignature << protoMaterial->getTechnique(0)->getPass(0)->getTextureUnitState(0)->getTextureVScroll() << "|";

   FadedMaterialMap::iterator it = s_mapFadedMaterial.find(materialSignature.str());
   if (it != s_mapFadedMaterial.end())
      return it->second; //Use the existing fade material
   else
   {
      MaterialPtr fadeMaterial = protoMaterial->clone(getUniqueID("ImpostorFade"));

      bool isglsl = Root::getSingleton().getRenderSystem()->getName() == "OpenGL Rendering Subsystem" ? true : false;

      //And apply the fade shader
      for (unsigned short t = 0; t < fadeMaterial->getNumTechniques(); ++t)
      {
         Technique *tech = fadeMaterial->getTechnique(t);
         for (unsigned short p = 0; p < tech->getNumPasses(); ++p)
         {
            Pass *pass = tech->getPass(p);

            //Setup vertex program
            pass->setVertexProgram("SpriteFade_vp");
            GpuProgramParametersSharedPtr params = pass->getVertexProgramParameters();

            //glsl can use the built in gl_ModelViewProjectionMatrix
            if (!isglsl)
               params->setNamedAutoConstant("worldViewProj", GpuProgramParameters::ACT_WORLDVIEWPROJ_MATRIX);

            static const Ogre::String uScroll = "uScroll", vScroll = "vScroll",
               preRotatedQuad0 = "preRotatedQuad[0]", preRotatedQuad1 = "preRotatedQuad[1]",
               preRotatedQuad2 = "preRotatedQuad[2]", preRotatedQuad3 = "preRotatedQuad[3]",
               camPos = "camPos", fadeGap = "fadeGap", invisibleDist = "invisibleDist";

            params->setNamedAutoConstant(uScroll, GpuProgramParameters::ACT_CUSTOM);
            params->setNamedAutoConstant(vScroll, GpuProgramParameters::ACT_CUSTOM);
            params->setNamedAutoConstant(preRotatedQuad0, GpuProgramParameters::ACT_CUSTOM);
            params->setNamedAutoConstant(preRotatedQuad1, GpuProgramParameters::ACT_CUSTOM);
            params->setNamedAutoConstant(preRotatedQuad2, GpuProgramParameters::ACT_CUSTOM);
            params->setNamedAutoConstant(preRotatedQuad3, GpuProgramParameters::ACT_CUSTOM);

            params->setNamedAutoConstant(camPos, GpuProgramParameters::ACT_CAMERA_POSITION_OBJECT_SPACE);
            params->setNamedAutoConstant(fadeGap, GpuProgramParameters::ACT_CUSTOM);
            params->setNamedAutoConstant(invisibleDist, GpuProgramParameters::ACT_CUSTOM);

            //Set fade ranges
            params->setNamedConstant(invisibleDist, invisibleDist_);
            params->setNamedConstant(fadeGap, invisibleDist_ - visibleDist_);

            pass->setSceneBlending(SBT_TRANSPARENT_ALPHA);
            //pass->setAlphaRejectFunction(CMPF_ALWAYS_PASS);
            //pass->setDepthWriteEnabled(false);

         }  // for Pass

      }  // for Technique

      //Add it to the list so it can be reused later
      s_mapFadedMaterial.insert(std::pair<String, MaterialPtr>(materialSignature.str(), fadeMaterial));

      return fadeMaterial;
   }
}
示例#26
0
bool Oculus::setupOgre(Ogre::SceneManager *sm, Ogre::RenderWindow *win, Ogre::SceneNode *parent)
{
	m_window = win;
	m_sceneManager = sm;
	Ogre::LogManager::getSingleton().logMessage("Oculus: Setting up Ogre");
	if(parent)
		m_cameraNode = parent->createChildSceneNode("StereoCameraNode");
	else
		m_cameraNode = sm->getRootSceneNode()->createChildSceneNode("StereoCameraNode");

	m_cameras[0] = sm->createCamera("CameraLeft");
	m_cameras[1] = sm->createCamera("CameraRight");
	
	Ogre::MaterialPtr matLeft = Ogre::MaterialManager::getSingleton().getByName("Ogre/Compositor/Oculus");
	Ogre::MaterialPtr matRight = matLeft->clone("Ogre/Compositor/Oculus/Right");
	Ogre::GpuProgramParametersSharedPtr pParamsLeft = matLeft->getTechnique(0)->getPass(0)->getFragmentProgramParameters();
	Ogre::GpuProgramParametersSharedPtr pParamsRight = matRight->getTechnique(0)->getPass(0)->getFragmentProgramParameters();
	Ogre::Vector4 hmdwarp;
	if(m_stereoConfig)
	{
		hmdwarp = Ogre::Vector4(m_stereoConfig->GetDistortionK(0),
								m_stereoConfig->GetDistortionK(1),
								m_stereoConfig->GetDistortionK(2),
								m_stereoConfig->GetDistortionK(3));
	}
	else
	{
		hmdwarp = Ogre::Vector4(g_defaultDistortion[0],
								g_defaultDistortion[1],
								g_defaultDistortion[2],
								g_defaultDistortion[3]);
	}
	pParamsLeft->setNamedConstant("HmdWarpParam", hmdwarp);
	pParamsRight->setNamedConstant("HmdWarpParam", hmdwarp);
	pParamsLeft->setNamedConstant("LensCentre", 0.5f+(m_stereoConfig->GetProjectionCenterOffset()/2.0f));
	pParamsRight->setNamedConstant("LensCentre", 0.5f-(m_stereoConfig->GetProjectionCenterOffset()/2.0f));

	Ogre::CompositorPtr comp = Ogre::CompositorManager::getSingleton().getByName("OculusRight");
	comp->getTechnique(0)->getOutputTargetPass()->getPass(0)->setMaterialName("Ogre/Compositor/Oculus/Right");

	for(int i=0;i<2;++i)
	{
		m_cameraNode->attachObject(m_cameras[i]);
		if(m_stereoConfig)
		{
			// Setup cameras.
			m_cameras[i]->setNearClipDistance(m_stereoConfig->GetEyeToScreenDistance());
			m_cameras[i]->setFarClipDistance(g_defaultFarClip);
			m_cameras[i]->setPosition((i * 2 - 1) * m_stereoConfig->GetIPD() * 0.5f, 0, 0);
			m_cameras[i]->setAspectRatio(m_stereoConfig->GetAspect());
			m_cameras[i]->setFOVy(Ogre::Radian(m_stereoConfig->GetYFOVRadians()));
			
			// Oculus requires offset projection, create a custom projection matrix
			Ogre::Matrix4 proj = Ogre::Matrix4::IDENTITY;
			float temp = m_stereoConfig->GetProjectionCenterOffset();
			proj.setTrans(Ogre::Vector3(-m_stereoConfig->GetProjectionCenterOffset() * (2 * i - 1), 0, 0));
			m_cameras[i]->setCustomProjectionMatrix(true, proj * m_cameras[i]->getProjectionMatrix());
		}
		else
		{
			m_cameras[i]->setNearClipDistance(g_defaultNearClip);
			m_cameras[i]->setFarClipDistance(g_defaultFarClip);
			m_cameras[i]->setPosition((i*2-1) * g_defaultIPD * 0.5f, 0, 0);
		}
		m_viewports[i] = win->addViewport(m_cameras[i], i, 0.5f*i, 0, 0.5f, 1.0f);
		m_viewports[i]->setBackgroundColour(g_defaultViewportColour);
		m_compositors[i] = Ogre::CompositorManager::getSingleton().addCompositor(m_viewports[i],i==0?"OculusLeft":"OculusRight");
		m_compositors[i]->setEnabled(true);
	}

	m_ogreReady = true;
	Ogre::LogManager::getSingleton().logMessage("Oculus: Oculus setup completed successfully");
	return true;
}
示例#27
0
Ogre::MaterialPtr OgreMaterialProperties::ToOgreMaterial()
{
    // Make clone from the original and uset that for creating the new material.
    Ogre::MaterialPtr matPtr = material_->GetMaterial();
    Ogre::MaterialPtr matPtrClone = matPtr->clone(objectName().toStdString() + "Clone");

    // Material
    if (!matPtrClone.isNull())
    {
        // Technique
        Ogre::Material::TechniqueIterator tIter = matPtrClone->getTechniqueIterator();
        while(tIter.hasMoreElements())
        {
            Ogre::Technique *tech = tIter.getNext();
            Ogre::Technique::PassIterator pIter = tech->getPassIterator();
            while(pIter.hasMoreElements())
            {
                // Pass
                Ogre::Pass *pass = pIter.getNext();
                if (!pass)
                    continue;

                if (pass->hasVertexProgram())
                {
                    // Vertex program
                    const Ogre::GpuProgramPtr &verProg = pass->getVertexProgram();
                    if (!verProg.isNull())
                    {
                        Ogre::GpuProgramParametersSharedPtr verPtr = pass->getVertexProgramParameters();
                        if (verPtr->hasNamedParameters())
                        {
                            // Named parameters (constants)
                            Ogre::GpuConstantDefinitionIterator mapIter = verPtr->getConstantDefinitionIterator();
                            int constNum = 0;
                            while(mapIter.hasMoreElements())
                            {
                                QString paramName(mapIter.peekNextKey().c_str());
                                const Ogre::GpuConstantDefinition &paramDef  = mapIter.getNext();

                                // Filter names that end with '[0]'
                                if (paramName.lastIndexOf("[0]") != -1)
                                    continue;

                                if (!paramDef.isFloat())
                                    continue;

                                size_t size = paramDef.elementSize * paramDef.arraySize;
                                QVector<float> newParamValue;
                                QVector<float>::iterator it;
                                newParamValue.resize(size);

                                // Find the corresponding property value.
                                QVariant val = property(paramName.append(" VP").toLatin1());
                                if (!val.isValid() || val.isNull())
                                    continue;

                                TypeValuePair typeValuePair = val.toMap();
                                QString newValueString(typeValuePair.begin().value().toByteArray());
                                newValueString.trimmed();

                                // fill the float vector with new values
                                it = newParamValue.begin();
                                int i = 0, j = 0;
                                bool ok = true;
                                while(j != -1 && ok)
                                {
                                    j = newValueString.indexOf(' ', i);
                                    QString newValue = newValueString.mid(i, j == -1 ? j : j - i);
                                    if (!newValue.isEmpty())
                                    {
                                        *it = newValue.toFloat(&ok);
                                        ++it;
                                    }
                                    i = j + 1;
                                }

                                // Set the new value.
                                ///\todo use the exact count rather than just 4 values if needed.
                                if (size == 16)
                                {
                                    Ogre::Matrix4 matrix(newParamValue[0], newParamValue[1], newParamValue[2], newParamValue[3],
                                        newParamValue[4], newParamValue[5], newParamValue[6], newParamValue[7],
                                        newParamValue[8], newParamValue[9], newParamValue[10], newParamValue[11],
                                        newParamValue[12], newParamValue[13], newParamValue[14], newParamValue[15]);

#if OGRE_VERSION_MINOR <= 6 && OGRE_VERSION_MAJOR <= 1
                                    verPtr->_writeRawConstant(paramDef.physicalIndex, matrix);
#else
                                    verPtr->_writeRawConstant(paramDef.physicalIndex, matrix, size);
#endif
                                }
                                else
                                {
                                    Ogre::Vector4 vector(newParamValue[0], newParamValue[1], newParamValue[2], newParamValue[3]);
                                    verPtr->_writeRawConstant(paramDef.physicalIndex, vector);
                                }
                            }
                        }
                    }
                }

                if (pass->hasFragmentProgram())
                {
                    // Fragment program
                    const Ogre::GpuProgramPtr &fragProg = pass->getFragmentProgram();
                    if (!fragProg.isNull())
                    {
                        Ogre::GpuProgramParametersSharedPtr fragPtr = pass->getFragmentProgramParameters();
                        if (!fragPtr.isNull())
                        {
                            if (fragPtr->hasNamedParameters())
                            {
                                // Named parameters (constants)
                                Ogre::GpuConstantDefinitionIterator mapIter = fragPtr->getConstantDefinitionIterator();
                                while(mapIter.hasMoreElements())
                                {
                                    QString paramName(mapIter.peekNextKey().c_str());
                                    const Ogre::GpuConstantDefinition &paramDef  = mapIter.getNext();

                                    // Filter names that end with '[0]'
                                    if (paramName.lastIndexOf("[0]") != -1)
                                        continue;

                                    if (!paramDef.isFloat())
                                        continue;

                                    size_t size = paramDef.elementSize * paramDef.arraySize;
                                    QVector<float> newParamValue;
                                    QVector<float>::iterator it;
                                    newParamValue.resize(size);

                                    // Find the corresponding property value.
                                    QVariant val = property(paramName.append(" FP").toLatin1());
                                    if (!val.isValid() || val.isNull())
                                        continue;

                                    TypeValuePair typeValuePair = val.toMap();
                                    QString newValueString(typeValuePair.begin().value().toByteArray());
                                    newValueString.trimmed();

                                    // Fill the float vector with new values.
                                    it = newParamValue.begin();
                                    int i = 0, j = 0;
                                    bool ok = true;
                                    while(j != -1 && ok)
                                    {
                                        j = newValueString.indexOf(' ', i);
                                        QString newValue = newValueString.mid(i, j == -1 ? j : j - i);
                                        if (!newValue.isEmpty())
                                        {
                                            *it = *it = newValue.toFloat(&ok);
                                            ++it;
                                        }
                                        i = j + 1;
                                    }

                                    // Set the new value.
                                    ///\todo use the exact count rather than just 4 values if needed.
                                    if (size == 16)
                                    {
                                        Ogre::Matrix4 matrix(newParamValue[0], newParamValue[1], newParamValue[2], newParamValue[3],
                                            newParamValue[4], newParamValue[5], newParamValue[6], newParamValue[7],
                                            newParamValue[8], newParamValue[9], newParamValue[10], newParamValue[11],
                                            newParamValue[12], newParamValue[13], newParamValue[14], newParamValue[15]);

#if OGRE_VERSION_MINOR <= 6 && OGRE_VERSION_MAJOR <= 1
                                    fragPtr->_writeRawConstant(paramDef.physicalIndex, matrix);
#else
                                    fragPtr->_writeRawConstant(paramDef.physicalIndex, matrix, size);
#endif
                                    }
                                    else
                                    {
                                        Ogre::Vector4 vector(newParamValue[0], newParamValue[1], newParamValue[2], newParamValue[3]);
                                        fragPtr->_writeRawConstant(paramDef.physicalIndex, vector);
                                    }
                                }
                            }
                        }
                    }
                }

                Ogre::Pass::TextureUnitStateIterator texIter = pass->getTextureUnitStateIterator();
                while(texIter.hasMoreElements())
                {
                    // Texture units
                    Ogre::TextureUnitState *tu = texIter.getNext();

                    // Replace the texture name (uuid) with the new one
                    QString tu_name(tu->getName().c_str());

                    QVariant val = property(tu_name.append(" TU").toLatin1());
                    if (!val.isValid() || val.isNull())
                        continue;

                    TypeValuePair typeValuePair = val.toMap();
                    QString newValueString(typeValuePair.begin().value().toByteArray());
                    newValueString.trimmed();

                    tu->setTextureName(newValueString.toStdString());
                    /*
                    //QString new_texture_name = iter->second;
                    RexUUID new_name(iter->second);
                    // If new texture is UUID-based one, make sure the corresponding RexOgreTexture gets created,
                    // because we may not be able to load it later if load fails now
                    if (RexUUID::IsValid(new_texture_name))
                    {
                        RexUUID imageID(new_texture_name);
                        if (!imageID.IsNull())
                        {
                            image* image = imageList.getImage(imageID);
                            if (image)
                            {
                                image->getOgreTexture();
                            }
                        }
                    }
                    //tu->setTextureName(iter->second);
                    */
                }
            }
        }

        return matPtrClone;
    }

    matPtrClone.setNull();
    return matPtrClone;
}
示例#28
0
const Ogre::MaterialPtr&
Terrain::_getGridMaterial(const TerrainData::GridInfo &gridInfo, ushort depthBias, int nTileX, int nTileZ)
{
    assert(mData != NULL);

    size_t textureIds[TerrainData::NumLayers] = { 0 };
    for (size_t i = 0; i < TerrainData::NumLayers; ++i)
    {
        if (gridInfo.layers[i].pixmapId)
        {
            textureIds[i] = _getPixmapAtlasId(gridInfo.layers[i].pixmapId - 1) + 1;
        }
    }
    assert(textureIds[0] && "Internal fault while create grid material");

    bool lightmapped = mData->mLightmapImage && getLightmapQuality() != LMQ_NONE;
   Ogre::ulong lightmapId = lightmapped ? (nTileZ << 16) | nTileX : ~0;

    MaterialId id(textureIds[0], textureIds[1], lightmapId, depthBias);

    // find the material that already created
    MaterialMap::const_iterator it = mMaterials.find(id);
    if (it != mMaterials.end())
        return it->second;

   Ogre::String name = "Terrain/";
    if (!mData->mName.empty())
        name += mData->mName + "/";
    name += Ogre::StringConverter::toString(textureIds[0]) + "." + Ogre::StringConverter::toString(textureIds[1]);
    if (depthBias)
        name += "_" + Ogre::StringConverter::toString(depthBias);

   Ogre::String lightmapName = "<Lightmap>(" +
        Ogre::StringConverter::toString(nTileX / mData->mTileSize) + "," +
        Ogre::StringConverter::toString(nTileZ / mData->mTileSize) + ")";
    if (lightmapped)
        name += "_" + lightmapName;

	Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().getByName(name);
    if (material.isNull())
    {
        // get user supplied material
       Ogre::String templateName = textureIds[1] ? "TwoLayer" : "OneLayer";
		if (lightmapped)
            templateName += "Lightmap";

        TerrainData::MaterialTemplates::const_iterator it =
            mData->mMaterialTemplates.find(templateName);
        if (it == mData->mMaterialTemplates.end())
            OGRE_EXCEPT(Ogre::Exception::ERR_ITEM_NOT_FOUND,
                "Can't found grid material template for '" + templateName + "'!", 
                "Terrain::_getGridMaterial");

        const Ogre::String& baseName = it->second;
        Ogre::MaterialPtr templateMaterial = Ogre::MaterialManager::getSingleton().getByName(baseName);
        if (templateMaterial.isNull())
            OGRE_EXCEPT(Ogre::Exception::ERR_ITEM_NOT_FOUND, 
                "Can't load grid material template '" + baseName + "'!", 
                "Terrain::_getGridMaterial");

        // clone the material
        material = templateMaterial->clone(name, true, BRUSH_RESOURCE_GROUP_NAME);

        // Setup texture alias list
        Ogre::AliasTextureNamePairList aliasList;
        aliasList["<layer0>"] = mAtlases[textureIds[0]-1].texture->getName();
        if (textureIds[1])
            aliasList["<layer1>"] = mAtlases[textureIds[1]-1].texture->getName();
        if (lightmapped)
            aliasList["<lightmap>"] = lightmapName;

        // Applies texture names
        material->applyTextureAliases(aliasList);

        // Applies surface params
        _applySurfaceParams(material);

        // Applies fog
        _applyFogMode(material, Ogre::FOG_NONE, mCurrentFogMode);

        // Adjust other material attributes
        Ogre::Material::TechniqueIterator ti = material->getTechniqueIterator();
        while (ti.hasMoreElements())
        {
            Ogre::Technique* technique = ti.getNext();
            Ogre::Technique::PassIterator pi = technique->getPassIterator();
            while (pi.hasMoreElements())
            {
                Ogre::Pass* pass = pi.getNext();
                if (depthBias)
                {
#if OGRE_VERSION >= 0x010300
                    pass->setDepthBias(depthBias + pass->getDepthBiasConstant(), pass->getDepthBiasSlopeScale());
#else
                    pass->setDepthBias(depthBias + pass->getDepthBias());
#endif
                }
            }
        }
    }

    // The material will load on demand

    std::pair<MaterialMap::iterator, bool> inserted =
        mMaterials.insert(MaterialMap::value_type(id, material));
    assert(inserted.second && "Internal fault while create grid material");
    return inserted.first->second;
}
示例#29
0
//--------------------------------------------------------------------------------------------------
bool DiscoApplication::frameStarted( const Ogre::FrameEvent& evt )
{
	static Ogre::Timer a;

	static uint32_t lastTimeMS;
	static uint32_t curTimeMS;

	curTimeMS = a.getMilliseconds();
	uint32_t timeDiffMS = curTimeMS - lastTimeMS;

	if ( timeDiffMS > 0 )
	{
		//printf( "FPS = %f\n", 1000.0/(float)timeDiffMS );//1.0/((float)timeDiffMS/1000.0) );
	}
	lastTimeMS = curTimeMS;

	const int32_t MAX_DEPTH_MM = 10000;
	const float FOCAL_LENGTH = 0.525f;	// Focal length in metres
	const float FADE_START_XZ_DISTANCE = 0.5f;
	const float FADE_MAX_XZ_DISTANCE = 6.0f;

	xn::SceneMetaData sceneMD;
	xn::DepthMetaData depthMD;

	mpKinectController->getContext().WaitAndUpdateAll();
	mpKinectController->getDepthGenerator().GetMetaData( depthMD );
	mpKinectController->getUserGenerator().GetUserPixels( 0, sceneMD );

	XnUserID userIdx[15];
	XnUInt16 numUsers = 15;
	mpKinectController->getUserGenerator().GetUsers( userIdx, numUsers );

	if ( 0 == numUsers )
	{
		// Restart the time if there are no users to record
		mRecordingGapTimer.reset();
	}
	else
	{
		for ( uint32_t i = 0; i < numUsers; i++ )
		{
			if ( tryToAttachParticleToUser( userIdx[ i ] ) )
			{
				break;
			}
		}
	}

	// Start recording if we see a person
	if ( numUsers > 0 && !mbRecording
		&& mRecordingGapTimer.getMilliseconds() > TIME_BETWEEN_RECORDINGS_MS )
	{
		mbRecording = true;
		memset( mpImageData, 0, RECORDED_DATA_SIZE );
		mRecordingFrameIdx = 0;
	}


	// Build an accumulative histogram to work out the colour for each point
	uint32_t depthHist[ MAX_DEPTH_MM ];
	memset( depthHist, 0, sizeof( depthHist ) );

	uint32_t numPoints = 0;

	const XnDepthPixel* pDepth = depthMD.Data();

	int32_t recordingPixelStepX = depthMD.XRes() / SMALL_FRAME_WIDTH;
	int32_t recordingPixelStepY = depthMD.YRes() / SMALL_FRAME_HEIGHT;
	if ( recordingPixelStepX <= 0 ) recordingPixelStepX = 1;
	if ( recordingPixelStepY <= 0 ) recordingPixelStepY = 1;

	for ( uint32_t y = 0; y < depthMD.YRes(); y++ )
	{
		for ( uint32_t x = 0; x < depthMD.XRes(); x++ )
		{
			XnUInt16 value = *pDepth;

			if ( 0 != value )
			{
				depthHist[ value ]++;
				numPoints++;
			}

			pDepth++;
		}
	}

	for ( uint32_t i = 1; i < MAX_DEPTH_MM; i++ )
	{
		depthHist[ i ] += depthHist[ i - 1 ];
	}

	if ( numPoints > 0 )
	{
		for ( uint32_t i = 1; i < MAX_DEPTH_MM; i++ )
		{
			depthHist[ i ] = (unsigned int)(256 * (1.0f - ((float)depthHist[ i ] / numPoints)));
		}
	}

	// Update the point cloud to reflect the depth data
	const float COLOURS[][3] =
	{
		{0,1,1},
		{0,0,1},
		{0,1,0},
		{1,1,0},
		{1,0,0},
		{1,.5,0},
		{.5,1,0},
		{0,.5,1},
		{.5,0,1},
		{1,1,.5},
		{1,1,1}
	};
	const uint32_t NUM_COLOURS = 10;

	pDepth = depthMD.Data();
	const XnLabel* pLabels = sceneMD.Data();


	mpRosPointCloud->clear();

	ogre_tools::PointCloud::Point* pPoints = new ogre_tools::PointCloud::Point[ numPoints ];
	int32_t pointIdx = 0;

	int32_t width = depthMD.XRes();
	int32_t height = depthMD.YRes();
	int32_t halfWidth = width / 2;
	int32_t halfHeight = height / 2;

	for ( int32_t y = 0; y < height; y++ )
	{
		for ( int32_t x = 0; x < width; x++ )
		{
			XnUInt16 value = *pDepth;
			XnLabel label = *pLabels;
			XnUInt32 colorId = label % NUM_COLOURS;

			float fade = 1.0;

			if (label == 0)
			{
				// Ignore background
				colorId = NUM_COLOURS;
			}


			{

				float worldZ = (float)(*pDepth)/1000.0;		// Convert from mm to m
				float worldX = (((float)(x-halfWidth)/1000.0)*worldZ) / FOCAL_LENGTH;

				float distanceXZ = sqrtf( worldX*worldX + worldZ*worldZ );
				if ( distanceXZ > FADE_MAX_XZ_DISTANCE )
				{
					fade = 0.0f;
				}
				else if ( distanceXZ > FADE_START_XZ_DISTANCE )
				{
					fade = 1.0 - (distanceXZ - FADE_START_XZ_DISTANCE)/(FADE_MAX_XZ_DISTANCE - FADE_START_XZ_DISTANCE);
				}
			}

			if ( //mbRecording
				0 != value && fade > 0.0
				&& ( SHOW_BACKGROUND || label != 0 ) )
			{
				float worldZ = (float)(*pDepth)/1000.0;		// Convert from mm to m
				float worldX = (((float)(x-halfWidth)/1000.0)*worldZ) / FOCAL_LENGTH;
				float worldY = (((float)(y-halfHeight)/1000.0)*worldZ) / FOCAL_LENGTH;
				//float worldY = (((float)(((height-1)-y)-halfHeight)/1000.0)*worldZ) / FOCAL_LENGTH;

				float histValue = (float)depthHist[ value ]/255.0;

				pPoints[ pointIdx ].setColor(
					fade * histValue * COLOURS[ colorId ][ 0 ],
					fade * histValue * COLOURS[ colorId ][ 1 ],
					fade * histValue * COLOURS[ colorId ][ 2 ] );

				pPoints[ pointIdx ].x = worldX;
				pPoints[ pointIdx ].y = worldY;
				pPoints[ pointIdx ].z = worldZ;

				pointIdx++;

				if ( mbRecording && label != 0
					&& x%recordingPixelStepX == 0 && y%recordingPixelStepY == 0 )
				{
					int32_t smallFrameX = x / recordingPixelStepX;
					int32_t smallFrameY = y / recordingPixelStepY;

					int32_t smallPixelIdx = mRecordingFrameIdx*SMALL_FRAME_WIDTH*SMALL_FRAME_HEIGHT
						+ smallFrameY*SMALL_FRAME_WIDTH + smallFrameX;

					//((uint16_t*)mpImageData)[ smallPixelIdx ] = 0xFFFF;
					//((uint32_t*)mpImageData)[ smallPixelIdx ] = 0xFFFFFFFF;

					mpImageData[ smallPixelIdx ] = 0xFF; // 255; //(uint8_t)(fade * histValue * 255.0);
					//printf( "recorded %i to pixel %i\n", mpImageData[ smallPixelIdx ], smallPixelIdx );
				}
			}

			pDepth++;
			pLabels++;
		}
	}

	mpRosPointCloud->addPoints( pPoints, pointIdx );
	//printf( "Added %i points\n", pointIdx );

	delete [] pPoints;

	// Draw the crowd
	uint32_t numCrowdMembers = mCrowdMembers.size();
	mpCrowdObject->clear();
	mpCrowdObject->estimateVertexCount( numCrowdMembers*4 );
	mpCrowdObject->estimateIndexCount( numCrowdMembers*12 );

	for ( uint32_t personIdx = 0; personIdx < numCrowdMembers; personIdx++ )
	{
		CrowdMember& crowdMember = mCrowdMembers[ personIdx ];

		float startV = (float)crowdMember.mFrameIdx/(float)NUM_FRAMES_TO_RECORD;
		float endV = (float)(crowdMember.mFrameIdx+1)/(float)NUM_FRAMES_TO_RECORD;

		mpCrowdObject->begin( crowdMember.mMaterialName, Ogre::RenderOperation::OT_TRIANGLE_LIST );

		//float startV = 0.0; //(float)crowdMember.mFrameIdx/(float)NUM_FRAMES_TO_RECORD;
		//float endV = 1.0;// (float)(crowdMember.mFrameIdx+1)/(float)NUM_FRAMES_TO_RECORD;

		//mpCrowdObject->begin( "Template/CutOut", Ogre::RenderOperation::OT_TRIANGLE_LIST );


		mpCrowdObject->position( crowdMember.mPos + Ogre::Vector3( -0.5f, -0.375f, 0.0f ) );
		mpCrowdObject->textureCoord( 0.0, startV );
		mpCrowdObject->colour( COLOURS[ crowdMember.mColourIdx ][ 0 ],
			COLOURS[ crowdMember.mColourIdx ][ 1 ], COLOURS[ crowdMember.mColourIdx ][ 2 ], 1.0 );

		mpCrowdObject->position( crowdMember.mPos + Ogre::Vector3( 0.5f, -0.375f, 0.0f ) );
		mpCrowdObject->textureCoord( 1.0, startV );

		mpCrowdObject->position( crowdMember.mPos + Ogre::Vector3( 0.5f, 0.375f, 0.0f ) );
		mpCrowdObject->textureCoord( 1.0, endV );

		mpCrowdObject->position( crowdMember.mPos + Ogre::Vector3( -0.5f, 0.375f, 0.0f ) );
		mpCrowdObject->textureCoord( 0.0, endV );

		//mpCrowdObject->quad( 0, 1, 2, 3 );
		mpCrowdObject->quad( 3, 2, 1, 0 );

		mpCrowdObject->end();

		// Move to the next frame
		if ( crowdMember.mbReversing )
		{
			crowdMember.mFrameIdx--;
			if ( crowdMember.mFrameIdx < 0 )
			{
				crowdMember.mFrameIdx = 1;
				crowdMember.mbReversing = false;
			}
		}
		else
		{
			crowdMember.mFrameIdx++;
			if ( crowdMember.mFrameIdx >= NUM_FRAMES_TO_RECORD )
			{
				crowdMember.mFrameIdx = NUM_FRAMES_TO_RECORD-1;
				crowdMember.mbReversing = true;
			}
		}
	}


	// Check to see if we can stop recording
	if ( mbRecording )
	{
		mRecordingFrameIdx++;
		if ( mRecordingFrameIdx >= NUM_FRAMES_TO_RECORD )
		{
			// Create a new crowd member
			Ogre::Image image;
			image.loadDynamicImage(
				mpImageData, SMALL_FRAME_WIDTH, NUM_FRAMES_TO_RECORD*SMALL_FRAME_HEIGHT, 1, Ogre::PF_A4L4 );

			std::stringstream ss;
			ss << "RecordedSequenceTex_" << numCrowdMembers;
			Ogre::String texName = ss.str();

			Ogre::TextureManager* pTextureMgr = Ogre::TextureManager::getSingletonPtr();
			Ogre::TexturePtr pTexture = pTextureMgr->loadImage( texName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, image );

			ss.clear();
			ss << "RecordedSequenceMat_" << numCrowdMembers;
			Ogre::String matName = ss.str();

			Ogre::MaterialManager* pMatMgr = Ogre::MaterialManager::getSingletonPtr();
			Ogre::MaterialPtr pSrcMat = (Ogre::MaterialPtr)pMatMgr->getByName( "Template/CutOut", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME );
			Ogre::MaterialPtr pMat = pSrcMat->clone( matName ); //  (Ogre::MaterialPtr)pMatMgr->create( matName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME );

			pMat->getTechnique( 0 )->getPass( 0 )->removeAllTextureUnitStates();
			Ogre::TextureUnitState* pTex = pMat->getTechnique( 0 )->getPass( 0 )->createTextureUnitState( texName, 0 );
			pMat->getTechnique( 0 )->getPass( 0 )->addTextureUnitState( pTex );

			/*Ogre::Technique* pTech = pMat->getTechnique( 0 );
			pTech->setSceneBlending( Ogre::SBT_TRANSPARENT_ALPHA );

			Ogre::Pass *pPass = pTech->createPass();

			pPass->setLightingEnabled( false );

			pPass->setAmbient( 1.0, 1.0, 1.0 );
			pPass->setDiffuse( 1.0, 1.0, 1.0, 1.0 );
			pPass->setSpecular( 0.0, 0.0, 0.0, 0.0 );

			Ogre::ColourValue val(0.0f, 0.0f, 0.0f, 1.0f);
			pPass->setSelfIllumination(val);

			//pPass->setE ( 0.0, 0.0, 0.0, 0.0 );

			pPass->setSceneBlending( Ogre::SBT_TRANSPARENT_ALPHA );
			pPass->setDepthWriteEnabled( false );

			Ogre::TextureUnitState* pTex = pPass->createTextureUnitState( texName, 0 );
			pPass->addTextureUnitState( pTex );


			pTex->setColourOperation( Ogre::LBO_MODULATE );*/

			pMat->setCullingMode( Ogre::CULL_NONE );
			pMat->compile();

			CrowdMember crowdMember;
			crowdMember.mMaterialName = matName;
			crowdMember.mFrameIdx = 0;
			crowdMember.mColourIdx = rand()%NUM_COLOURS;
			crowdMember.mbReversing = false;

			int32_t rowIdx = rand()%NUM_ROWS;
			float angle = MIN_CROWD_ANGLE + ((float)rand()/(float)RAND_MAX)*(MAX_CROWD_ANGLE-MIN_CROWD_ANGLE);
			float x = ROW_DEPTHS[ rowIdx ]*sin( angle );
			float z = ROW_DEPTHS[ rowIdx ]*cos( angle );
			crowdMember.mPos = Ogre::Vector3( x, ROW_HEIGHTS[ rowIdx ], z );
			mCrowdMembers.push_back( crowdMember );

			mbRecording = false;
			mRecordingGapTimer.reset();		// Reset time so that there's a gap between recording
			printf( "Got frame\n" );
		}
	}

	return true;
}
示例#30
0
bool GUIRadarLayout::Load()
{
	//
	rect = new Ogre::Rectangle2D(TRUE);
	rect->setMaterial("Radar/Background");	
	rect->getMaterial()->setDepthCheckEnabled(false);
	rect->getMaterial()->setDepthWriteEnabled(false);	
	rect->setRenderQueueGroup(Ogre::RENDER_QUEUE_6-3);
	//rect->setBoundingBox(Ogre::AxisAlignedBox(-1000000 * Ogre::Vector3::UNIT_SCALE, 1000000 * Ogre::Vector3::UNIT_SCALE)); 
	//CommonDeclarations::GetSceneManager()->getRootSceneNode()->attachObject(rect); 
	//rect->setCorners(0.5, -0.5, 1, -1);
	//

	// Create a manual object for 2D	
	//char name[10];
	Ogre::Rectangle2D *row = NULL;
	Ogre::Rectangle2D *obj = NULL;
	//Ogre::AxisAlignedBox aabInf;
	//aabInf.setInfinite();
	
	if (!Ogre::MaterialManager::getSingleton().resourceExists("CompasMaterial"))
	{
		Ogre::MaterialPtr mat = Ogre::MaterialManager::getSingleton().getByName("BaseWhiteNoLighting");
		CompasMaterial = mat->clone("CompasMaterial");
		CompasMaterial->setDepthCheckEnabled(false);
		CompasMaterial->setDepthWriteEnabled(false);
		CompasMaterial->setLightingEnabled(true);
		CompasMaterial->setAmbient(Ogre::ColourValue::Green);
	}

	if (!Ogre::MaterialManager::getSingleton().resourceExists("RadarRowMaterial"))
	{
		Ogre::MaterialPtr mat = Ogre::MaterialManager::getSingleton().getByName("BaseWhiteNoLighting");
		RadarRowMaterial = mat->clone("RadarRowMaterial");
		RadarRowMaterial->setDepthCheckEnabled(false);
		RadarRowMaterial->setDepthWriteEnabled(false);
		RadarRowMaterial->setLightingEnabled(true);
		RadarRowMaterial->setAmbient(Ogre::ColourValue::Red);
	}

	/*if (!Ogre::MaterialManager::getSingleton().resourceExists("RadarObjMaterial"))
	{
		Ogre::MaterialPtr mat = Ogre::MaterialManager::getSingleton().getByName("BaseWhiteNoLighting");
		RadarObjMaterial = mat->clone("RadarObjMaterial");
		RadarObjMaterial->setDepthCheckEnabled(false);
		RadarObjMaterial->setDepthWriteEnabled(false);
		RadarObjMaterial->setLightingEnabled(true);
		RadarObjMaterial->setAmbient(Ogre::ColourValue::Red);
	}*/
	
	for (unsigned i=0;i<CommonDeclarations::RadarObjectsCount;++i)
	{		
		//
		row = new Ogre::Rectangle2D(TRUE);
		row->setMaterial("RadarRowMaterial");		
		row->setRenderQueueGroup(Ogre::RENDER_QUEUE_6-2);		
		//CommonDeclarations::GetSceneManager()->getRootSceneNode()->attachObject(row); 
		//rect->setCorners(0.5, -0.5, 1, -1);
		Rows.Data[i] = row;
		//

		//
		obj = new Ogre::Rectangle2D(TRUE);
		obj->setMaterial("Radar/ObjMaterialUp");
		obj->setRenderQueueGroup(Ogre::RENDER_QUEUE_6-2);		
		//CommonDeclarations::GetSceneManager()->getRootSceneNode()->attachObject(obj); 
		//rect->setCorners(0.5, -0.5, 1, -1);
		Objects.Data[i] = obj;
		//		
	}

    InitCompasRect(CompasRect);
    InitCompasRect(CompasObj);    
		
	return true;
}