void addTextureDebugOverlay( TrayLocation loc, const String& texname, size_t i )
 {// Create material
   String matName = "Ogre/DebugTexture" + StringConverter::toString( i );
   MaterialPtr debugMat = MaterialManager::getSingleton().getByName( matName );
   if( debugMat.isNull() )
   {
     debugMat = MaterialManager::getSingleton().create( matName,
       ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME );
   }
   Pass* p = debugMat->getTechnique( 0 )->getPass( 0 );
   p->removeAllTextureUnitStates();
   p->setLightingEnabled( false );
   TextureUnitState *t = p->createTextureUnitState( texname );
   t->setTextureAddressingMode( TextureUnitState::TAM_CLAMP );
   // create template
   if( !OverlayManager::getSingleton().hasOverlayElement( "Ogre/DebugTexOverlay", true ) )
   {
     OverlayElement* e = OverlayManager::getSingleton().createOverlayElement( "Panel", "Ogre/DebugTexOverlay", true );
     e->setMetricsMode( GMM_PIXELS );
     e->setWidth( 128 );
     e->setHeight( 128 );
   }
   // add widget
   String widgetName = "DebugTex" + StringConverter::toString( i );
   Widget* w = mTrayMgr->getWidget( widgetName );
   if( !w )
   {
     w = mTrayMgr->createDecorWidget( loc, widgetName, "Ogre/DebugTexOverlay" );
   }
   w->getOverlayElement()->setMaterialName( matName );
 }
예제 #2
0
	// ---------------------------------------------------------------------
	void MaterialService::createJorgeMaterial(const Ogre::String& resourceGroup) {
		std::string shaderName("@template0");

		if (!MaterialManager::getSingleton().resourceExists(shaderName)) {
			MaterialPtr shadMat = MaterialManager::getSingleton().create(shaderName, resourceGroup);
			shadMat->setReceiveShadows(true);

			Pass *shadPass = shadMat->getTechnique(0)->getPass(0);

			shadPass->setAmbient(0.5, 0.5, 0.5);
			shadPass->setDiffuse(1, 1, 1, 1);
			shadPass->setSpecular(1, 1, 1, 1);

			// Texture unit state for the main texture...
			// jorge.png is compiled-in - see the RenderService::prepareHardcodedMedia
			TextureUnitState* tus = shadPass->createTextureUnitState("jorge.png");


			// Set replace on all first layer textures for now
			tus->setTextureAddressingMode(TextureUnitState::TAM_WRAP);
			tus->setTextureCoordSet(0);
			tus->setTextureFiltering(TFO_BILINEAR);

			tus->setTextureUScale(1.0f);
			tus->setTextureVScale(1.0f);

			// No dynamic lighting
			shadMat->setLightingEnabled(false);

			shadMat->load();
			addWorldMaterialTemplate(0, shadMat); // fixed at slot 0
		}
	}
예제 #3
0
void GraphicsController::addTextureDebugOverlay(const Ogre::String& texname, size_t i)
{
    using namespace Ogre;
    Overlay* debugOverlay = OverlayManager::getSingleton().getByName("PRJZ/DebugOverlay");

	MaterialPtr debugMat = MaterialManager::getSingleton().getByName("PRJZ/BasicTexture", "PROJECT_ZOMBIE");
	if(debugMat.isNull())
		OGRE_EXCEPT(Ogre::Exception::ERR_INVALIDPARAMS, "PRJZ/BasicTexture material was not found.", "GraphicsController::addTextureDebugOverlay");
    debugMat->getTechnique(0)->getPass(0)->setLightingEnabled(false);
    TextureUnitState *t = debugMat->getTechnique(0)->getPass(0)->createTextureUnitState(texname);
    t->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);

    Ogre::TexturePtr tex = Ogre::TextureManager::getSingleton().getByName(texname);
    Ogre::Real tWidth = tex->getWidth();
    Ogre::Real tHeight = tex->getHeight();

    //ratio 
    Ogre::Real ratio = tHeight / tWidth;
    OverlayContainer* debugPanel = (OverlayContainer*)
        (OverlayManager::getSingleton().createOverlayElement("Panel", "Ogre/DebugTexPanel" + StringConverter::toString(i)));
    debugPanel->_setPosition(0.0, 0.0);
    debugPanel->_setDimensions(0.5f, 0.5f * ratio);
    debugPanel->setMaterialName(debugMat->getName());
    debugOverlay->add2D(debugPanel);
}
예제 #4
0
	//------------------------------------------------------
	void MaterialService::prepareMaterialInstance(MaterialPtr& mat, unsigned int idx, int tag) {
		if (tag < 0) // Should not be here if the polygon is sky textured
			OPDE_EXCEPT("Non-instanced material instance requested", "MaterialService::prepareMaterialInstance");

		mat->setReceiveShadows(true);

		StringUtil::StrStreamType lightmapName;
		lightmapName << "@lightmap" << tag;

		Pass *shadPass = mat->getTechnique(0)->getPass(0);

		if (shadPass->getNumTextureUnitStates() <= 1) {
			// Lightmap texture is added here
			TextureUnitState* tex = shadPass->createTextureUnitState(lightmapName.str());


			// Blend
			tex->setColourOperation(LBO_MODULATE);
			// Use 2nd texture co-ordinate set
			tex->setTextureCoordSet(1);

			// Clamp
			tex->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);


			// Switch filtering off to see lmap pixels: TFO_NONE
			tex->setTextureFiltering(TFO_BILINEAR);
		} else {
			// There is a definition of the lightmapping pass already, we only update that definition
			TextureUnitState* tex = shadPass->getTextureUnitState(1);
			tex->setTextureName(lightmapName.str());
			tex->setTextureCoordSet(1);
		}
	}
