コード例 #1
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);
	}
コード例 #2
0
ファイル: Viewer.cpp プロジェクト: bytewrench/NxOgre-Pinball
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

    }
コード例 #3
0
ファイル: ogre_nif_loader.cpp プロジェクト: Thynix/openmw
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);
}
コード例 #4
0
	//---------------------------------------------------------------------
	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);
			}
		}

	}
コード例 #5
0
ファイル: OgreRenderSystem.cpp プロジェクト: logtcn/ogre
//-----------------------------------------------------------------------
void RenderSystem::_setTextureUnitSettings(size_t texUnit, TextureUnitState& tl)
{
    // This method is only ever called to set a texture unit to valid details
    // The method _disableTextureUnit is called to turn a unit off

    const TexturePtr& tex = tl._getTexturePtr();
    // Vertex texture binding?
    if (mCurrentCapabilities->hasCapability(RSC_VERTEX_TEXTURE_FETCH) &&
            !mCurrentCapabilities->getVertexTextureUnitsShared())
    {
        if (tl.getBindingType() == TextureUnitState::BT_VERTEX)
        {
            // Bind vertex texture
            _setVertexTexture(texUnit, tex);
            // bind nothing to fragment unit (hardware isn't shared but fragment
            // unit can't be using the same index
            _setTexture(texUnit, true, sNullTexPtr);
        }
        else
        {
            // vice versa
            _setVertexTexture(texUnit, sNullTexPtr);
            _setTexture(texUnit, true, tex);
        }
    }
    else
    {
        // Shared vertex / fragment textures or no vertex texture support
        // Bind texture (may be blank)
        _setTexture(texUnit, true, tex);
    }

    // Set texture coordinate set
    _setTextureCoordSet(texUnit, tl.getTextureCoordSet());

    // Set texture layer filtering
    _setTextureUnitFiltering(texUnit,
                             tl.getTextureFiltering(FT_MIN),
                             tl.getTextureFiltering(FT_MAG),
                             tl.getTextureFiltering(FT_MIP));

    // Set texture layer filtering
    _setTextureLayerAnisotropy(texUnit, tl.getTextureAnisotropy());

    // Set mipmap biasing
    _setTextureMipmapBias(texUnit, tl.getTextureMipmapBias());

    // Set blend modes
    // Note, colour before alpha is important
    _setTextureBlendMode(texUnit, tl.getColourBlendMode());
    _setTextureBlendMode(texUnit, tl.getAlphaBlendMode());

    // Texture addressing mode
    const TextureUnitState::UVWAddressingMode& uvw = tl.getTextureAddressingMode();
    _setTextureAddressingMode(texUnit, uvw);
    // Set texture border colour only if required
    if (uvw.u == TextureUnitState::TAM_BORDER ||
            uvw.v == TextureUnitState::TAM_BORDER ||
            uvw.w == TextureUnitState::TAM_BORDER)
    {
        _setTextureBorderColour(texUnit, tl.getTextureBorderColour());
    }

    // Set texture effects
    TextureUnitState::EffectMap::iterator effi;
    // Iterate over new effects
    bool anyCalcs = false;
    for (effi = tl.mEffects.begin(); effi != tl.mEffects.end(); ++effi)
    {
        switch (effi->second.type)
        {
        case TextureUnitState::ET_ENVIRONMENT_MAP:
            if (effi->second.subtype == TextureUnitState::ENV_CURVED)
            {
                _setTextureCoordCalculation(texUnit, TEXCALC_ENVIRONMENT_MAP);
                anyCalcs = true;
            }
            else if (effi->second.subtype == TextureUnitState::ENV_PLANAR)
            {
                _setTextureCoordCalculation(texUnit, TEXCALC_ENVIRONMENT_MAP_PLANAR);
                anyCalcs = true;
            }
            else if (effi->second.subtype == TextureUnitState::ENV_REFLECTION)
            {
                _setTextureCoordCalculation(texUnit, TEXCALC_ENVIRONMENT_MAP_REFLECTION);
                anyCalcs = true;
            }
            else if (effi->second.subtype == TextureUnitState::ENV_NORMAL)
            {
                _setTextureCoordCalculation(texUnit, TEXCALC_ENVIRONMENT_MAP_NORMAL);
                anyCalcs = true;
            }
            break;
        case TextureUnitState::ET_UVSCROLL:
        case TextureUnitState::ET_USCROLL:
        case TextureUnitState::ET_VSCROLL:
        case TextureUnitState::ET_ROTATE:
        case TextureUnitState::ET_TRANSFORM:
            break;
        case TextureUnitState::ET_PROJECTIVE_TEXTURE:
            _setTextureCoordCalculation(texUnit, TEXCALC_PROJECTIVE_TEXTURE,
                                        effi->second.frustum);
            anyCalcs = true;
            break;
        }
    }
    // Ensure any previous texcoord calc settings are reset if there are now none
    if (!anyCalcs)
    {
        _setTextureCoordCalculation(texUnit, TEXCALC_NONE);
    }

    // Change tetxure matrix
    _setTextureMatrix(texUnit, tl.getTextureTransform());


}
コード例 #6
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 = WFT_SINE;
                    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;
    }
