Exemplo n.º 1
0
Ogre::TexturePtr Simple::updateShadowTexture(Ogre::MaterialPtr material, const TerrainPageShadow* terrainPageShadow, std::set<std::string>& managedTextures) const
{
	auto shadowTextureName = getShadowTextureName(material);

	Ogre::TexturePtr texture = static_cast<Ogre::TexturePtr>(Ogre::Root::getSingletonPtr()->getTextureManager()->getByName(shadowTextureName));
	if (texture.isNull()) {
		texture = Ogre::Root::getSingletonPtr()->getTextureManager()->createManual(shadowTextureName, "General", Ogre::TEX_TYPE_2D, mPage.getBlendMapSize(), mPage.getBlendMapSize(), 1, Ogre::PF_L8, Ogre::TU_DYNAMIC_WRITE_ONLY);
		managedTextures.insert(texture->getName());
	}

	Ogre::Image ogreImage;
	terrainPageShadow->loadIntoImage(ogreImage);

	texture->loadImage(ogreImage);

	//blit the whole image to the hardware buffer
	Ogre::PixelBox sourceBox(ogreImage.getPixelBox());
	//blit for each mipmap
	for (unsigned int i = 0; i <= texture->getNumMipmaps(); ++i) {
		Ogre::HardwarePixelBufferSharedPtr hardwareBuffer(texture->getBuffer(0, i));
		hardwareBuffer->blitFromMemory(sourceBox);
	}

	return texture;
}
Exemplo n.º 2
0
	void Material::update() {
		if(!baseMaterial.isNull()) {
			Ogre::ColourValue ambient = baseMaterial->getTechnique(0)->getPass(0)->getAmbient();
			Ogre::ColourValue diffuse = baseMaterial->getTechnique(0)->getPass(0)->getDiffuse();
			Ogre::ColourValue specular = baseMaterial->getTechnique(0)->getPass(0)->getSpecular();
			Ogre::ColourValue emissive = baseMaterial->getTechnique(0)->getPass(0)->getEmissive();
			float shininess = baseMaterial->getTechnique(0)->getPass(0)->getShininess();
			GLuint tex = 0;
			if(baseMaterial->getNumTechniques()!=0 && baseMaterial->getTechnique(0)->getNumPasses()!=0 && baseMaterial->getTechnique(0)->getPass(0)->getNumTextureUnitStates()!=0) {
				Ogre::String texName = baseMaterial->getTechnique(0)->getPass(0)->getTextureUnitState(0)->getTextureName();
				if(Ogre::TextureManager::getSingleton().resourceExists(texName)) {
					Ogre::TexturePtr texPtr = Ogre::TextureManager::getSingleton().getByName(texName);
					Ogre::Image img;
					texPtr->convertToImage(img);
					Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().createManual(texPtr->getName()+"_optixformat", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D, texPtr->getWidth(), texPtr->getHeight(), 0, Ogre::PF_FLOAT32_RGBA, Ogre::TU_DYNAMIC_WRITE_ONLY_DISCARDABLE);
					texture->loadImage(img);
					tex = ((Ogre::GLTexturePtr)texture)->getGLID();
				}
			}
			prepareMaterial(glm::vec3(ambient.r,ambient.g,ambient.b),
							glm::vec3(diffuse.r,diffuse.g,diffuse.b),
							glm::vec3(specular.r,specular.g,specular.b),
							glm::vec3(emissive.r,emissive.g,emissive.b),
							shininess,tex);
		}
	}
