/// <summary> /// Register layer /// </summary> /// <param name="cloudLayerPass">Pass where register the cloud layer</param> public void RegisterCloudLayer(Pass cloudLayerPass) { Unregister(); cloudLayerPass.SetSceneBlending(SceneBlendType.SBT_TRANSPARENT_ALPHA); cloudLayerPass.CullingMode = CullingMode.CULL_NONE; cloudLayerPass.LightingEnabled = false; cloudLayerPass.DepthWriteEnabled = false; cloudLayerPass.SetVertexProgram("SkyX_Clouds_VP"); if (this.SkyX.LightingMode == LightingMode.Ldr) { cloudLayerPass.SetFragmentProgram("SkyX_Clouds_LDR_FP"); } else { cloudLayerPass.SetFragmentProgram("SkyX_Clouds_HDR_FP"); } //TODO //cloudLayerPass.CreateTextureUnitState("Cloud1.png").TextureAddressing = TextureUnitState.TextureAddressingMode.TAM_WRAP; //cloudLayerPass.CreateTextureUnitState("c22n.png").TextureAddressing = TextureUnitState.TextureAddressingMode.TAM_WRAP; //cloudLayerPass.CreateTextureUnitState("c22.png").TextureAddressing = TextureUnitState.TextureAddressingMode.TAM_WRAP; cloudLayerPass.CreateTextureUnitState("Cloud1.png").SetTextureAddressingMode(TextureUnitState.TextureAddressingMode.TAM_WRAP); cloudLayerPass.CreateTextureUnitState("c22n.png").SetTextureAddressingMode(TextureUnitState.TextureAddressingMode.TAM_WRAP); cloudLayerPass.CreateTextureUnitState("c22.png").SetTextureAddressingMode(TextureUnitState.TextureAddressingMode.TAM_WRAP); _cloudLayerPass = cloudLayerPass; UpdatePassParameters(); }
protected override void CreateScene() { // since whole screen is being redrawn every frame, dont bother clearing // option works for GL right now, uncomment to test it out. huge fps increase // also, depth_write in the skybox material must be set to on //mainViewport.ClearEveryFrame = false; // set some ambient light scene.TargetRenderSystem.LightingEnabled = true; scene.AmbientLight = ColorEx.Gray; // create a point light (default) Light light = scene.CreateLight("MainLight"); light.Position = new Vector3(20, 80, 50); CreateScalingPlane(); CreateScrollingKnot(); CreateWateryPlane(); // set up a material for the skydome Material skyMaterial = scene.CreateMaterial("SkyMat"); skyMaterial.Lighting = false; // use a cloudy sky Pass pass = skyMaterial.GetTechnique(0).GetPass(0); TextureUnitState textureLayer = pass.CreateTextureUnitState("clouds.jpg"); // scroll the clouds textureLayer.SetScrollAnimation(0.15f, 0); // create the skydome scene.SetSkyDome(true, "SkyMat", -5, 2); }
protected override void CreateScene() { mSceneMgr.AmbientLight = new ColourValue(1, 1, 1); //Entity ent = mSceneMgr.CreateEntity("Head", "ogrehead.mesh"); //SceneNode node = mSceneMgr.RootSceneNode.CreateChildSceneNode("HeadNode"); //node.AttachObject(ent); MaterialPtr mat = MaterialManager.Singleton.Create("BoxColor", "General", true); Technique tech = mat.GetTechnique(0); Pass pass = tech.GetPass(0); TextureUnitState tex = pass.CreateTextureUnitState(); tex.SetTextureName("sphax.jpg", TextureType.TEX_TYPE_2D); tex.NumMipmaps = 0; tex.TextureAnisotropy = 0; tex.SetTextureFiltering(FilterOptions.FO_POINT, FilterOptions.FO_POINT, FilterOptions.FO_POINT); //pass.DepthWriteEnabled=false; //pass.SetSceneBlending(SceneBlendType.SBT_TRANSPARENT_ALPHA); //pass.CullingMode = CullingMode.CULL_NONE; //mCamMan = new Tutorials.CameraMan(mCamera,mc); //mCameraMan = null; mCamera.SetPosition((float)mc.x, (float)mc.y, (float)mc.z); mCamera.Pitch(new Degree(mc.pitch).ValueRadians); mCamera.Yaw(new Degree(mc.yaw).ValueRadians); oldCamPos = mCamera.Position; }
void CreateFixedPipelineTechnique() { Technique tecnhique = BaseMaterial.CreateTechnique(); Pass pass = tecnhique.CreatePass(); pass.NormalizeNormals = true; pass.CreateTextureUnitState(ConvertToFullPath(DiffuseMap)); }
public void BuildMaterialPasses(PageDecalInfo pageInfo) { Technique t = FindPageTechnique(pageInfo.Coord); if (t != null) { float pageX = pageInfo.Coord.X * TerrainManager.Instance.PageSize * TerrainManager.oneMeter; float pageZ = pageInfo.Coord.Z * TerrainManager.Instance.PageSize * TerrainManager.oneMeter; int availableTexUnits = 0; int curTexUnit = 0; int texUnitsPerPass = 8; Pass p = null; foreach (DecalElement element in pageInfo.Decals) { // if there are no texture units available, allocate a new pass if (availableTexUnits == 0) { p = t.CreatePass(); pageInfo.Passes.Add(p); p.SetSceneBlending(SceneBlendType.TransparentAlpha); // TODO: Unclear what should happen here. The new Ogre interface // supports SetDepthBias(constantBias, slopeBias), but the units are // different. Ask Jeff. p.DepthBias = 1; curTexUnit = 0; availableTexUnits = texUnitsPerPass; } TextureUnitState texUnit = p.CreateTextureUnitState(element.ImageName, 0); if (curTexUnit == 0) { texUnit.SetColorOperation(LayerBlendOperation.Replace); texUnit.SetAlphaOperation(LayerBlendOperationEx.Source1, LayerBlendSource.Texture, LayerBlendSource.Current, 0, 0, 0); } else { texUnit.SetColorOperation(LayerBlendOperation.AlphaBlend); texUnit.SetAlphaOperation(LayerBlendOperationEx.AddSmooth, LayerBlendSource.Texture, LayerBlendSource.Current, 0, 0, 0); } texUnit.TextureAddressing = TextureAddressing.Border; texUnit.TextureBorderColor = new ColorEx(0, 0, 0, 0); element.UpdateTextureTransform(texUnit, pageX, pageZ); // bump the counts curTexUnit++; availableTexUnits--; } } }
public override bool PreAddToRenderState(TargetRenderState targetRenderState, Pass srcPass, Pass dstPass) { TextureUnitState textureUnit; //Create the mask texture unit. textureUnit = dstPass.CreateTextureUnitState(); textureUnit.SetTextureName(this.maskMapTextureName); this.maskMapSamplerIndex = dstPass.TextureUnitStatesCount - 1; //Create the reflection texture unit. textureUnit = dstPass.CreateTextureUnitState(); if (this.reflectionMapType == TextureType.TwoD) { textureUnit.SetTextureName(this.reflectionMapTextureName); } else { textureUnit.SetCubicTextureName(this.reflectionMapTextureName, true); } this.reflectionMapSamplerIndex = dstPass.TextureUnitStatesCount - 1; return(true); }
public static void CreateEditNode(string key, Vector3 position, Quaternion orientation) { WorldEntity worldEntity = Engine.World.GetWorldEntity(key); SceneNode sceneNode = worldEntity.CreateSceneNode(position, orientation); if (sceneNode != null) { EditNode editNode = new EditNode(key, worldEntity, sceneNode); ushort numObjects = sceneNode.NumAttachedObjects(); ushort numEntities = 0; for (ushort i = 0; i < numObjects; i++) { Entity entity = sceneNode.GetAttachedObject(i) as Entity; // if we haven't found an entity by now we need to make one ourselves if (entity == null && i == numObjects - 1 && numEntities == 0) { entity = Engine.Graphics.SceneManager.CreateEntity("ball.mesh"); sceneNode.AttachObject(entity); } // setup special material scheme used in the editor only if (entity != null) { for (uint j = 0; j < entity.NumSubEntities; j++) { Technique technique = entity.GetSubEntity(j).GetMaterial().CreateTechnique(); technique.SchemeName = "WireframeScheme"; Pass pass = technique.CreatePass(); pass.LightingEnabled = false; TextureUnitState textureUnit = pass.CreateTextureUnitState(); textureUnit.SetColourOperationEx(LayerBlendOperationEx.LBX_SOURCE1, LayerBlendSource.LBS_MANUAL, LayerBlendSource.LBS_CURRENT, new ColourValue( 0.5f + Mogre.Math.RangeRandom(0, 0.5f), 0.5f + Mogre.Math.RangeRandom(0, 0.5f), 0.5f + Mogre.Math.RangeRandom(0, 0.5f))); } entity.UserObject = editNode; numEntities++; } } Editor.editNodes.Add(editNode); } }
public Program(string name, HighLevelGpuProgram vs, HighLevelGpuProgram ps, IEnumerable <VariableDescription> samplers) { VertexShader = vs; PixelShader = ps; LogManager.Instance.Write("VS:"); LogManager.Instance.Write("================================================================================"); LogManager.Instance.Write(vs.Source); LogManager.Instance.Write("PS:"); LogManager.Instance.Write("================================================================================"); LogManager.Instance.Write(ps.Source); var mm = MaterialManager.Instance; Material = (Material)mm.Create(name, "SLSharp"); var mat = Material; mat.RemoveAllTechniques(); _tech = mat.CreateTechnique(); _tech.SchemeName = "SLSharp"; _tech.RemoveAllPasses(); Pass = _tech.CreatePass(); if (vs != null) { Pass.SetVertexProgram(vs.Name); } if (ps != null) { Pass.SetFragmentProgram(ps.Name); } foreach (var s in samplers) { var tu = Pass.CreateTextureUnitState(); tu.Name = s.Name; _textureUnits.Add(s.Name, tu); } Pass.LightingEnabled = false; mat.Load(); MatToProg.Add(mat, this); }
private void SetupFontMaterial() { Technique technique = fontMaterial.CreateTechnique(); Pass pass = technique.CreatePass(); TextureUnitState texUnitState = pass.CreateTextureUnitState(); texUnitState.SetTextureName(font.TextureName); // texUnitState.SetAlphaOperation(LayerBlendOperation.AlphaBlend); // texUnitState.SetTextureFiltering(FilterOptions.Linear); texUnitState.TextureAddressing = TextureAddressing.Clamp; texUnitState.TextureMatrix = Matrix4.Identity; texUnitState.TextureCoordSet = 0; // renderSystem.SetTextureCoordCalculation( 0, TexCoordCalcMethod.None ); // renderSystem.SetTextureUnitFiltering(0, FilterOptions.Linear, FilterOptions.Linear, FilterOptions.Point); // renderSystem.SetAlphaRejectSettings(0, CompareFunction.AlwaysPass, 0); // renderSystem.SetTextureBlendMode( 0, unitState.ColorBlendMode ); // renderSystem.SetTextureBlendMode( 0, unitState.AlphaBlendMode ); // // // enable alpha blending // renderSystem.SetSceneBlending(SceneBlendFactor.SourceAlpha, SceneBlendFactor.OneMinusSourceAlpha); }
/// <summary> /// Helper function to replace an entity in the scene. Adjusts the /// texture coordinates to flip the video. That may be wrong on /// everything except DirectX / DirectShow. /// </summary> /// <param name="en"> /// The entity we're going to replace. /// </param> /// <param name="meshName"> /// The name of the mesh to create. /// </param> /// <param name="materialName"> /// The name of the material to create. /// </param> /// <param name="textureName"> /// The name of the texture to create. /// </param> /// <param name="videoSize"> /// The size of the movie, in width by height pixels. /// </param> /// <param name="textureSize"> /// The size of the texture, in width by height pixels. /// </param> /// <returns></returns> private static bool ReplaceEntity( Entity en, string meshName, string materialName, string textureName, Size videoSize, Size textureSize) { Mesh me = MeshManager.Instance.CreatePlane( meshName, // name new Axiom.MathLib.Plane(new Axiom.MathLib.Vector3(0, 0, -1), new Axiom.MathLib.Vector3(0, 0, 0)), videoSize.Width, videoSize.Height, 1, // xsegments 1, // ysegments true, // normals 1, // numtexcoords 1.0f, // utile 1.0f, // vtile new Axiom.MathLib.Vector3(0, 1, 0) // upvec ); en.Mesh = me; Axiom.Graphics.Material m = MaterialManager.Instance.GetByName(materialName); if (m == null) { m = (Axiom.Graphics.Material) MaterialManager.Instance.Create(materialName, true); ColorEx c = new ColorEx(1.0f, 1.0f, 1.0f); m.Ambient = c; m.Diffuse = c; for (int i = 0; i < m.GetTechnique(0).NumPasses; i++) { Pass p = m.GetTechnique(0).GetPass(i); p.RemoveAllTextureUnitStates(); p.CreateTextureUnitState(textureName); } } en.MaterialName = materialName; return(true); }
/// <summary> /// Creates this shader as an OGRE material. /// </summary> /// <remarks> /// Creates a new material based on this shaders settings and registers it with the /// SceneManager passed in. /// Material name is in the format of: shader#lightmap. /// </remarks> /// <param name="sm">SceneManager to register the material with.</param> /// <param name="lightmapNumber">Lightmap number</param> public Material CreateAsMaterial(int lightmapNumber) { string materialName = String.Format("{0}#{1}", Name, lightmapNumber); string groupName = ResourceGroupManager.Instance.WorldResourceGroupName; var material = (Material)MaterialManager.Instance.Create(materialName, groupName); Pass pass = material.GetTechnique(0).GetPass(0); LogManager.Instance.Write("Using Q3 shader {0}", Name); for (int p = 0; p < this._pass.Count; ++p) { TextureUnitState t; // Create basic texture if (this._pass[p].textureName == "$lightmap") { string lightmapName = String.Format("@lightmap{0}", lightmapNumber); t = pass.CreateTextureUnitState(lightmapName); } // Animated texture support else if (this._pass[p].animNumFrames > 0) { float sequenceTime = this._pass[p].animNumFrames / this._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 (uint alt = 0; alt < this._pass[p].animNumFrames; ++alt) { if (!ResourceGroupManager.Instance.ResourceExists(groupName, this._pass[p].frames[alt])) { // Try alternate extension this._pass[p].frames[alt] = GetAlternateName(this._pass[p].frames[alt]); if (!ResourceGroupManager.Instance.ResourceExists(groupName, this._pass[p].frames[alt])) { // stuffed - no texture continue; } } } t = pass.CreateTextureUnitState(""); t.SetAnimatedTextureName(this._pass[p].frames, this._pass[p].animNumFrames, sequenceTime); if (t.IsBlank) { for (int alt = 0; alt < this._pass[p].animNumFrames; alt++) { this._pass[p].frames[alt] = GetAlternateName(this._pass[p].frames[alt]); } t.SetAnimatedTextureName(this._pass[p].frames, this._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.Instance.ResourceExists(groupName, this._pass[p].textureName)) { // Try alternate extension this._pass[p].textureName = GetAlternateName(this._pass[p].textureName); if (!ResourceGroupManager.Instance.ResourceExists(groupName, this._pass[p].textureName)) { // stuffed - no texture continue; } } t = pass.CreateTextureUnitState(this._pass[p].textureName); } // Blending if (p == 0) { // scene blend material.SetSceneBlending(this._pass[p].blendSrc, this._pass[p].blendDest); if (material.IsTransparent && (this._pass[p].blendSrc != SceneBlendFactor.SourceAlpha)) { material.DepthWrite = false; } t.SetColorOperation(LayerBlendOperation.Replace); // Alpha Settings pass.SetAlphaRejectSettings(this._pass[p].alphaFunc, this._pass[p].alphaVal); } else { if (this._pass[p].customBlend) { // Fallback for now t.SetColorOperation(LayerBlendOperation.Modulate); } else { t.SetColorOperation(this._pass[p].blend); } // Alpha mode, prefer 'most alphary' CompareFunction currFunc = pass.AlphaRejectFunction; int currValue = pass.AlphaRejectValue; if (this._pass[p].alphaFunc > currFunc || (this._pass[p].alphaFunc == currFunc && this._pass[p].alphaVal < currValue)) { pass.SetAlphaRejectSettings(this._pass[p].alphaFunc, this._pass[p].alphaVal); } } // Tex coords if (this._pass[p].texGen == ShaderTextureGen.Base) { t.TextureCoordSet = 0; } else if (this._pass[p].texGen == ShaderTextureGen.Lightmap) { t.TextureCoordSet = 1; } else if (this._pass[p].texGen == ShaderTextureGen.Environment) { t.SetEnvironmentMap(true, EnvironmentMap.Planar); } // Tex mod // Scale t.SetTextureScaleU(this._pass[p].tcModScale[0]); t.SetTextureScaleV(this._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 (this._pass[p].texGen != ShaderTextureGen.Environment) { if (this._pass[p].tcModRotate != 0.0f) { t.SetRotateAnimation(this._pass[p].tcModRotate); } if ((this._pass[p].tcModScroll[0] != 0.0f) || (this._pass[p].tcModScroll[1] != 0.0f)) { if (this._pass[p].tcModTurbOn) { // Turbulent scroll if (this._pass[p].tcModScroll[0] != 0.0f) { t.SetTransformAnimation(TextureTransform.TranslateU, WaveformType.Sine, this._pass[p].tcModTurb[0], this._pass[p].tcModTurb[3], this._pass[p].tcModTurb[2], this._pass[p].tcModTurb[1]); } if (this._pass[p].tcModScroll[1] != 0.0f) { t.SetTransformAnimation(TextureTransform.TranslateV, WaveformType.Sine, this._pass[p].tcModTurb[0], this._pass[p].tcModTurb[3], this._pass[p].tcModTurb[2], this._pass[p].tcModTurb[1]); } } else { // Constant scroll t.SetScrollAnimation(this._pass[p].tcModScroll[0], this._pass[p].tcModScroll[1]); } } if (this._pass[p].tcModStretchWave != ShaderWaveType.None) { WaveformType wft = WaveformType.Sine; switch (this._pass[p].tcModStretchWave) { case ShaderWaveType.Sin: wft = WaveformType.Sine; break; case ShaderWaveType.Triangle: wft = WaveformType.Triangle; break; case ShaderWaveType.Square: wft = WaveformType.Square; break; case ShaderWaveType.SawTooth: wft = WaveformType.Sawtooth; break; case ShaderWaveType.InverseSawtooth: wft = WaveformType.InverseSawtooth; break; } // Create wave-based stretcher t.SetTransformAnimation(TextureTransform.ScaleU, wft, this._pass[p].tcModStretchParams[3], this._pass[p].tcModStretchParams[0], this._pass[p].tcModStretchParams[2], this._pass[p].tcModStretchParams[1]); t.SetTransformAnimation(TextureTransform.ScaleV, wft, this._pass[p].tcModStretchParams[3], this._pass[p].tcModStretchParams[0], this._pass[p].tcModStretchParams[2], this._pass[p].tcModStretchParams[1]); } } // Address mode t.SetTextureAddressingMode(this._pass[p].addressMode); } // Do farbox (create new material) // Do skydome (use this material) //if ( _skyDome ) //{ // float halfAngle = 0.5f * ( 0.5f * ( 4.0f * (float)System.Math.Atan( 1.0f ) ) ); // float sin = (float)Utility.Sin( halfAngle ); // // Quake3 is always aligned with Z upwards // Quaternion q = new Quaternion( // (float)Utility.Cos( halfAngle ), // sin * Vector3.UnitX.x, // sin * Vector3.UnitY.y, // sin * Vector3.UnitX.z // ); // // Also draw last, and make close to camera (far clip plane is shorter) // sm.SetSkyDome( true, materialName, 20 - ( _cloudHeight / 256 * 18 ), 12, 2000, false, q ); //} material.CullingMode = Axiom.Graphics.CullingMode.None; material.ManualCullingMode = this._cullingMode; material.Lighting = false; material.Load(); return(material); }
/// <summary> /// Register layer /// </summary> /// <param name="cloudLayerPass">Pass where register the cloud layer</param> public void RegisterCloudLayer(Pass cloudLayerPass) { Unregister(); cloudLayerPass.SetSceneBlending(SceneBlendType.SBT_TRANSPARENT_ALPHA); cloudLayerPass.CullingMode = CullingMode.CULL_NONE; cloudLayerPass.LightingEnabled = false; cloudLayerPass.DepthWriteEnabled = false; cloudLayerPass.SetVertexProgram("SkyX_Clouds_VP"); if (this.SkyX.LightingMode == LightingMode.Ldr) { cloudLayerPass.SetFragmentProgram("SkyX_Clouds_LDR_FP"); } else { cloudLayerPass.SetFragmentProgram("SkyX_Clouds_HDR_FP"); } //TODO //cloudLayerPass.CreateTextureUnitState("Cloud1.png").TextureAddressing = TextureUnitState.TextureAddressingMode.TAM_WRAP; //cloudLayerPass.CreateTextureUnitState("c22n.png").TextureAddressing = TextureUnitState.TextureAddressingMode.TAM_WRAP; //cloudLayerPass.CreateTextureUnitState("c22.png").TextureAddressing = TextureUnitState.TextureAddressingMode.TAM_WRAP; cloudLayerPass.CreateTextureUnitState("Cloud1.png").SetTextureAddressingMode(TextureUnitState.TextureAddressingMode.TAM_WRAP ); cloudLayerPass.CreateTextureUnitState("c22n.png").SetTextureAddressingMode( TextureUnitState.TextureAddressingMode.TAM_WRAP); cloudLayerPass.CreateTextureUnitState("c22.png").SetTextureAddressingMode( TextureUnitState.TextureAddressingMode.TAM_WRAP); _cloudLayerPass = cloudLayerPass; UpdatePassParameters(); }
bool CreateDefaultTechnique() { string sourceFile = "Base\\Shaders\\SimpleExample.cg_hlsl"; string vertexSyntax; string fragmentSyntax; { if (RenderSystem.Instance.IsDirect3D()) { vertexSyntax = "vs_3_0"; fragmentSyntax = "ps_3_0"; } else if (RenderSystem.Instance.IsOpenGLES()) { vertexSyntax = "hlsl2glsl"; fragmentSyntax = "hlsl2glsl"; } else { vertexSyntax = "arbvp1"; fragmentSyntax = "arbfp1"; } } //technique is supported? if (!GpuProgramManager.Instance.IsSyntaxSupported(fragmentSyntax)) { return(false); } if (!GpuProgramManager.Instance.IsSyntaxSupported(vertexSyntax)) { return(false); } BaseMaterial.ReceiveShadows = false; //create techniques foreach (MaterialSchemes materialScheme in Enum.GetValues(typeof(MaterialSchemes))) { Technique technique = BaseMaterial.CreateTechnique(); technique.SchemeName = materialScheme.ToString(); //pass 0: ambient pass //pass 1: directional light //pass 2: point light //pass 3: spot light for (int nPass = 0; nPass < 4; nPass++) { //create pass Pass pass = technique.CreatePass(); bool ambientPass = nPass <= 1; bool lightPass = nPass >= 1; RenderLightType lightType = RenderLightType.Directional; ambientPass = nPass == 0; lightPass = nPass != 0; switch (nPass) { case 1: lightType = RenderLightType.Directional; break; case 2: lightType = RenderLightType.Point; break; case 3: lightType = RenderLightType.Spot; break; } if (lightPass) { pass.SpecialRendering = true; pass.SpecialRenderingIteratePerLight = true; pass.SpecialRenderingLightType = lightType; } int lightCount = lightPass ? 1 : 0; ///////////////////////////////////// //configure general pass settings { //disable Direct3D standard fog features pass.SetFogOverride(FogMode.None, new ColorValue(0, 0, 0), 0, 0, 0); //Light pass if (!ambientPass) { pass.DepthWrite = false; pass.SourceBlendFactor = SceneBlendFactor.One; pass.DestBlendFactor = SceneBlendFactor.One; } } ///////////////////////////////////// //generate general compile arguments and create texture unit states StringBuilder generalArguments = new StringBuilder(256); { if (RenderSystem.Instance.IsDirect3D()) { generalArguments.Append(" -DDIRECT3D"); } if (RenderSystem.Instance.IsOpenGL()) { generalArguments.Append(" -DOPENGL"); } if (RenderSystem.Instance.IsOpenGLES()) { generalArguments.Append(" -DOPENGL_ES"); } if (ambientPass) { generalArguments.Append(" -DAMBIENT_PASS"); } generalArguments.AppendFormat(" -DLIGHT_COUNT={0}", lightCount); generalArguments.Append(" -DLIGHTING"); //DiffuseMap if (!string.IsNullOrEmpty(DiffuseMap)) { generalArguments.Append(" -DDIFFUSE_MAP"); pass.CreateTextureUnitState(ConvertToFullPath(DiffuseMap)); } } ///////////////////////////////////// //generate programs //generate program for only ambient pass if (ambientPass && !lightPass) { string error; //vertex program GpuProgram vertexProgram = GpuProgramCacheManager.Instance.AddProgram( "SimpleExample_Vertex_", GpuProgramType.Vertex, sourceFile, "main_vp", vertexSyntax, generalArguments.ToString(), out error); if (vertexProgram == null) { Log.Fatal(error); return(false); } SetProgramAutoConstants(vertexProgram.DefaultParameters, 0); pass.VertexProgramName = vertexProgram.Name; //fragment program GpuProgram fragmentProgram = GpuProgramCacheManager.Instance.AddProgram( "SimpleExample_Fragment_", GpuProgramType.Fragment, sourceFile, "main_fp", fragmentSyntax, generalArguments.ToString(), out error); if (fragmentProgram == null) { Log.Fatal(error); return(false); } SetProgramAutoConstants(fragmentProgram.DefaultParameters, 0); pass.FragmentProgramName = fragmentProgram.Name; } //generate program for light passes if (lightPass) { string error; StringBuilder arguments = new StringBuilder(generalArguments.Length + 100); arguments.Append(generalArguments.ToString()); arguments.AppendFormat(" -DLIGHTTYPE_{0}", lightType.ToString().ToUpper()); //vertex program GpuProgram vertexProgram = GpuProgramCacheManager.Instance.AddProgram( "SimpleExample_Vertex_", GpuProgramType.Vertex, sourceFile, "main_vp", vertexSyntax, arguments.ToString(), out error); if (vertexProgram == null) { Log.Fatal(error); return(false); } SetProgramAutoConstants(vertexProgram.DefaultParameters, lightCount); pass.VertexProgramName = vertexProgram.Name; //fragment program GpuProgram fragmentProgram = GpuProgramCacheManager.Instance.AddProgram( "SimpleExample_Fragment_", GpuProgramType.Fragment, sourceFile, "main_fp", fragmentSyntax, arguments.ToString(), out error); if (fragmentProgram == null) { Log.Fatal(error); return(false); } SetProgramAutoConstants(fragmentProgram.DefaultParameters, lightCount); pass.FragmentProgramName = fragmentProgram.Name; } } } return(true); }
//------------------------------------------------------------------------- public void SetupTerrainMaterial() { if (string.IsNullOrEmpty(this.mCustomMaterialName)) { // define our own material Options.terrainMaterial = (Material)MaterialManager.Instance.GetByName(TERRAIN_MATERIAL_NAME); // Make unique terrain material name string s = mName + "/Terrain"; Options.terrainMaterial = (Material)MaterialManager.Instance.GetByName(s); if (null == Options.terrainMaterial) { Options.terrainMaterial = (Material)MaterialManager.Instance.Create(s, ResourceGroupManager.Instance.WorldResourceGroupName); } else { Options.terrainMaterial.GetTechnique(0).GetPass(0).RemoveAllTextureUnitStates(); } Pass pass = Options.terrainMaterial.GetTechnique(0).GetPass(0); if (this.mWorldTextureName != "") { pass.CreateTextureUnitState(this.mWorldTextureName, 0); } if (this.mDetailTextureName != "") { pass.CreateTextureUnitState(this.mDetailTextureName, 1); } Options.terrainMaterial.Lighting = Options.lit; if (Options.lodMorph && mPCZSM.TargetRenderSystem.Capabilities.HasCapability(Capabilities.VertexPrograms) && GpuProgramManager.Instance.GetByName("Terrain/VertexMorph") == null) { // Create & assign LOD morphing vertex program String syntax; if (GpuProgramManager.Instance.IsSyntaxSupported("arbvp1")) { syntax = "arbvp1"; } else { syntax = "vs_1_1"; } // Get source, and take into account current fog mode FogMode fm = mPCZSM.FogMode; string source = new TerrainVertexProgram().getProgramSource(fm, syntax, false); GpuProgram prog = GpuProgramManager.Instance.CreateProgramFromString("Terrain/VertexMorph", ResourceGroupManager.Instance. WorldResourceGroupName, source, GpuProgramType.Vertex, syntax); // Attach pass.SetVertexProgram("Terrain/VertexMorph"); // Get params GpuProgramParameters paras = pass.VertexProgramParameters; // worldviewproj paras.SetAutoConstant(0, GpuProgramParameters.AutoConstantType.WorldViewProjMatrix); // morph factor paras.SetAutoConstant(4, GpuProgramParameters.AutoConstantType.Custom, TerrainZoneRenderable.MORPH_CUSTOM_PARAM_ID); // fog exp density(if relevant) if (fm == FogMode.Exp || fm == FogMode.Exp2) { paras.SetConstant(5, new Vector3(mPCZSM.FogDensity, 0, 0)); // Override scene fog since otherwise it's applied twice // Set to linear and we derive [0,1] fog value in the shader pass.SetFog(true, FogMode.Linear, mPCZSM.FogColor, 0, 1, 0); } // Also set shadow receiver program string source2 = new TerrainVertexProgram().getProgramSource(fm, syntax, true); prog = GpuProgramManager.Instance.CreateProgramFromString("Terrain/VertexMorphShadowReceive", ResourceGroupManager.Instance.WorldResourceGroupName, source2, GpuProgramType.Vertex, syntax); pass.SetShadowReceiverVertexProgram("Terrain/VertexMorphShadowReceive"); paras = pass.ShadowReceiverVertexProgramParameters; // worldviewproj paras.SetAutoConstant(0, GpuProgramParameters.AutoConstantType.WorldViewProjMatrix); // world paras.SetAutoConstant(4, GpuProgramParameters.AutoConstantType.WorldMatrix); // texture view / proj paras.SetAutoConstant(8, GpuProgramParameters.AutoConstantType.TextureViewProjMatrix); // morph factor paras.SetAutoConstant(12, GpuProgramParameters.AutoConstantType.Custom, TerrainZoneRenderable.MORPH_CUSTOM_PARAM_ID); // Set param index this.mLodMorphParamName = ""; this.mLodMorphParamIndex = 4; } Options.terrainMaterial.Load(); } else { // Custom material Options.terrainMaterial = (Material)MaterialManager.Instance.GetByName(this.mCustomMaterialName); Options.terrainMaterial.Load(); } // now set up the linkage between vertex program and LOD morph param if (Options.lodMorph) { Technique t = Options.terrainMaterial.GetBestTechnique(); for (ushort i = 0; i < t.PassCount; ++i) { Pass p = t.GetPass(i); if (p.HasVertexProgram) { // we have to assume vertex program includes LOD morph capability GpuProgramParameters paras = p.VertexProgramParameters; // Check to see if custom param is already there //GpuProgramParameters::AutoConstantIterator aci = params->getAutoConstantIterator(); bool found = false; foreach (GpuProgramParameters.AutoConstantEntry ace in paras.AutoConstantList) { if (ace.Type == GpuProgramParameters.AutoConstantType.Custom && ace.Data == TerrainZoneRenderable.MORPH_CUSTOM_PARAM_ID) { found = true; break; } } if (!found) { if (this.mLodMorphParamName != "") { paras.SetNamedAutoConstant(this.mLodMorphParamName, GpuProgramParameters.AutoConstantType.Custom, TerrainZoneRenderable.MORPH_CUSTOM_PARAM_ID); } else { paras.SetAutoConstant(this.mLodMorphParamIndex, GpuProgramParameters.AutoConstantType.Custom, TerrainZoneRenderable.MORPH_CUSTOM_PARAM_ID); } } } } } }
public static MaterialPtr BuildPreloaderMaterial(int maxTextures) { Pass pass = null; Technique t; string name = "PreloaderMaterial"; MaterialPtr mptr; if (MaterialManager.Singleton.ResourceExists(name)) { mptr = (MaterialPtr)MaterialManager.Singleton.Load(name, MaterialManager.DEFAULT_SCHEME_NAME); if (mptr.GetBestTechnique().NumPasses > 1) { // material jest juz gotowy return(mptr); } } else { return(null); } int freeMB = ((int)TextureManager.Singleton.MemoryUsage / (1024 * 1024)); LogManager.Singleton.LogMessage(LogMessageLevel.LML_CRITICAL, "Building hardware preloader material. Free system memory: " + freeMB); t = mptr.GetBestTechnique(); ResourceManager.ResourceMapIterator i = TextureManager.Singleton.GetResourceIterator(); int j = 0; int k = 0; int total = 0; while (i.MoveNext()) { if (j < System.Math.Ceiling(maxTextures / 2.0f)) { j++; TexturePtr texture = (TexturePtr)(i.Current); if (!texture.Name.Contains(AdManager.C_ADS_DIR)) { pass = t.CreatePass(); pass.CreateTextureUnitState(texture.Name); pass.SetSceneBlending(SceneBlendFactor.SBF_ZERO, SceneBlendFactor.SBF_ONE); LogManager.Singleton.LogMessage(LogMessageLevel.LML_CRITICAL, "Material will be preloaded (" + k + ") - " + texture.Name); } else { } k++; if (i.MoveNext()) { if (!texture.Name.Contains(AdManager.C_ADS_DIR)) { texture = (TexturePtr)(i.Current); if (pass == null) { pass = t.CreatePass(); } pass.CreateTextureUnitState(texture.Name); LogManager.Singleton.LogMessage(LogMessageLevel.LML_CRITICAL, "Material will be preloaded (" + k + ") - " + texture.Name); } k++; total++; } pass = null; } total++; } LogManager.Singleton.LogMessage(LogMessageLevel.LML_CRITICAL, "Total materials to be hardware preloaded: " + k + "/" + total); mptr.Load(); mptr.Compile(); return(mptr); }
/// <summary> /// /// </summary> protected void Initialize() { // Create geometry int nvertices = this.slices * 4; // n+1 planes int elemsize = 3 * 3; int dsize = elemsize * nvertices; int x; var indexData = new IndexData(); var vertexData = new VertexData(); var vertices = new float[dsize]; var coords = new float[4, 2] { { 0.0f, 0.0f }, { 0.0f, 1.0f }, { 1.0f, 0.0f }, { 1.0f, 1.0f } }; for (x = 0; x < this.slices; x++) { for (int y = 0; y < 4; y++) { float xcoord = coords[y, 0] - 0.5f; float ycoord = coords[y, 1] - 0.5f; float zcoord = -((float)x / (float)(this.slices - 1) - 0.5f); // 1.0f .. a/(a+1) // coordinate vertices[x * 4 * elemsize + y * elemsize + 0] = xcoord * (this.size / 2.0f); vertices[x * 4 * elemsize + y * elemsize + 1] = ycoord * (this.size / 2.0f); vertices[x * 4 * elemsize + y * elemsize + 2] = zcoord * (this.size / 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 * Utility.Sqrt(3.0f); vertices[x * 4 * elemsize + y * elemsize + 7] = ycoord * Utility.Sqrt(3.0f); vertices[x * 4 * elemsize + y * elemsize + 8] = zcoord * Utility.Sqrt(3.0f); } } var faces = new short[this.slices * 6]; for (x = 0; x < this.slices; x++) { faces[x * 6 + 0] = (short)(x * 4 + 0); faces[x * 6 + 1] = (short)(x * 4 + 1); faces[x * 6 + 2] = (short)(x * 4 + 2); faces[x * 6 + 3] = (short)(x * 4 + 1); faces[x * 6 + 4] = (short)(x * 4 + 2); faces[x * 6 + 5] = (short)(x * 4 + 3); } //setup buffers vertexData.vertexStart = 0; vertexData.vertexCount = nvertices; VertexDeclaration decl = vertexData.vertexDeclaration; VertexBufferBinding bind = vertexData.vertexBufferBinding; int offset = 0; offset += decl.AddElement(0, 0, VertexElementType.Float3, VertexElementSemantic.Position).Size; offset += decl.AddElement(0, offset, VertexElementType.Float3, VertexElementSemantic.Normal).Size; offset += decl.AddElement(0, offset, VertexElementType.Float3, VertexElementSemantic.TexCoords).Size; HardwareVertexBuffer vertexBuffer = HardwareBufferManager.Instance.CreateVertexBuffer(decl, nvertices, BufferUsage.StaticWriteOnly); bind.SetBinding(0, vertexBuffer); HardwareIndexBuffer indexBuffer = HardwareBufferManager.Instance.CreateIndexBuffer(IndexType.Size16, this.slices * 6, BufferUsage.StaticWriteOnly); indexData.indexBuffer = indexBuffer; indexData.indexCount = this.slices * 6; indexData.indexStart = 0; indexBuffer.WriteData(0, indexBuffer.Size, faces, true); vertexBuffer.WriteData(0, vertexBuffer.Size, vertices); vertices = null; faces = null; // Now make the render operation renderOperation.operationType = OperationType.TriangleList; renderOperation.indexData = indexData; renderOperation.vertexData = vertexData; renderOperation.useIndices = true; // Create a brand new private material if (!ResourceGroupManager.Instance.GetResourceGroups().Contains("VolumeRendable")) { ResourceGroupManager.Instance.CreateResourceGroup("VolumeRendable"); } var material = (Material)MaterialManager.Instance.Create(this.texture, "VolumeRendable"); // 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(SceneBlendType.TransparentAlpha); pass.DepthWrite = false; pass.CullingMode = CullingMode.None; pass.LightingEnabled = false; textureUnit.SetTextureAddressingMode(TextureAddressing.Clamp); textureUnit.SetTextureName(this.texture, TextureType.ThreeD); textureUnit.SetTextureFiltering(TextureFiltering.Trilinear); this.unit = textureUnit; base.material = material; }
void FixedPipelineAddDiffuseMapsToPass( Pass pass ) { for( int mapIndex = 1; mapIndex <= 4; mapIndex++ ) { MapItem map = null; switch( mapIndex ) { case 1: map = diffuse1Map; break; case 2: map = diffuse2Map; break; case 3: map = diffuse3Map; break; case 4: map = diffuse4Map; break; } if( !string.IsNullOrEmpty( map.Texture ) ) { TextureUnitState state = pass.CreateTextureUnitState( map.GetTextureFullPath(), (int)map.TexCoord ); if( map.Clamp ) state.SetTextureAddressingMode( TextureAddressingMode.Clamp ); if( projectiveTexturing && map.TexCoord == TexCoordIndexes.Projective ) state.SetProjectiveTexturing( projectiveTexturingFrustum ); if( map.textureUnitStatesForFixedPipeline == null ) map.textureUnitStatesForFixedPipeline = new List<TextureUnitState>(); map.textureUnitStatesForFixedPipeline.Add( state ); UpdateMapTransformForFixedPipeline( map ); if( mapIndex > 1 && mapIndex < 5 ) { DiffuseMapItem.MapBlendingTypes mapBlending = ( (DiffuseMapItem)map ).Blending; switch( mapBlending ) { case DiffuseMapItem.MapBlendingTypes.Add: state.SetColorOperation( LayerBlendOperation.Add ); break; case DiffuseMapItem.MapBlendingTypes.Modulate: state.SetColorOperation( LayerBlendOperation.Modulate ); break; case DiffuseMapItem.MapBlendingTypes.AlphaBlend: state.SetColorOperation( LayerBlendOperation.AlphaBlend ); break; } } } } }
protected void EnsureObjectsCreated() { ClearCreatedObjects(); Texture prototypeTexture = null; if (useTextures) { prototypeMaterial = MaterialManager.Instance.Load("barrel.barrel"); if (uniqueTextures) { prototypeTexture = TextureManager.Instance.Load("blank.dds"); } } else { prototypeMaterial = MaterialManager.Instance.Load("unit_box.unit_box"); } prototypeMaterial.Compile(); if (objectCount == 0) { return; } int materialCount = (animatedObjects ? 0 : (numObjectsSharingMaterial == 0 ? objectCount : (numObjectsSharingMaterial >= objectCount ? 1 : (objectCount + numObjectsSharingMaterial - 1) / numObjectsSharingMaterial))); materialCountLabel.Text = "Material Count: " + materialCount; if (whichObjects == WhichObjectsEnum.woPlane || whichObjects == WhichObjectsEnum.woRandom) { Mesh plane = meshes[(int)WhichObjectsEnum.woPlane]; if (plane != null) { plane.Unload(); } // Create the plane float planeSide = 1000f; int planeUnits = Int32.Parse(planeUnitsTextBox.Text); plane = MeshManager.Instance.CreatePlane("testerPlane", new Plane(Vector3.UnitZ, Vector3.Zero), planeSide, planeSide, planeUnits, planeUnits, true, 1, planeSide / planeUnits, planeSide / planeUnits, Vector3.UnitY); meshes[(int)WhichObjectsEnum.woPlane] = plane; } // Create the new materials for (int i = 0; i < materialCount; i++) { Material mat = prototypeMaterial.Clone("mat" + i); Pass p = mat.GetTechnique(0).GetPass(0); if (!animatedObjects && uniqueTextures) { Texture t = prototypeTexture; Texture texture = TextureManager.Instance.CreateManual("texture" + i, t.TextureType, t.Width, t.Height, t.NumMipMaps, t.Format, t.Usage); textureList.Add(texture); p.CreateTextureUnitState(texture.Name); } // Make the materials lovely shades of blue p.Ambient = new ColorEx(1f, .2f, .2f, (1f / materialCount) * i); p.Diffuse = new ColorEx(p.Ambient); p.Specular = new ColorEx(1f, 0f, 0f, 0f); materialList.Add(mat); } // Create the entities and scene nodes for (int i = 0; i < objectCount; i++) { Mesh mesh = selectMesh(); Material mat = null; if (materialCount > 0) { mat = materialList[i % materialCount]; } Entity entity = scene.CreateEntity("entity" + i, mesh); if (animatedObjects) { string[] visibleSubs = visibleSubMeshes[(int)whichObjects - (int)WhichObjectsEnum.woZombie]; for (int j = 0; j < entity.SubEntityCount; ++j) { SubEntity sub = entity.GetSubEntity(j); bool visible = false; foreach (string s in visibleSubs) { if (s == sub.SubMesh.Name) { visible = true; break; } } sub.IsVisible = visible; if (visible) { totalVertexCount += sub.SubMesh.VertexData.vertexCount; } } } else { if (mesh.SharedVertexData != null) { totalVertexCount += mesh.SharedVertexData.vertexCount; } else { for (int j = 0; j < mesh.SubMeshCount; j++) { SubMesh subMesh = mesh.GetSubMesh(j); totalVertexCount += subMesh.VertexData.vertexCount; } } } if (animatedObjects && animateCheckBox.Checked) { AnimationState currentAnimation = entity.GetAnimationState(GetAnimationName()); currentAnimation.IsEnabled = true; if (!animationInitialized) { currentAnimationLength = entity.GetAnimationState(GetAnimationName()).Length; animationInitialized = true; } } if (mat != null) { entity.MaterialName = mat.Name; } entityList.Add(entity); SceneNode node = scene.RootSceneNode.CreateChildSceneNode(); sceneNodeList.Add(node); node.AttachObject(entity); node.Position = new Vector3(randomCoord(), randomCoord(), randomCoord()); if (randomSizes) { node.ScaleFactor = Vector3.UnitScale * randomScale(); } else if (randomScales) { node.ScaleFactor = new Vector3(randomScale(), randomScale(), randomScale()); } else { node.ScaleFactor = Vector3.UnitScale * 1f; } if (randomOrientations) { Vector3 axis = new Vector3((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()); node.Orientation = Vector3.UnitY.GetRotationTo(axis.ToNormalized()); } else { node.Orientation = Quaternion.Identity; } } }
private void CreateShaderMaterials(Quake3Level q3lvl, SceneManager sm) { // NB this only works for the 'default' shaders for now // i.e. those that don't have a .shader script and thus default // to just texture + lightmap // TODO: pre-parse all .shader files and create lookup for next stage (use ROGL shader_file_t) // Material names are shadername#lightmapnumber // This is because I like to define materials up front completely // rather than combine lightmap and shader dynamically (it's // more generic). It results in more materials, but they're small // beer anyway. Texture duplication is prevented by infrastructure. // To do this I actually need to parse the faces since they have the // shader/lightmap combo (lightmap number is not in the shader since // it can be used with multiple lightmaps) string shaderName; int face = q3lvl.Faces.Length; while (face-- > 0) { // Check to see if existing material // Format shader#lightmap int shadIdx = q3lvl.Faces[face].shader; shaderName = String.Format("{0}#{1}", q3lvl.Shaders[shadIdx].name, q3lvl.Faces[face].lmTexture); Material shadMat = sm.GetMaterial(shaderName); if (shadMat == null && !bspOptions.useLightmaps) { // try the no-lightmap material shaderName = String.Format("{0}#n", q3lvl.Shaders[shadIdx].name); shadMat = sm.GetMaterial(shaderName); } if (shadMat == null) { // Colour layer // NB no extension in Q3A(doh), have to try shader, .jpg, .tga string tryName = q3lvl.Shaders[shadIdx].name; // Try shader first Quake3Shader shader = (Quake3Shader)Quake3ShaderManager.Instance.GetByName(tryName); if (shader != null) { shadMat = shader.CreateAsMaterial(sm, q3lvl.Faces[face].lmTexture); } else { // No shader script, try default type texture shadMat = sm.CreateMaterial(shaderName); Pass shadPass = shadMat.GetTechnique(0).GetPass(0); // Try jpg TextureUnitState tex = shadPass.CreateTextureUnitState(tryName + ".jpg"); tex.Load(); if (tex.IsBlank) { // Try tga tex.SetTextureName(tryName + ".tga"); } // Set replace on all first layer textures for now tex.SetColorOperation(LayerBlendOperation.Replace); tex.TextureAddressing = TextureAddressing.Wrap; // for ambient lighting tex.ColorBlendMode.source2 = LayerBlendSource.Manual; if (bspOptions.useLightmaps && q3lvl.Faces[face].lmTexture != -1) { // Add lightmap, additive blending tex = shadPass.CreateTextureUnitState(String.Format("@lightmap{0}", q3lvl.Faces[face].lmTexture)); // Blend tex.SetColorOperation(LayerBlendOperation.Modulate); // Use 2nd texture co-ordinate set tex.TextureCoordSet = 1; // Clamp tex.TextureAddressing = TextureAddressing.Clamp; } shadMat.CullingMode = CullingMode.None; shadMat.Lighting = false; } } shadMat.Load(); // Copy face data BspStaticFaceGroup dest = CopyShaderFaceData(q3lvl, face, shadMat, shadIdx); faceGroups[face] = dest; } }
/// <summary> /// /// </summary> /// <param name="group"></param> /// <param name="entity"></param> protected ImpostorTexture(ImpostorPage group, Entity entity) { //Store scene manager and entity mSceneMgr = group.SceneManager; mEntity = entity; //Add self to list of ImpostorTexture's mEntityKey = ImpostorBatch.GenerateEntityKey(entity); mSelfList.Add(mEntityKey, this); //Calculate the entity's bounding box and it's diameter mBoundingBox = entity.BoundingBox; //Note - this radius calculation assumes the object is somewhat rounded (like trees/rocks/etc.) float tmp = 0; mEntityRadius = mBoundingBox.Maximum.x - mBoundingBox.Center.x; tmp = mBoundingBox.Maximum.y - mBoundingBox.Center.y; if (tmp > mEntityRadius) { mEntityRadius = tmp; } tmp = mBoundingBox.Maximum.z - mBoundingBox.Center.z; if (tmp > mEntityRadius) { mEntityRadius = tmp; } mEntityDiameter = 2.0f * mEntityRadius; mEntityCenter = mBoundingBox.Center; //Render impostor textures RenderTextures(false); //Set up materials for (int o = 0; o < ImpostorYawAngles; o++) { for (int i = 0; i < ImpostorPitchAngles; i++) { mMaterial[i, o] = (Material)MaterialManager.Instance.Create(GetUniqueID("ImpostorMaterial"), "Impostors"); Material m = mMaterial[i, o]; Pass p = m.GetTechnique(0).GetPass(0); TextureUnitState t = p.CreateTextureUnitState(mTexture.Name); t.TextureScrollU = (float)(o / ImpostorYawAngles); t.TextureScrollV = (float)(i / ImpostorPitchAngles); p.LightingEnabled = false; m.ReceiveShadows = false; if (group.BlendMode == ImpostorBlendMode.AlphaReject) { p.AlphaRejectFunction = CompareFunction.GreaterEqual; p.AlphaRejectValue = 128; } else if (group.BlendMode == ImpostorBlendMode.AlphaBlend) { p.SetSceneBlending(SceneBlendFactor.SourceAlpha, SceneBlendFactor.OneMinusSourceAlpha); } } } }
/// <summary> /// /// </summary> /// <param name="meshName"></param> private void PrepareEntity(string meshName) { if (objectEntity != null) { ClearEntity(); } // load mesh if necessary originalMesh = (Mesh)MeshManager.Instance.GetByName(meshName); // load mesh with shadow buffer so we can do fast reads if (originalMesh == null) { originalMesh = (Mesh)MeshManager.Instance.Load( meshName, BufferUsage.StaticWriteOnly, BufferUsage.StaticWriteOnly, true, true, 1); if (originalMesh == null) { throw new Exception(string.Format("Can't find mesh named '{0}'.", meshName)); } } PrepareClonedMesh(); // create a new entity based on the cloned mesh objectEntity = scene.CreateEntity(ENTITY_NAME, MESH_NAME); // setting the material here propogates it down to cloned sub entites, no need to clone them objectEntity.MaterialName = material.Name; Pass pass = material.GetTechnique(0).GetPass(0); // add original sub mesh texture layers after the new cube map recently added for (int i = 0; i < clonedMesh.SubMeshCount; i++) { SubMesh subMesh = clonedMesh.GetSubMesh(i); SubEntity subEntity = objectEntity.GetSubEntity(i); // does this mesh have its own material set? if (subMesh.IsMaterialInitialized) { string matName = subMesh.MaterialName; Material subMat = MaterialManager.Instance.GetByName(matName); if (subMat != null) { subMat.Load(); // Clone the sub entities material Material cloned = subMat.Clone(string.Format("CubeMapTempMaterial#{0}", i)); Pass clonedPass = cloned.GetTechnique(0).GetPass(0); // add global texture layers to the existing material of the entity for (int j = 0; j < pass.NumTextureUnitStages; j++) { TextureUnitState orgLayer = pass.GetTextureUnitState(j); TextureUnitState newLayer = clonedPass.CreateTextureUnitState(orgLayer.TextureName); orgLayer.CopyTo(newLayer); newLayer.SetColorOperationEx(currentLbx); } // set the new material for the subentity and cache it subEntity.MaterialName = cloned.Name; clonedMaterials.Add(cloned); } } } // attach the entity to the scene objectNode.AttachObject(objectEntity); // update noise if currently set to on if (noiseOn) { UpdateNoise(); } }