예제 #5
0
void FiveApp::makeMaterialReceiveDecal(const String & matName)
{
	MaterialPtr mat = (MaterialPtr)MaterialManager::getSingleton().getByName(matName);
	Pass *pass = mat->getTechnique(0)->createPass();

	pass->setSceneBlending(SBT_TRANSPARENT_ALPHA);
	pass->setDepthBias(1);
	pass->setLightingEnabled(true);

	TextureUnitState *texState = pass->createTextureUnitState("decal.png");
	texState->setProjectiveTexturing(true,mDecalFrustum);
	texState->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);
	texState->setTextureFiltering(FO_LINEAR,FO_LINEAR,FO_NONE);

	texState = pass->createTextureUnitState("decal_filter.png");
	texState->setProjectiveTexturing(true,mFilterFrustum);
	texState->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);
	texState->setTextureFiltering(TFO_NONE);
}
예제 #6
0
int ShadowManager::updateShadowTechnique()
{
    float scoef = 0.5;
    gEnv->sceneManager->setShadowColour(Ogre::ColourValue(0.563 + scoef, 0.578 + scoef, 0.625 + scoef));
    gEnv->sceneManager->setShowDebugShadows(false);

    RoR::App::GfxShadowType type = RoR::App::GetGfxShadowType();

    if (type == RoR::App::GFX_SHADOW_TYPE_TEXTURE)
    {
        gEnv->sceneManager->setShadowFarDistance(RoR::App::GetGfxSightRange());
        processTextureShadows();
    }
    else if (type == RoR::App::GFX_SHADOW_TYPE_PSSM)
    {
        processPSSM();
        if (gEnv->sceneManager->getShowDebugShadows())
        {
            // add the overlay elements to show the shadow maps:
            // init overlay elements
            OverlayManager& mgr = Ogre::OverlayManager::getSingleton();
            Overlay* overlay = mgr.create("DebugOverlay");

            for (int i = 0; i < PSSM_Shadows.ShadowsTextureNum; ++i)
            {
                TexturePtr tex = gEnv->sceneManager->getShadowTexture(i);

                // Set up a debug panel to display the shadow
                MaterialPtr debugMat = MaterialManager::getSingleton().create("Ogre/DebugTexture" + StringConverter::toString(i), ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
                debugMat->getTechnique(0)->getPass(0)->setLightingEnabled(false);
                TextureUnitState* t = debugMat->getTechnique(0)->getPass(0)->createTextureUnitState(tex->getName());
                t->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);

                OverlayContainer* debugPanel = (OverlayContainer*)(OverlayManager::getSingleton().createOverlayElement("Panel", "Ogre/DebugTexPanel" + StringConverter::toString(i)));
                debugPanel->_setPosition(0.8, i * 0.25);
                debugPanel->_setDimensions(0.2, 0.24);
                debugPanel->setMaterialName(debugMat->getName());
                debugPanel->setEnabled(true);
                overlay->add2D(debugPanel);
                overlay->show();
            }
        }
    }
    return 0;
}
예제 #7
0
파일: Water.cpp 프로젝트: Argos86/dt2370
void prepareCircleMaterial()
{
	char *bmap = new char[256 * 256 * 4] ;
	memset(bmap, 127, 256 * 256 * 4);
	for(int b=0;b<16;b++) {
		int x0 = b % 4 ;
		int y0 = b >> 2 ;
		Real radius = 4.0f + 1.4 * (float) b ;
		for(int x=0;x<64;x++) {
			for(int y=0;y<64;y++) {
				Real dist = Math::Sqrt((x-32)*(x-32)+(y-32)*(y-32)); // 0..ca.45
				dist = fabs(dist -radius -2) / 2.0f ;
				dist = dist * 255.0f;
				if (dist>255)
					dist=255 ;
				int colour = 255-(int)dist ;
				colour = (int)( ((Real)(15-b))/15.0f * (Real) colour );

				bmap[4*(256*(y+64*y0)+x+64*x0)+0]=colour ;
				bmap[4*(256*(y+64*y0)+x+64*x0)+1]=colour ;
				bmap[4*(256*(y+64*y0)+x+64*x0)+2]=colour ;
				bmap[4*(256*(y+64*y0)+x+64*x0)+3]=colour ;
			}
		}
	}

	DataStreamPtr imgstream(new MemoryDataStream(bmap, 256 * 256 * 4));
	//~ Image img;
	//~ img.loadRawData( imgstream, 256, 256, PF_A8R8G8B8 );
	//~ TextureManager::getSingleton().loadImage( CIRCLES_MATERIAL , img );
	TextureManager::getSingleton().loadRawData(CIRCLES_MATERIAL,
        ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
		imgstream, 256, 256, PF_A8R8G8B8);
	MaterialPtr material =
		MaterialManager::getSingleton().create( CIRCLES_MATERIAL,
        ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
	TextureUnitState *texLayer = material->getTechnique(0)->getPass(0)->createTextureUnitState( CIRCLES_MATERIAL );
	texLayer->setTextureAddressingMode( TextureUnitState::TAM_CLAMP );
	material->setSceneBlending( SBT_ADD );
	material->setDepthWriteEnabled( false ) ;
    material->load();
    // finished with bmap so release the memory
    delete [] bmap;
}
//-----------------------------------------------------------------------
bool IntegratedPSSM3::preAddToRenderState(const RenderState* renderState, 
                                         Pass* srcPass, Pass* dstPass)
{
    if (srcPass->getLightingEnabled() == false ||
        srcPass->getParent()->getParent()->getReceiveShadows() == false)
        return false;

    ShadowTextureParamsIterator it = mShadowTextureParamsList.begin();

    while(it != mShadowTextureParamsList.end())
    {
        TextureUnitState* curShadowTexture = dstPass->createTextureUnitState();
            
        curShadowTexture->setContentType(TextureUnitState::CONTENT_SHADOW);
        curShadowTexture->setTextureAddressingMode(TextureUnitState::TAM_BORDER);
        curShadowTexture->setTextureBorderColour(ColourValue::White);
        it->mTextureSamplerIndex = dstPass->getNumTextureUnitStates() - 1;
        ++it;
    }

    

    return true;
}
예제 #9
0
    //-----------------------------------------------------------------------
    MaterialPtr Quake3Shader::createAsMaterial(int lightmapNumber)
    {
		String matName;
		StringUtil::StrStreamType str;
        String resourceGroup = ResourceGroupManager::getSingleton().getWorldResourceGroupName();

        str << mName << "#" << lightmapNumber;
		matName = str.str();

        MaterialPtr mat = MaterialManager::getSingleton().create(matName, 
            resourceGroup);
		Ogre::Pass* ogrePass = mat->getTechnique(0)->getPass(0);

        LogManager::getSingleton().logMessage("Using Q3 shader " + mName, LML_CRITICAL);
        for (int p = 0; p < numPasses; ++p)
        {
            TextureUnitState* t;
            // Create basic texture
            if (pass[p].textureName == "$lightmap")
            {
                StringUtil::StrStreamType str2;
				str2 << "@lightmap" << lightmapNumber;
                t = ogrePass->createTextureUnitState(str2.str());
            }
            // Animated texture support
            else if (pass[p].animNumFrames > 0)
            {
                Real sequenceTime = pass[p].animNumFrames / pass[p].animFps;
                /* Pre-load textures
                   We need to know if each one was loaded OK since extensions may change for each
                   Quake3 can still include alternate extension filenames e.g. jpg instead of tga
                   Pain in the arse - have to check for each frame as letters<n>.tga for example
                   is different per frame!
                */
                for (unsigned int alt = 0; alt < pass[p].animNumFrames; ++alt)
                {
                    if (!ResourceGroupManager::getSingleton().resourceExists(
                        resourceGroup, pass[p].frames[alt]))
                    {
                        // Try alternate extension
                        pass[p].frames[alt] = getAlternateName(pass[p].frames[alt]);
                        if (!ResourceGroupManager::getSingleton().resourceExists(
                            resourceGroup, pass[p].frames[alt]))
                        { 
                            // stuffed - no texture
                            continue;
                        }
                    }

                }

                t = ogrePass->createTextureUnitState("");
                t->setAnimatedTextureName(pass[p].frames, pass[p].animNumFrames, sequenceTime);

            }
            else
            {
                // Quake3 can still include alternate extension filenames e.g. jpg instead of tga
                // Pain in the arse - have to check for failure
                if (!ResourceGroupManager::getSingleton().resourceExists(
                    resourceGroup, pass[p].textureName))
                {
                    // Try alternate extension
                    pass[p].textureName = getAlternateName(pass[p].textureName);
                    if (!ResourceGroupManager::getSingleton().resourceExists(
                        resourceGroup, pass[p].textureName))
                    { 
                        // stuffed - no texture
                        continue;
                    }
                }
                t = ogrePass->createTextureUnitState(pass[p].textureName);
            }
            // Blending
            if (p == 0)
            {
                // scene blend
                mat->setSceneBlending(pass[p].blendSrc, pass[p].blendDest);
                if (mat->isTransparent())
                    mat->setDepthWriteEnabled(false);

                t->setColourOperation(LBO_REPLACE);
				// Alpha mode
				ogrePass->setAlphaRejectSettings(
					pass[p].alphaFunc, pass[p].alphaVal);
            }
            else
            {
                if (pass[p].customBlend)
                {
                    // Fallback for now
                    t->setColourOperation(LBO_MODULATE);
                }
                else
                {
                    // simple layer blend
                    t->setColourOperation(pass[p].blend);
                }
				// Alpha mode, prefer 'most alphary'
				CompareFunction currFunc = ogrePass->getAlphaRejectFunction();
				unsigned char currVal = ogrePass->getAlphaRejectValue();
				if (pass[p].alphaFunc > currFunc ||
					(pass[p].alphaFunc == currFunc && pass[p].alphaVal < currVal))
				{
					ogrePass->setAlphaRejectSettings(
						pass[p].alphaFunc, pass[p].alphaVal);
				}
            }
            // Tex coords
            if (pass[p].texGen == TEXGEN_BASE)
            {
                t->setTextureCoordSet(0);
            }
            else if (pass[p].texGen == TEXGEN_LIGHTMAP)
            {
                t->setTextureCoordSet(1);
            }
            else if (pass[p].texGen == TEXGEN_ENVIRONMENT)
            {
                t->setEnvironmentMap(true, TextureUnitState::ENV_PLANAR);
            }
            // Tex mod
            // Scale
            t->setTextureUScale(pass[p].tcModScale[0]);
            t->setTextureVScale(pass[p].tcModScale[1]);
            // Procedural mods
            // Custom - don't use mod if generating environment
            // Because I do env a different way it look horrible
            if (pass[p].texGen != TEXGEN_ENVIRONMENT)
            {
                if (pass[p].tcModRotate)
                {
                    t->setRotateAnimation(pass[p].tcModRotate);
                }
                if (pass[p].tcModScroll[0] || pass[p].tcModScroll[1])
                {
                    if (pass[p].tcModTurbOn)
                    {
                        // Turbulent scroll
                        if (pass[p].tcModScroll[0])
                        {
                            t->setTransformAnimation(TextureUnitState::TT_TRANSLATE_U, WFT_SINE,
                                pass[p].tcModTurb[0], pass[p].tcModTurb[3], pass[p].tcModTurb[2], pass[p].tcModTurb[1]);
                        }
                        if (pass[p].tcModScroll[1])
                        {
                            t->setTransformAnimation(TextureUnitState::TT_TRANSLATE_V, WFT_SINE,
                                pass[p].tcModTurb[0], pass[p].tcModTurb[3], pass[p].tcModTurb[2], pass[p].tcModTurb[1]);
                        }
                    }
                    else
                    {
                        // Constant scroll
                        t->setScrollAnimation(pass[p].tcModScroll[0], pass[p].tcModScroll[1]);
                    }
                }
                if (pass[p].tcModStretchWave != SHADER_FUNC_NONE)
                {
                    WaveformType wft;
                    switch(pass[p].tcModStretchWave)
                    {
                    case SHADER_FUNC_SIN:
                        wft = WFT_SINE;
                        break;
                    case SHADER_FUNC_TRIANGLE:
                        wft = WFT_TRIANGLE;
                        break;
                    case SHADER_FUNC_SQUARE:
                        wft = WFT_SQUARE;
                        break;
                    case SHADER_FUNC_SAWTOOTH:
                        wft = WFT_SAWTOOTH;
                        break;
                    case SHADER_FUNC_INVERSESAWTOOTH:
                        wft = WFT_INVERSE_SAWTOOTH;
                        break;
                    default:
                        break;
                    }
                    // Create wave-based stretcher
                    t->setTransformAnimation(TextureUnitState::TT_SCALE_U, wft, pass[p].tcModStretchParams[3],
                        pass[p].tcModStretchParams[0], pass[p].tcModStretchParams[2], pass[p].tcModStretchParams[1]);
                    t->setTransformAnimation(TextureUnitState::TT_SCALE_V, wft, pass[p].tcModStretchParams[3],
                        pass[p].tcModStretchParams[0], pass[p].tcModStretchParams[2], pass[p].tcModStretchParams[1]);
                }
            }
            // Address mode
            t->setTextureAddressingMode(pass[p].addressMode);

            //assert(!t->isBlank());


        }
        // Do farbox (create new material)

        // Set culling mode and lighting to defaults
        mat->setCullingMode(CULL_NONE);
        mat->setManualCullingMode(cullMode);
        mat->setLightingEnabled(false);
        mat->load();
        return mat;
    }
예제 #10
0
void VolumeRenderable::initialise()
{
	// Create geometry
	size_t nvertices = mSlices*4; // n+1 planes
	size_t elemsize = 3*3;
	size_t dsize = elemsize*nvertices;
	size_t x;
	
	Ogre::IndexData *idata = new Ogre::IndexData();
	Ogre::VertexData *vdata = new Ogre::VertexData();
	
	// Create  structures
	float *vertices = new float[dsize];
	
	float coords[4][2] = {
		{0.0f, 0.0f},
		{0.0f, 1.0f},
		{1.0f, 0.0f},
		{1.0f, 1.0f}
	};
	for(x=0; x<mSlices; x++) 
	{
		for(size_t y=0; y<4; y++)
		{
			float xcoord = coords[y][0]-0.5;
			float ycoord = coords[y][1]-0.5;
			float zcoord = -((float)x/(float)(mSlices-1)  - 0.5f);
			// 1.0f .. a/(a+1)
			// coordinate
			vertices[x*4*elemsize+y*elemsize+0] = xcoord*(mSize/2.0f);
			vertices[x*4*elemsize+y*elemsize+1] = ycoord*(mSize/2.0f);
			vertices[x*4*elemsize+y*elemsize+2] = zcoord*(mSize/2.0f);
			// normal
			vertices[x*4*elemsize+y*elemsize+3] = 0.0f;
			vertices[x*4*elemsize+y*elemsize+4] = 0.0f;
			vertices[x*4*elemsize+y*elemsize+5] = 1.0f;
			// tex
			vertices[x*4*elemsize+y*elemsize+6] = xcoord*sqrtf(3.0f);
			vertices[x*4*elemsize+y*elemsize+7] = ycoord*sqrtf(3.0f);
			vertices[x*4*elemsize+y*elemsize+8] = zcoord*sqrtf(3.0f);
		} 
	}
	unsigned short *faces = new unsigned short[mSlices*6];
	for(x=0; x<mSlices; x++) 
	{
		faces[x*6+0] = x*4+0;
		faces[x*6+1] = x*4+1;
		faces[x*6+2] = x*4+2;
		faces[x*6+3] = x*4+1;
		faces[x*6+4] = x*4+2;
		faces[x*6+5] = x*4+3;
	}
	// Setup buffers
	vdata->vertexStart = 0;
	vdata->vertexCount = nvertices;
	
	VertexDeclaration* decl = vdata->vertexDeclaration;
	VertexBufferBinding* bind = vdata->vertexBufferBinding;

	size_t offset = 0;
	decl->addElement(0, offset, VET_FLOAT3, VES_POSITION);
	offset += VertexElement::getTypeSize(VET_FLOAT3);
	decl->addElement(0, offset, VET_FLOAT3, VES_NORMAL);
	offset += VertexElement::getTypeSize(VET_FLOAT3);
	decl->addElement(0, offset, VET_FLOAT3, VES_TEXTURE_COORDINATES);
	offset += VertexElement::getTypeSize(VET_FLOAT3);

	HardwareVertexBufferSharedPtr vbuf = 
	HardwareBufferManager::getSingleton().createVertexBuffer(
		offset, nvertices, HardwareBuffer::HBU_STATIC_WRITE_ONLY);

	bind->setBinding(0, vbuf);

	vbuf->writeData(0, vbuf->getSizeInBytes(), vertices, true);
	
	HardwareIndexBufferSharedPtr ibuf = HardwareBufferManager::getSingleton().
		createIndexBuffer(
			HardwareIndexBuffer::IT_16BIT, 
			mSlices*6, 
			HardwareBuffer::HBU_STATIC_WRITE_ONLY);

	idata->indexBuffer = ibuf;
	idata->indexCount = mSlices*6;
	idata->indexStart = 0;
	ibuf->writeData(0, ibuf->getSizeInBytes(), faces, true);

	// Delete temporary buffers
	delete [] vertices;
	delete [] faces;
	
	// Now make the render operation
	mRenderOp.operationType = Ogre::RenderOperation::OT_TRIANGLE_LIST;
	mRenderOp.indexData = idata;
	mRenderOp.vertexData = vdata;
	mRenderOp.useIndexes = true;
	
	 // Create a brand new private material
	MaterialPtr material = 
		MaterialManager::getSingleton().create(mTexture, "VolumeRenderable",
			false, 0); // Manual, loader

	// Remove pre-created technique from defaults
	material->removeAllTechniques();
	
	// Create a techinique and a pass and a texture unit
 	Technique * technique = material->createTechnique();
	Pass * pass = technique->createPass();
	TextureUnitState * textureUnit = pass->createTextureUnitState();
	
	// Set pass parameters
	pass->setSceneBlending(SBT_TRANSPARENT_ALPHA);
	pass->setDepthWriteEnabled(false);
	pass->setCullingMode(CULL_NONE);
	pass->setLightingEnabled(false);
	
	// Set texture unit parameters
	textureUnit->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);
	textureUnit->setTextureName(mTexture, TEX_TYPE_3D);
	textureUnit->setTextureFiltering(TFO_TRILINEAR);
	
	mUnit = textureUnit;
	m_pMaterial = material;
}
예제 #11
0
///  Shadows config
//---------------------------------------------------------------------------------------------------
void CScene::changeShadows()
{	
	Ogre::Timer ti;
	
	//  get settings
	SETTINGS* pSet = app->pSet;
	bool enabled = pSet->shadow_type != Sh_None;
	bool bDepth = pSet->shadow_type >= Sh_Depth;
	bool bSoft = pSet->shadow_type == Sh_Soft;
	
	pSet->shadow_size = std::max(0,std::min(ciShadowSizesNum-1, pSet->shadow_size));
	int fTex = ciShadowSizesA[pSet->shadow_size], fTex2 = fTex/2;
	int num = pSet->shadow_count;

	sh::Vector4* fade = new sh::Vector4(
		pSet->shadow_dist,
		pSet->shadow_dist * 0.6, // fade start
		0, 0);

	sh::Factory* mFactory = app->mFactory;
	SceneManager* mSceneMgr = app->mSceneMgr;

	if (terrain)
		mFactory->setTextureAlias("TerrainLightMap", terrain->getLightmap()->getName());

		
	// disable 4 shadow textures (does not work because no texcoord's left in shader)
	if (num == 4)  num = 3;


	if (!enabled)
		mSceneMgr->setShadowTechnique(SHADOWTYPE_NONE);
	else
	{
		// General scene setup
		//mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_ADDITIVE_INTEGRATED);
		mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE_INTEGRATED);
		mSceneMgr->setShadowFarDistance(pSet->shadow_dist);  // 3000
		mSceneMgr->setShadowTextureCountPerLightType(Light::LT_DIRECTIONAL, num);

		if (num == 1)  // 1 tex, fast
		{
			ShadowCameraSetupPtr mShadowCameraSetup = ShadowCameraSetupPtr(new LiSPSMShadowCameraSetup());
			mSceneMgr->setShadowCameraSetup(mShadowCameraSetup);
		}else
		{	if (mPSSMSetup.isNull())  // pssm
			{
				PSSMShadowCameraSetup* pssmSetup = new PSSMShadowCameraSetup();
				#ifndef SR_EDITOR
				pssmSetup->setSplitPadding(app->mSplitMgr->mCameras.front()->getNearClipDistance());
				pssmSetup->calculateSplitPoints(num, app->mSplitMgr->mCameras.front()->getNearClipDistance(), mSceneMgr->getShadowFarDistance());
				#else
				pssmSetup->setSplitPadding(app->mCamera->getNearClipDistance());
				pssmSetup->calculateSplitPoints(num, app->mCamera->getNearClipDistance(), app->mSceneMgr->getShadowFarDistance());
				#endif
				for (int i=0; i < num; ++i)
				{	//int size = i==0 ? fTex : fTex2;
					const Real cAdjfA[5] = {2, 1, 0.5, 0.25, 0.125};
					pssmSetup->setOptimalAdjustFactor(i, cAdjfA[std::min(i, 4)]);
				}
				mPSSMSetup.bind(pssmSetup);
			}
			mSceneMgr->setShadowCameraSetup(mPSSMSetup);
		}

		mSceneMgr->setShadowTextureCount(num);
		for (int i=0; i < num; ++i)
		{	int size = i==0 ? fTex : fTex2;
		
			PixelFormat pf;
			if (bDepth && !bSoft) pf = PF_FLOAT32_R;
			else if (bSoft) pf = PF_FLOAT16_RGB;
			else pf = PF_X8B8G8R8;
			
			mSceneMgr->setShadowTextureConfig(i, size, size, pf);
		}
		
		mSceneMgr->setShadowTextureSelfShadow(bDepth ? true : false);  //-?
		mSceneMgr->setShadowCasterRenderBackFaces((bDepth && !bSoft) ? true : false);

		mSceneMgr->setShadowTextureCasterMaterial(bDepth ? "shadowcaster_default" : "");
	}

	mSceneMgr->setShadowColour(Ogre::ColourValue(0,0,0,1));