Exemplo n.º 3
0
//-------------------------------------------------------
Ogre::Material* Ground::CreateGroundMaterialTextured(const std::string & name, const Ogre::Image* texture)
{
    Ogre::TexturePtr heightMapTexture = Ogre::TextureManager::getSingleton().loadImage("Texture/Terrain",
        Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, *texture);

    Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().create(name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
    {
        Ogre::Technique* techniqueGL = material->getTechnique(0);
        Ogre::Pass* pass = techniqueGL->getPass(0);
        {
            auto vprogram = Ogre::HighLevelGpuProgramManager::getSingleton().createProgram("Shader/" + CLASS_NAME + "/GL/Textured/V",
                Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, "glsl", Ogre::GPT_VERTEX_PROGRAM);
            vprogram->setSource(Shader_GL_Simple_V);
            //auto vparams = vprogram->createParameters();
            //vparams->setNamedAutoConstant("modelviewproj", Ogre::GpuProgramParameters::ACT_WORLDVIEWPROJ_MATRIX);

            pass->setVertexProgram(vprogram->getName());
        }
        {
            auto fprogram = Ogre::HighLevelGpuProgramManager::getSingleton().createProgram("Shader/" + CLASS_NAME + "/GL/Textured/F",
                Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, "glsl", Ogre::GPT_FRAGMENT_PROGRAM);
            fprogram->setSource(Shader_GL_Simple_F);

            auto unit0 = pass->createTextureUnitState(heightMapTexture->getName());
            unit0->setTextureAddressingMode(Ogre::TextureUnitState::TAM_CLAMP);
            unit0->setTextureFiltering(Ogre::TFO_NONE);

            pass->setFragmentProgram(fprogram->getName());
        }
    }
#if !NDEBUG
    material->load();
#endif
    return material.get();
}
Exemplo n.º 4
0
TexturePair AssetsManager::showTexture(const std::string textureName)
{
	// 	if (!mOgreCEGUITexture) {
	// 		S_LOG_WARNING("You must first create a valid OgreCEGUITexture instance.");
	// 		return;
	// 	}
	if (Ogre::TextureManager::getSingleton().resourceExists(textureName)) {
		Ogre::TexturePtr texturePtr = static_cast<Ogre::TexturePtr>(Ogre::TextureManager::getSingleton().getByName(textureName));
		if (!texturePtr.isNull()) {
			if (!texturePtr->isLoaded()) {
				try {
					texturePtr->load();
				} catch (...) {
					S_LOG_WARNING("Error when loading " << textureName << ". This texture will not be shown.");
					return TexturePair();
				}
			}
			std::string textureName(texturePtr->getName());
			std::string imageSetName(textureName + "_AssetsManager");

			return createTextureImage(texturePtr, imageSetName);
			// 			mOgreCEGUITexture->setOgreTexture(texturePtr);
		}
	}
	return TexturePair();

}
Exemplo n.º 5
0
	void UiManager::resizeTexture(const QSize &aSize, const Ogre::MaterialPtr &aMaterial, const Ogre::TexturePtr &aTexture)
	{
		assert(!aMaterial.isNull());
		assert(!aTexture.isNull());
		
		// get the smallest power of two dimension that is at least as large as the new UI size
		Ogre::uint newTexWidth = nextHigherPowerOfTwo(aSize.width());
		Ogre::uint newTexHeight = nextHigherPowerOfTwo(aSize.height());
	
		if (!aTexture.isNull())
		{
			std::string txtrName = aTexture->getName();
			
			// remove the old texture
			aTexture->unload();
			aMaterial->getTechnique(0)->getPass(0)->removeAllTextureUnitStates();
			Ogre::TextureManager::getSingleton().remove(aTexture->getHandle());
	
			Ogre::TexturePtr newTxtr = Ogre::TextureManager::getSingleton().createManual(
					txtrName, "General", Ogre::TEX_TYPE_2D, newTexWidth, newTexHeight, 0, Ogre::PF_A8R8G8B8,
					Ogre::TU_DYNAMIC_WRITE_ONLY);
	
			// add the new texture
			Ogre::TextureUnitState* txtrUstate = aMaterial->getTechnique(0)->getPass(0)->createTextureUnitState(txtrName);
	
			// adjust it to stay aligned and scaled to the window
			Ogre::Real txtrUScale = (Ogre::Real)newTexWidth / aSize.width();
			Ogre::Real txtrVScale = (Ogre::Real)newTexHeight / aSize.height();
			txtrUstate->setTextureScale(txtrUScale, txtrVScale);
			txtrUstate->setTextureScroll((1 / txtrUScale) / 2 - 0.5, (1 / txtrVScale) / 2 - 0.5);
		}
	}
Exemplo n.º 6
0
bool PersonShape::createMaterial( const std::string& image_name,
                                  const std::string& resource_group)
{
  if (image_name == "default")
  {
    material_ = Ogre::MaterialManager::getSingleton().create( "default",
                                                              Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME );
    material_->setCullingMode(Ogre::CULL_NONE);
    return true;
  }
  material_ = Ogre::MaterialManager::getSingleton().load( image_name, resource_group );
  material_->setCullingMode(Ogre::CULL_NONE);
  if( material_.isNull() )
    return false;

  Ogre::Pass* first_pass = material_->getTechnique(0)->getPass(0);

  if( first_pass->getNumTextureUnitStates() == 0 )
  {
    Ogre::TextureUnitState* texture_unit = first_pass->createTextureUnitState();
    Ogre::TexturePtr texture
        = Ogre::TextureManager::getSingleton().load( image_name, resource_group );
    if( texture.isNull() )
      return false;
#if (OGRE_VERSION_MINOR >=8)
    texture_unit->setTexture( texture ); // or setTextureName if Ogre 1.8?
#else
    texture_unit->setTextureName( texture->getName());
#endif
  }
  return true;
}
Exemplo n.º 7
0
void Simple::addLightingPass(Ogre::Technique* technique, std::set<std::string>& managedTextures) const
{
	Ogre::Pass* lightingPass = technique->createPass();

	lightingPass->setSceneBlending(Ogre::SBT_MODULATE);
	lightingPass->setLightingEnabled(false);

	Ogre::TextureUnitState * textureUnitStateSplat = lightingPass->createTextureUnitState();

	//we need an unique name for our alpha texture
	std::stringstream lightingTextureNameSS;
	lightingTextureNameSS << technique->getParent()->getName() << "_lighting";
	const Ogre::String lightingTextureName(lightingTextureNameSS.str());

	Ogre::TexturePtr texture = static_cast<Ogre::TexturePtr>(Ogre::Root::getSingletonPtr()->getTextureManager()->getByName(lightingTextureName));
	if (texture.isNull()) {
		texture = Ogre::Root::getSingletonPtr()->getTextureManager()->createManual(lightingTextureName, "General", Ogre::TEX_TYPE_2D, mPage.getBlendMapSize(), mPage.getBlendMapSize(), 1, Ogre::PF_L8, Ogre::TU_DYNAMIC_WRITE_ONLY);
		managedTextures.insert(texture->getName());
	}

	Ogre::Image ogreImage;
	ogreImage.loadDynamicImage(const_cast<unsigned char*>(mLightingImage->getData()), mLightingImage->getResolution(), mLightingImage->getResolution(), 1, Ogre::PF_L8);

	texture->loadImage(ogreImage);

	//blit the whole image to the hardware buffer
	Ogre::PixelBox sourceBox(ogreImage.getPixelBox());
	//blit for each mipmap
	for (unsigned int i = 0; i <= texture->getNumMipmaps(); ++i) {
		Ogre::HardwarePixelBufferSharedPtr hardwareBuffer(texture->getBuffer(0, i));
		hardwareBuffer->blitFromMemory(sourceBox);
	}

	textureUnitStateSplat->setTextureName(texture->getName());

	textureUnitStateSplat->setTextureCoordSet(0);
	textureUnitStateSplat->setTextureAddressingMode(Ogre::TextureUnitState::TAM_CLAMP);
	textureUnitStateSplat->setTextureFiltering(Ogre::TFO_ANISOTROPIC);

}
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);
	}
}
Exemplo n.º 9
0
TexturePair AssetsManager::createTextureImage(Ogre::TexturePtr texturePtr, const std::string& imageName)
{
	// 	if (mOgreCEGUITexture) {
	// 		GUIManager::getSingleton().getGuiRenderer()->destroyTexture(mOgreCEGUITexture);
	// 		mOgreCEGUITexture = 0;
	// 	}

	auto renderer = CEGUI::System::getSingleton().getRenderer();

	CEGUI::Texture* ogreCEGUITexture;
	if (renderer->isTextureDefined(texturePtr->getName())) {
		ogreCEGUITexture = &renderer->getTexture(texturePtr->getName());
		static_cast<CEGUI::OgreTexture*>(ogreCEGUITexture)->setOgreTexture(texturePtr);
	} else {
		//create a CEGUI texture from our Ogre texture
		S_LOG_VERBOSE("Creating new CEGUI texture from Ogre texture.");
		ogreCEGUITexture = &GUIManager::getSingleton().createTexture(texturePtr);
	}

	//assign our image element to the StaticImage widget
	CEGUI::Image* textureImage;
	if (CEGUI::ImageManager::getSingleton().isDefined(imageName)) {
		textureImage = &CEGUI::ImageManager::getSingleton().get(imageName);
	} else {
		textureImage = &CEGUI::ImageManager::getSingleton().create("BasicImage", imageName);
	}

	CEGUI::BasicImage* basicImage = static_cast<CEGUI::BasicImage*>(textureImage);
	basicImage->setTexture(ogreCEGUITexture);
	auto area = CEGUI::Rectf(0, 0, ogreCEGUITexture->getSize().d_width, ogreCEGUITexture->getSize().d_height);
	basicImage->setArea(area);
	basicImage->setNativeResolution(area.getSize());
	basicImage->setAutoScaled(CEGUI::ASM_Both);

	return TexturePair(texturePtr, textureImage);

}
Exemplo n.º 10
0
void Simple::addShadow(Ogre::Technique* technique, const TerrainPageShadow* terrainPageShadow, Ogre::MaterialPtr material, std::set<std::string>& managedTextures) const
{
	Ogre::Pass* shadowPass = technique->createPass();

	shadowPass->setSceneBlending(Ogre::SBT_MODULATE);
	shadowPass->setLightingEnabled(false);
//	shadowPass->setFog(true, Ogre::FOG_NONE);

	Ogre::TextureUnitState * textureUnitStateSplat = shadowPass->createTextureUnitState();
	Ogre::TexturePtr texture = updateShadowTexture(material, terrainPageShadow, managedTextures);
	textureUnitStateSplat->setTextureName(texture->getName());

	textureUnitStateSplat->setTextureCoordSet(0);
	textureUnitStateSplat->setTextureAddressingMode(Ogre::TextureUnitState::TAM_CLAMP);
	textureUnitStateSplat->setTextureFiltering(Ogre::TFO_ANISOTROPIC);
}
Ogre::MaterialPtr OgrePlanarReflectionMaterial::createMaterial(const Ogre::TexturePtr& texture, const Ogre::Camera& projectionCamera)
{
    using namespace::Ogre;

    Ogre::MaterialPtr matPtr = MaterialManager::getSingleton().create(this->getName(),"General");
    Ogre::TextureUnitState* t;
    if(! textureFilename.getValue().empty() )
    {
        t = matPtr->getTechnique(0)->getPass(0)->createTextureUnitState(textureFilename.getValue());
    }
    t = matPtr->getTechnique(0)->getPass(0)->createTextureUnitState(texture->getName() );
    t->setColourOperationEx(Ogre::LBX_BLEND_MANUAL, Ogre::LBS_TEXTURE, Ogre::LBS_CURRENT,
            Ogre::ColourValue::White, Ogre::ColourValue::White,
            blendingFactor.getValue());
    t->setTextureAddressingMode(Ogre::TextureUnitState::TAM_CLAMP);
    t->setProjectiveTexturing(true,&projectionCamera);

    matPtr->compile();
    return matPtr;
}
Exemplo n.º 12
0
void
    GraphicsController::_attachTextureToMaterials(const Ogre::String &textureUnitName, Ogre::TexturePtr texturePtr, 
    const std::vector<Ogre::String> materialNames)
{
    //for(auto iter = materialNames.cbegin(); iter != materialNames.cend(); ++iter)
	for(const Ogre::String &materialName : materialNames)
	{
        Ogre::MaterialPtr mat = Ogre::MaterialManager::getSingleton().getByName(materialName);
        Ogre::String errorMessage("This material ");
        errorMessage += materialName + " was not found.";
        if(mat.isNull())
        {
            OGRE_EXCEPT(Ogre::Exception::ERR_INVALIDPARAMS, errorMessage, "GraphicsController::_attachTextureToMaterials");
        }
        Ogre::TextureUnitState* txUnit = mat->getTechnique(0)->getPass(0)->getTextureUnitState(textureUnitName);
        if(!txUnit)
            OGRE_EXCEPT(Ogre::Exception::ERR_ITEM_NOT_FOUND, textureUnitName + " was not found", "GraphicsController::_attachTextureToMaterials");
        txUnit->setTextureName(texturePtr->getName());
    }
}
void ImageSelectionToolCustom::onInitialize()
{
    move_tool_->initialize( context_ );

    // Create our highlight rectangle
    Ogre::SceneManager* scene_manager = context_->getSceneManager();
    highlight_node_ = scene_manager->getRootSceneNode()->createChildSceneNode();

    std::stringstream ss;
    static int count = 0;
    ss << "ImageSelectionRect" << count++;
    highlight_rectangle_ = new Ogre::Rectangle2D(true);

    const static uint32_t texture_data[1] = { 0xffff0070 };
    Ogre::DataStreamPtr pixel_stream;
    pixel_stream.bind(new Ogre::MemoryDataStream( (void*)&texture_data[0], 4 ));

    Ogre::TexturePtr tex = Ogre::TextureManager::getSingleton().loadRawData(ss.str() + "Texture", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, pixel_stream, 1, 1, Ogre::PF_R8G8B8A8, Ogre::TEX_TYPE_2D, 0);

    Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().create(ss.str(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
    material->setLightingEnabled(false);
    //material->getTechnique(0)->getPass(0)->setPolygonMode(Ogre::PM_WIREFRAME);
    highlight_rectangle_->setMaterial(material->getName());
    Ogre::AxisAlignedBox aabInf;
    aabInf.setInfinite();
    highlight_rectangle_->setBoundingBox(aabInf);
    highlight_rectangle_->setRenderQueueGroup(Ogre::RENDER_QUEUE_OVERLAY + 4);
    material->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA);
    material->setCullingMode(Ogre::CULL_NONE);

    Ogre::TextureUnitState* tex_unit = material->getTechnique(0)->getPass(0)->createTextureUnitState();
    tex_unit->setTextureName(tex->getName());
    tex_unit->setTextureFiltering( Ogre::TFO_NONE );

    highlight_node_->attachObject(highlight_rectangle_);
}
Exemplo n.º 14
0
void Ogre2dManager::renderBuffer()
{
   Ogre::RenderSystem* rs=Ogre::Root::getSingleton().getRenderSystem();
   std::list<Ogre2dSprite>::iterator currSpr, endSpr;
 
   VertexChunk thisChunk;
   std::list<VertexChunk> chunks;
 
   unsigned int newSize;
 
   newSize=sprites.size()*6;
   if (newSize<OGRE2D_MINIMAL_HARDWARE_BUFFER_SIZE)
      newSize=OGRE2D_MINIMAL_HARDWARE_BUFFER_SIZE;
 
   // grow hardware buffer if needed
   if (hardwareBuffer.isNull() || hardwareBuffer->getNumVertices()<newSize)
   {
      if (!hardwareBuffer.isNull())
         destroyHardwareBuffer();
 
      createHardwareBuffer(newSize);
   }
 
   if (sprites.empty()) return;
 
   // write quads to the hardware buffer, and remember chunks
   float* buffer;
   float z=-1;
 
   buffer=(float*)hardwareBuffer->lock(Ogre::HardwareBuffer::HBL_DISCARD);
 
   endSpr=sprites.end();
   currSpr=sprites.begin();
   thisChunk.texHandle=currSpr->texHandle;
   thisChunk.vertexCount=0;
   while (currSpr!=endSpr)
   {
      // 1st point (left bottom)
      *buffer=currSpr->x1; buffer++;
      *buffer=currSpr->y2; buffer++;
      *buffer=z; buffer++;
      *buffer=currSpr->tx1; buffer++;
      *buffer=currSpr->ty2; buffer++;
      // 2st point (right top)
      *buffer=currSpr->x2; buffer++;
      *buffer=currSpr->y1; buffer++;
      *buffer=z; buffer++;
      *buffer=currSpr->tx2; buffer++;
      *buffer=currSpr->ty1; buffer++;
      // 3rd point (left top)
      *buffer=currSpr->x1; buffer++;
      *buffer=currSpr->y1; buffer++;
      *buffer=z; buffer++;
      *buffer=currSpr->tx1; buffer++;
      *buffer=currSpr->ty1; buffer++;
 
      // 4th point (left bottom)
      *buffer=currSpr->x1; buffer++;
      *buffer=currSpr->y2; buffer++;
      *buffer=z; buffer++;
      *buffer=currSpr->tx1; buffer++;
      *buffer=currSpr->ty2; buffer++;
      // 5th point (right bottom)
      *buffer=currSpr->x2; buffer++;
      *buffer=currSpr->y1; buffer++;
      *buffer=z; buffer++;
      *buffer=currSpr->tx2; buffer++;
      *buffer=currSpr->ty1; buffer++;
      // 6th point (right top)
      *buffer=currSpr->x2; buffer++;
      *buffer=currSpr->y2; buffer++;
      *buffer=z; buffer++;
      *buffer=currSpr->tx2; buffer++;
      *buffer=currSpr->ty2; buffer++;
 
      // remember this chunk
      thisChunk.vertexCount+=6;
      currSpr++;
      if (currSpr==endSpr || thisChunk.texHandle!=currSpr->texHandle)
      {
         chunks.push_back(thisChunk);
         if (currSpr!=endSpr)
         {
            thisChunk.texHandle=currSpr->texHandle;
            thisChunk.vertexCount=0;
         }
      }
   }
 
   hardwareBuffer->unlock();
 
   // set up...
   prepareForRender();
 
   // do the real render!
   Ogre::TexturePtr tp;
   std::list<VertexChunk>::iterator currChunk, endChunk;
 
   endChunk=chunks.end();
   renderOp.vertexData->vertexStart=0;
   for (currChunk=chunks.begin(); currChunk!=endChunk; currChunk++)
   {
      renderOp.vertexData->vertexCount=currChunk->vertexCount;
      tp=Ogre::TextureManager::getSingleton().getByHandle(currChunk->texHandle);
      rs->_setTexture(0, true, tp->getName());
      rs->_render(renderOp);
      renderOp.vertexData->vertexStart+=currChunk->vertexCount;
   }
 
   // sprites go home!
   sprites.clear();
}
Exemplo n.º 15
0
// void TerrainPageSurfaceCompiler::addTextureUnitsToPass(Ogre::Pass* pass, const Ogre::String& splatTextureName) {
//
// 	if (getMaxTextureUnits() - pass->getNumTextureUnitStates() < 2 || pass->getParent()->getNumPasses() > 1)  {
// 		addPassToTechnique(pass->getParent(), splatTextureName);
// // 		S_LOG_WARNING("Trying to add texture units to pass with too few available texture unit states.");
// 		return;
// 	}
//
// 	S_LOG_VERBOSE("Adding new texture unit (detailtexture: " << mTextureName << " alphatexture: " << splatTextureName << ") to pass nr " << pass->getIndex() << " in technique for material " << pass->getParent()->getParent()->getName());
//
// /*	pass->setSelfIllumination(Ogre::ColourValue(1,1,1));
// 	pass->setAmbient(Ogre::ColourValue(1,1,1));
// 	pass->setDiffuse(Ogre::ColourValue(1,1,1));
// 	pass->setLightingEnabled(true);*/
// 	Ogre::TextureUnitState * textureUnitStateSplat = pass->createTextureUnitState();
//     textureUnitStateSplat->setTextureName(splatTextureName);
//
//     textureUnitStateSplat->setTextureCoordSet(0);
// 	textureUnitStateSplat->setTextureFiltering(Ogre::TFO_ANISOTROPIC);
// 	textureUnitStateSplat->setAlphaOperation(Ogre::LBX_SOURCE1, Ogre::LBS_TEXTURE, Ogre::LBS_TEXTURE);
// 	textureUnitStateSplat->setColourOperationEx(Ogre::LBX_SOURCE1, Ogre::LBS_CURRENT, Ogre::LBS_CURRENT);
//     textureUnitStateSplat->setTextureAddressingMode(Ogre::TextureUnitState::TAM_CLAMP);
// // 	textureUnitStateSplat->setColourOperationEx(Ogre::LBX_BLEND_DIFFUSE_ALPHA, Ogre::LBS_CURRENT, Ogre::LBS_TEXTURE);
// //	textureUnitStateSplat->setColourOperationEx(Ogre::LBX_BLEND_TEXTURE_ALPHA, Ogre::LBS_CURRENT, Ogre::LBS_TEXTURE);
//
// 	Ogre::TextureUnitState * textureUnitState = pass->createTextureUnitState();
//     textureUnitState->setTextureName(mTextureName);
//     textureUnitState->setTextureAddressingMode(Ogre::TextureUnitState::TAM_WRAP);
// /*	textureUnitState->setTextureCoordSet(0);*/
// 	textureUnitState->setTextureScale(0.025, 0.025);
// 	textureUnitState->setColourOperationEx(Ogre::LBX_BLEND_CURRENT_ALPHA, Ogre::LBS_TEXTURE, Ogre::LBS_CURRENT);
//
// /*	Ogre::TextureUnitState * alphaTextureState= pass->createTextureUnitState();
//     alphaTextureState->setTextureName(mTextureName);
// //     alphaTextureState->setTextureName(splatTextureName);
//     alphaTextureState->setTextureCoordSet(0);
// 	alphaTextureState->setTextureFiltering(Ogre::TFO_ANISOTROPIC);
//     alphaTextureState->setTextureAddressingMode(Ogre::TextureUnitState::TAM_CLAMP);
//  	alphaTextureState->setColourOperationEx(Ogre::LBX_BLEND_DIFFUSE_ALPHA, Ogre::LBS_CURRENT, Ogre::LBS_TEXTURE);
//
//
//
// // 	detailTextureState->setAlphaOperation(Ogre::LBX_SOURCE1, Ogre::LBS_TEXTURE, Ogre::LBS_TEXTURE);
// // 	detailTextureState->setColourOperationEx(Ogre::LBX_SOURCE1, Ogre::LBS_CURRENT, Ogre::LBS_CURRENT);
//
// 	Ogre::TextureUnitState * detailTextureState  = pass->createTextureUnitState();
//     detailTextureState ->setTextureName(splatTextureName);
// //     detailTextureState ->setTextureName(mTextureName);
//     detailTextureState ->setTextureAddressingMode(Ogre::TextureUnitState::TAM_WRAP);
// 	detailTextureState ->setTextureCoordSet(0);
// 	detailTextureState ->setTextureScale(0.01, 0.01);
// 	//detailTextureState ->setColourOperationEx(Ogre::LBX_BLEND_CURRENT_ALPHA, Ogre::LBS_TEXTURE, Ogre::LBS_CURRENT);*/
//
// }
//
Ogre::Pass* Simple::addPassToTechnique(const TerrainPageGeometry& geometry, Ogre::Technique* technique, const Layer& layer, std::set<std::string>& managedTextures) const
{
	//check if we instead can reuse the existing pass
	// 	if (technique->getNumPasses() != 0) {
	// 		Ogre::Pass* pass = technique->getPass(technique->getNumPasses() - 1);
	// 		if (4 - pass->getNumTextureUnitStates() >= 2) {
	// 			//there's more than two texture units available, use those instead of creating a new pass
	// 			S_LOG_VERBOSE("Reusing existing pass. ("<< pass->getNumTextureUnitStates() << " of "<< mNumberOfTextureUnitsOnCard << " texture unit used)");
	// 			addTextureUnitsToPass(pass, splatTextureName);
	// 			return pass;
	// 		}
	//
	// 	}

	const OgreImage& ogreImage = *layer.blendMap;
	Ogre::Image image;

	image.loadDynamicImage(const_cast<unsigned char*>(ogreImage.getData()), ogreImage.getResolution(), ogreImage.getResolution(), 1, Ogre::PF_A8);

	std::stringstream splatTextureNameSS;
	splatTextureNameSS << "terrain_" << mPage.getWFPosition().x() << "_" << mPage.getWFPosition().y() << "_" << technique->getNumPasses();
	const Ogre::String splatTextureName(splatTextureNameSS.str());
	Ogre::TexturePtr blendMapTexture;
	if (Ogre::Root::getSingletonPtr()->getTextureManager()->resourceExists(splatTextureName)) {
		blendMapTexture = static_cast<Ogre::TexturePtr>(Ogre::Root::getSingletonPtr()->getTextureManager()->getByName(splatTextureName));
		blendMapTexture->loadImage(image);

		Ogre::HardwarePixelBufferSharedPtr hardwareBuffer(blendMapTexture->getBuffer());
		//blit the whole image to the hardware buffer
		Ogre::PixelBox sourceBox(image.getPixelBox());
		hardwareBuffer->blitFromMemory(sourceBox);
	} else {
		blendMapTexture = Ogre::Root::getSingletonPtr()->getTextureManager()->loadImage(splatTextureName, "General", image, Ogre::TEX_TYPE_2D, 0);
		managedTextures.insert(blendMapTexture->getName());
	}

	//we need to create the image, update it and then destroy it again (to keep the memory usage down)
	//	if (layer->getBlendMapTextureName() == "") {
	//		//no texture yet; let's create one
	//		layer->createBlendMapImage();
	//		layer->updateBlendMapImage(geometry);
	//		layer->createTexture();
	//	} else {
	//		//a texture exists, so we just need to update the image
	//		layer->updateBlendMapImage(geometry); //calling this will also update the texture since the method will blit the image onto it
	//	}

	Ogre::Pass* pass = technique->createPass();

	pass->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA);
	pass->setAmbient(1, 1, 1);
	pass->setDiffuse(1, 1, 1, 1);
	pass->setLightingEnabled(false);

	Ogre::TextureUnitState * textureUnitState = pass->createTextureUnitState();
	textureUnitState->setTextureName(layer.surfaceLayer.getDiffuseTextureName());
	textureUnitState->setTextureAddressingMode(Ogre::TextureUnitState::TAM_WRAP);
	textureUnitState->setTextureCoordSet(0);
	textureUnitState->setTextureScale(1.0f / layer.surfaceLayer.getScale(), 1.0f / layer.surfaceLayer.getScale());

	Ogre::TextureUnitState * textureUnitStateSplat = pass->createTextureUnitState();
	textureUnitStateSplat->setTextureName(blendMapTexture->getName());

	textureUnitStateSplat->setTextureCoordSet(0);
	textureUnitStateSplat->setTextureAddressingMode(Ogre::TextureUnitState::TAM_CLAMP);
	textureUnitStateSplat->setTextureFiltering(Ogre::TFO_ANISOTROPIC);
	//	textureUnitStateSplat->setAlphaOperation(Ogre::LBX_SOURCE1, Ogre::LBS_TEXTURE, Ogre::LBS_TEXTURE);
	textureUnitStateSplat->setAlphaOperation(Ogre::LBX_BLEND_DIFFUSE_COLOUR, Ogre::LBS_TEXTURE, Ogre::LBS_CURRENT);
	textureUnitStateSplat->setColourOperationEx(Ogre::LBX_SOURCE1, Ogre::LBS_CURRENT, Ogre::LBS_CURRENT);
	return pass;

}
Exemplo n.º 16
0
void MeshObject::loadMesh()
{
    try
    {
        Ogre::String resourceGroup = Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME;
        mesh = static_cast<Ogre::MeshPtr>(Ogre::MeshManager::getSingleton().create(meshName, resourceGroup));
        if(backgroundLoading)
        {
            mesh->setBackgroundLoaded(true);
            mesh->addListener(this);
            ticket = Ogre::ResourceBackgroundQueue::getSingleton().load(
                         Ogre::MeshManager::getSingletonPtr()->getResourceType(),
                         mesh->getName(),
                         resourceGroup,
                         false,
                         0,
                         0,
                         0);

            // try to load its textures in the background
            for(int i=0; i<mesh->getNumSubMeshes(); i++)
            {
                SubMesh *sm = mesh->getSubMesh(i);
                String materialName = sm->getMaterialName();
                Ogre::MaterialPtr mat = static_cast<Ogre::MaterialPtr>(Ogre::MaterialManager::getSingleton().getByName(materialName)); //, resourceGroup));
                if(mat.isNull()) continue;
                for(int tn=0; tn<mat->getNumTechniques(); tn++)
                {
                    Technique *t = mat->getTechnique(tn);
                    for(int pn=0; pn<t->getNumPasses(); pn++)
                    {
                        Pass *p = t->getPass(pn);
                        for(int tun=0; tun<p->getNumTextureUnitStates(); tun++)
                        {
                            TextureUnitState *tu = p->getTextureUnitState(tun);
                            String textureName = tu->getTextureName();
                            // now add this texture to the background loading queue
                            Ogre::TexturePtr tex = static_cast<Ogre::TexturePtr>(Ogre::TextureManager::getSingleton().create(textureName, resourceGroup));
                            tex->setBackgroundLoaded(true);
                            tex->addListener(this);
                            ticket = Ogre::ResourceBackgroundQueue::getSingleton().load(
                                         Ogre::TextureManager::getSingletonPtr()->getResourceType(),
                                         tex->getName(),
                                         resourceGroup,
                                         false,
                                         0,
                                         0,
                                         0);

                        }
                    }

                }
            }
        }

        if(!backgroundLoading)
            postProcess();
    }
    catch (Ogre::Exception* e)
    {
        LOG("exception while loading mesh: " + e->getFullDescription());
    }

}
Exemplo n.º 17
0
void ZoneListWidget::_createImages(ImageMap& retlist)
{
    retlist.clear();

    Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().createManual( "EntityTex",
                   Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D,
                   256, 256, 0, Ogre::PF_A8R8G8B8 , Ogre::TU_RENDERTARGET );

    Ogre::RenderTexture *rttTex = texture->getBuffer()->getRenderTarget();
    Ogre::SceneManager *mSceneMgr = Ogre::Root::getSingletonPtr()->createSceneManager("OctreeSceneManager", "EntityTexMgr");

    Ogre::Light *dirl = mSceneMgr->createLight("DisplayLight");
    dirl->setDirection(-1,-1,-1);
    dirl->setDiffuseColour(1,1,1);
    dirl->setType(Ogre::Light::LT_DIRECTIONAL);

    Ogre::Camera* RTTCam = mSceneMgr->createCamera("EntityCam");
    RTTCam->setNearClipDistance(0.01F);
    RTTCam->setFarClipDistance(0);
    RTTCam->setAspectRatio(1);
    RTTCam->setFOVy(Ogre::Degree(90));
    RTTCam->setPosition(0,0,1);
    RTTCam->lookAt(0,0,0);

    Ogre::Viewport *v = rttTex->addViewport( RTTCam );
    v->setClearEveryFrame( true );
    v->setBackgroundColour(Ogre::ColourValue(0,0,0,0));

    ModularZoneFactory* factory = dynamic_cast<ModularZoneFactory*>(OgitorsRoot::getSingletonPtr()->GetEditorObjectFactory("Modular Zone Object"));
    if(!factory)return;
    factory->loadZoneTemplates();
    ZoneInfoMap zoneTemplates = factory->getZoneTemplateMap();

    Ogre::Entity *mEntity;

    unsigned char dataptr[300 * 300 * 6];
    unsigned char *dataptr2;
    Ogre::PixelBox pb(256,256,1,Ogre::PF_A8R8G8B8, dataptr);

    EntityMap entities;
    ZoneInfoMap::iterator zi;
    for(zi=zoneTemplates.begin();zi!=zoneTemplates.end();++zi)
    {
        Ogre::String addstr = (*zi).second.mMesh;
        if(entities.find((*zi).first) == entities.end())
            entities.insert(EntityMap::value_type((*zi).first,addstr));
    }

    EntityMap::const_iterator ite = entities.begin();

    while(ite != entities.end())
    {
        Ogre::String addstr = ite->second;

        mEntity = mSceneMgr->createEntity("MZP_Preview", addstr);

        mSceneMgr->getRootSceneNode()->attachObject(mEntity);

        //TODO: It would be nice to retrieve a Preview Camera Position from
        //the .zone file
        //TODO: also render portal outlines clearly so that the user can see
        //how the zone is laid out
        Ogre::Vector3 vSize = mEntity->getBoundingBox().getCorner(Ogre::AxisAlignedBox::NEAR_RIGHT_TOP);//.getHalfSize();//============
        Ogre::Vector3 vCenter = mEntity->getBoundingBox().getCenter();

//FIXME ------ NICE PREVIEWS NEEDED - bigger

        vSize += Ogre::Vector3(vSize.z, vSize.z, vSize.z);

        float maxsize = std::max(std::max(vSize.x,vSize.y),vSize.z);

        //vSize = Ogre::Vector3(0, 0, maxsize * 1.1f) + vCenter;
        vSize = Ogre::Vector3(maxsize * 0.5f, vSize.y, maxsize * 0.5f) + vCenter;
        //vSize.x +=vSize.x/2;//Maybe test to see which is larger x/2 or z/2 and use that?
        //vSize.z +=vSize.x/2;
        //RTTCam->setProjectionType(Ogre::PT_ORTHOGRAPHIC);

        RTTCam->setPosition(vSize.x,vSize.y,vSize.z);
        RTTCam->lookAt(vCenter.x,vCenter.y,vCenter.z);

        rttTex->update();
        rttTex->copyContentsToMemory(pb, Ogre::RenderTarget::FB_FRONT);


        dataptr2 = new unsigned char[96 * 96 * 4];
        Ogre::PixelBox pb2(96,96,1,Ogre::PF_A8R8G8B8, dataptr2);
        Ogre::Image::scale(pb,pb2);

        addstr.erase(addstr.length() - 5, 5);
        retlist.insert(ImageMap::value_type((*ite).first, dataptr2));

        mEntity->detachFromParent();
        mSceneMgr->destroyEntity(mEntity);

        ite++;
    }

    rttTex->removeAllViewports();
    Ogre::Root::getSingletonPtr()->destroySceneManager(mSceneMgr);
    Ogre::TextureManager::getSingletonPtr()->unload(texture->getName());
    Ogre::TextureManager::getSingletonPtr()->remove(texture->getName());
}
Exemplo n.º 18
0
void RenderedTexture::renderTextures()
{
    //Set up RTT texture
    Ogre::TexturePtr renderTexture;
    if (renderTexture.isNull()) {
        renderTexture = Ogre::TextureManager::getSingleton().createManual(
            getUniqueID("RenderedEntityMaterial"), "EntityRenderer",
            Ogre::TEX_TYPE_2D, textureSize, textureSize, 0,
            Ogre::PF_A8R8G8B8, Ogre::TU_RENDERTARGET, 0);
    }
    renderTexture->setNumMipmaps(0);

    //Set up render target
    Ogre::RenderTexture* renderTarget = renderTexture->getBuffer()->getRenderTarget(); 
    renderTarget->setAutoUpdated(false);

    //Set up camera
    Ogre::SceneNode* camNode = sceneMgr->getSceneNode("EntityRenderer::cameraNode");
    Ogre::Camera* renderCamera = sceneMgr->createCamera(getUniqueID("EntityRendererCam"));
    camNode->attachObject(renderCamera);
    renderCamera->setLodBias(1000.0f);

    Ogre::Viewport* renderViewport = renderTarget->addViewport(renderCamera);
    renderViewport->setOverlaysEnabled(false);
    renderViewport->setClearEveryFrame(true);
    renderViewport->setShadowsEnabled(false);
    renderViewport->setBackgroundColour(Ogre::ColourValue(0.0f, 0.0f, 0.0f, 0.0f));

    //Set up scene node
    Ogre::SceneNode* node = sceneMgr->getSceneNode("EntityRenderer::renderNode");

    Ogre::SceneNode* oldSceneNode = entity->getParentSceneNode();
    if (oldSceneNode)
        oldSceneNode->detachObject(entity);
    node->attachObject(entity);
    node->setPosition(-entityCenter);

    //Set up camera FOV
    const Ogre::Real objDist = entityRadius * 100;
    const Ogre::Real nearDist = objDist - (entityRadius + 1); 
    const Ogre::Real farDist = objDist + (entityRadius + 1);

    renderCamera->setAspectRatio(1.0f);
    renderCamera->setFOVy(Ogre::Math::ATan(2.0 * entityRadius / objDist));
    renderCamera->setNearClipDistance(nearDist);
    renderCamera->setFarClipDistance(farDist);

    //Disable mipmapping (without this, masked textures look bad)
    Ogre::MaterialManager* mm = Ogre::MaterialManager::getSingletonPtr();
    Ogre::FilterOptions oldMinFilter = mm->getDefaultTextureFiltering(Ogre::FT_MIN);
    Ogre::FilterOptions oldMagFilter = mm->getDefaultTextureFiltering(Ogre::FT_MAG);
    Ogre::FilterOptions oldMipFilter = mm->getDefaultTextureFiltering(Ogre::FT_MIP);
    mm->setDefaultTextureFiltering(Ogre::FO_POINT, Ogre::FO_LINEAR,Ogre:: FO_NONE);

    //Disable fog
    Ogre::FogMode oldFogMode = sceneMgr->getFogMode();
    Ogre::ColourValue oldFogColor = sceneMgr->getFogColour();
    Ogre::Real oldFogDensity = sceneMgr->getFogDensity();
    Ogre::Real oldFogStart = sceneMgr->getFogStart();
    Ogre::Real oldFogEnd = sceneMgr->getFogEnd();
    sceneMgr->setFog(Ogre::FOG_NONE);

    // Get current status of the queue mode
    Ogre::SceneManager::SpecialCaseRenderQueueMode OldSpecialCaseRenderQueueMode =
        sceneMgr->getSpecialCaseRenderQueueMode();
    //Only render the entity
    sceneMgr->setSpecialCaseRenderQueueMode(Ogre::SceneManager::SCRQM_INCLUDE); 
    sceneMgr->addSpecialCaseRenderQueue(renderQueueGroup);

    Ogre::uint8 oldRenderQueueGroup = entity->getRenderQueueGroup();
    entity->setRenderQueueGroup(renderQueueGroup);
    bool oldVisible = entity->getVisible();
    entity->setVisible(true);
    float oldMaxDistance = entity->getRenderingDistance();
    entity->setRenderingDistance(0);

    //Calculate the filename hash used to uniquely identity this render
    std::string strKey = entityKey;
    char key[32] = {0};
    Ogre::uint32 i = 0;
    for (std::string::const_iterator it = entityKey.begin(); it != entityKey.end(); ++it) {
        key[i] ^= *it;
        i = (i+1) % sizeof(key);
    }
    for (i = 0; i < sizeof(key); ++i)
        key[i] = (key[i] % 26) + 'A';

    Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
        GetUserDir().string(), "FileSystem", "BinFolder");
    std::string fileNamePNG =
        "Rendered." + std::string(key, sizeof(key)) + '.' +
        Ogre::StringConverter::toString(textureSize) + ".png";

    //Attempt to load the pre-render file if allowed
    bool needsRegen = false;
    if (!needsRegen) {
        try{
            texture = Ogre::TextureManager::getSingleton().load(
                fileNamePNG, "BinFolder", Ogre::TEX_TYPE_2D, 0);
        } catch (...) {
            needsRegen = true;
        }
    }

    if (needsRegen) {
        //If this has not been pre-rendered, do so now

        //Position camera
        camNode->setPosition(0, 0, 0);
        // TODO camNode->setOrientation(Quaternion(yaw, Vector3::UNIT_Y) * Quaternion(-pitch, Vector3::UNIT_X));
        camNode->translate(Ogre::Vector3(0, 0, objDist), Ogre::Node::TS_LOCAL);
						
        renderTarget->update();

        //Save RTT to file
        renderTarget->writeContentsToFile((GetUserDir() / fileNamePNG).string());

        //Load the render into the appropriate texture view
        texture = Ogre::TextureManager::getSingleton().load(fileNamePNG, "BinFolder", Ogre::TEX_TYPE_2D, 0);

        ggTexture = ClientUI::GetTexture(GetUserDir() / fileNamePNG);
    }

    entity->setVisible(oldVisible);
    entity->setRenderQueueGroup(oldRenderQueueGroup);
    entity->setRenderingDistance(oldMaxDistance);
    sceneMgr->removeSpecialCaseRenderQueue(renderQueueGroup);
    // Restore original state
    sceneMgr->setSpecialCaseRenderQueueMode(OldSpecialCaseRenderQueueMode); 

    //Re-enable mipmapping
    mm->setDefaultTextureFiltering(oldMinFilter, oldMagFilter, oldMipFilter);

    //Re-enable fog
    sceneMgr->setFog(oldFogMode, oldFogColor, oldFogDensity, oldFogStart, oldFogEnd);

    //Delete camera
    renderTarget->removeViewport(0);
    renderCamera->getSceneManager()->destroyCamera(renderCamera);

    //Delete scene node
    node->detachAllObjects();
    if (oldSceneNode)
        oldSceneNode->attachObject(entity);

    //Delete RTT texture
    assert(!renderTexture.isNull());
    std::string texName2(renderTexture->getName());

    renderTexture.setNull();
    if (Ogre::TextureManager::getSingletonPtr())
        Ogre::TextureManager::getSingleton().remove(texName2);
}
Exemplo n.º 19
0
    // ----------------------------------------------------------------------
    void FontSerializer::importFont(Ogre::DataStreamPtr &stream, Font *pDest)
    {
        uint32 fccomp;
        stream->read(&fccomp, sizeof(uint32));
        if(fccomp != Font::mFourCC)
            SONETTO_THROW("Invalid Font File");
        stream->read(&pDest->mVersion, sizeof(uint32));
        stream->read(&pDest->mEncode, sizeof(uint32));
        stream->read(&pDest->mVerticalOffsetTop, sizeof(float));
        stream->read(&pDest->mVerticalOffsetBottom, sizeof(float));
        stream->read(&pDest->mHorizontalScale, sizeof(float));

        pDest->mIName = loadString(stream);

        // setup material
        pDest->mMaterial = Ogre::MaterialManager::getSingleton().create(pDest->mIName+"_mat",pDest->getGroup());

        if(pDest->mMaterial.isNull())
            SONETTO_THROW("Unable to create material for font.");

        Ogre::Pass * pass = pDest->mMaterial->getTechnique(0)->getPass(0);

        bool has_separate_blend;
        uint32 mat_scene_blend_source;
        uint32 mat_scene_blend_dest;
        uint32 mat_scene_blend_source_a;
        uint32 mat_scene_blend_dest_a;
        stream->read(&has_separate_blend, sizeof(bool));
        stream->read(&mat_scene_blend_source, sizeof(uint32));
        stream->read(&mat_scene_blend_dest, sizeof(uint32));
        stream->read(&mat_scene_blend_source_a, sizeof(uint32));
        stream->read(&mat_scene_blend_dest_a, sizeof(uint32));

        if(has_separate_blend)
        {
            pass->setSeparateSceneBlending( (Ogre::SceneBlendFactor)mat_scene_blend_source,
                                            (Ogre::SceneBlendFactor)mat_scene_blend_dest,
                                            (Ogre::SceneBlendFactor)mat_scene_blend_source_a,
                                            (Ogre::SceneBlendFactor)mat_scene_blend_dest_a);
        } else {
            pass->setSceneBlending((Ogre::SceneBlendFactor)mat_scene_blend_source,(Ogre::SceneBlendFactor)mat_scene_blend_dest);
        }
        uint32 mat_alpha_reject_func;
        uint8 mat_alpha_reject_val;
        bool map_alpha_reject_atc;
        stream->read(&mat_alpha_reject_func, sizeof(uint32));
        stream->read(&mat_alpha_reject_val, sizeof(uint8));
        stream->read(&map_alpha_reject_atc, sizeof(bool));

        pass->setAlphaRejectSettings((Ogre::CompareFunction) mat_alpha_reject_func, mat_alpha_reject_val, map_alpha_reject_atc);

        pass->setDepthCheckEnabled(false);
        pass->setDepthWriteEnabled(false);
        pass->setLightingEnabled(false);

        Ogre::TextureUnitState * tex_unit = pass->createTextureUnitState();

        uint32 tex_address_mode_u;
        uint32 tex_address_mode_v;
        uint32 tex_address_mode_w;
        uint32 tex_filtering_min;
        uint32 tex_filtering_mag;
        Ogre::ColourValue tex_border_color;
        stream->read(&tex_address_mode_u, sizeof(uint32));
        stream->read(&tex_address_mode_v, sizeof(uint32));
        stream->read(&tex_address_mode_w, sizeof(uint32));
        stream->read(&tex_filtering_min, sizeof(uint32));
        stream->read(&tex_filtering_mag, sizeof(uint32));
        stream->read(tex_border_color.ptr(), sizeof(float) * 4);

        tex_unit->setTextureAddressingMode( (Ogre::TextureUnitState::TextureAddressingMode) tex_address_mode_u,
                                            (Ogre::TextureUnitState::TextureAddressingMode) tex_address_mode_v,
                                            (Ogre::TextureUnitState::TextureAddressingMode) tex_address_mode_w);
        tex_unit->setTextureFiltering((Ogre::FilterOptions)tex_filtering_min, (Ogre::FilterOptions)tex_filtering_mag, Ogre::FO_NONE);
        tex_unit->setTextureBorderColour(tex_border_color);

        uint32 numcol = 0;
        stream->read(&numcol, sizeof(uint32));
        for(uint32 l = 0; l != numcol; ++l)
        {
            std::cout << "reading color #"<<l<<"...\n";
            Ogre::ColourValue color;
            stream->read(color.ptr(), sizeof(float) * 4);
            pDest->mColorList.push_back(color);
            std::cout << "color #"<<l<<" read complete...\n";
        }
        std::cout << "all color values have been read correctly...\n";
        std::cout << "reading font glyph list...\n";
        for(uint16 i = 0; i != 256; ++i)
        {
            std::cout << "reading glyph #"<<(int)i<<"...\n";
            FontGlyph glyph;
            stream->read(&glyph, sizeof(FontGlyph));
            pDest->mGlyph.push_back(glyph);
            std::cout << "glyph #"<<(int)i<<" read complete...\n";
        }
        std::cout << "all font glyph have been read correctly...\n";
        // size_t width, size_t height, size_t depth, size_t pixel format
        size_t txt_width, txt_height, txt_depth, txt_pixelformat, txt_faces, txt_mipmaps = 0;
        stream->read(&txt_width, sizeof(size_t));
        stream->read(&txt_height, sizeof(size_t));
        stream->read(&txt_depth, sizeof(size_t));
        stream->read(&txt_pixelformat, sizeof(size_t));
        stream->read(&txt_faces, sizeof(size_t));
        stream->read(&txt_mipmaps, sizeof(size_t));

        std::cout <<
        "Loading Font Texture Data...\n"
        "Texture Width: "<<txt_width<<"\n"
        "Texture Height: "<<txt_height<<"\n"
        "Texture Depth: "<<txt_depth<<"\n"
        "Texture Pixel Format: "<<txt_pixelformat<<"\n"
        "Texture Faces: "<<txt_faces<<"\n"
        "Texture Mipmaps: "<<txt_mipmaps<<"\n";

        pDest->mFontImage = new Ogre::Image();

        size_t totalimagesize = Ogre::Image::calculateSize(txt_mipmaps, txt_faces, txt_width, txt_height, txt_depth, (Ogre::PixelFormat)txt_pixelformat);

        std::cout << "Current position at file: "<<stream->tell()<<"\n"
        "Target Image Size: "<<totalimagesize<<"\n"
        "Remaining File Size: "<<stream->size()<<"\n";

        unsigned char * imgbuffer = new unsigned char [totalimagesize];

        stream->read(imgbuffer, totalimagesize);

        pDest->mFontImage->loadDynamicImage(imgbuffer, txt_width, txt_height, txt_depth, (Ogre::PixelFormat)txt_pixelformat, true, txt_faces, txt_mipmaps);

        Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().loadImage(pDest->mIName+"_tex",pDest->getGroup(), *pDest->mFontImage, Ogre::TEX_TYPE_2D, 0);

        tex_unit->setTextureName(texture->getName(), Ogre::TEX_TYPE_2D);
    }
