Esempio n. 1
0
SimpleRenderContext::SimpleRenderContext(const std::string& prefix, Ogre::TexturePtr texture) :
		mMainLight(0), mSceneManager(0), mWidth(texture->getWidth()), mHeight(texture->getHeight()), mRenderTexture(0), mCameraNode(0), mCameraPitchNode(0), mEntityNode(0), mRootNode(0), mCamera(0), mViewPort(0), mResourceLoader(*this), mBackgroundColour(Ogre::ColourValue::Black), mCameraPositionMode(CPM_OBJECTCENTER), mTextureOwned(false)
{

	setupScene(prefix);
	setTexture(texture);

	Ogre::Real aspectRatio = static_cast<float>(texture->getWidth()) / static_cast<float>(texture->getHeight());

	S_LOG_VERBOSE("Setting aspect ratio of camera to " << aspectRatio);
	mCamera->setAspectRatio(aspectRatio);

}
Esempio n. 2
0
 void ReliefApp::GenerateRelief()
 {
     //Get depth data
     Ogre::TexturePtr depthTex = Ogre::TextureManager::getSingleton().createManual(  
         "DepthTexture",      // name   
         Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,  
         Ogre::TEX_TYPE_2D,   // type   
         512,  // width   
         512,  // height   
         0,                   // number of mipmaps   
         //Ogre::PF_B8G8R8A8,   // pixel format
         Ogre::PF_FLOAT32_R,
         Ogre::TU_RENDERTARGET
         ); 
     Ogre::RenderTarget* pTarget = depthTex->getBuffer()->getRenderTarget();
     Ogre::Camera* pOrthCam = MagicCore::RenderSystem::GetSingleton()->GetMainCamera();
     pOrthCam->setProjectionType(Ogre::PT_ORTHOGRAPHIC);
     pOrthCam->setOrthoWindow(3, 3);
     pOrthCam->setPosition(0, 0, 3);
     pOrthCam->lookAt(0, 0, 0);
     pOrthCam->setAspectRatio(1.0);
     pOrthCam->setNearClipDistance(0.5);
     pOrthCam->setFarClipDistance(5);
     Ogre::Viewport* pViewport = pTarget->addViewport(pOrthCam);
     pViewport->setDimensions(0, 0, 1, 1);
     MagicCore::RenderSystem::GetSingleton()->RenderLightMesh3D("RenderMesh", "Depth", mpLightMesh);
     MagicCore::RenderSystem::GetSingleton()->Update();
     Ogre::Image img;
     depthTex->convertToImage(img);
     std::vector<double> heightField(512 * 512);
     for(int x = 0; x < 512; x++)  
     {  
         for(int y = 0; y < 512; y++)  
         {
             heightField.at(x * 512 + y) = (img.getColourAt(x, 511 - y, 0))[1];
         }
     }
     Ogre::TextureManager::getSingleton().remove("DepthTexture");
     //
     MagicDGP::LightMesh3D* pReliefMesh = MagicDGP::ReliefGeneration::PlaneReliefFromHeightField(heightField, 511, 511);
     //MagicDGP::LightMesh3D* pReliefMesh = MagicDGP::ReliefGeneration::CylinderReliefFromHeightField(heightField, 511, 511);
     if (pReliefMesh != NULL)
     {
         delete mpLightMesh;
         mpLightMesh = pReliefMesh;
         mpLightMesh->UnifyPosition(2);
         mpLightMesh->UpdateNormal();
     }
     MagicCore::RenderSystem::GetSingleton()->SetupCameraDefaultParameter();
     MagicCore::RenderSystem::GetSingleton()->RenderLightMesh3D("RenderMesh", "MyCookTorrance", mpLightMesh);
 }