#if 0  /// TEST overlays
	//  add overlay elements to show shadow or terrain maps
	OverlayManager& mgr = OverlayManager::getSingleton();
	Overlay* overlay = mgr.getByName("DebugOverlay");
	if (overlay)
		mgr.destroy(overlay);
	overlay = mgr.create("DebugOverlay");
	TexturePtr tex;

	#if 0  /// shadow
	for (int i = 0; i < pSet->shadow_count; ++i)
	{	
		TexturePtr tex = mSceneMgr->getShadowTexture(i);
	#else  /// terrain
	for (int i = 0; i < 2/*pSet->shadow_count*/; ++i)
	{	
		TexturePtr tex = !terrain ? mSceneMgr->getShadowTexture(i) :
			i==0 ? terrain->getCompositeMap() : terrain->getLightmap();
	#endif
		// Set up a debug panel to display the shadow
		if (MaterialManager::getSingleton().resourceExists("Ogre/DebugTexture" + toStr(i)))
			MaterialManager::getSingleton().remove("Ogre/DebugTexture" + toStr(i));
		MaterialPtr debugMat = MaterialManager::getSingleton().create(
			"Ogre/DebugTexture" + toStr(i), rgDef);
			
		debugMat->getTechnique(0)->getPass(0)->setLightingEnabled(false);
		TextureUnitState *t = debugMat->getTechnique(0)->getPass(0)->createTextureUnitState(tex->getName());
		t->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);

		OverlayContainer* debugPanel;
		
		// destroy container if exists
		try
		{
			if (debugPanel = static_cast<OverlayContainer*>(mgr.getOverlayElement("Ogre/DebugTexPanel" + toStr(i))))
				mgr.destroyOverlayElement(debugPanel);
		}
		catch (Ogre::Exception&) {}
		
		debugPanel = (OverlayContainer*)
			(OverlayManager::getSingleton().createOverlayElement("Panel", "Ogre/DebugTexPanel" + StringConverter::toString(i)));
		debugPanel->_setPosition(0.8, i*0.31);  //aspect.. 0.25 0.24
		debugPanel->_setDimensions(0.2, 0.3);
		debugPanel->setMaterialName(debugMat->getName());
		debugPanel->show();
		overlay->add2D(debugPanel);
		overlay->show();
	}