コード例 #7
0
    //-----------------------------------------------------------------------
    void Technique::_compileIlluminationPasses(void)
    {
        clearIlluminationPasses();

		if (!checkManuallyOrganisedIlluminationPasses())
		{
			// Build based on our own heuristics

			Passes::iterator i, iend;
			iend = mPasses.end();
			i = mPasses.begin();

			IlluminationStage iStage = IS_AMBIENT;

			bool haveAmbient = false;
			while (i != iend)
			{
				IlluminationPass* iPass;
				Pass* p = *i;
				switch(iStage)
				{
				case IS_AMBIENT:
					// Keep looking for ambient only
					if (p->isAmbientOnly())
					{
						// Add this pass wholesale
						iPass = OGRE_NEW IlluminationPass();
						iPass->destroyOnShutdown = false;
						iPass->originalPass = iPass->pass = p;
						iPass->stage = iStage;
						mIlluminationPasses.push_back(iPass);
						haveAmbient = true;
						// progress to next pass
						++i;
					}
					else
					{
						// Split off any ambient part
						if (p->getAmbient() != ColourValue::Black ||
							p->getSelfIllumination() != ColourValue::Black ||
							p->getAlphaRejectFunction() != CMPF_ALWAYS_PASS)
						{
							// Copy existing pass
							Pass* newPass = OGRE_NEW Pass(this, p->getIndex(), *p);
							if (newPass->getAlphaRejectFunction() != CMPF_ALWAYS_PASS)
							{
								// Alpha rejection passes must retain their transparency, so
								// we allow the texture units, but override the colour functions
								Pass::TextureUnitStateIterator tusi = newPass->getTextureUnitStateIterator();
								while (tusi.hasMoreElements())
								{
									TextureUnitState* tus = tusi.getNext();
									tus->setColourOperationEx(LBX_SOURCE1, LBS_CURRENT);
								}
							}
							else
							{
								// Remove any texture units
								newPass->removeAllTextureUnitStates();
							}
							// Remove any fragment program
							if (newPass->hasFragmentProgram())
								newPass->setFragmentProgram("");
							// We have to leave vertex program alone (if any) and
							// just trust that the author is using light bindings, which
							// we will ensure there are none in the ambient pass
							newPass->setDiffuse(0, 0, 0, newPass->getDiffuse().a);  // Preserving alpha
							newPass->setSpecular(ColourValue::Black);

							// Calculate hash value for new pass, because we are compiling
							// illumination passes on demand, which will loss hash calculate
							// before it add to render queue first time.
							newPass->_recalculateHash();

							iPass = OGRE_NEW IlluminationPass();
							iPass->destroyOnShutdown = true;
							iPass->originalPass = p;
							iPass->pass = newPass;
							iPass->stage = iStage;

							mIlluminationPasses.push_back(iPass);
							haveAmbient = true;

						}

						if (!haveAmbient)
						{
							// Make up a new basic pass
							Pass* newPass = OGRE_NEW Pass(this, p->getIndex());
							newPass->setAmbient(ColourValue::Black);
							newPass->setDiffuse(ColourValue::Black);

							// Calculate hash value for new pass, because we are compiling
							// illumination passes on demand, which will loss hash calculate
							// before it add to render queue first time.
							newPass->_recalculateHash();

							iPass = OGRE_NEW IlluminationPass();
							iPass->destroyOnShutdown = true;
							iPass->originalPass = p;
							iPass->pass = newPass;
							iPass->stage = iStage;
							mIlluminationPasses.push_back(iPass);
							haveAmbient = true;
						}
						// This means we're done with ambients, progress to per-light
						iStage = IS_PER_LIGHT;
					}
					break;
				case IS_PER_LIGHT:
					if (p->getIteratePerLight())
					{
						// If this is per-light already, use it directly
						iPass = OGRE_NEW IlluminationPass();
						iPass->destroyOnShutdown = false;
						iPass->originalPass = iPass->pass = p;
						iPass->stage = iStage;
						mIlluminationPasses.push_back(iPass);
						// progress to next pass
						++i;
					}
					else
					{
						// Split off per-light details (can only be done for one)
						if (p->getLightingEnabled() &&
							(p->getDiffuse() != ColourValue::Black ||
							p->getSpecular() != ColourValue::Black))
						{
							// Copy existing pass
							Pass* newPass = OGRE_NEW Pass(this, p->getIndex(), *p);
							if (newPass->getAlphaRejectFunction() != CMPF_ALWAYS_PASS)
							{
								// Alpha rejection passes must retain their transparency, so
								// we allow the texture units, but override the colour functions
								Pass::TextureUnitStateIterator tusi = newPass->getTextureUnitStateIterator();
								while (tusi.hasMoreElements())
								{
									TextureUnitState* tus = tusi.getNext();
									tus->setColourOperationEx(LBX_SOURCE1, LBS_CURRENT);
								}
							}
							else
							{
								// remove texture units
								newPass->removeAllTextureUnitStates();
							}
							// remove fragment programs
							if (newPass->hasFragmentProgram())
								newPass->setFragmentProgram("");
							// Cannot remove vertex program, have to assume that
							// it will process diffuse lights, ambient will be turned off
							newPass->setAmbient(ColourValue::Black);
							newPass->setSelfIllumination(ColourValue::Black);
							// must be additive
							newPass->setSceneBlending(SBF_ONE, SBF_ONE);

							// Calculate hash value for new pass, because we are compiling
							// illumination passes on demand, which will loss hash calculate
							// before it add to render queue first time.
							newPass->_recalculateHash();

							iPass = OGRE_NEW IlluminationPass();
							iPass->destroyOnShutdown = true;
							iPass->originalPass = p;
							iPass->pass = newPass;
							iPass->stage = iStage;

							mIlluminationPasses.push_back(iPass);

						}
						// This means the end of per-light passes
						iStage = IS_DECAL;
					}
					break;
				case IS_DECAL:
					// We just want a 'lighting off' pass to finish off
					// and only if there are texture units
					if (p->getNumTextureUnitStates() > 0)
					{
						if (!p->getLightingEnabled())
						{
							// we assume this pass already combines as required with the scene
							iPass = OGRE_NEW IlluminationPass();
							iPass->destroyOnShutdown = false;
							iPass->originalPass = iPass->pass = p;
							iPass->stage = iStage;
							mIlluminationPasses.push_back(iPass);
						}
						else
						{
							// Copy the pass and tweak away the lighting parts
							Pass* newPass = OGRE_NEW Pass(this, p->getIndex(), *p);
							newPass->setAmbient(ColourValue::Black);
							newPass->setDiffuse(0, 0, 0, newPass->getDiffuse().a);  // Preserving alpha
							newPass->setSpecular(ColourValue::Black);
							newPass->setSelfIllumination(ColourValue::Black);
							newPass->setLightingEnabled(false);
							newPass->setIteratePerLight(false, false);
							// modulate
							newPass->setSceneBlending(SBF_DEST_COLOUR, SBF_ZERO);

							// Calculate hash value for new pass, because we are compiling
							// illumination passes on demand, which will loss hash calculate
							// before it add to render queue first time.
							newPass->_recalculateHash();

							// NB there is nothing we can do about vertex & fragment
							// programs here, so people will just have to make their
							// programs friendly-like if they want to use this technique
							iPass = OGRE_NEW IlluminationPass();
							iPass->destroyOnShutdown = true;
							iPass->originalPass = p;
							iPass->pass = newPass;
							iPass->stage = iStage;
							mIlluminationPasses.push_back(iPass);

						}
					}
					++i; // always increment on decal, since nothing more to do with this pass

					break;
                case IS_UNKNOWN:
                    break;
				}
			}
		}

    }