Esempio n. 3
0
void EC_RttTarget::PrepareRtt()
{
    if (!ViewEnabled())
        return;

    //\todo XXX reconfig via AttributeUpdated when these change
    int x = width.Get();
    int y = height.Get();

    // Get the camera ec
    EC_Camera *ec_camera = ParentEntity()->GetComponent<EC_Camera>().get();
    if (!ec_camera)
    {
        LogInfo("No camera for rtt.");
        return; //XXX note: doesn't reschedule, so won't start working if cam added afterwards
    }

    ec_camera->GetCamera()->setAspectRatio(Ogre::Real(x) / Ogre::Real(y));

    Ogre::TexturePtr tex = Ogre::TextureManager::getSingleton().getByName(textureName.Get().toStdString());
    if (tex.isNull())
    {
        tex = Ogre::TextureManager::getSingleton().createManual(textureName.Get().toStdString(),
            Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D, x, y, 0,
            Ogre::PF_A8R8G8B8, Ogre::TU_RENDERTARGET);
    }

    Ogre::RenderTexture *render_texture = tex->getBuffer()->getRenderTarget();
    if (render_texture)
    {
        render_texture->removeAllViewports();
        Ogre::Viewport *vp = 0;
        vp = render_texture->addViewport(ec_camera->GetCamera());
        // Exclude ui overlays
        vp->setOverlaysEnabled(false);
        // Exclude highlight mesh from rendering
        vp->setVisibilityMask(0x2);

        render_texture->update(false);
        tex->getBuffer()->getRenderTarget()->setAutoUpdated(false); 
    }
    else
        LogError("render target texture getting failed.");

    //create material to show the texture
    material_name_ = textureName.Get().toStdString() + "_mat"; //renderer_.lock()->GetUniqueObjectName("EC_BillboardWidget_mat");
    OgreRenderer::CloneMaterial("HoveringText", material_name_); //would LitTextured be the right thing? XXX \todo
    Ogre::MaterialManager &material_manager = Ogre::MaterialManager::getSingleton();
    Ogre::MaterialPtr material = material_manager.getByName(material_name_);
    OgreRenderer::SetTextureUnitOnMaterial(material, textureName.Get().toStdString());
}
Esempio n. 4
0
int GUIHelper::getTextureHeight(const Ogre::String &materialName)
{
	Ogre::MaterialPtr mat = Ogre::MaterialManager::getSingleton().getByName(materialName);
	if(mat.isNull() || /*!mat->getTechnique(0) ||
			!mat->getTechnique(0)->getPass(0) ||*/
			!mat->getTechnique(0)->getPass(0)->getTextureUnitState(0))
		return -1;

	Ogre::TexturePtr text = Ogre::TextureManager::getSingleton().getByName(
			mat->getTechnique(0)->getPass(0)->getTextureUnitState(
					0)->getTextureName());
	if(text.isNull()) return -1;
	return text->getHeight();
}
Esempio n. 5
0
 Ogre::MaterialPtr GetOrCreateLegacyMaterial(const std::string& texture_name, uint variation)
 {
     if (variation >= MAX_MATERIAL_VARIATIONS)
     {
         OgreRenderingModule::LogWarning("Requested suffix for non-existing material variation " + ToString<uint>(variation));
         variation = 0;
     }
     const std::string& suffix = MaterialSuffix[variation];
     
     Ogre::TextureManager &tm = Ogre::TextureManager::getSingleton();
     Ogre::MaterialManager &mm = Ogre::MaterialManager::getSingleton();
     
     std::string material_name = texture_name + suffix;
     Ogre::MaterialPtr material = mm.getByName(material_name);
     
     if (!material.get())
     {
         material = mm.create(material_name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
         assert(material.get());
     }
     else
         return material;
     
     Ogre::TexturePtr tex = tm.getByName(texture_name);
     bool has_alpha = false;
     if (!tex.isNull())
     {
         // As far as the legacy materials are concerned, DXT1 is not alpha
         if (tex->getFormat() == Ogre::PF_DXT1)
             has_alpha = false;
         else if (Ogre::PixelUtil::hasAlpha(tex->getFormat()))
             has_alpha = true;
     }
     
     Ogre::MaterialPtr base_material;
     if (!has_alpha)
         base_material = mm.getByName(BaseMaterials[variation]);
     else
         base_material = mm.getByName(AlphaBaseMaterials[variation]);
     if (!base_material.get())
     {
         OgreRenderingModule::LogError("Could not find " + MaterialSuffix[variation] + " base material for " + texture_name);
         return Ogre::MaterialPtr();
     }
     
     base_material->copyDetailsTo(material);
     SetTextureUnitOnMaterial(material, texture_name, 0);
     
     return material;
 }
Esempio n. 6
0
void PlayState::enter()
{
    mLuaState = lua_open();
    luaL_openlibs(mLuaState);
    luabind::open(mLuaState);
    LuaBinding binder(mLuaState);
    binder.bindLua();

    mKeyboard = InputManager::getSingletonPtr()->getKeyboard();
    mMouse = InputManager::getSingletonPtr()->getMouse();
    mRoot = Root::getSingletonPtr();
    mSoundMgr = SoundManager::getSingletonPtr();
    mGUI = 0;
    mViewport = 0;
    //mCurrentLevel = 0;
    createSounds();
    mContinue = true;
    mRotate = 0.13;
    mFriendScore = 0;
    mFocusActor = 0;
    mRivalScore = 0;
    mFriendLastScore = 0;
    mRivalLastScore = 0;
    firstConsoleInit = true;

    Ogre::ShadowTextureManager::getSingletonPtr()->clear();
    mSceneMgr = mRoot->createSceneManager(Ogre::ST_EXTERIOR_CLOSE, "Default SceneManager");
    mSceneMgr->setShadowTechnique(SHADOWTYPE_NONE);

    DotLevelLoader loader(mLuaState);
    loader.parseLevels("game.levels", mLevels);
    createScene();

    mViewport = mRoot->getAutoCreatedWindow()->addViewport(mCamera);
    initPlayerCam();
    mViewport->setBackgroundColour(ColourValue(0.0, 0.0, 0.0));

    initGUI();

    mWindow = mRoot->getAutoCreatedWindow();

    Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().createManual("RttTex",
                               ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, TEX_TYPE_2D, mWindow->getWidth(), mWindow->getHeight(), 0, PF_R8G8B8,
                               TU_RENDERTARGET);

    mRenderTexture = texture->getBuffer()->getRenderTarget();
    mRenderTexture->addViewport(mCamera);
    mRenderTexture->getViewport(0)->setBackgroundColour(ColourValue::Black);
    mRenderTexture->getViewport(0)->setOverlaysEnabled(true);
}
Esempio n. 7
0
/****************************************************************************
**
** Copyright (C) 2016 - 2017
**
** This file is part of the Magus toolkit
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
****************************************************************************/

#include "constants.h"
#include "texturelayer.h"
#include "OgreHlmsPbs.h"
#include "OgreHlmsManager.h"
#include "OgreLogManager.h"
#include "OgreStringConverter.h"
#include <fstream>
#include <ctime>

//****************************************************************************/
TextureLayer::TextureLayer(void) :
    mTextureOnWhichIsPaintedWidth(0),
    mTextureOnWhichIsPaintedHeight(0),
    mTextureOnWhichIsPaintedHasAlpha(false),
    mNumMipMaps(0),
    mTextureTypeDefined(false),
    mMaxSequence(0)
{
    mTextureType = Ogre::PBSM_DIFFUSE;
    mDatablockId = "";
    mTextureFileName = "";
}

//****************************************************************************/
TextureLayer::~TextureLayer(void)
{
}

//****************************************************************************/
void TextureLayer::setDatablockIdAndTexture (const Ogre::IdString& datablockId,
                                             Ogre::PbsTextureTypes textureType,
                                             const Ogre::String& textureFileName)
{
    mDatablockId = datablockId;
    mTextureType = textureType;
    mTextureFileName = textureFileName;
    mTextureTypeDefined = true;

    // Load the texture as image; assume it can be loaded, because it was already loaded as part of the material
    setFirstTextureGeneration();

    // Create the pixelbox of the original texture; this MUST be a separate image
    mOriginalTexture.load(textureFileName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
    mPixelboxOriginalTexture = mOriginalTexture.getPixelBox(0, 0);

    // Debug texture
    //Ogre::LogManager::getSingleton().logMessage("Debug texture: " + textureFileName);
    //Ogre::LogManager::getSingleton().logMessage("Depth: " + Ogre::StringConverter::toString(mOriginalTexture.getDepth()));
    //Ogre::LogManager::getSingleton().logMessage("Pixel format: " + Ogre::StringConverter::toString(mOriginalTexture.getFormat()));
    //Ogre::LogManager::getSingleton().logMessage("Alpha: " + Ogre::StringConverter::toString(mOriginalTexture.getHasAlpha()));
    //Ogre::LogManager::getSingleton().logMessage("Height: " + Ogre::StringConverter::toString(mOriginalTexture.getHeight()));
    //Ogre::LogManager::getSingleton().logMessage("Number of faces: " + Ogre::StringConverter::toString(mOriginalTexture.getNumFaces()));
    //Ogre::LogManager::getSingleton().logMessage("Number of mipmaps: " + Ogre::StringConverter::toString(mOriginalTexture.getNumMipmaps()));
    //Ogre::LogManager::getSingleton().logMessage("Width: " + Ogre::StringConverter::toString(mOriginalTexture.getWidth()));
}

//****************************************************************************/
void TextureLayer::blitTexture (void)
{
    /* Always get the actual pointers, because they may change. That is the reason why the datablock pointer cannot be cached.
     * The same seems to apply to the texture pointer.
     */
    Ogre::HlmsDatablock* datablock;
    Ogre::HlmsPbsDatablock* datablockPbs;
    Ogre::TexturePtr texture;
    Ogre::HlmsManager* hlmsManager = Ogre::Root::getSingletonPtr()->getHlmsManager();
    Ogre::HlmsPbs* hlmsPbs = static_cast<Ogre::HlmsPbs*>(hlmsManager->getHlms(Ogre::HLMS_PBS));
    datablock = hlmsPbs->getDatablock(mDatablockId);
    if (!datablock)
        return;

    datablockPbs = static_cast<Ogre::HlmsPbsDatablock*>(datablock);
    try
    {
        // Get texture on GPU
        if (!datablockPbs->getTexture(mTextureType).isNull())
        {
            texture = datablockPbs->getTexture(mTextureType); // TextureType MUST exist, otherwise the application crashes
            mNumMipMaps = texture->getNumMipmaps();
        }
    }
    catch (Ogre::Exception e){}

    if (texture.isNull())
        return;

    Ogre::uint8 maxMipMaps = mNumMipMaps + 1; // Increase with one, because there is always one image to blit
    maxMipMaps = maxMipMaps > PAINT_MAX_MIP_MAPS ? PAINT_MAX_MIP_MAPS : maxMipMaps; // Just paint a few mipmaps (not all)
    Ogre::Image textureOnWhichIsPaintedScaled = mTextureOnWhichIsPainted; // Temporary image must be used, otherwise painting doesn't work
    size_t w = mTextureOnWhichIsPaintedWidth;
    size_t h = mTextureOnWhichIsPaintedHeight;
    Ogre::v1::HardwarePixelBuffer* buffer;
    for (Ogre::uint8 i = 0; i < maxMipMaps; ++i)
    {
        buffer = texture->getBuffer(0, i).getPointer();
        buffer->blitFromMemory(textureOnWhichIsPaintedScaled.getPixelBox(0, 0), Ogre::Box(0, 0, 0, w, h, 1));
        w*=0.5f; // Mipmaps always are half of the previous one
        h*=0.5f;
        if (w < 1.0f || h < 1.0f)
            break; // Stop when the mipmaps are too small

        textureOnWhichIsPaintedScaled.resize(w, h);

    }
    textureOnWhichIsPaintedScaled.freeMemory();
}
Esempio n. 8
0
void RenderWindow::UpdateOverlayImage(const QImage &src)
{
    if (!overlay)
        return;

    PROFILE(RenderWindow_UpdateOverlayImage);

    Ogre::Box bounds(0, 0, src.width(), src.height());
    Ogre::PixelBox bufbox(bounds, Ogre::PF_A8R8G8B8, (void *)src.bits());

    Ogre::TextureManager &mgr = Ogre::TextureManager::getSingleton();
    Ogre::TexturePtr texture = mgr.getByName(rttTextureName);
    assert(texture.get());
    texture->getBuffer()->blitFromMemory(bufbox);
}
Esempio n. 9
0
TexturePair AssetsManager::createTextureImage(Ogre::TexturePtr texturePtr, const std::string& imageSetName)
{
	// 	if (mOgreCEGUITexture) {
	// 		GUIManager::getSingleton().getGuiRenderer()->destroyTexture(mOgreCEGUITexture);
	// 		mOgreCEGUITexture = 0;
	// 	}


	CEGUI::Imageset* textureImageset;

	if (CEGUI::ImagesetManager::getSingleton().isDefined(imageSetName)) {
		textureImageset = &CEGUI::ImagesetManager::getSingleton().get(imageSetName);
	} else {
		//create a CEGUI texture from our Ogre texture
		S_LOG_VERBOSE("Creating new CEGUI texture from Ogre texture.");
		CEGUI::Texture* ogreCEGUITexture = &GUIManager::getSingleton().getGuiRenderer()->createTexture(texturePtr);

		//we need a imageset in order to create GUI elements from the ceguiTexture
		S_LOG_VERBOSE("Creating new CEGUI imageset with name " << imageSetName);
		textureImageset = &CEGUI::ImagesetManager::getSingleton().create(imageSetName, *ogreCEGUITexture);

		//we only want one element: the whole texture
		textureImageset->defineImage("full_image", CEGUI::Rect(0, 0, texturePtr->getWidth(), texturePtr->getHeight()), CEGUI::Point(0, 0));
	}
	//assign our image element to the StaticImage widget
	const CEGUI::Image* textureImage = &textureImageset->getImage("full_image");

	return TexturePair(texturePtr, textureImage, textureImageset);

}
Esempio n. 10
0
	bool TextureManager::_createTexture(Ogre::TexturePtr &Texture, const Ogre::String &Name, const Size &Size)
	{
		try
		{
			Ogre::TextureManager::getSingleton().remove(Name);

			Texture = Ogre::TextureManager::getSingleton().
				createManual(Name,
				HYDRAX_RESOURCE_GROUP, 
				Ogre::TEX_TYPE_2D,
				Size.Width, Size.Height,
				0,
				Ogre::PF_BYTE_BGRA,
				Ogre::TU_DYNAMIC_WRITE_ONLY_DISCARDABLE);

			Texture->load();
		}
		catch(Ogre::Exception &e)
		{
			HydraxLOG(e.getFullDescription());

			return false;
		}

		return true;
	}
Esempio n. 11
0
void SimpleRenderContext::setTexture(Ogre::TexturePtr texture)
{
    if (texture != mTexture) {
        if (mRenderTexture) {
            mRenderTexture->removeAllViewports();
        }
        mTexture = texture;
        mRenderTexture = texture->getBuffer()->getRenderTarget();
        mRenderTexture->removeAllViewports();

        mRenderTexture->setAutoUpdated(false);
        //initially deactivate it until setActive(true) is called
        mRenderTexture->setActive(false);

        S_LOG_VERBOSE("Adding camera.");
        mViewPort = mRenderTexture->addViewport(mCamera);
        mViewPort->setOverlaysEnabled(false);
        mViewPort->setShadowsEnabled(false);
        //make sure the camera renders into this new texture
        //this should preferrably be a transparent background, so that CEGUI could itself decide what to show behind it, but alas I couldn't get it to work, thus black
        mViewPort->setBackgroundColour(mBackgroundColour);
        //	mViewPort->setBackgroundColour(Ogre::ColourValue::ZERO);
        //don't show the CEGUI
        mViewPort->setOverlaysEnabled(false);
        //the cegui renderer wants a TexturePtr (not a RenderTexturePtr), so we just ask the texturemanager for texture we just created (rttex)
    }
}
Esempio n. 12
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);
}
Esempio n. 13
0
 void OnPaint(CefRefPtr<CefBrowser> browser, PaintElementType type, const RectList &dirtyRects, const void *buffer, int width, int height)
 {
     Ogre::HardwarePixelBufferSharedPtr texBuf = m_renderTexture->getBuffer();
     texBuf->lock(Ogre::HardwareBuffer::HBL_DISCARD);
     memcpy(texBuf->getCurrentLock().data, buffer, width*height*4);
     texBuf->unlock();
 }