#endif
	
	UpdPSSMMaterials();


	//  rebuild static geom after materials change
	if (vdrTrack)
	{
		vdrTrack->destroy();
		vdrTrack->build();
	}

	LogO(String("::: Time Shadows: ") + fToStr(ti.getMilliseconds(),0,3) + " ms");
}


/// . . . . . . . . 
void CScene::UpdPSSMMaterials()
{
	if (app->pSet->shadow_type == Sh_None)  return;
	
	if (app->pSet->shadow_count == 1)  // 1 tex
	{
		float dist = app->pSet->shadow_dist;
		sh::Vector3* splits = new sh::Vector3(dist, 0,0);  //dist*2, dist*3);
		sh::Factory::getInstance().setSharedParameter("pssmSplitPoints", sh::makeProperty<sh::Vector3>(splits));
		return;
	}
	
	if (!mPSSMSetup.get())  return;
	
	//--  pssm params
	PSSMShadowCameraSetup* pssmSetup = static_cast<PSSMShadowCameraSetup*>(mPSSMSetup.get());
	const PSSMShadowCameraSetup::SplitPointList& sp = pssmSetup->getSplitPoints();
	const int last = sp.size()-1;

	sh::Vector3* splits = new sh::Vector3(
		sp[std::min(1,last)], sp[std::min(2,last)], sp[std::min(3,last)] );

	sh::Factory::getInstance().setSharedParameter("pssmSplitPoints", sh::makeProperty<sh::Vector3>(splits));
}
	//---------------------------------------------------------------------
	void TerrainMaterialGeneratorC::SM2Profile::addTechnique(
		const MaterialPtr& mat, const Terrain* terrain, TechniqueType tt)
	{
		Technique* tech = mat->createTechnique();
		tech->setSchemeName("GBuffer");
 
		// Only supporting one pass
		Pass* pass = tech->createPass();
		//pass->setName("NO_DEFERRED");
 
		GpuProgramManager& gmgr = GpuProgramManager::getSingleton();
		HighLevelGpuProgramManager& hmgr = HighLevelGpuProgramManager::getSingleton();
		if (!mShaderGen)
		{
			if (hmgr.isLanguageSupported("cg"))
				mShaderGen = OGRE_NEW ShaderHelperCg();
			else
			{
				// todo
			}
 
			// check SM3 features
			mSM3Available = GpuProgramManager::getSingleton().isSyntaxSupported("ps_3_0");
			mSM4Available = GpuProgramManager::getSingleton().isSyntaxSupported("ps_4_0");
 
		}
		HighLevelGpuProgramPtr vprog = mShaderGen->generateVertexProgram(this, terrain, tt);
		HighLevelGpuProgramPtr fprog = mShaderGen->generateFragmentProgram(this, terrain, tt);
 
		pass->setVertexProgram(vprog->getName());
		pass->setFragmentProgram(fprog->getName());
 
		if (tt == HIGH_LOD || tt == RENDER_COMPOSITE_MAP)
		{
			// global normal map
			TextureUnitState* tu = pass->createTextureUnitState();
			tu->setTextureName(terrain->getTerrainNormalMap()->getName());
			tu->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);
 
			// global colour map
			if (terrain->getGlobalColourMapEnabled() && isGlobalColourMapEnabled())
			{
				tu = pass->createTextureUnitState(terrain->getGlobalColourMap()->getName());
				tu->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);
			}
 
			// light map
			if (isLightmapEnabled())
			{
				tu = pass->createTextureUnitState(terrain->getLightmap()->getName());
				tu->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);
			}
 
			// blend maps
			uint maxLayers = getMaxLayers(terrain);
			uint numBlendTextures = std::min(terrain->getBlendTextureCount(maxLayers), terrain->getBlendTextureCount());
			uint numLayers = std::min(maxLayers, static_cast<uint>(terrain->getLayerCount()));
			for (uint i = 0; i < numBlendTextures; ++i)
			{
				tu = pass->createTextureUnitState(terrain->getBlendTextureName(i));
				tu->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);
			}
 
			// layer textures
			for (uint i = 0; i < numLayers; ++i)
			{
				// diffuse / specular
				pass->createTextureUnitState(terrain->getLayerTextureName(i, 0));
 
				// normal / height
				pass->createTextureUnitState(terrain->getLayerTextureName(i, 1));
			}
 
		}
		else
		{
			// LOW_LOD textures
			// composite map
			TextureUnitState* tu = pass->createTextureUnitState();
			tu->setTextureName(terrain->getCompositeMap()->getName());
			tu->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);
 
			// That's it!
 
		}
	}