コード例 #8
0
ファイル: MeshObject.cpp プロジェクト: Winceros/main
void MeshObject::loadMesh()
{
    try
    {
        Ogre::String resourceGroup = Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME;
        mesh = static_cast<Ogre::MeshPtr>(Ogre::MeshManager::getSingleton().create(meshName, resourceGroup));
        if(backgroundLoading)
        {
            mesh->setBackgroundLoaded(true);
            mesh->addListener(this);
            ticket = Ogre::ResourceBackgroundQueue::getSingleton().load(
                         Ogre::MeshManager::getSingletonPtr()->getResourceType(),
                         mesh->getName(),
                         resourceGroup,
                         false,
                         0,
                         0,
                         0);

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

                        }
                    }

                }
            }
        }

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

}
コード例 #9
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");
}
コード例 #10
0
void WaterMaterialGenerator::generate()
{
	mMaterial = prepareMaterial(mDef->getName());
	
	resetTexUnitCounter();
	
	// we need a lot of uniform constants, disabling shadows reduces them significantly so that it can still run on PS2
	const RenderSystemCapabilities *caps = Root::getSingleton().getRenderSystem()->getCapabilities();
	if(!caps->isShaderProfileSupported("ps_4_0") && !caps->isShaderProfileSupported("fp40"))
		mDef->mProps->receivesShadows = false;

	
	// -------------------------- Main technique ----------------------------- //
	Ogre::Technique* technique = mMaterial->createTechnique();

	//  Main pass -----------------------------------------------------------
	Ogre::Pass* pass = technique->createPass();
	
	pass->setCullingMode(CULL_NONE);
	pass->setDepthWriteEnabled(true);
	
	if (!mParent->getRefract())
		pass->setSceneBlending(SBT_TRANSPARENT_ALPHA);
	
	Ogre::TextureUnitState* tu;
	//  normal map
	mNormalMap = pickTexture(&mDef->mProps->normalMaps);
	tu = pass->createTextureUnitState( mNormalMap );
	tu->setName("normalMap");
	mNormalTexUnit = mTexUnit_i; mTexUnit_i++;

	// global terrain lightmap (static)
	if (needTerrainLightMap())
	{
		tu = pass->createTextureUnitState(""); // texture name set later (in changeShadows)
		tu->setName("terrainLightMap");
		mTerrainLightTexUnit = mTexUnit_i; mTexUnit_i++;
	}

	if (mParent->getRefract())
	{
		tu = pass->createTextureUnitState( "PlaneRefraction" );
		tu->setName("refractionMap");
		tu->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);
		mScreenRefrUnit = mTexUnit_i++;
	}
	if (mParent->getReflect())
	{
		tu = pass->createTextureUnitState( "PlaneReflection" );
		tu->setName("reflectionMap");
		tu->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);
		mScreenReflUnit = mTexUnit_i++;
	}
	//else
	{
		// retrieve sky texture name from scene
		std::string skyTexName;
		if (mParent->pApp->terrain)
		{
			MaterialPtr mtrSky = MaterialManager::getSingleton().getByName(mParent->pApp->sc.skyMtr);
			if(!mtrSky.isNull())
			{
				Pass* passSky = mtrSky->getTechnique(0)->getPass(0);
				TextureUnitState* tusSky = passSky->getTextureUnitState(0);

				skyTexName = tusSky->getTextureName();
			}
		}
		else skyTexName = String("white.png");
		
		tu = pass->createTextureUnitState( skyTexName );
		tu->setName("skyMap");
		tu->setTextureAddressingMode(TextureUnitState::TAM_MIRROR);
		mEnvTexUnit = mTexUnit_i++;
	}
	
	//  waterDepth
	tu = pass->createTextureUnitState( "waterDepth.png" );
	tu->setName("depthMap");
	tu->setTextureAddressingMode(TextureUnitState::TAM_BORDER);
	tu->setTextureBorderColour(ColourValue::White);  // outside tex water always visible
	mWaterDepthUnit = mTexUnit_i;  mTexUnit_i++;
	
	
	// realtime shadow maps
	if (needShadows())
	{
		mShadowTexUnit_start = mTexUnit_i;
		for (int i = 0; i < mParent->getNumShadowTex(); ++i)
		{
			tu = pass->createTextureUnitState();
			tu->setName("shadowMap" + toStr(i));
			tu->setContentType(TextureUnitState::CONTENT_SHADOW);
			tu->setTextureAddressingMode(TextureUnitState::TAM_BORDER);
			tu->setTextureBorderColour(ColourValue::White);
			mTexUnit_i++;
		}
	}
	
	// shader
	if (!mShaderCached)
	{
		mVertexProgram = createVertexProgram();
		mFragmentProgram = createFragmentProgram();
	}
	
	pass->setVertexProgram(mVertexProgram->getName());
	pass->setFragmentProgram(mFragmentProgram->getName());
	
	if (mShaderCached)
	{
		individualFragmentProgramParams(pass->getFragmentProgramParameters());
		individualVertexProgramParams(pass->getFragmentProgramParameters());
	}

	// ----------------------------------------------------------------------- //
	
	createSSAOTechnique();
	createOccluderTechnique();

	// indicate we need 'time' parameter set every frame
	mParent->timeMtrs.push_back(mDef->getName());
	/*
	if (mDef->getName() == "Grease_jelly")
	{
		LogO("[MaterialFactory] Vertex program source: ");
		StringUtil::StrStreamType vSourceStr;
		generateVertexProgramSource(vSourceStr);
		LogO(vSourceStr.str());
		LogO("[MaterialFactory] Fragment program source: ");
		StringUtil::StrStreamType fSourceStr;
		generateFragmentProgramSource(fSourceStr);
		LogO(fSourceStr.str());
	}
	/**/
}
コード例 #11
0
ファイル: Shadows.cpp プロジェクト: ddxxpp/stuntrally
///  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));
}
コード例 #12
0
ファイル: CarReflection.cpp プロジェクト: jsj2008/stuntrally
void CarReflection::Create()
{
	bFirstFrame = true;
	if (pSet->refl_mode == "single")  cubetexName = "ReflectionCube"; // single: use 1st cubemap
	else if (pSet->refl_mode == "full")
	{
		cubetexName = "ReflectionCube" + toStr(iIndex);
		// first cubemap: no index
		if (cubetexName == "ReflectionCube0")
			cubetexName = "ReflectionCube";
	}
	else /* static */
		cubetexName = "ReflectionCube";
	
	TextureManager* tm = TextureManager::getSingletonPtr();
	int size = ciShadowSizesA[pSet->refl_size];  // /2 ?

	//  create cube render texture
	if (! (pSet->refl_mode == "single" && iIndex != 0) )
	{
		cubetex = tm->createManual(cubetexName, 
			ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, TEX_TYPE_CUBE_MAP, 
			size,size, 0/*mips*/, PF_R8G8B8, TU_RENDERTARGET);
			//LogO("created rt cube");

		for (int face = 0; face < 6; face++)
		{
			Camera* mCam = pSceneMgr->createCamera("Reflect_" + toStr(iIndex) + "_" + toStr(face));
			mCam->setAspectRatio(1.0f);  mCam->setFOVy(Degree(90));
			mCam->setNearClipDistance(0.1);
			//mCam->setFarClipDistance(pSet->refl_dist);  //sky-

			RenderTarget* mRT = cubetex->getBuffer(face)->getRenderTarget();
			//LogO( "rt face Name: " + mRT->getName() );
			mRT->removeAllViewports();
			Viewport* vp = mRT->addViewport(mCam);
			vp->setOverlaysEnabled(false);
			vp->setVisibilityMask(RV_MaskReflect);
			mRT->setAutoUpdated(false);
			//mRT->addListener(this);  //-
			mCam->setPosition(Vector3::ZERO);

			Vector3 lookAt(0,0,0), up(0,0,0), right(0,0,0);  switch(face)
			{
				case 0:  lookAt.x =-1;  up.y = 1;  right.z = 1;  break;  // +X
				case 1:  lookAt.x = 1;  up.y = 1;  right.z =-1;  break;	 // -X
				case 2:  lookAt.y =-1;  up.z = 1;  right.x = 1;  break;	 // +Y
				case 3:  lookAt.y = 1;  up.z =-1;  right.x = 1;  break;	 // -Y
				case 4:  lookAt.z = 1;  up.y = 1;  right.x =-1;  break;	 // +Z
				case 5:  lookAt.z =-1;  up.y = 1;  right.x =-1;  break;	 // -Z
			}
			Quaternion orient( right, up, lookAt );  mCam->setOrientation( orient );
			pCams[face] = mCam;
			pRTs[face] = mRT;
		}
	}
	
	// Iterate through our materials and add an index to ReflectionCube texture reference
	for (int i=0; i < NumMaterials; i++)
	{
		MaterialPtr mtr = MaterialManager::getSingleton().getByName(sMtr[i]);
		if (!mtr.isNull())
		{	Material::TechniqueIterator techIt = mtr->getTechniqueIterator();
			while (techIt.hasMoreElements())
			{	Technique* tech = techIt.getNext();
				Technique::PassIterator passIt = tech->getPassIterator();
				while (passIt.hasMoreElements())
				{	Pass* pass = passIt.getNext();
					Pass::TextureUnitStateIterator tusIt = pass->getTextureUnitStateIterator();
					while (tusIt.hasMoreElements())
					{	
						TextureUnitState* tus = tusIt.getNext();
						if (tus->getTextureName() == "ReflectionCube")
							tus->setTextureName(cubetexName);
	}	}	}	}	}
}
コード例 #13
0
void MaterialFactory::setShaderParams(MaterialPtr mat)
{
	if (mat.isNull()) return;
		
	Material::TechniqueIterator techIt = mat->getTechniqueIterator();
	while (techIt.hasMoreElements())
	{
		Technique* tech = techIt.getNext();
		Technique::PassIterator passIt = tech->getPassIterator();
		while (passIt.hasMoreElements())
		{
			Pass* pass = passIt.getNext();
								
			if (pass->hasFragmentProgram())
			{
				// shadow fading parameters
				if ( getShadowsFade()
					&& pass->getFragmentProgramParameters()->_findNamedConstantDefinition("fadeStart_farDist", false)
					&& mSceneMgr
				)
				{
					float fadeDist;
					if (mSceneMgr->getShadowFarDistance() != 0)
						fadeDist = getShadowsFadeDistance()/mSceneMgr->getShadowFarDistance();
					else
						fadeDist = 0.f;
														
					pass->getFragmentProgramParameters()->setNamedConstant("fadeStart_farDist", Vector3(
						fadeDist,
						mSceneMgr->getShadowFarDistance(),
						float(getShadowsFade())
					));
				}
				// terrain lightmap name & size
				if ( mTerrain && !mTerrain->getLightmap().isNull() )
				{
					if (pass->getFragmentProgramParameters()->_findNamedConstantDefinition("terrainWorldSize", false))
						pass->getFragmentProgramParameters()->setNamedConstant( "terrainWorldSize", Real( mTerrain->getWorldSize() ) );
					
					Pass::TextureUnitStateIterator tusIt = pass->getTextureUnitStateIterator();
					while (tusIt.hasMoreElements())
					{
						TextureUnitState* tus = tusIt.getNext();
						if (tus->getName() == "terrainLightMap")
						{
							tus->setTextureName( mTerrain->getLightmap()->getName() );
						}
					}
				}
				
				if (pass->getFragmentProgramParameters()->_findNamedConstantDefinition("invTerSize", false))
					pass->getFragmentProgramParameters()->setNamedConstant("invTerSize", 1.f / Real(pApp->sc.td.fTerWorldSize));

				// pssm split points
				if ( pass->getFragmentProgramParameters()->_findNamedConstantDefinition("pssmSplitPoints", false) && mPSSM)
				{
					const PSSMShadowCameraSetup::SplitPointList& splitPointList = mPSSM->getSplitPoints();
					Vector4 splitPoints;
					for (size_t i = 0; i < splitPointList.size(); ++i)
						splitPoints[i] = splitPointList[i];
						
					pass->getFragmentProgramParameters()->setNamedConstant("pssmSplitPoints", splitPoints);
				}
			}
		}
	}
}
コード例 #14
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.5f;
			float ycoord = coords[y][1]-0.5f;
			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
	if (!ResourceGroupManager::getSingleton().resourceGroupExists("VolumeRenderable"))
	{
		ResourceGroupManager::getSingleton().createResourceGroup("VolumeRenderable");
	}
	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;
	mMaterial = material;
}
コード例 #15
0
	//---------------------------------------------------------------------
	bool Technique::checkHardwareSupport(bool autoManageTextureUnits, StringStream& compileErrors)
	{
		// Go through each pass, checking requirements
		Passes::iterator i;
		unsigned short passNum = 0;
		const RenderSystemCapabilities* caps =
			Root::getSingleton().getRenderSystem()->getCapabilities();
		unsigned short numTexUnits = caps->getNumTextureUnits();
		for (i = mPasses.begin(); i != mPasses.end(); ++i, ++passNum)
		{
			Pass* currPass = *i;
			// Adjust pass index
			currPass->_notifyIndex(passNum);
			// Check for advanced blending operation support
			if((currPass->getSceneBlendingOperation() != SBO_ADD || currPass->getSceneBlendingOperationAlpha() != SBO_ADD) && 
				!caps->hasCapability(RSC_ADVANCED_BLEND_OPERATIONS))
			{
				return false;		
			}
			// Check texture unit requirements
			size_t numTexUnitsRequested = currPass->getNumTextureUnitStates();
			// Don't trust getNumTextureUnits for programmable
			if(!currPass->hasFragmentProgram())
			{
#if defined(OGRE_PRETEND_TEXTURE_UNITS) && OGRE_PRETEND_TEXTURE_UNITS > 0
				if (numTexUnits > OGRE_PRETEND_TEXTURE_UNITS)
					numTexUnits = OGRE_PRETEND_TEXTURE_UNITS;
#endif
				if (numTexUnitsRequested > numTexUnits)
				{
					if (!autoManageTextureUnits)
					{
						// The user disabled auto pass split
						compileErrors << "Pass " << passNum << 
							": Too many texture units for the current hardware and no splitting allowed."
							<< std::endl;
						return false;
					}
					else if (currPass->hasVertexProgram())
					{
						// Can't do this one, and can't split a programmable pass
						compileErrors << "Pass " << passNum << 
							": Too many texture units for the current hardware and "
							"cannot split programmable passes."
							<< std::endl;
						return false;
					}
				}
			}
			if (currPass->hasComputeProgram())
			{
				// Check fragment program version
				if (!currPass->getComputeProgram()->isSupported())
				{
					// Can't do this one
					compileErrors << "Pass " << passNum << 
						": Compute program " << currPass->getComputeProgram()->getName()
						<< " cannot be used - ";
					if (currPass->getComputeProgram()->hasCompileError())
						compileErrors << "compile error.";
					else
						compileErrors << "not supported.";

					compileErrors << std::endl;
					return false;
				}
			}
			if (currPass->hasVertexProgram())
			{
				// Check vertex program version
				if (!currPass->getVertexProgram()->isSupported() )
				{
					// Can't do this one
					compileErrors << "Pass " << passNum << 
						": Vertex program " << currPass->getVertexProgram()->getName()
						<< " cannot be used - ";
					if (currPass->getVertexProgram()->hasCompileError())
						compileErrors << "compile error.";
					else
						compileErrors << "not supported.";

					compileErrors << std::endl;
					return false;
				}
			}
			if (currPass->hasTessellationHullProgram())
			{
				// Check tessellation control program version
				if (!currPass->getTessellationHullProgram()->isSupported() )
				{
					// Can't do this one
					compileErrors << "Pass " << passNum << 
						": Tessellation Hull program " << currPass->getTessellationHullProgram()->getName()
						<< " cannot be used - ";
					if (currPass->getTessellationHullProgram()->hasCompileError())
						compileErrors << "compile error.";
					else
						compileErrors << "not supported.";

					compileErrors << std::endl;
					return false;
				}
			}
			if (currPass->hasTessellationDomainProgram())
			{
				// Check tessellation control program version
				if (!currPass->getTessellationDomainProgram()->isSupported() )
				{
					// Can't do this one
					compileErrors << "Pass " << passNum << 
						": Tessellation Domain program " << currPass->getTessellationDomainProgram()->getName()
						<< " cannot be used - ";
					if (currPass->getTessellationDomainProgram()->hasCompileError())
						compileErrors << "compile error.";
					else
						compileErrors << "not supported.";

					compileErrors << std::endl;
					return false;
				}
			}
			if (currPass->hasGeometryProgram())
			{
				// Check geometry program version
				if (!currPass->getGeometryProgram()->isSupported() )
				{
					// Can't do this one
					compileErrors << "Pass " << passNum << 
						": Geometry program " << currPass->getGeometryProgram()->getName()
						<< " cannot be used - ";
					if (currPass->getGeometryProgram()->hasCompileError())
						compileErrors << "compile error.";
					else
						compileErrors << "not supported.";

					compileErrors << std::endl;
					return false;
				}
			}
			if (currPass->hasFragmentProgram())
			{
				// Check fragment program version
				if (!currPass->getFragmentProgram()->isSupported())
				{
					// Can't do this one
					compileErrors << "Pass " << passNum << 
						": Fragment program " << currPass->getFragmentProgram()->getName()
						<< " cannot be used - ";
					if (currPass->getFragmentProgram()->hasCompileError())
						compileErrors << "compile error.";
					else
						compileErrors << "not supported.";

					compileErrors << std::endl;
					return false;
				}
			}
			else
			{
				// Check a few fixed-function options in texture layers
				Pass::TextureUnitStateIterator texi = currPass->getTextureUnitStateIterator();
				size_t texUnit = 0;
				while (texi.hasMoreElements())
				{
					TextureUnitState* tex = texi.getNext();
					// Any Cube textures? NB we make the assumption that any
					// card capable of running fragment programs can support
					// cubic textures, which has to be true, surely?
					if (tex->is3D() && !caps->hasCapability(RSC_CUBEMAPPING))
					{
						// Fail
						compileErrors << "Pass " << passNum << 
							" Tex " << texUnit <<
							": Cube maps not supported by current environment."
							<< std::endl;
						return false;
					}
					// Any 3D textures? NB we make the assumption that any
					// card capable of running fragment programs can support
					// 3D textures, which has to be true, surely?
					if (((tex->getTextureType() == TEX_TYPE_3D) || (tex->getTextureType() == TEX_TYPE_2D_ARRAY)) && 
                         !caps->hasCapability(RSC_TEXTURE_3D))
					{
						// Fail
						compileErrors << "Pass " << passNum << 
							" Tex " << texUnit <<
							": Volume textures not supported by current environment."
							<< std::endl;
						return false;
					}
					// Any Dot3 blending?
					if (tex->getColourBlendMode().operation == LBX_DOTPRODUCT &&
						!caps->hasCapability(RSC_DOT3))
					{
						// Fail
						compileErrors << "Pass " << passNum << 
							" Tex " << texUnit <<
							": DOT3 blending not supported by current environment."
							<< std::endl;
						return false;
					}
					++texUnit;
				}

				// We're ok on operations, now we need to check # texture units
				if (!currPass->hasFragmentProgram())
				{
					// Keep splitting this pass so long as units requested > gpu units
					while (numTexUnitsRequested > numTexUnits)
					{
						// chop this pass into many passes
						currPass = currPass->_split(numTexUnits);
						numTexUnitsRequested = currPass->getNumTextureUnitStates();
						// Advance pass number
						++passNum;
						// Reset iterator
						i = mPasses.begin() + passNum;
						// Move the new pass to the right place (will have been created
						// at the end, may be other passes in between)
						assert(mPasses.back() == currPass);
						std::copy_backward(i, (mPasses.end()-1), mPasses.end());
						*i = currPass;
						// Adjust pass index
						currPass->_notifyIndex(passNum);
					}
				}
			}

		}
		// If we got this far, we're ok
		return true;
	}