Exemplo n.º 20
0
void AerialMapDisplay::assembleScene() {
  if (!dirty_) {
    return; //  nothing to update
  }
  dirty_ = false;
  
  if (!loader_) {
    return; //  no tiles loaded, don't do anything
  }
  
  //  get rid of old geometry, we will re-build this
  clearGeometry();
  
  //  iterate over all tiles and create an object for each of them
  const double resolution = loader_->resolution();
  const std::vector<TileLoader::MapTile> &tiles = loader_->tiles();
  for (const TileLoader::MapTile &tile : tiles) {
    const int w = tile.image().width();
    const int h = tile.image().height();
    //  we here assume that the tiles are uniformly sized...
    const double tileW = w * resolution;
    const double tileH = h * resolution;
    const double origin_x = -loader_->originX() * tileW;
    const double origin_y = -(1 - loader_->originY()) * tileH;

    //  determine location of this tile
    const double x = (tile.x() - loader_->tileX()) * tileW + origin_x;
    const double y = -(tile.y() - loader_->tileY()) * tileH + origin_y;
    //  don't re-use any ids
    const std::string name_suffix =
        std::to_string(tile.x()) + "_" + std::to_string(tile.y()) + "_" +
        std::to_string(map_id_) + "_" + std::to_string(scene_id_);

    Ogre::TexturePtr tex;
    if (tile.hasImage()) {
      //  one material per texture
      std::string matName = "material_" + name_suffix;
      Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().create(
          matName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
      material->setReceiveShadows(false);
      material->getTechnique(0)->setLightingEnabled(false);
      material->setDepthBias(-16.0f,
                             0.0f); /// @todo: what the f**k does this do?
      material->setCullingMode(Ogre::CULL_NONE);
      material->setDepthWriteEnabled(false);

      //  create textureing unit
      Ogre::Pass *pass = material->getTechnique(0)->getPass(0);
      Ogre::TextureUnitState *tex_unit = NULL;
      if (pass->getNumTextureUnitStates() > 0) {
        tex_unit = pass->getTextureUnitState(0);
      } else {
        tex_unit = pass->createTextureUnitState();
      }

      //  only add if we have a texture for it
      tex = textureFromImage(tile.image(), "texture_" + name_suffix);

      ROS_INFO("Rendering with texture: %s", tex->getName().c_str());
      tex_unit->setTextureName(tex->getName());
      tex_unit->setTextureFiltering(Ogre::TFO_BILINEAR);

      //  create an object
      const std::string obj_name = "object_" + name_suffix;
      Ogre::ManualObject *obj = scene_manager_->createManualObject(obj_name);
      scene_node_->attachObject(obj);

      //  configure depth & alpha properties
      if (alpha_ >= 0.9998) {
        material->setDepthWriteEnabled(!draw_under_);
        material->setSceneBlending(Ogre::SBT_REPLACE);
      } else {
        material->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA);
        material->setDepthWriteEnabled(false);
      }

      if (draw_under_) {
        obj->setRenderQueueGroup(Ogre::RENDER_QUEUE_4);
      } else {
        obj->setRenderQueueGroup(Ogre::RENDER_QUEUE_MAIN);
      }

      tex_unit->setAlphaOperation(Ogre::LBX_SOURCE1, Ogre::LBS_MANUAL,
                                  Ogre::LBS_CURRENT, alpha_);

      //  create a quad for this tile
      obj->begin(material->getName(), Ogre::RenderOperation::OT_TRIANGLE_LIST);

      //  bottom left
      obj->position(x, y, 0.0f);
      obj->textureCoord(0.0f, 0.0f);
      obj->normal(0.0f, 0.0f, 1.0f);

      // top right
      obj->position(x + tileW, y + tileH, 0.0f);
      obj->textureCoord(1.0f, 1.0f);
      obj->normal(0.0f, 0.0f, 1.0f);

      // top left
      obj->position(x, y + tileH, 0.0f);
      obj->textureCoord(0.0f, 1.0f);
      obj->normal(0.0f, 0.0f, 1.0f);

      //  bottom left
      obj->position(x, y, 0.0f);
      obj->textureCoord(0.0f, 0.0f);
      obj->normal(0.0f, 0.0f, 1.0f);

      // bottom right
      obj->position(x + tileW, y, 0.0f);
      obj->textureCoord(1.0f, 0.0f);
      obj->normal(0.0f, 0.0f, 1.0f);

      // top right
      obj->position(x + tileW, y + tileH, 0.0f);
      obj->textureCoord(1.0f, 1.0f);
      obj->normal(0.0f, 0.0f, 1.0f);

      obj->end();

      if (draw_under_property_->getValue().toBool()) {
        //  render under everything else
        obj->setRenderQueueGroup(Ogre::RENDER_QUEUE_4);
      }

      MapObject object;
      object.object = obj;
      object.texture = tex;
      object.material = material;
      objects_.push_back(object);
    }
  }
  scene_id_++;
}
Exemplo n.º 21
0
void
    GraphicsController::addTextureToDebugOverlay(Ogre::TexturePtr tex)
{
    addTextureDebugOverlay(tex->getName(), 0); //0 is wrong, should be current debug idx.
}
Exemplo n.º 22
0
void GraphicsController::addTextureDebugOverlay(Ogre::TexturePtr tex, size_t i)
{
    addTextureDebugOverlay(tex->getName(), i);
}