예제 #13
0
void Viewer::setupLights ()
    {
        mSceneMgr->setAmbientLight(ColourValue(0.8, 0.8, 0.8));

		
		if ( Ogre::Root::getSingletonPtr()->getRenderSystem()->getCapabilities()->hasCapability(RSC_HWRENDER_TO_TEXTURE) )
		{
			mSceneMgr->setShadowTextureSettings(1024, 2);
		}
		else
		{
			mSceneMgr->setShadowTextureSettings(512, 2);
		}
		
		
		mSceneMgr->setShadowColour(ColourValue(0.5,0.5,0.5));

        Light * mSunLight = mSceneMgr->createLight("SunLight");
		
		mSunLight->setCastShadows(true);

        mSunLight->setType(Light::LT_SPOTLIGHT);
        mSunLight->setPosition(500, 500, 500);
        mSunLight->setSpotlightRange(Degree(30), Degree(50));
        Vector3 dir;
        dir = - mSunLight->getPosition();
        dir.normalise();
        mSunLight->setDirection(dir);
        mSunLight->setDiffuseColour(0.35, 0.35, 0.38);
        mSunLight->setSpecularColour(0.9, 0.9, 1);

		timeSince = 0.0f;
        mBuildMode = BM_NONE;
		
#if 0

        mReflectCam = mSceneMgr->createCamera("ReflectCam");

        mRTTTex = mRenderer->getRoot()->getRenderSystem()->createRenderTexture("RttTex",    512, 384,
                                                                               TEX_TYPE_2D, PF_R8G8B8);

        {
        mReflectCam = mSceneMgr->createCamera("ReflectCam");
        mReflectCam->setPosition(mCamera->getPosition());
        mReflectCam->setOrientation(mCamera->getOrientation());
        mReflectCam->setNearClipDistance(mCamera->getNearClipDistance());
        mReflectCam->setFarClipDistance(mCamera->getFarClipDistance());

        Viewport * v = mRTTTex->addViewport(mReflectCam);
        mReflectCam->setAspectRatio(Real(v->getWidth()) / Real(v->getHeight()));
        v->setOverlaysEnabled(false);
        v->setClearEveryFrame(true);
        v->setBackgroundColour(ColourValue::Black);
        }

        MaterialPtr mat = MaterialManager::getSingleton().create("RttMat",
                                                                 ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
        TextureUnitState * t = mat->getTechnique(0)->getPass(0)->createTextureUnitState("RttTex");
        t->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);
        //t->setProjectiveTexturing(true, mReflectCam);

        mat->clone("RttMat.over");

        //mGui->createWindow(Vector4(16, 16, 512, 384), "RttMat", BetaGUI::WFT_NONE, "");

#endif

    }