コード例 #16
0
ファイル: bground.cpp プロジェクト: fishilico/funguloids
// Create the background nebulae
void createBackground(SceneManager *sceneMgr) {
	
	// Get the background image
	String bgImage = ScriptSystem::getSingleton().getScriptString("backgroundImage");
	MaterialPtr mat = MaterialManager::getSingleton().getByName("Background");
	mat->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setTextureName(bgImage);

	// Get the nebula textures, and set their colors
	ColourValue col;
	col.r = ScriptSystem::getSingleton().getScriptNumber("nebula1_R");
	col.g = ScriptSystem::getSingleton().getScriptNumber("nebula1_G");
	col.b = ScriptSystem::getSingleton().getScriptNumber("nebula1_B");
	mat = MaterialManager::getSingleton().getByName("BackgroundNebula1");
	TextureUnitState *tu = mat->getTechnique(0)->getPass(0)->getTextureUnitState(1);
	tu->setColourOperationEx(LBX_MODULATE, LBS_CURRENT, LBS_MANUAL, col, col);

	col.r = ScriptSystem::getSingleton().getScriptNumber("nebula2_R");
	col.g = ScriptSystem::getSingleton().getScriptNumber("nebula2_G");
	col.b = ScriptSystem::getSingleton().getScriptNumber("nebula2_B");
	mat = MaterialManager::getSingleton().getByName("BackgroundNebula2");
	tu = mat->getTechnique(0)->getPass(0)->getTextureUnitState(1);
	tu->setColourOperationEx(LBX_MODULATE, LBS_CURRENT, LBS_MANUAL, col, col);

	col.r = ScriptSystem::getSingleton().getScriptNumber("nebula3_R");
	col.g = ScriptSystem::getSingleton().getScriptNumber("nebula3_G");
	col.b = ScriptSystem::getSingleton().getScriptNumber("nebula3_B");
	mat = MaterialManager::getSingleton().getByName("BackgroundNebula3");
	tu = mat->getTechnique(0)->getPass(0)->getTextureUnitState(1);
	tu->setColourOperationEx(LBX_MODULATE, LBS_CURRENT, LBS_MANUAL, col, col);


	// Create background rectangle covering the whole screen
	bgRect = new Rectangle2D(true);
	// Flipping and mirroring
	Real bgx = rand()%100 < 50 ? -1.0f : 1.0f;
	Real bgy = rand()%100 < 50 ? -1.0f : 1.0f;
	bgRect->setCorners(-bgx, bgy, bgx, -bgy);
	bgRect->setMaterial(MaterialManager::getSingleton().getByName("Background"));

	// Render the background before everything else
	bgRect->setRenderQueueGroup(RENDER_QUEUE_SKIES_EARLY);
	AxisAlignedBox box; box.setInfinite();
	bgRect->setBoundingBox(box);

	// Attach background to the scene
	SceneNode* node = sceneMgr->getRootSceneNode()->createChildSceneNode("Background");
	node->attachObject(bgRect);


	// Background stars
	int starsCount = (int)ScriptSystem::getSingleton().getScriptNumber("starsCount");
	ManualObject *stars[4];
	for(int ii=0; ii<4; ii++) {
		stars[ii] = sceneMgr->createManualObject("BackgroundStars" + StringConverter::toString(ii+1));
		stars[ii]->begin("BackgroundStars", RenderOperation::OT_POINT_LIST);
		for(int j=0; j<starsCount; j++) {
			Vector3 pos;
			pos.x = Math::RangeRandom(-playfieldWidth, playfieldWidth);
			pos.y = Math::RangeRandom(-playfieldHeight, playfieldHeight);
			pos.z = Math::RangeRandom(-140, -5);
			stars[ii]->position(pos);

			Real c = Math::RangeRandom(0.1f, 1.0f);
			stars[ii]->colour(c, c, c);
			stars[ii]->index(j);
		}
		stars[ii]->end();
		stars[ii]->setRenderQueueGroup(RENDER_QUEUE_1);
		stars[ii]->setCastShadows(false);
	}

	// Create four groups of stars
	SceneNode *starsNode = sceneMgr->getRootSceneNode()->createChildSceneNode("BackgroundStars1");
	starsNode->attachObject(stars[0]);
	starsNode->translate(-playfieldWidth/2, -playfieldHeight/2, 0);

	starsNode = sceneMgr->getRootSceneNode()->createChildSceneNode("BackgroundStars2");
	starsNode->attachObject(stars[1]);
	starsNode->translate(+playfieldWidth/2, -playfieldHeight/2, 0);

	starsNode = sceneMgr->getRootSceneNode()->createChildSceneNode("BackgroundStars3");
	starsNode->attachObject(stars[2]);
	starsNode->translate(+playfieldWidth/2, +playfieldHeight/2, 0);

	starsNode = sceneMgr->getRootSceneNode()->createChildSceneNode("BackgroundStars4");
	starsNode->attachObject(stars[3]);
	starsNode->translate(-playfieldWidth/2, +playfieldHeight/2, 0);


	// Create the nebulae
	nebulaCount = (int)ScriptSystem::getSingleton().getScriptNumber("nebulaCount");
	for(int f=0; f<nebulaCount; f++) {
		Entity *ent = sceneMgr->createEntity("BackgroundNebula" + StringConverter::toString(f), "Plane.mesh");
		ent->setMaterialName("BackgroundNebula" + StringConverter::toString(f%3 + 1));
		ent->setCastShadows(false);
		ent->setRenderQueueGroup(RENDER_QUEUE_SKIES_EARLY);

		Vector3 pos;
		pos.x = Math::RangeRandom(-playfieldWidth, playfieldWidth);
		pos.y = Math::RangeRandom(-playfieldHeight, playfieldHeight);
		pos.z = Math::RangeRandom(-30, -5);

		SceneNode *node = sceneMgr->getRootSceneNode()->createChildSceneNode("NebulaNode" + StringConverter::toString(f), pos);
		node->attachObject(ent);

		Real s = Math::RangeRandom(25, 55);
		node->scale(s,s,s);
		node->roll(Degree(Math::RangeRandom(0,360)));
		node->yaw(Degree(Math::RangeRandom(-15,15)));
	}
}
コード例 #17
0
ファイル: Shader.cpp プロジェクト: whztt07/Mermelin
void Shader::setTexture(std::string name, std::string parameterName)
{
    TextureUnitState* texture = getPass()->createTextureUnitState(name);
    texture->setTextureNameAlias(parameterName);
    texture->setName(parameterName);
}
コード例 #18
0
	//---------------------------------------------------------------------
	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!
 
		}
	}