Esempio n. 14
0
 ITexture* getTexture(const std::string& _name)
 {
     MapTexture::const_iterator item = mTextures.find(_name);
     if (item == mTextures.end())
     {
         Ogre::TexturePtr texture = (Ogre::TexturePtr)Ogre::TextureManager::getSingleton().getByName(_name);
         if (!texture.isNull())
         {
             ITexture* result = createTexture(_name);
             static_cast<OgreTexture*>(result)->setOgreTexture(texture);
             return result;
         }
         return nullptr;
     }
     return item->second;
 }
Esempio n. 15
0
 Ogre::TexturePtr GetLocalTexture(const std::string& name)
 {
     Ogre::TextureManager& manager = Ogre::TextureManager::getSingleton();
     
     Ogre::TexturePtr tex = manager.getByName(name);
     if (tex.isNull())
     {
         try
         {
             manager.load(name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
             tex = manager.getByName(name);
         }
         catch(...) {}
     }
     
     return tex;
 }
Esempio n. 16
0
    void CreateLegacyMaterials(const std::string& texture_name, bool update)
    {
        Ogre::TextureManager &tm = Ogre::TextureManager::getSingleton();
        Ogre::MaterialManager &mm = Ogre::MaterialManager::getSingleton();
        
        Ogre::TexturePtr tex = tm.getByName(texture_name);
        bool has_alpha = false;
        if (!tex.isNull())
        {
            if (Ogre::PixelUtil::hasAlpha(tex->getFormat()))
                has_alpha = true;
        }
        
        // Early out: if texture does not yet exist and materials have already been created once
        if (((tex.isNull()) || (!update)) && (!mm.getByName(texture_name).isNull()))
            return;
        
        for (uint i = 0; i < MAX_MATERIAL_VARIATIONS; ++i)
        {
            const std::string& base_material_name = BaseMaterials[i];
            const std::string& alpha_base_material_name = AlphaBaseMaterials[i];
            
            std::string material_name = texture_name + MaterialSuffix[i];
            Ogre::MaterialPtr material = mm.getByName(material_name);

            if (!material.get())
            {
                material = mm.create(material_name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
                assert(material.get());
            }
            
            Ogre::MaterialPtr base_material;
            if (!has_alpha)
                base_material = mm.getByName(base_material_name);
            else
                base_material = mm.getByName(alpha_base_material_name);
            if (!base_material.get())
            {
                OgreRenderingModule::LogError("Could not find " + MaterialSuffix[i] + " base material for " + texture_name);
                return;
            }

            base_material->copyDetailsTo(material);
            SetTextureUnitOnMaterial(material, texture_name, 0);
        }
    }
Esempio n. 17
0
        skin::skin(const string &n):
            _name(n),
            _prefix("gui/skins/" + _name + "/" + _name)
        {
            txml::document doc;
            doc.LoadFile((engine::DATA_DIR + _prefix + ".xml").c_str());
            if (doc.Error())
            {
                engine::log("failed to load GUI skin " + _name);
                return;
            }

            txml::element *rootElem = doc.RootElement();

            for (txml::node *i = rootElem->FirstChild(); i; i = i->NextSibling())
            {
                pieceList &pl = _elements[i->Value()];

                for (txml::node *j = i->FirstChild(); j; j = j->NextSibling())
                {
                    txml::element *element = j->ToElement();
                    if (element)
                    {
                        piece &p = pl[element->Value()];
                        string tex = element->attrib<string>("image", string());

                        if (!tex.empty())
                        {
                            p.tex = "gui/skins/" + _name + "/" + tex;

                            Ogre::TexturePtr tex = gfx::getTexture(p.tex);
                            if (tex.get())
                                p.size = vec2(tex->getWidth(), tex->getHeight());
                            else
                                p.size = vec2(0, 0);
                        }
                        else
                        {
                            p.tex.clear();
                            p.size = vec2(0, 0);
                        }
                    }
                }
            }
        }
Esempio n. 18
0
void EC_WidgetCanvas::Update()
{
    if (framework->IsHeadless())
        return;

    if (!widget_.data() || texture_name_.empty())
        return;
    if (widget_->width() <= 0 || widget_->height() <= 0)
        return;

    try
    {
        Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().getByName(texture_name_);
        if (texture.isNull())
            return;

        if (buffer_.size() != widget_->size())
            buffer_ = QImage(widget_->size(), QImage::Format_ARGB32_Premultiplied);
        if (buffer_.width() <= 0 || buffer_.height() <= 0)
            return;

        QPainter painter(&buffer_);
        widget_->render(&painter);

        // Set texture to material
        if (update_internals_ && !material_name_.empty())
        {
            Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().getByName(material_name_);
            if (material.isNull())
                return;
            // Just for good measure, this is done once in the ctor already if everything went well.
            OgreRenderer::SetTextureUnitOnMaterial(material, texture_name_);
            UpdateSubmeshes();
            update_internals_ = false;
        }

        if ((int)texture->getWidth() != buffer_.width() || (int)texture->getHeight() != buffer_.height())
        {
            texture->freeInternalResources();
            texture->setWidth(buffer_.width());
            texture->setHeight(buffer_.height());
            texture->createInternalResources();
        }

        Blit(buffer_, texture);
    }
    catch (Ogre::Exception &e) // inherits std::exception
    {
        LogError("Exception occurred while blitting texture data from memory: " + std::string(e.what()));
    }
    catch (...)
    {
        LogError("Unknown exception occurred while blitting texture data from memory.");
    }
}
Esempio n. 19
0
void EC_WidgetCanvas::Update(QImage buffer)
{
    if (framework->IsHeadless())
        return;
    if (buffer.width() <= 0 || buffer.height() <= 0)
        return;

    if (buffer.format() != QImage::Format_ARGB32 && buffer.format() != QImage::Format_ARGB32_Premultiplied)
    {
        LogWarning("EC_WidgetCanvas::Update(QImage buffer): Input format needs to be Format_ARGB32 or Format_ARGB32_Premultiplied, preforming auto conversion!");
        buffer = buffer.convertToFormat(QImage::Format_ARGB32);
        if (buffer.isNull())
        {
            LogError("-- Auto conversion failed, not updating!");
            return;
        }
    }

    try
    {
        Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().getByName(texture_name_);
        if (texture.isNull())
            return;

        // Set texture to material if need be
        if (update_internals_ && !material_name_.empty())
        {
            Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().getByName(material_name_);
            if (material.isNull())
                return;
            // Just for good measure, this is done once in the ctor already if everything went well.
            OgreRenderer::SetTextureUnitOnMaterial(material, texture_name_);
            UpdateSubmeshes();
            update_internals_ = false;
        }

        if ((int)texture->getWidth() != buffer.width() || (int)texture->getHeight() != buffer.height())
        {
            texture->freeInternalResources();
            texture->setWidth(buffer.width());
            texture->setHeight(buffer.height());
            texture->createInternalResources();
        }

        Blit(buffer, texture);
    }
    catch (Ogre::Exception &e) // inherits std::exception
    {
        LogError("Exception occurred while blitting texture data from memory: " + std::string(e.what()));
    }
    catch (...)
    {
        LogError("Unknown exception occurred while blitting texture data from memory.");
    }
}
Esempio n. 20
0
void EMBOgre::createOgreTexture(EMBFile *file, size_t index) {
    string ogre_emb_name = name + "_";
    string emb_texture_name = file->getName();

    if (emb_texture_name.size()) {
        ogre_emb_name += emb_texture_name;
    }
    else {
        ogre_emb_name += ToString(index);
    }

    Ogre::DataStreamPtr data_stream(new EMBOgreDataStream(file));
    Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().createResource(ogre_emb_name, XENOVIEWER_RESOURCE_GROUP).staticCast<Ogre::Texture>();
    Ogre::Image image;
    image.load(data_stream, "DDS");
    texture->loadImage(image);

    ogre_textures[index] = texture;
}
Esempio n. 21
0
	void UiManager::renderIntoTexture(const Ogre::TexturePtr &aTexture)
	{
		assert(!aTexture.isNull());
		assert(isViewSizeMatching(aTexture));
		
		Ogre::HardwarePixelBufferSharedPtr hwBuffer = aTexture->getBuffer(0, 0);
		hwBuffer->lock(Ogre::HardwareBuffer::HBL_DISCARD);
		
		const Ogre::PixelBox &pb = hwBuffer->getCurrentLock();
		
		// render into texture buffer
		QImage textureImg((uchar *)pb.data, pb.getWidth(), pb.getHeight(), QImage::Format_ARGB32);
		textureImg.fill(0);
		
		QPainter painter(&textureImg);
		mWidgetView->render(&painter, QRect(QPoint(0, 0), mWidgetView->size()), QRect(QPoint(0, 0), mWidgetView->size()));
		
		hwBuffer->unlock();
	}
void GPGPUDemo::launch()
{
	// create rendertarget
	Ogre::TexturePtr tex = Ogre::TextureManager::getSingleton().createManual("Ogre/GPGPU/RT", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D, 512, 512, 0, Ogre::PF_R8G8B8A8, Ogre::TU_RENDERTARGET);

	// load material
	Ogre::MaterialPtr mat = Ogre::MaterialManager::getSingleton().getByName("GPGPUDemo");
	mat->load();

	Ogre::GPGPU::Root* gpgpu = new Ogre::GPGPU::Root;
	Ogre::GPGPU::Result* result = gpgpu->createResult(tex->getBuffer(0, 0));
	Ogre::GPGPU::Operation* op  = gpgpu->createOperation(mat->getTechnique(0)->getPass(0));

	Chrono chrono(true);
	for (unsigned int i=0; i<5000; ++i)
		gpgpu->compute(result, op);
	result->save("gpgpu_computing.png");
	std::cout << chrono.getTimeElapsed() << "ms [rendering+saving]" << std::endl;
}
Esempio n. 23
0
EC_WidgetCanvas::EC_WidgetCanvas(Scene *scene) :
    IComponent(scene),
    widget_(0),
    update_internals_(false),
    mesh_hooked_(false),
    refresh_timer_(0),
    update_interval_msec_(0),
    material_name_(""),
    texture_name_("")
{
    if (framework->IsHeadless())
        return;
	
	if (framework->Renderer())
    {
        // Create texture
        texture_name_ = framework->Renderer()->GetUniqueObjectName("EC_3DCanvas_tex");
        Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().createManual(
            texture_name_, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
            Ogre::TEX_TYPE_2D, 1, 1, 0, Ogre::PF_A8R8G8B8, 
            Ogre::TU_DYNAMIC_WRITE_ONLY_DISCARDABLE);
        if (texture.isNull())
        {
            LogError("EC_WidgetCanvas: Could not create texture for usage!");
            return;
        }

        // Create material: Make sure we have one tech with one pass with one texture unit.
        // Don't use our lit textured templates here as emissive will not work there as it has vertex etc programs in it.
        material_name_ = framework->Renderer()->GetUniqueObjectName("EC_3DCanvas_mat");
        Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().create(material_name_, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
        if (material->getNumTechniques() == 0)
            material->createTechnique();
        if (material->getTechnique(0) && 
            material->getTechnique(0)->getNumPasses() == 0)
            material->getTechnique(0)->createPass();
        if (material->getTechnique(0)->getPass(0) && 
            material->getTechnique(0)->getPass(0)->getNumTextureUnitStates() == 0)
            material->getTechnique(0)->getPass(0)->createTextureUnitState(texture_name_);        
    }

    connect(this, SIGNAL(ParentEntitySet()), SLOT(ParentEntitySet()), Qt::UniqueConnection);
}
Esempio n. 24
0
    void TerrainWeightEditor::ApplyWeightTexture()
    {
        if(!GetSceneManager())
            return;

        QImage map  = CreateImageFromCanvases();
        if(map.isNull())
            return;
        
        if(map.format() != QImage::Format_ARGB32)
        {
            map = map.convertToFormat(QImage::Format_ARGB32/*,Qt::NoOpaqueDetection*/);
        }
        Ogre::Box bounds(0, 0, map.width(), map.height());
        Ogre::PixelBox bufbox(bounds, Ogre::PF_A8R8G8B8, (void *)map.bits());
        Scene::EntityList list = scene_manager_->GetEntitiesWithComponent("EC_Terrain");
        Scene::EntityList::const_iterator it = list.begin();
        while(it!= list.end())
        {
            boost::shared_ptr<EC_Terrain> ptr = (*it)->GetComponent<EC_Terrain>();
            QString texname;
            texname += (*it)->GetName();
            texname += ptr->TypeName();
            texname += ptr->Name();
            texname += ".png";
            Ogre::String str(texname.toStdString());
            Ogre::TextureManager::getSingleton().remove(str);
            Ogre::TexturePtr tex = Ogre::TextureManager::getSingleton().createManual(str, "General", Ogre::TEX_TYPE_2D, bufbox.getWidth(), bufbox.getHeight(),bufbox.getDepth(),0,bufbox.format,Ogre::TU_DYNAMIC_WRITE_ONLY);
            if(tex.get())
            {
                tex->getBuffer()->blitFromMemory(bufbox);
            }
            ptr->texture0.Set(AssetReference(texname/*, "OgreTexture"*/), AttributeChange::Disconnected);
            it++;

            ///For now we just save this to assets folder. Later on, this should be replicated to server/clients etc.
            QImageWriter writer("data/assets/" + texname);
            writer.setCompression(0);
            writer.write(map);
            
        }
    }
Esempio n. 25
0
void TreeLoader2D::setColorMap(Ogre::TexturePtr map, MapChannel channel)
{
  if (colorMap) {
    colorMap->unload();
    colorMap = NULL;
  }
  if (map.isNull() == false) {
    colorMap = ColorMap::load(map, channel);
    colorMap->setFilter(colorMapFilter);
  }
}
Esempio n. 26
0
	ITexture* OgreRenderManager::getTexture(const std::string& _name)
	{
		MapTexture::const_iterator item = mTextures.find(_name);
		if (item == mTextures.end())
		{
#if (OGRE_VERSION < MYGUI_DEFINE_VERSION(1, 9, 0))
			Ogre::TexturePtr texture = (Ogre::TexturePtr)Ogre::TextureManager::getSingleton().getByName(_name);
#else
			Ogre::TexturePtr texture = (Ogre::TexturePtr)Ogre::TextureManager::getSingleton().getByName(_name).staticCast<Ogre::Texture>();
#endif
			if (!texture.isNull())
			{
				ITexture* result = createTexture(_name);
				static_cast<OgreTexture*>(result)->setOgreTexture(texture);
				return result;
			}
			return nullptr;
		}
		return item->second;
	}
Esempio n. 27
0
bool RocketInterface::GenerateTexture(Rocket::Core::TextureHandle& textureHandle,
                                      const Rocket::Core::byte* source,
                                      const Rocket::Core::Vector2i& dimensions)
{
    static int id = 1;

    Ogre::DataStreamPtr stream(OGRE_NEW Ogre::MemoryDataStream(
        (void*)source, dimensions.x * dimensions.y * sizeof(unsigned int)));
    Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().loadRawData(
        Rocket::Core::String(16, "%d", id++).CString(),
        Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, stream,
        (Ogre::ushort)dimensions.x, (Ogre::ushort)dimensions.y, Ogre::PF_A8B8G8R8,
        Ogre::TEX_TYPE_2D, 0);

    if (texture.isNull())
        return false;

    textureHandle = reinterpret_cast<Rocket::Core::TextureHandle>(new RocketOgreTexture(texture));
    return true;
}
Esempio n. 28
0
void McsHudGui::addFrameGraph(CEGUI::Window* sheet)
{
    Ogre::TexturePtr tex = mOgreRoot->getTextureManager()->createManual(
                               "FrameGraph", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D,
                               TimeGraphMaxFrames, TimeGraphMaxResolution, 0, Ogre::PF_R8G8B8, Ogre::TU_RENDERTARGET);

    Ogre::SceneManager* debugSceneMgr = mOgreRoot->createSceneManager(Ogre::ST_GENERIC);
    debugSceneMgr->setAmbientLight(Ogre::ColourValue(1.0f, 1.0f, 1.0f));

    Ogre::MaterialPtr frameLinesMaterial = Ogre::MaterialManager::getSingleton().create("frameLinesMaterial","Game");
    frameLinesMaterial->setReceiveShadows(false);
    frameLinesMaterial->getTechnique(0)->setLightingEnabled(false);
    frameLinesMaterial->getTechnique(0)->getPass(0)->setDepthCheckEnabled(false);
    frameLinesMaterial->getTechnique(0)->getPass(0)->setDepthWriteEnabled(false);

    mFrameLines = new FrameGraphRenderable(TimeGraphMaxFrames, TimeGraphMaxResolution);
    mFrameLines->setMaterial("frameLinesMaterial");

    Ogre::SceneNode* frameLinesNode = debugSceneMgr->getRootSceneNode()->createChildSceneNode("frameGraph_node");
    frameLinesNode->attachObject(mFrameLines);
    Ogre::Camera* dbg_camera = debugSceneMgr->createCamera("item_camera");
    dbg_camera->setAspectRatio(static_cast<Ogre::Real>(TimeGraphMaxFrames) / static_cast<Ogre::Real>(TimeGraphMaxResolution));
    Ogre::Viewport *v = tex->getBuffer()->getRenderTarget()->addViewport(dbg_camera);
    v->setClearEveryFrame( true );
    v->setBackgroundColour( Ogre::ColourValue::Black );



    CEGUI::Texture& guiTex = mCeRenderer->createTexture(tex);
    CEGUI::Imageset& imageSet = CEGUI::ImagesetManager::getSingleton().create("FrameGraphImageset", guiTex);
    imageSet.defineImage("FrameGraphImage", CEGUI::Point(0.0f, 0.0f), CEGUI::Size(guiTex.getSize()), CEGUI::Point(0.0f, 0.0f));
    CEGUI::Window* si = CEGUI::WindowManager::getSingleton().createWindow("TaharezLook/StaticImage", "FrameGraphWindow");
    si->setSize(CEGUI::UVector2(CEGUI::UDim(0.0f, TimeGraphMaxFrames), CEGUI::UDim(0.0f, TimeGraphMaxResolution)));
    si->setPosition(CEGUI::UVector2(CEGUI::UDim(0.0f, 0), CEGUI::UDim(1.0f, -TimeGraphMaxResolution)));
    si->setProperty("Image", CEGUI::PropertyHelper::imageToString(&imageSet.getImage("FrameGraphImage")));
    si->setAlpha(0.6f);
    si->setProperty("BackgroundEnabled", "False");
    si->setProperty("FrameEnabled", "False");

    sheet->addChildWindow(si);
}
Esempio n. 29
0
//----------------------------------------------------------------------------------------
ImageConverter::ImageConverter(const size_t& width/*=128*/, const size_t& height/*=128*/)
{
    mWidth = width;
    mHeight = height;

    mResourceManager = Ogre::ResourceGroupManager::getSingletonPtr();
    mResourceManager->createResourceGroup("QTImageConverter");
    mResourceManager->initialiseResourceGroup("QTImageConverter");
    
    mSceneMgrPtr = Ogre::Root::getSingletonPtr()->createSceneManager("OctreeSceneManager", "QTImageConverterSceneManager");
    mSceneMgrPtr->setAmbientLight(Ogre::ColourValue(1, 1, 1));

    Ogre::TexturePtr rendertexture = Ogre::TextureManager::getSingleton().createManual("RenderTex", 
                   "QTImageConverter", Ogre::TEX_TYPE_2D, 
                   mWidth, mHeight, 1, Ogre::PF_R8G8B8, Ogre::TU_RENDERTARGET);

    mRttTex = rendertexture->getBuffer()->getRenderTarget();

    // create our plane to set a texture to
    Ogre::Plane plane(Ogre::Vector3::UNIT_Z, 0);
    Ogre::MeshManager::getSingleton().createPlane("terrain", "QTImageConverter",
        plane, 100, 100, 1, 1, true, 1, 1, 1, Ogre::Vector3::UNIT_Y);

    // attach the plane to the scene manager and rotate it so the camera can see it
    mEntityTerrain = mSceneMgrPtr->createEntity("terrainEntity", "terrain");
    Ogre::SceneNode* node = mSceneMgrPtr->getRootSceneNode()->createChildSceneNode();
    node->attachObject(mEntityTerrain);
    mEntityTerrain->setCastShadows(false);    
    
    Ogre::Camera* RTTCam = mSceneMgrPtr->createCamera("QTImageConverterCam");
    RTTCam->setNearClipDistance(0.01F);
    RTTCam->setFarClipDistance(0);
    RTTCam->setAspectRatio(1);
    RTTCam->setFOVy(Ogre::Degree(90));
    RTTCam->setPosition(0, 0, 50);
    RTTCam->lookAt(0, 0, 0);
    
    Ogre::Viewport *v = mRttTex->addViewport(RTTCam);
    v->setBackgroundColour(Ogre::ColourValue(1, 1, 1));
    v->setClearEveryFrame(true);
}
Esempio n. 30
0
//!
//! Callback when instance of this class is registered as Ogre::CompositorListener.
//! 
//! \param pass_id Id to identifiy current compositor pass.
//! \param mat Material this pass is currently using.
//!
void BadPrintingNode::notifyMaterialRender(Ogre::uint32 pass_id, Ogre::MaterialPtr &mat)
{
    Ogre::TexturePtr inputTexture = getTextureValue("Input Map");
    if (inputTexture.isNull())
        return;

    // watercolor pass
    if (pass_id == 0000) {
        // set shader parameters
        Ogre::GpuProgramParametersSharedPtr fpParams = getShaderParameters(mat);
        if (!fpParams.isNull()) {
            
			// setShaderParameter(fpParams, "speed1", (Ogre::Real)(getDoubleValue("Speed1") / 100.0));
			// setShaderParameter(fpParams, "speed2", (Ogre::Real)(getDoubleValue("Speed2") / 100.0));
			// setShaderParameter(fpParams, "speed1", (Ogre::Real)(getDoubleValue("Speed1") / 100.0));
			// setShaderParameter(fpParams, "scratchIntensity", (Ogre::Real)(getDoubleValue("ScratchIntensity") / 100.0));
			// setShaderParameter(fpParams, "is", (Ogre::Real)(getDoubleValue("IS") / 100.0));
			
        }

        // set texture name
        setTexture(mat, inputTexture, 0);
    }

	if (pass_id == 0001) {
        // set shader parameters
        Ogre::GpuProgramParametersSharedPtr fpParams = getShaderParameters(mat);
        if (!fpParams.isNull()) {
            
			// setShaderParameter(fpParams, "speed1", (Ogre::Real)(getDoubleValue("Speed1") / 100.0));
			// setShaderParameter(fpParams, "speed2", (Ogre::Real)(getDoubleValue("Speed2") / 100.0));
			// setShaderParameter(fpParams, "speed1", (Ogre::Real)(getDoubleValue("Speed1") / 100.0));
			// setShaderParameter(fpParams, "scratchIntensity", (Ogre::Real)(getDoubleValue("ScratchIntensity") / 100.0));
			// setShaderParameter(fpParams, "is", (Ogre::Real)(getDoubleValue("IS") / 100.0));
			
        }

        // set texture name
        setTexture(mat, inputTexture, 0);
    }
}