예제 #14
0
///  Shadows config
//---------------------------------------------------------------------------------------------------
void App::changeShadows()
{	
	QTimer ti;  ti.update();  /// time
	
	//  get settings
	bool enabled = pSet->shadow_type != 0;
	bool bDepth = pSet->shadow_type >= 2;
	bool bSoft = pSet->shadow_type == 3;
	
	pSet->shadow_size = std::max(0,std::min(ciShadowNumSizes-1, pSet->shadow_size));
	int fTex = /*2048*/ ciShadowSizesA[pSet->shadow_size], fTex2 = fTex/2;
	int num = /*3*/ pSet->shadow_count;
		
	// disable 4 shadow textures (does not work because no texcoord's left in shader)
	if (num == 4) num = 3;

	TerrainMaterialGeneratorB::SM2Profile* matProfile = 0;
	
	if (mTerrainGlobals)
	{
		matProfile = (TerrainMaterialGeneratorB::SM2Profile*) mTerrainGlobals->getDefaultMaterialGenerator()->getActiveProfile();
		if (matProfile)
		{	matProfile->setReceiveDynamicShadowsEnabled(enabled);
			matProfile->setReceiveDynamicShadowsLowLod(true);
			matProfile->setGlobalColourMapEnabled(false);

			matProfile->setLayerSpecularMappingEnabled(pSet->ter_mtr >= 1);  // ter mtr
			matProfile->setLayerNormalMappingEnabled(  pSet->ter_mtr >= 2);
			matProfile->setLayerParallaxMappingEnabled(pSet->ter_mtr >= 3);
	}	}
	

	if (!enabled)  {
		mSceneMgr->setShadowTechnique(SHADOWTYPE_NONE);  /*return;*/ }

	else
	{
		// General scene setup
		//mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_ADDITIVE_INTEGRATED);
		mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE_INTEGRATED);
		mSceneMgr->setShadowFarDistance(pSet->shadow_dist);  // 3000
		mSceneMgr->setShadowTextureCountPerLightType(Light::LT_DIRECTIONAL, num);

		if (mPSSMSetup.isNull())
		{
			// shadow camera setup
			PSSMShadowCameraSetup* pssmSetup = new PSSMShadowCameraSetup();
			#ifndef ROAD_EDITOR
			pssmSetup->setSplitPadding(mSplitMgr->mCameras.front()->getNearClipDistance());
			//pssmSetup->setSplitPadding(10);
			pssmSetup->calculateSplitPoints(num, mSplitMgr->mCameras.front()->getNearClipDistance(), mSceneMgr->getShadowFarDistance());
			#else
			pssmSetup->setSplitPadding(mCamera->getNearClipDistance());
			//pssmSetup->setSplitPadding(10);
			pssmSetup->calculateSplitPoints(num, mCamera->getNearClipDistance(), mSceneMgr->getShadowFarDistance());
			#endif
			for (int i=0; i < num; ++i)
			{	//int size = i==0 ? fTex : fTex2;
				const Real cAdjfA[5] = {2, 1, 0.5, 0.25, 0.125};
				pssmSetup->setOptimalAdjustFactor(i, cAdjfA[std::min(i, 4)]);
			}
			materialFactory->setPSSMCameraSetup(pssmSetup);
			mPSSMSetup.bind(pssmSetup);
		}
		mSceneMgr->setShadowCameraSetup(mPSSMSetup);

		mSceneMgr->setShadowTextureCount(num);
		for (int i=0; i < num; ++i)
		{	int size = i==0 ? fTex : fTex2;
		
			PixelFormat pf;
			if (bDepth && !bSoft) pf = PF_FLOAT32_R;
			else if (bSoft) pf = PF_FLOAT16_RGB;
			else pf = PF_X8B8G8R8;
			
			mSceneMgr->setShadowTextureConfig(i, size, size, pf);
		}
		
		mSceneMgr->setShadowTextureSelfShadow(bDepth ? true : false);  //-?
		mSceneMgr->setShadowCasterRenderBackFaces((bDepth && !bSoft) ? true : false);
		
		String shadowCasterMat;
		if (bDepth && !bSoft) shadowCasterMat = "PSSM/shadow_caster";
		else if (bSoft) shadowCasterMat = "PSVSM/shadow_caster";
		else shadowCasterMat = StringUtil::BLANK;
		
		mSceneMgr->setShadowTextureCasterMaterial(shadowCasterMat);

		if (matProfile && terrain)  {
			matProfile->setReceiveDynamicShadowsDepth(bDepth);
			matProfile->setReceiveDynamicShadowsPSSM(static_cast<PSSMShadowCameraSetup*>(mPSSMSetup.get()));
			MaterialPtr mtr = matProfile->generateForCompositeMap(terrain);
			//LogO(mtr->getBestTechnique()->getPass(0)->getTextureUnitState(0)->getName());
			//LogO(String("Ter mtr: ") + mtr->getName());

		}
	}
	
	materialFactory->setTerrain(terrain);
	materialFactory->setNumShadowTex(num);
	materialFactory->setShadows(pSet->shadow_type != 0);
	materialFactory->setShadowsDepth(bDepth);
	materialFactory->setShadowsSoft(bSoft);
	materialFactory->generate();
	
	#if 0	// shadow tex overlay
	// add the overlay elements to show the shadow maps:
	// init overlay elements
	OverlayManager& mgr = OverlayManager::getSingleton();
	Overlay* overlay;
	
	// destroy if already exists
	if (overlay = mgr.getByName("DebugOverlay"))
		mgr.destroy(overlay);
		
	overlay = mgr.create("DebugOverlay");
	
	TexturePtr tex;
	for (size_t i = 0; i < 2; ++i) {
		//TexturePtr tex = mSceneMgr->getShadowTexture(i);
		if (i == 0) tex = TextureManager::getSingleton().getByName("PlaneReflection"); 
		else tex = TextureManager::getSingleton().getByName("PlaneRefraction"); 
		
		// Set up a debug panel to display the shadow
		
		if (MaterialManager::getSingleton().resourceExists("Ogre/DebugTexture" + toStr(i)))
			MaterialManager::getSingleton().remove("Ogre/DebugTexture" + toStr(i));
		MaterialPtr debugMat = MaterialManager::getSingleton().create(
			"Ogre/DebugTexture" + toStr(i), 
			ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
			
		debugMat->getTechnique(0)->getPass(0)->setLightingEnabled(false);
		TextureUnitState *t = debugMat->getTechnique(0)->getPass(0)->createTextureUnitState(tex->getName());
		t->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);

		OverlayContainer* debugPanel;
		
		// destroy container if exists
		try
		{
			if (debugPanel = 
				static_cast<OverlayContainer*>(
					mgr.getOverlayElement("Ogre/DebugTexPanel" + toStr(i)
				)))
				mgr.destroyOverlayElement(debugPanel);
		}
		catch (Ogre::Exception&) {}
		
		debugPanel = (OverlayContainer*)
			(OverlayManager::getSingleton().createOverlayElement("Panel", "Ogre/DebugTexPanel" + StringConverter::toString(i)));
		debugPanel->_setPosition(0.8, i*0.25);
		debugPanel->_setDimensions(0.2, 0.24);
		debugPanel->setMaterialName(debugMat->getName());
		debugPanel->show();
		overlay->add2D(debugPanel);
		overlay->show();
	}
	#endif
	
	// -------------------   update the paged-geom materials
	
	// grass is not cloned, just need to set new shader parameters
	if (grass)
	{
		GrassLoader *grassLoader = static_cast<GrassLoader*>(grass->getPageLoader());
		for (std::list<GrassLayer*>::iterator it= grassLoader->getLayerList().begin();
			it != grassLoader->getLayerList().end(); ++it)
		{
			GrassLayer* layer = (*it);
			layer->applyShader();
		}
	}
	
	// trees are more complicated since they are cloned
	//!todo this doesn't work (tree material does not update immediately)
	if(trees)
	{
		trees->reloadGeometry();
		std::vector<ResourcePtr> reosurceToDelete;
		ResourceManager::ResourceMapIterator it = MaterialManager::getSingleton().getResourceIterator();
		while (it.hasMoreElements())
		{
			ResourcePtr material = it.getNext();
			String materialName = material->getName();
			std::string::size_type pos =materialName.find("BatchMat|");
			if( pos != std::string::npos ) {
				reosurceToDelete.push_back(material);
			}
		}
		for(int i=0;i<reosurceToDelete.size();i++)
		{
			MaterialManager::getSingleton().remove(reosurceToDelete[i]);
		}
	}
	UpdPSSMMaterials();

	ti.update();	/// time
	float dt = ti.dt * 1000.f;
	LogO(String("::: Time Shadows: ") + toStr(dt) + " ms");
}
예제 #15
0
	//-----------------------------------------------------------------------
	void MaterialService::createStandardMaterial(unsigned int idx, std::string matName, std::string textureName,
	        std::string resourceGroup) {
		Image tex;
		bool loaded = false; // indicates we were successful finding the texture

		StringVectorPtr texnames = ResourceGroupManager::getSingleton().findResourceNames(resourceGroup, textureName
		        + ".*");

		if (texnames->size() <= 0) {
			// no results, try the localised version
			// prev. path + /language/filename
			String locresname = mConfigService->getLocalisedResourcePath(textureName);

			LOG_INFO("Specified resource (%s) was not found, trying localized version: %s", textureName.c_str(), locresname.c_str());

			texnames = ResourceGroupManager::getSingleton().findResourceNames(resourceGroup, locresname
					        + ".*");
		}

		String txtfile;

		// Let's try the extensions from the extensions vector
		StringVector::iterator it = texnames->begin();

		for (; it != texnames->end(); it++) { // Try loading every given
			try {
				tex.load((*it), resourceGroup);

				TextureManager::getSingleton().loadImage(textureName, resourceGroup, tex, TEX_TYPE_2D, 5, 1.0f);

				txtfile = (*it);

				loaded = true;

				break; // we got it!
			} catch (Ogre::Exception) {
				// Nothing. We are trying more extensions
			}
		}

		if (!loaded)
			LOG_ERROR("Image %s was not found, texture will be invalid!", textureName.c_str());

		// Construct a material out of this texture. We'll just clone the material upstairs to enable lmap-txture combinations
		MaterialPtr shadMat = MaterialManager::getSingleton().create(matName, resourceGroup);

		shadMat->setReceiveShadows(true);

		Pass *shadPass = shadMat->getTechnique(0)->getPass(0);

		shadPass->setAmbient(0.5, 0.5, 0.5);
		shadPass->setDiffuse(1, 1, 1, 1);
		shadPass->setSpecular(1, 1, 1, 1);

		TextureUnitState* tus = createAnimatedTextureState(shadPass, txtfile, resourceGroup, 5);

		// Set replace on all first layer textures for now
		// tus->setColourOperation(LBO_REPLACE);
		tus->setTextureAddressingMode(TextureUnitState::TAM_WRAP);
		tus->setTextureCoordSet(0);
		tus->setTextureFiltering(TFO_BILINEAR);

		tus->setTextureUScale(1.0f);
		tus->setTextureVScale(1.0f);
		// tus->setTextureFiltering(TFO_NONE);

		// Set culling mode to none
		// shadMat->setCullingMode(CULL_ANTICLOCKWISE);

		// No dynamic lighting
		shadMat->setLightingEnabled(false);

		// DYNL:
		shadMat->load();


		// standard size
		addWorldMaterialTemplate(idx, shadMat);
	}