コード例 #19
0
ファイル: texture.cpp プロジェクト: kimziv/toy3d
bool init()
{
    int   width = WINDOW_W, height = WINDOW_H;
    //int   texid;
    int   texUnit = 0;
    Real  limit;
    Entity *entity;

    world = new World ();
    printf("pointer world: %d.\n", world);
    world->setSize(width, height);
    world->setBackColor (1.0, 1.0, 1.0, 1.0);

    camera = world->createCamera ("camera1");
    win = world->createRenderWindow ();
    win->addViewport (camera, 0, 0, width, height);

    //shader
    ShaderProgram *shaderProgram = ShaderProgramManager::getInstance()->createShaderProgram();
    shaderProgram->loadShaderSource (SHADER_VERT_FILE, SHADER_FRAG_FILE);
    printf("shaderProgram id: %d\n", shaderProgram->getShaderProgramID());


    ShaderProgramParams *params = ShaderProgramManager::getInstance()->createShaderProgramParams();

    //shader auto constant
    params->setNamedAutoConstant (TOY3D_ACT_PROJECTION_MATRIX, "proj_mat");
    params->setNamedAutoConstant (TOY3D_ACT_VIEW_MATRIX, "view_mat");
    params->setNamedAutoConstant (TOY3D_ACT_WORLD_MATRIX, "world_mat");

    //shader attributes
    params->setNamedAttrConstant(TOY3D_ATTR_VERTEX, "vPosition");
    params->setNamedAttrConstant(TOY3D_ATTR_UV, "vTexture");

    //shader custom constant
    limit = 0.1f;
    printf("limit = %f.\n", limit);
    params->setNamedCustUniformConstant(TOY3D_CUST_REAL1, "limit", limit);
    params->setNamedCustUniformConstant(TOY3D_CUST_SAMPLER2D, "sampler2d", texUnit);

    shaderProgram->bindShaderParameters(params);

    Texture *tex = TextureManager::getInstance()->createTextureByFile(TEXTURE_FILE);
    //unsigned char *temp = generateColorData(64, 64,4);
    //Texture *tex = TextureManager::getInstance()->createTexture(temp, 64, 64, 4);

    Material *mat = MaterialManager::getInstance()->createMaterial();
    mat->setShaderProgram (shaderProgram);
    //mat->setSceneBlending(T3D_SRC_ALPHA, T3D_ONE_MINUS_SRC_ALPHA, T3D_ADD);
    TextureUnitState *texUS;
    texUS = mat->createTextureUnitState("TexUnit1");
    if(!texUS)
    {
        TOY3D_TIPS("Error: createTextureUnitState failed.\n");
        return FALSE;
    }

    texUS->setID(texUnit);
    texUS->setTexture(tex);
    texUS->setTextureType(T3D_TEXTURE_2D);
    texUS->setTextureParameter(T3D_LINEAR, T3D_LINEAR, T3D_CLAMP_TO_EDGE, T3D_CLAMP_TO_EDGE);
    //mat->setTexture(tex);

    Mesh* mesh = MeshManager::getInstance()->createMesh();
    mesh->setRenderMode (TOY3D_TRIANGLE_STRIP);
    mesh->setVertices (vertices, VERTEX_COUNT);
    mesh->setUVs( uvs, VERTEX_COUNT);

    entity = world->createEntity();
    entity->setMesh(mesh);
    entity->setMaterial (mat);

    return true;
}
コード例 #20
0
ファイル: Hud.cpp プロジェクト: jsj2008/stuntrally
void App::CreateHUD()
{	
	//  minimap from road img
	asp = 1.f;
	if (terrain)
	{
		ofsX=0; ofsY=0;
		float t = sc.td.fTerWorldSize*0.5;
		minX = -t;  minY = -t;  maxX = t;  maxY = t;

		float fMapSizeX = maxX - minX, fMapSizeY = maxY - minY;  // map size
		float size = std::max(fMapSizeX, fMapSizeY*asp);
		scX = 1.f / size;  scY = 1.f / size;

		//for (int c=0; c<2; ++c)
		String sMat = "circle_minimap";  //*/"road_minimap_inv";
		asp = 1.f;  //_temp
		ManualObject* m = Create2D(sMat,mSplitMgr->mHUDSceneMgr,1,true,true);  miniC = m;
		//asp = float(mWindow->getWidth())/float(mWindow->getHeight());
		m->setVisibilityFlags(RV_Hud);  m->setRenderQueueGroup(RQG_Hud1);
		
		///  change minimap image
		MaterialPtr mm = MaterialManager::getSingleton().getByName(sMat);
		Pass* pass = mm->getTechnique(0)->getPass(0);
		TextureUnitState* tus = pass->getTextureUnitState(0);
		if (tus)  tus->setTextureName(pSet->track + "_mini.png");
		tus = pass->getTextureUnitState(2);
		if (tus)  tus->setTextureName(pSet->track + "_ter.jpg");
		UpdMiniTer();
		

		float fHudSize = pSet->size_minimap;
		const float marg = 1.f + 0.05f;  // from border
		fMiniX = 1 - fHudSize * marg, fMiniY = 1 - fHudSize*asp * marg;

		ndMap = mSplitMgr->mHUDSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(fMiniX,fMiniY,0));
		ndMap->scale(fHudSize, fHudSize*asp, 1);
		ndMap->attachObject(m);
		
		//  car pos dot - for all carModels (ghost and remote too)
		vMoPos.clear();
		vNdPos.clear();
		for (int i=0; i < /*pSet->local_players*/carModels.size(); ++i)
		{	vMoPos.push_back(0);
			vMoPos[i] = Create2D("hud/CarPos", mSplitMgr->mHUDSceneMgr, 0.4f, true, true);
			vMoPos[i]->setVisibilityFlags(RV_Hud);  vMoPos[i]->setRenderQueueGroup(RQG_Hud3);
			vNdPos.push_back(0);
			vNdPos[i] = ndMap->createChildSceneNode();
			vNdPos[i]->scale(fHudSize*1.5f, fHudSize*1.5f, 1);
			vNdPos[i]->attachObject(vMoPos[i]);  /*vNdPos[i]->setVisible(false);  */}
		ndMap->setVisible(false/*pSet->trackmap*/);
	}

	
	//  backgr  gauges
	ManualObject* mrpmB = Create2D("hud/rpm",mSplitMgr->mHUDSceneMgr,1);	mrpmB->setVisibilityFlags(RV_Hud);
	mrpmB->setRenderQueueGroup(RQG_Hud1);
	nrpmB = mSplitMgr->mHUDSceneMgr->getRootSceneNode()->createChildSceneNode();
	nrpmB->attachObject(mrpmB);	nrpmB->setScale(0,0,0);  nrpmB->setVisible(false);

	ManualObject* mvelBk = Create2D("hud/kmh",mSplitMgr->mHUDSceneMgr,1);	mvelBk->setVisibilityFlags(RV_Hud);
	mvelBk->setRenderQueueGroup(RQG_Hud1);
	nvelBk = mSplitMgr->mHUDSceneMgr->getRootSceneNode()->createChildSceneNode();
	nvelBk->attachObject(mvelBk);	nvelBk->setScale(0,0,0);  mvelBk->setVisible(false);
		
	ManualObject* mvelBm = Create2D("hud/mph",mSplitMgr->mHUDSceneMgr,1);	mvelBm->setVisibilityFlags(RV_Hud);
	mvelBm->setRenderQueueGroup(RQG_Hud1);
	nvelBm = mSplitMgr->mHUDSceneMgr->getRootSceneNode()->createChildSceneNode();
	nvelBm->attachObject(mvelBm);	nvelBm->setScale(0,0,0);  mvelBm->setVisible(false);
		
	//  needles
	mrpm = Create2D("hud/needle",mSplitMgr->mHUDSceneMgr,1,true);  mrpm->setVisibilityFlags(RV_Hud);
	mrpm->setRenderQueueGroup(RQG_Hud3);
	nrpm = mSplitMgr->mHUDSceneMgr->getRootSceneNode()->createChildSceneNode();
	nrpm->attachObject(mrpm);	nrpm->setScale(0,0,0);	nrpm->setVisible(false);
	
	mvel = Create2D("hud/needle",mSplitMgr->mHUDSceneMgr,1,true);  mvel->setVisibilityFlags(RV_Hud);
	mvel->setRenderQueueGroup(RQG_Hud3);
	nvel = mSplitMgr->mHUDSceneMgr->getRootSceneNode()->createChildSceneNode();
	nvel->attachObject(mvel);	nvel->setScale(0,0,0);	nvel->setVisible(false);


	//  overlays
	OverlayManager& ovr = OverlayManager::getSingleton();
	ovCam = ovr.getByName("Car/CameraOverlay");

	ovGear = ovr.getByName("Hud/Gear");		hudGear = ovr.getOverlayElement("Hud/GearText");
	ovVel = ovr.getByName("Hud/Vel");		hudVel = ovr.getOverlayElement("Hud/VelText");
	ovBoost = ovr.getByName("Hud/Boost");	hudBoost = ovr.getOverlayElement("Hud/BoostText");
	ovAbsTcs = ovr.getByName("Hud/AbsTcs");	hudAbs = ovr.getOverlayElement("Hud/AbsText");
	ovCarDbg = ovr.getByName("Car/Stats");	hudTcs = ovr.getOverlayElement("Hud/TcsText");
	ovTimes = ovr.getByName("Hud/Times");	hudTimes = ovr.getOverlayElement("Hud/TimesText");

	ovOpp = ovr.getByName("Hud/Opponents"); hudOppB = ovr.getOverlayElement("Hud/OpponentsPanel");
	for (int o=0; o < 5; ++o)  for (int c=0; c < 3; ++c)  {
		hudOpp[o][c] = ovr.getOverlayElement("Hud/OppText"+toStr(o)+"_"+toStr(c));  hudOpp[o][c]->setCaption("");  }
	
	for (int o=0; o < carModels.size(); ++o)  // fill car names, not changed during play
	{
		const CarModel* cm = carModels[o];
		if (cm->eType != CarModel::CT_REPLAY)
		{
			hudOpp[o][2]->setCaption(cm->sDispName);
			hudOpp[o][2]->setColour(cm->color);
		}
	}

	ovWarnWin = ovr.getByName("Hud/WarnAndWin");
	hudWarnChk = ovr.getOverlayElement("Hud/Warning");
	hudWarnChk->setCaption(String(TR("#{WrongChk}")));
	hudWonPlace = ovr.getOverlayElement("Hud/WonPlace");

	//  dbg lines
	ovCarDbgTxt = ovr.getByName("Car/StatsTxt");  //ovCarDbgTxt->show();
	ovCarDbg = ovr.getByName("Car/Stats");  //ovCarDbg->show();  // bars
	for (int i=0; i < 5; i++)
	{	ovL[i] = ovr.getOverlayElement("L_"+toStr(i+1));
		ovR[i] = ovr.getOverlayElement("R_"+toStr(i+1));
		ovS[i] = ovr.getOverlayElement("S_"+toStr(i+1));
		ovU[i] = ovr.getOverlayElement("U_"+toStr(i+1));	}
		
	ShowHUD();  //_
	bSizeHUD = true;
	//SizeHUD(true);
}
コード例 #21
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);
	}
}
コード例 #22
0
ファイル: PlayPenSamples.cpp プロジェクト: Anti-Mage/ogre
void PlayPen_testProjectSphere::setupContent()
{
	mSceneMgr->setAmbientLight(ColourValue::White);


	Plane plane;
	plane.normal = Vector3::UNIT_Y;
	plane.d = 0;
	MeshManager::getSingleton().createPlane("Myplane",
		TRANSIENT_RESOURCE_GROUP, plane,
		4500,4500,10,10,true,1,5,5,Vector3::UNIT_Z);
	Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" );
	pPlaneEnt->setMaterialName("Examples/GrassFloor");
	pPlaneEnt->setCastShadows(false);
	mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt);

	mProjectionSphere = new Sphere(Vector3(0, 2000, 0), 1500.0);

	ManualObject* debugSphere = mSceneMgr->createManualObject("debugSphere");
	debugSphere->begin("BaseWhiteNoLighting", RenderOperation::OT_LINE_STRIP);
	for (int i = 0; i <= 20; ++i)
	{
		Vector3 basePos(mProjectionSphere->getRadius(), 0, 0);
		Quaternion quat;
		quat.FromAngleAxis(Radian(((float)i/(float)20)*Math::TWO_PI), Vector3::UNIT_Y);
		basePos = quat * basePos;
		debugSphere->position(basePos);
	}
	for (int i = 0; i <= 20; ++i)
	{
		Vector3 basePos(mProjectionSphere->getRadius(), 0, 0);
		Quaternion quat;
		quat.FromAngleAxis(Radian(((float)i/(float)20)*Math::TWO_PI), Vector3::UNIT_Z);
		basePos = quat * basePos;
		debugSphere->position(basePos);
	}
	debugSphere->end();

	mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0,2000,0))->attachObject(debugSphere);

	MaterialPtr mat = MaterialManager::getSingleton().create("scissormat", 
		TRANSIENT_RESOURCE_GROUP);
	Pass* p = mat->getTechnique(0)->getPass(0);
	p->setDepthWriteEnabled(false);
	p->setSceneBlending(SBT_TRANSPARENT_ALPHA);
	TextureUnitState* t = p->createTextureUnitState();
	t->setColourOperationEx(LBX_SOURCE1, LBS_MANUAL, LBS_CURRENT, 
		ColourValue::Red);
	t->setAlphaOperation(LBX_SOURCE1, LBS_MANUAL, LBS_CURRENT, 0.5f);


	mScissorRect = mSceneMgr->createManualObject("mScissorRect");
	mScissorRect->setUseIdentityProjection(true);
	mScissorRect->setUseIdentityView(true);
	AxisAlignedBox aabb;
	aabb.setInfinite();
	mScissorRect->setBoundingBox(aabb);
	mScissorRect->begin(mat->getName());
	mScissorRect->position(Vector3::ZERO);
	mScissorRect->position(Vector3::ZERO);
	mScissorRect->position(Vector3::ZERO);
	mScissorRect->quad(0, 1, 2, 3);
	mScissorRect->end();
	mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(mScissorRect);

	mCamera->setPosition(0,3000,5000);
	mCamera->lookAt(mProjectionSphere->getCenter());


}
コード例 #23
0
//------------------------------------------------------
void MaterialService::addWorldMaterialTemplate(
    unsigned int idx, const Ogre::MaterialPtr &material) {
    assert(material);

    mTemplateMaterials.insert(make_pair(idx, material));

    TextureDimensions2D dimensions;

    dimensions.first = 64;
    dimensions.second = 64;

    if (material->getNumTechniques() > 0) {
        Pass *shadPass = material->getTechnique(0)->getPass(0);

        if (shadPass->getNumTextureUnitStates() > 0) {
            TextureUnitState *tus = shadPass->getTextureUnitState(0);

            try {
                // ensure the material is loaded before getting the dimensions
                material->escalateLoading();

                // This is stupid, but can happen - the getTextureDimensions
                // seems buggy in this regard
                if (tus->getNumFrames() <= 0) {
                    LOG_ERROR("MaterialService: Error getting texture "
                              "dimensions (Mat. %s) : Zero frame count!",
                              material->getName().c_str());
                } else {
                    dimensions = tus->getTextureDimensions();

                    // register the scale
                    std::pair<float, float> tscale;

                    tscale.first = tus->getTextureUScale();
                    tscale.second = tus->getTextureVScale();

                    // register the texture scale...
                    setWRTextureScale(idx, tscale);

                    // reset the scale back, it is canceled out by the fact we
                    // UV map with different txt dimensions
                    tus->setTextureUScale(1.0f);
                    tus->setTextureVScale(1.0f);

                    dimensions.first = static_cast<unsigned int>(
                        tscale.first * dimensions.first);
                    dimensions.second = static_cast<unsigned int>(
                        tscale.second * dimensions.second);
                }
            } catch (Ogre::Exception &e) {
                // Nothing, just log it could not be done
                LOG_ERROR(
                    "MaterialService: Error getting texture dimensions : %s",
                    e.getFullDescription().c_str());
            }
        }
    }

    LOG_INFO("MaterialService: Registered a WR template material %u - %s", idx,
             material->getName().c_str());

    // insert
    mTextureDimensionMap.insert(make_pair(idx, dimensions));
}