예제 #16
0
void NIFLoader::createMaterial(const String &name,
                           const Vector &ambient,
                           const Vector &diffuse,
                           const Vector &specular,
                           const Vector &emissive,
                           float glossiness, float alpha,
                           int alphaFlags, float alphaTest,
                           const String &texName)
{
    MaterialPtr material = MaterialManager::getSingleton().create(name, resourceGroup);


    //Hardware Skinning code, textures may be the wrong color if enabled

    /* if(!mSkel.isNull()){
    material->removeAllTechniques();

        Ogre::Technique* tech = material->createTechnique();
        //tech->setSchemeName("blahblah");
        Pass* pass = tech->createPass();
        pass->setVertexProgram("Ogre/BasicVertexPrograms/AmbientOneTexture");*/
   

    // This assigns the texture to this material. If the texture name is
    // a file name, and this file exists (in a resource directory), it
    // will automatically be loaded when needed. If not (such as for
    // internal NIF textures that we might support later), we should
    // already have inserted a manual loader for the texture.


    if (!texName.empty())
    {
        Pass *pass = material->getTechnique(0)->getPass(0);
        /*TextureUnitState *txt =*/
        pass->createTextureUnitState(texName);

        pass->setVertexColourTracking(TVC_DIFFUSE);

        // As of yet UNTESTED code from Chris:
        /*pass->setTextureFiltering(Ogre::TFO_ANISOTROPIC);
        pass->setDepthFunction(Ogre::CMPF_LESS_EQUAL);
        pass->setDepthCheckEnabled(true);

        // Add transparency if NiAlphaProperty was present
        if (alphaFlags != -1)
        {
            std::cout << "Alpha flags set!" << endl;
            if ((alphaFlags&1))
            {
                pass->setDepthWriteEnabled(false);
                pass->setSceneBlending(getBlendFactor((alphaFlags>>1)&0xf),
                                       getBlendFactor((alphaFlags>>5)&0xf));
            }
            else
                pass->setDepthWriteEnabled(true);

            if ((alphaFlags>>9)&1)
                pass->setAlphaRejectSettings(getTestMode((alphaFlags>>10)&0x7),
                                             alphaTest);

            pass->setTransparentSortingEnabled(!((alphaFlags>>13)&1));
        }
        else
            pass->setDepthWriteEnabled(true); */


        // Add transparency if NiAlphaProperty was present
        if (alphaFlags != -1)
        {
            // The 237 alpha flags are by far the most common. Check
            // NiAlphaProperty in nif/property.h if you need to decode
            // other values. 237 basically means normal transparencly.
            if (alphaFlags == 237)
            {
                NifOverrides::TransparencyResult result = NifOverrides::Overrides::getTransparencyOverride(texName);
                if (result.first)
                {
                    pass->setAlphaRejectFunction(CMPF_GREATER_EQUAL);
                    pass->setAlphaRejectValue(result.second);
                }
                else
                {
                    // Enable transparency
                    pass->setSceneBlending(SBT_TRANSPARENT_ALPHA);

                    //pass->setDepthCheckEnabled(false);
                    pass->setDepthWriteEnabled(false);
                    //std::cout << "alpha 237; material: " << name << " texName: " << texName << std::endl;
                }
            }
            else
                warn("Unhandled alpha setting for texture " + texName);
        }
        else
        {
            material->getTechnique(0)->setShadowCasterMaterial("depth_shadow_caster_noalpha");
        }
    }

    if (Settings::Manager::getBool("enabled", "Shadows"))
    {
        bool split = Settings::Manager::getBool("split", "Shadows");
        const int numsplits = 3;
		for (int i = 0; i < (split ? numsplits : 1); ++i)
		{
            TextureUnitState* tu = material->getTechnique(0)->getPass(0)->createTextureUnitState();
            tu->setName("shadowMap" + StringConverter::toString(i));
            tu->setContentType(TextureUnitState::CONTENT_SHADOW);
            tu->setTextureAddressingMode(TextureUnitState::TAM_BORDER);
            tu->setTextureBorderColour(ColourValue::White);
		}
    }

    if (Settings::Manager::getBool("shaders", "Objects"))
    {
        material->getTechnique(0)->getPass(0)->setVertexProgram("main_vp");
        material->getTechnique(0)->getPass(0)->setFragmentProgram("main_fp");

        material->getTechnique(0)->getPass(0)->setFog(true); // force-disable fixed function fog, it is calculated in shader
    }

    // Create a fallback technique without shadows and without mrt
    Technique* tech2 = material->createTechnique();
    tech2->setSchemeName("Fallback");
    Pass* pass2 = tech2->createPass();
    pass2->createTextureUnitState(texName);
    pass2->setVertexColourTracking(TVC_DIFFUSE);
    if (Settings::Manager::getBool("shaders", "Objects"))
    {
        pass2->setVertexProgram("main_fallback_vp");
        pass2->setFragmentProgram("main_fallback_fp");
        pass2->setFog(true); // force-disable fixed function fog, it is calculated in shader
    }

    // Add material bells and whistles
    material->setAmbient(ambient.array[0], ambient.array[1], ambient.array[2]);
    material->setDiffuse(diffuse.array[0], diffuse.array[1], diffuse.array[2], alpha);
    material->setSpecular(specular.array[0], specular.array[1], specular.array[2], alpha);
    material->setSelfIllumination(emissive.array[0], emissive.array[1], emissive.array[2]);
    material->setShininess(glossiness);
}
	//---------------------------------------------------------------------
	void TerrainMaterialGeneratorA::SM2Profile::addTechnique(
		const MaterialPtr& mat, const Terrain* terrain, TechniqueType tt)
	{
		Technique* tech = mat->createTechnique();

		// Only supporting one pass
		Pass* pass = tech->createPass();

		GpuProgramManager& gmgr = GpuProgramManager::getSingleton();
		HighLevelGpuProgramManager& hmgr = HighLevelGpuProgramManager::getSingleton();
		if (!mShaderGen)
		{
			bool check2x = mLayerNormalMappingEnabled || mLayerParallaxMappingEnabled;
			if (hmgr.isLanguageSupported("cg"))
            {
				mShaderGen = OGRE_NEW ShaderHelperCg();
            }
			else if (hmgr.isLanguageSupported("hlsl") &&
				((check2x && gmgr.isSyntaxSupported("ps_4_0")) ||
				(check2x && gmgr.isSyntaxSupported("ps_2_x")) ||
				(!check2x && gmgr.isSyntaxSupported("ps_2_0"))))
            {
				mShaderGen = OGRE_NEW ShaderHelperHLSL();
            }
			else if (hmgr.isLanguageSupported("glsl"))
            {
				mShaderGen = OGRE_NEW ShaderHelperGLSL();
            }
			else if (hmgr.isLanguageSupported("glsles"))
            {
				mShaderGen = OGRE_NEW ShaderHelperGLSLES();
            }
			
			// check SM3 features
			mSM3Available = GpuProgramManager::getSingleton().isSyntaxSupported("ps_3_0");
			mSM4Available = GpuProgramManager::getSingleton().isSyntaxSupported("ps_4_0");
		}

		HighLevelGpuProgramPtr vprog = mShaderGen->generateVertexProgram(this, terrain, tt);
		HighLevelGpuProgramPtr fprog = mShaderGen->generateFragmentProgram(this, terrain, tt);

		pass->setVertexProgram(vprog->getName());
		pass->setFragmentProgram(fprog->getName());

		if (tt == HIGH_LOD || tt == RENDER_COMPOSITE_MAP)
		{
			// global normal map
			TextureUnitState* tu = pass->createTextureUnitState();
			tu->setTextureName(terrain->getTerrainNormalMap()->getName());
			tu->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);

			// global colour map
			if (terrain->getGlobalColourMapEnabled() && isGlobalColourMapEnabled())
			{
				tu = pass->createTextureUnitState(terrain->getGlobalColourMap()->getName());
				tu->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);
			}

			// light map
			if (isLightmapEnabled())
			{
				tu = pass->createTextureUnitState(terrain->getLightmap()->getName());
				tu->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);
			}

			// blend maps
			uint maxLayers = getMaxLayers(terrain);
			uint numBlendTextures = std::min(terrain->getBlendTextureCount(maxLayers), terrain->getBlendTextureCount());
			uint numLayers = std::min(maxLayers, static_cast<uint>(terrain->getLayerCount()));
			for (uint i = 0; i < numBlendTextures; ++i)
			{
				tu = pass->createTextureUnitState(terrain->getBlendTextureName(i));
				tu->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);
			}

			// layer textures
			for (uint i = 0; i < numLayers; ++i)
			{
				// diffuse / specular
				pass->createTextureUnitState(terrain->getLayerTextureName(i, 0));
				// normal / height
				pass->createTextureUnitState(terrain->getLayerTextureName(i, 1));
			}

		}
		else
		{
			// LOW_LOD textures
			// composite map
			TextureUnitState* tu = pass->createTextureUnitState();
			tu->setTextureName(terrain->getCompositeMap()->getName());
			tu->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);

			// That's it!

		}

		// Add shadow textures (always at the end)
		if (isShadowingEnabled(tt, terrain))
		{
			uint numTextures = 1;
			if (getReceiveDynamicShadowsPSSM())
			{
				numTextures = (uint)getReceiveDynamicShadowsPSSM()->getSplitCount();
			}
			for (uint i = 0; i < numTextures; ++i)
			{
				TextureUnitState* tu = pass->createTextureUnitState();
				tu->setContentType(TextureUnitState::CONTENT_SHADOW);
				tu->setTextureAddressingMode(TextureUnitState::TAM_BORDER);
				tu->setTextureBorderColour(ColourValue::White);
			}
		}

	}
예제 #18
0
//-------------------------------------------------------------------------------------
void BasicTutorial2::createScene(void)
{

	mSceneMgr->setAmbientLight(Ogre::ColourValue(0, 0, 0));
	//mSceneMgr->setShadowTechnique(Ogre::SHADOWTYPE_STENCIL_ADDITIVE);

	Ogre::Entity* entNinja = mSceneMgr->createEntity("Ninja", "ninja.mesh");
	entNinja->setCastShadows(true);
	mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(entNinja);

	Ogre::Plane plane(Ogre::Vector3::UNIT_Y, 0);

	Ogre::MeshManager::getSingleton().createPlane("ground", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
		plane, 1500, 1500, 20, 20, true, 1, 5, 5, Ogre::Vector3::UNIT_Z);

	Ogre::Entity* entGround = mSceneMgr->createEntity("GroundEntity", "ground");
	mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(entGround);

	entGround->setMaterialName("Examples/Rockwall");
	//entGround->setMaterialName("RttMat");
	entGround->setCastShadows(false);

	Ogre::Entity* ogreHead = mSceneMgr->createEntity("Head", "ogrehead.mesh");
	Ogre::SceneNode* headNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("HeadNode");
	headNode->attachObject(ogreHead);
	headNode->setPosition(50,120,0);

	Ogre::Light* pointLight = mSceneMgr->createLight("pointLight");
	pointLight->setType(Ogre::Light::LT_POINT);
	pointLight->setPosition(Ogre::Vector3(0, 150, 250));

	pointLight->setDiffuseColour(1.0, 0.0, 0.0);
	pointLight->setSpecularColour(1.0, 0.0, 0.0);

	Ogre::Light* directionalLight = mSceneMgr->createLight("directionalLight");
	directionalLight->setType(Ogre::Light::LT_DIRECTIONAL);
	directionalLight->setDiffuseColour(Ogre::ColourValue(.25, .25, 0));
	directionalLight->setSpecularColour(Ogre::ColourValue(.25, .25, 0));

	directionalLight->setDirection(Ogre::Vector3( 0, -1, 1 )); 

	Ogre::Light* spotLight = mSceneMgr->createLight("spotLight");
	spotLight->setType(Ogre::Light::LT_SPOTLIGHT);
	spotLight->setDiffuseColour(0, 0, 1.0);
	spotLight->setSpecularColour(0, 0, 1.0);

	spotLight->setDirection(-1, -1, 0);
	spotLight->setPosition(Ogre::Vector3(300, 300, 0));

	spotLight->setSpotlightRange(Ogre::Degree(35), Ogre::Degree(50));


	//------------------
	using namespace Ogre;
	TexturePtr texture = TextureManager::getSingleton().
		createManual( "RttTex",ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, 
		TEX_TYPE_2D,512, 512, 0, PF_R8G8B8, TU_RENDERTARGET );
	RenderTarget *rttTex = texture->getBuffer()->getRenderTarget();

	mReflectCam = mSceneMgr->createCamera("ReflectCam");
	mReflectCam->setOrientation(mCamera->getOrientation());
	mReflectCam->setPosition(mCamera->getPosition());
	mReflectCam->setNearClipDistance(mCamera->getNearClipDistance());

	mReflectCam->setFarClipDistance(mCamera->getFarClipDistance());

	mReflectCam->setAspectRatio(
		(Real)mWindow->getViewport(0)->getActualWidth() /
		(Real)mWindow->getViewport(0)->getActualHeight());
	Viewport *v = rttTex->addViewport( mReflectCam );
	v->setClearEveryFrame( true );
	v->setBackgroundColour( ColourValue::Black );

	//MaterialPtr mat = MaterialManager::getSingleton().create("RttMat",ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
	//TextureUnitState* t = mat->getTechnique(0)->getPass(0)->createTextureUnitState("RustedMetal.jpg");

	MaterialPtr mat;
	TextureUnitState *t = NULL;

	Entity *entMaterial = entGround ;

	int nCnt = entGround->getNumSubEntities();
	for ( int i=0; i<nCnt; i++)
	{
		SubEntity* _SubEnt = entMaterial->getSubEntity(i);
		MaterialPtr _MaterPtr;
		Pass * _Pass;
		mat = _SubEnt->getMaterial();
		break;
	}

	t = mat->getTechnique(0)->getPass(0)->createTextureUnitState("RttTex");
	// Blend with base texture
	t->setColourOperationEx(LBX_BLEND_MANUAL, LBS_TEXTURE, LBS_CURRENT,ColourValue::White,  ColourValue::White, 0.65);
	t->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);
	t->setProjectiveTexturing(true, mReflectCam);
	rttTex->addListener(this);
	// set up linked reflection
	mReflectCam->enableReflection(plane);
	// Also clip
	mReflectCam->enableCustomNearClipPlane(plane);
	//------------------
#if 0
	// skybox
	//mSceneMgr->setSkyBox(true, "Examples/SpaceSkyBox");//, 10);
	//mSceneMgr->setSkyBox(true, "Examples/SpaceSkyBox", 5000, false);
#endif
#if 0
	// skydome
	mSceneMgr->setSkyDome(true, "Examples/CloudySky", 5, 8);
#endif
#if 0
	//skyplane
	Ogre::Plane plane2;
	plane2.d = 1000;
	plane2.normal = Ogre::Vector3::NEGATIVE_UNIT_Y;
	//mSceneMgr->setSkyPlane(true, plane2, "Examples/SpaceSkyPlane", 1500, 75);
	mSceneMgr->setSkyPlane(true, plane, "Examples/CloudySky", 1500, 40, true, 1.5f, 150, 150);
#endif

#if 0
	Ogre::ColourValue fadeColour(0.9, 0.9, 0.9);
	mWindow->getViewport(0)->setBackgroundColour(fadeColour);
	//mSceneMgr->setFog(Ogre::FOG_LINEAR, fadeColour, 0.0, 50, 500);
	//mSceneMgr->setFog(Ogre::FOG_EXP, fadeColour, 0.005);
	mSceneMgr->setFog(Ogre::FOG_EXP2, fadeColour, 0.003);
#endif
	{
		Ogre::ColourValue fadeColour(0.1, 0.1, 0.1);
		mWindow->getViewport(0)->setBackgroundColour(fadeColour);
		mSceneMgr->setFog(Ogre::FOG_LINEAR, fadeColour, 0.0, 10, 150);

		Ogre::Plane plane;
		plane.d = 10;
		plane.normal = Ogre::Vector3::NEGATIVE_UNIT_Y;

		mSceneMgr->setSkyPlane(true, plane, "Examples/SpaceSkyPlane", 100, 45, true, 0.5, 150, 150);
	}
}