private void SetProgramAutoConstants(GpuProgramParameters parameters, int lightCount)
        {
            parameters.SetNamedAutoConstant("worldMatrix",
                GpuProgramParameters.AutoConstantType.WorldMatrix);
            parameters.SetNamedAutoConstant("worldViewProjMatrix",
                GpuProgramParameters.AutoConstantType.WorldViewProjMatrix);
            parameters.SetNamedAutoConstant("cameraPosition",
                GpuProgramParameters.AutoConstantType.CameraPosition);
            parameters.SetNamedAutoConstant("farClipDistance",
                GpuProgramParameters.AutoConstantType.FarClipDistance);

            parameters.SetNamedAutoConstant("ambientLightColor",
                GpuProgramParameters.AutoConstantType.AmbientLightColor);

            if (lightCount != 0)
            {
                parameters.SetNamedAutoConstant("lightPositionArray",
                    GpuProgramParameters.AutoConstantType.LightPositionArray, lightCount);
                parameters.SetNamedAutoConstant("lightPositionObjectSpaceArray",
                    GpuProgramParameters.AutoConstantType.LightPositionObjectSpaceArray, lightCount);
                parameters.SetNamedAutoConstant("lightDirectionArray",
                    GpuProgramParameters.AutoConstantType.LightDirectionArray, lightCount);
                parameters.SetNamedAutoConstant("lightDirectionObjectSpaceArray",
                    GpuProgramParameters.AutoConstantType.LightDirectionObjectSpaceArray, lightCount);
                parameters.SetNamedAutoConstant("lightAttenuationArray",
                    GpuProgramParameters.AutoConstantType.LightAttenuationArray, lightCount);
                parameters.SetNamedAutoConstant("lightDiffuseColorPowerScaledArray",
                    GpuProgramParameters.AutoConstantType.LightDiffuseColorPowerScaledArray, lightCount);
                parameters.SetNamedAutoConstant("spotLightParamsArray",
                    GpuProgramParameters.AutoConstantType.SpotLightParamsArray, lightCount);
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="visibleDist"></param>
        /// <param name="invisibleDist"></param>
        /// <returns></returns>
        private Material GetFadeMaterial(float visibleDist, float invisibleDist)
        {
            string materialSignature = string.Empty;

            materialSignature += mEntityName + "|";
            materialSignature += visibleDist + "|";
            materialSignature += invisibleDist + "|";
            materialSignature += mMaterial.GetTechnique(0).GetPass(0).GetTextureUnitState(0).TextureScrollU + "|";
            materialSignature += mMaterial.GetTechnique(0).GetPass(0).GetTextureUnitState(0).TextureScrollV + "|";

            Material fadeMaterial = null;

            if (!mFadedMaterialMap.TryGetValue(materialSignature, out fadeMaterial))
            {
                //clone the material
                fadeMaterial = mMaterial.Clone(GetUniqueID("ImpostorFade"));

                //And apply the fade shader
                for (int t = 0; t < fadeMaterial.TechniqueCount; t++)
                {
                    Technique tech = fadeMaterial.GetTechnique(t);
                    for (int p = 0; p < tech.PassCount; p++)
                    {
                        Pass pass = tech.GetPass(p);
                        //Setup vertex program
                        pass.SetVertexProgram("SpriteFade_vp");
                        GpuProgramParameters gparams = pass.VertexProgramParameters;
                        gparams.SetNamedAutoConstant("worldViewProj", GpuProgramParameters.AutoConstantType.WorldViewProjMatrix, 0);
                        gparams.SetNamedAutoConstant("uScroll", GpuProgramParameters.AutoConstantType.Custom, 0);
                        gparams.SetNamedAutoConstant("vScroll", GpuProgramParameters.AutoConstantType.Custom, 0);
                        gparams.SetNamedAutoConstant("preRotatedQuad[0]", GpuProgramParameters.AutoConstantType.Custom, 0);
                        gparams.SetNamedAutoConstant("preRotatedQuad[1]", GpuProgramParameters.AutoConstantType.Custom, 0);
                        gparams.SetNamedAutoConstant("preRotatedQuad[2]", GpuProgramParameters.AutoConstantType.Custom, 0);
                        gparams.SetNamedAutoConstant("preRotatedQuad[3]", GpuProgramParameters.AutoConstantType.Custom, 0);

                        gparams.SetNamedAutoConstant("camPos", GpuProgramParameters.AutoConstantType.CameraPositionObjectSpace, 0);
                        gparams.SetNamedAutoConstant("fadeGap", GpuProgramParameters.AutoConstantType.Custom, 0);
                        gparams.SetNamedAutoConstant("invisibleDist", GpuProgramParameters.AutoConstantType.Custom, 0);

                        //Set fade ranges
                        gparams.SetNamedConstant("invisibleDist", invisibleDist);
                        gparams.SetNamedConstant("fadeGap", invisibleDist - visibleDist);

                        pass.SetSceneBlending(SceneBlendType.TransparentAlpha);
                    }
                }

                //Add it to the list so it can be reused later
                mFadedMaterialMap.Add(materialSignature, fadeMaterial);
            }

            return(fadeMaterial);
        }
Esempio n. 3
0
        protected override void OnMaterialRender(uint passId, Material material, ref bool skipPass)
        {
            base.OnMaterialRender(passId, material, ref skipPass);

            if (passId == 100)
            {
                GpuProgramParameters parameters = material.Techniques[0].Passes[0].FragmentProgramParameters;
                if (parameters != null)
                {
                    parameters.SetNamedAutoConstant("farClipDistance",
                                                    GpuProgramParameters.AutoConstantType.FarClipDistance);
                    parameters.SetNamedAutoConstant("viewportSize",
                                                    GpuProgramParameters.AutoConstantType.ViewportSize);

                    parameters.SetNamedConstant("multiplier", Multiplier);
                }
            }
        }
Esempio n. 4
0
        protected override void OnMaterialRender(uint passId, Material material, ref bool skipPass)
        {
            base.OnMaterialRender(passId, material, ref skipPass);

            if (passId == 100)
            {
                GpuProgramParameters parameters = material.Techniques[0].Passes[0].FragmentProgramParameters;
                if (parameters != null)
                {
                    parameters.SetNamedAutoConstant("viewportSize", GpuProgramParameters.AutoConstantType.ViewportSize);
                    parameters.SetNamedConstant("sharp_strength", sharpStrength);
                    parameters.SetNamedConstant("sharp_clamp", sharpClamp);
                    parameters.SetNamedConstant("offset_bias", offsetBias);
                }
            }
        }
        private void SetProgramAutoConstants(GpuProgramParameters parameters)
        {
            parameters.SetNamedAutoConstant("worldMatrix",
                GpuProgramParameters.AutoConstantType.WorldMatrix);
            parameters.SetNamedAutoConstant("viewProjMatrix",
                GpuProgramParameters.AutoConstantType.ViewProjMatrix);
            parameters.SetNamedAutoConstant("texelOffsets",
                GpuProgramParameters.AutoConstantType.TexelOffsets);
            parameters.SetNamedAutoConstant("cameraPosition",
                GpuProgramParameters.AutoConstantType.CameraPosition);
            parameters.SetNamedAutoConstant("farClipDistance",
                GpuProgramParameters.AutoConstantType.FarClipDistance);

            parameters.SetNamedAutoConstant("shadowDirectionalLightBias",
                GpuProgramParameters.AutoConstantType.ShadowDirectionalLightBias);
            parameters.SetNamedAutoConstant("shadowSpotLightBias",
                GpuProgramParameters.AutoConstantType.ShadowSpotLightBias);
            parameters.SetNamedAutoConstant("shadowPointLightBias",
                GpuProgramParameters.AutoConstantType.ShadowPointLightBias);

            parameters.SetNamedAutoConstant("instancing",
                GpuProgramParameters.AutoConstantType.Instancing);
        }
Esempio n. 6
0
        private void SetProgramAutoConstants(GpuProgramParameters parameters)
        {
            parameters.SetNamedAutoConstant("worldMatrix",
                                            GpuProgramParameters.AutoConstantType.WorldMatrix);
            parameters.SetNamedAutoConstant("viewProjMatrix",
                                            GpuProgramParameters.AutoConstantType.ViewProjMatrix);
            parameters.SetNamedAutoConstant("texelOffsets",
                                            GpuProgramParameters.AutoConstantType.TexelOffsets);
            parameters.SetNamedAutoConstant("cameraPosition",
                                            GpuProgramParameters.AutoConstantType.CameraPosition);
            parameters.SetNamedAutoConstant("farClipDistance",
                                            GpuProgramParameters.AutoConstantType.FarClipDistance);

            parameters.SetNamedAutoConstant("shadowDirectionalLightBias",
                                            GpuProgramParameters.AutoConstantType.ShadowDirectionalLightBias);
            parameters.SetNamedAutoConstant("shadowSpotLightBias",
                                            GpuProgramParameters.AutoConstantType.ShadowSpotLightBias);
            parameters.SetNamedAutoConstant("shadowPointLightBias",
                                            GpuProgramParameters.AutoConstantType.ShadowPointLightBias);

            parameters.SetNamedAutoConstant("instancing",
                                            GpuProgramParameters.AutoConstantType.Instancing);
        }
Esempio n. 7
0
        protected override void OnMaterialRender(uint passId, Material material, ref bool skipPass)
        {
            base.OnMaterialRender(passId, material, ref skipPass);

            const int rt_downscale        = 100;
            const int rt_blurHorizontal   = 200;
            const int rt_blurVertical     = 300;
            const int rt_autoFocus1       = 400;
            const int rt_autoFocus2       = 401;
            const int rt_autoFocus3       = 402;
            const int rt_autoFocusFinal   = 403;
            const int rt_autoFocusCurrent = 404;
            //const int rt_blurFactors = 500;
            const int rt_targetOutput = 600;

            //Skip auto focus passes if no auto focus is enabled
            if (!autoFocus)
            {
                if (passId == rt_autoFocus1 || passId == rt_autoFocus2 || passId == rt_autoFocus3 ||
                    passId == rt_autoFocusFinal || passId == rt_autoFocusCurrent)
                {
                    skipPass = true;
                    return;
                }
            }

            // Prepare the fragment params offsets
            switch (passId)
            {
            case rt_downscale:
            {
                Vec2[] sampleOffsets = new Vec2[16];

                CalculateDownScale4x4SampleOffsets(Owner.DimensionsInPixels.Size, sampleOffsets);

                //convert to Vec4 array
                Vec4[] vec4Offsets = new Vec4[16];
                for (int n = 0; n < 16; n++)
                {
                    Vec2 offset = sampleOffsets[n];
                    vec4Offsets[n] = new Vec4(offset[0], offset[1], 0, 0);
                }

                GpuProgramParameters parameters = material.GetBestTechnique().
                                                  Passes[0].FragmentProgramParameters;
                parameters.SetNamedConstant("sampleOffsets", vec4Offsets);
            }
            break;

            case rt_blurHorizontal:
            case rt_blurVertical:
            {
                // horizontal and vertical blur
                bool horizontal = passId == rt_blurHorizontal;

                float[] sampleOffsets = new float[15];
                Vec4[]  sampleWeights = new Vec4[15];

                CalculateBlurSampleOffsets(horizontal ? downscaleTextureSize.X : downscaleTextureSize.Y,
                                           sampleOffsets, sampleWeights, 3, 1);

                //convert to Vec4 array
                Vec4[] vec4Offsets = new Vec4[15];
                for (int n = 0; n < 15; n++)
                {
                    float offset = sampleOffsets[n] * blurSpread;

                    if (horizontal)
                    {
                        vec4Offsets[n] = new Vec4(offset, 0, 0, 0);
                    }
                    else
                    {
                        vec4Offsets[n] = new Vec4(0, offset, 0, 0);
                    }
                }

                GpuProgramParameters parameters = material.GetBestTechnique().
                                                  Passes[0].FragmentProgramParameters;
                parameters.SetNamedConstant("sampleOffsets", vec4Offsets);
                parameters.SetNamedConstant("sampleWeights", sampleWeights);
            }
            break;

            case rt_autoFocus1:
            {
                GpuProgramParameters parameters = material.GetBestTechnique().
                                                  Passes[0].FragmentProgramParameters;
                parameters.SetNamedAutoConstant("farClipDistance",
                                                GpuProgramParameters.AutoConstantType.FarClipDistance);
            }
            break;

            case rt_autoFocus2:
            case rt_autoFocus3:
            {
                Vec2[] sampleOffsets = new Vec2[16];

                string textureSizeFrom = null;
                switch (passId)
                {
                case rt_autoFocus2: textureSizeFrom = "rt_autoFocus1"; break;

                case rt_autoFocus3: textureSizeFrom = "rt_autoFocus2"; break;

                default: Trace.Assert(false); break;
                }
                Vec2I sourceTextureSize = Technique.GetTextureDefinition(textureSizeFrom).Size;
                CalculateDownScale4x4SampleOffsets(sourceTextureSize, sampleOffsets);

                //convert to Vec4 array
                Vec4[] vec4Offsets = new Vec4[16];
                for (int n = 0; n < 16; n++)
                {
                    Vec2 offset = sampleOffsets[n];
                    vec4Offsets[n] = new Vec4(offset[0], offset[1], 0, 0);
                }

                GpuProgramParameters parameters = material.GetBestTechnique().
                                                  Passes[0].FragmentProgramParameters;
                parameters.SetNamedConstant("sampleOffsets", vec4Offsets);
            }
            break;

            case rt_autoFocusFinal:
            {
                GpuProgramParameters parameters = material.GetBestTechnique().
                                                  Passes[0].FragmentProgramParameters;

                Vec4 properties = Vec4.Zero;
                properties.X = autoFocusRange.Minimum;
                properties.Y = autoFocusRange.Maximum;
                properties.Z = RendererWorld.Instance.FrameRenderTimeStep * autoFocusTransitionSpeed;
                parameters.SetNamedConstant("properties", properties);
            }
            break;

            case rt_autoFocusCurrent:
                break;

            //case rt_blurFactors:
            //   {
            //      GpuProgramParameters parameters = material.GetBestTechnique().
            //         Passes[ 0 ].FragmentProgramParameters;
            //      parameters.SetNamedAutoConstant( "farClipDistance",
            //         GpuProgramParameters.AutoConstantType.FarClipDistance );

            //      Vec4 properties = Vec4.Zero;
            //      properties.X = autoFocus ? -1.0f : focalDistance;
            //      properties.Y = focalSize;
            //      properties.Z = backgroundTransitionLength;
            //      properties.W = blurForeground ? foregroundTransitionLength : -1;
            //      parameters.SetNamedConstant( "properties", properties );
            //   }
            //   break;

            //Final pass
            case rt_targetOutput:
            {
                GpuProgramParameters parameters = material.GetBestTechnique().
                                                  Passes[0].FragmentProgramParameters;

                parameters.SetNamedAutoConstant("farClipDistance",
                                                GpuProgramParameters.AutoConstantType.FarClipDistance);

                Vec4 properties = Vec4.Zero;
                properties.X = autoFocus ? -1.0f : focalDistance;
                properties.Y = focalSize;
                properties.Z = backgroundTransitionLength;
                properties.W = blurForeground ? foregroundTransitionLength : -1;
                parameters.SetNamedConstant("properties", properties);

                //Vec2[] sampleOffsets = new Vec2[ 49 ];
                //Vec2 textureSize = Owner.DimensionsInPixels.Size.ToVec2();
                //for( int y = -3; y <= 3; y++ )
                //   for( int x = -3; x <= 3; x++ )
                //      sampleOffsets[ ( y + 3 ) * 7 + ( x + 3 ) ] = new Vec2( x, y ) / textureSize;

                ////convert to Vec4 array
                //Vec4[] vec4Offsets = new Vec4[ 49 ];
                //for( int n = 0; n < 49; n++ )
                //{
                //   Vec2 offset = sampleOffsets[ n ];
                //   vec4Offsets[ n ] = new Vec4( offset[ 0 ], offset[ 1 ], 0, 0 );
                //}
                //parameters.SetNamedConstant( "sampleOffsets", vec4Offsets );
            }
            break;
            }
        }
Esempio n. 8
0
        /// <summary>
        ///
        /// </summary>
        internal void UpdateShaders()
        {
            if (mShaderNeedsUpdate)
            {
                mShaderNeedsUpdate = false;
                //Proceed only if there is no custom vertex shader and the user's computer supports vertex shaders
                RenderSystemCapabilities caps = Root.Singleton.RenderSystem.Capabilities;
                if (caps.HasCapability(Capabilities.VertexPrograms))
                {
                    //Generate a string ID that identifies the current set of vertex shader options
                    string tmpName = string.Empty;
                    tmpName += "GrassVS_";
                    if (mAnimate)
                    {
                        tmpName += "anim_";
                    }
                    if (mBlend)
                    {
                        tmpName += "blend_";
                    }
                    tmpName += mRenderTechnique.ToString() + "_";
                    tmpName += mFadeTechnique.ToString() + "_";
                    if (mFadeTechnique == FadeTechnique.Grow || mFadeTechnique == FadeTechnique.AlphaGrow)
                    {
                        tmpName += mMaxHeight + "_";
                    }
                    tmpName += "vp";

                    string vsName = tmpName;
                    //Generate a string ID that identifies the material combined with the vertex shader
                    string matName = mMaterial.Name + "_" + vsName;

                    //Check if the desired material already exists (if not, create it)
                    Material tmpMat = (Material)MaterialManager.Instance.GetByName(matName);
                    if (tmpMat == null)
                    {
                        //Clone the original material
                        tmpMat = mMaterial.Clone(matName);

                        //Disable lighting
                        tmpMat.Lighting = false;
                        //Check if the desired shader already exists (if not, compile it)
                        HighLevelGpuProgram vertexShader = (HighLevelGpuProgram)HighLevelGpuProgramManager.Instance.GetByName(vsName);
                        if (vertexShader == null)
                        {
                            //Generate the grass shader
                            string vertexProgSource = string.Empty;
                            vertexProgSource +=
                                "void main( \n" +
                                "	float4 iPosition : POSITION, \n"+
                                "	float4 iColor : COLOR, \n"+
                                "	float2 iUV       : TEXCOORD0,	\n"+
                                "	out float4 oPosition : POSITION, \n"+
                                "	out float4 oColor : COLOR, \n"+
                                "	out float2 oUV       : TEXCOORD0,	\n";

                            if (mAnimate)
                            {
                                vertexProgSource +=
                                    "	uniform float time,	\n"+
                                    "	uniform float frequency,	\n"+
                                    "	uniform float4 direction,	\n";
                            }
                            if (mFadeTechnique == FadeTechnique.Grow || mFadeTechnique == FadeTechnique.AlphaGrow)
                            {
                                vertexProgSource +=
                                    "	uniform float grassHeight,	\n";
                            }
                            if (mRenderTechnique == GrassTechnique.Sprite)
                            {
                                vertexProgSource +=
                                    "	float4 iNormal : NORMAL, \n";
                            }

                            vertexProgSource +=
                                "	uniform float4x4 worldViewProj,	\n"+
                                "	uniform float3 camPos, \n"+
                                "	uniform float fadeRange ) \n"+
                                "{	\n"+
                                "	oColor.rgb = iColor.rgb;   \n"+
                                "	float4 position = iPosition;	\n"+
                                "	float dist = distance(camPos.xz, position.xz);	\n";

                            if (mFadeTechnique == FadeTechnique.Alpha || mFadeTechnique == FadeTechnique.AlphaGrow)
                            {
                                vertexProgSource +=
                                    //Fade out in the distance
                                    "	oColor.a = 2.0f - (2.0f * dist / fadeRange);   \n";
                            }
                            else
                            {
                                vertexProgSource +=
                                    "	oColor.a = 1.0f;   \n";
                            }

                            vertexProgSource +=
                                "	float oldposx = position.x;	\n";

                            if (mRenderTechnique == GrassTechnique.Sprite)
                            {
                                vertexProgSource +=
                                    //Face the camera
                                    "	float3 dirVec = (float3)position - (float3)camPos;		\n"+
                                    "	float3 p = normalize(cross(float4(0,1,0,0), dirVec));	\n"+
                                    "	position += float4(p.x * iNormal.x, iNormal.y, p.z * iNormal.x, 0);	\n";
                            }

                            if (mAnimate)
                            {
                                vertexProgSource +=
                                    "	if (iUV.y == 0.0f){	\n"+
                                    //Wave grass in breeze
                                    "		float offset = sin(time + oldposx * frequency);	\n"+
                                    "		position += direction * offset;	\n"+
                                    "	}	\n";
                            }
                            if (mBlend && mAnimate)
                            {
                                vertexProgSource +=
                                    "	else {	\n";
                            }
                            else if (mBlend)
                            {
                                vertexProgSource +=
                                    "	if (iUV.y != 0.0f){	\n";
                            }
                            if (mBlend)
                            {
                                vertexProgSource +=
                                    //Blend the base of nearby grass into the terrain
                                    "		if (oColor.a >= 1.0f) \n"+
                                    "			oColor.a = 4.0f * ((dist / fadeRange) - 0.1f);	\n"+
                                    "	}	\n";
                            }
                            if (mFadeTechnique == FadeTechnique.Grow || mFadeTechnique == FadeTechnique.AlphaGrow)
                            {
                                vertexProgSource +=
                                    "	float offset = (2.0f * dist / fadeRange) - 1.0f; \n"+
                                    "	position.y -= grassHeight * clamp(offset, 0, 1); ";
                            }
                            vertexProgSource +=
                                "	oPosition = mul(worldViewProj, position);  \n";

                            vertexProgSource +=
                                "	oUV = iUV;\n"+
                                "}";
                            vertexShader = HighLevelGpuProgramManager.Instance.CreateProgram(
                                vsName,
                                ResourceGroupManager.DefaultResourceGroupName,
                                "cg", GpuProgramType.Vertex);
                            vertexShader.Source = vertexProgSource;
                            vertexShader.SetParam("profiles", "vs_1_1 arbvp1");
                            vertexShader.SetParam("entry_point", "main");
                            vertexShader.Load();
                        }
                        //Now the vertex shader (vertexShader) has either been found or just generated
                        //(depending on whether or not it was already generated).

                        //Apply the shader to the material
                        Pass pass = tmpMat.GetTechnique(0).GetPass(0);
                        pass.VertexProgramName = vsName;
                        GpuProgramParameters gparams = pass.VertexProgramParameters;

                        gparams.SetNamedAutoConstant("worldViewProj", GpuProgramParameters.AutoConstantType.WorldViewProjMatrix, 0);
                        gparams.SetNamedAutoConstant("camPos", GpuProgramParameters.AutoConstantType.CameraPositionObjectSpace, 0);
                        gparams.SetNamedAutoConstant("fadeRange", GpuProgramParameters.AutoConstantType.Custom, 1);

                        if (mAnimate)
                        {
                            gparams.SetNamedAutoConstant("time", GpuProgramParameters.AutoConstantType.Custom, 1);
                            gparams.SetNamedAutoConstant("frequency", GpuProgramParameters.AutoConstantType.Custom, 1);
                            gparams.SetNamedAutoConstant("direction", GpuProgramParameters.AutoConstantType.Custom, 4);
                        }

                        if (mFadeTechnique == FadeTechnique.Grow || mFadeTechnique == FadeTechnique.AlphaGrow)
                        {
                            gparams.SetNamedAutoConstant("grassHeight", GpuProgramParameters.AutoConstantType.Custom, 1);
                            gparams.SetNamedConstant("grassHeight", mMaxHeight * 1.05f);
                        }

                        float farViewDist = mGeom.DetailLevels[0].FarRange;
                        pass.VertexProgramParameters.SetNamedConstant("fadeRange", farViewDist / 1.225f);
                        //Note: 1.225 ~= sqrt(1.5), which is necessary since the far view distance is measured from the centers
                        //of pages, while the vertex shader needs to fade grass completely out (including the closest corner)
                        //before the page center is out of range.
                    }
                    //Now the material (tmpMat) has either been found or just created (depending on whether or not it was already
                    //created). The appropriate vertex shader should be applied and the material is ready for use.

                    //Apply the new material
                    mMaterial = tmpMat;
                }
            }
        }
Esempio n. 9
0
        //-------------------------------------------------------------------------
        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);
                            }
                        }
                    }
                }
            }
        }
Esempio n. 10
0
        static void SetProgramAutoConstants( GpuProgramParameters parameters )
        {
            //Matrix
            parameters.SetNamedAutoConstant( "worldViewProjMatrix",
                GpuProgramParameters.AutoConstantType.WorldViewProjMatrix );
            parameters.SetNamedAutoConstant( "worldViewMatrix",
                GpuProgramParameters.AutoConstantType.WorldViewMatrix );
            parameters.SetNamedAutoConstant( "cameraPositionObjectSpace",
                GpuProgramParameters.AutoConstantType.CameraPositionObjectSpace );

            //Fog
            parameters.SetNamedAutoConstant( "fogParams",
                GpuProgramParameters.AutoConstantType.FogParams );
            parameters.SetNamedAutoConstant( "fogColor",
                GpuProgramParameters.AutoConstantType.FogColor );

            //Time
            //parameters.SetNamedAutoConstantFloat( "timeValue",
            //   GpuProgramParameters.AutoConstantType.Time01, 20.0f );
            parameters.SetNamedAutoConstantFloat( "time0X",
                GpuProgramParameters.AutoConstantType.Time0X, 1000.0f );

            parameters.SetNamedAutoConstant( "renderTargetFlipping",
                GpuProgramParameters.AutoConstantType.RenderTargetFlipping );
        }
        protected override void OnMaterialRender(uint passId, Material material, ref bool skipPass)
        {
            base.OnMaterialRender(passId, material, ref skipPass);

            const int rt_depthDownsample1x1 = 100;
            const int rt_depthDownsample2x2 = 101;
            const int rt_depthDownsample3x3 = 102;
            const int rt_occlusion          = 200;
            const int rt_blurHorizontal     = 300;
            const int rt_blurVertical       = 400;
            const int rt_targetOutput       = 500;

            switch (passId)
            {
            case rt_depthDownsample1x1:
            case rt_depthDownsample2x2:
            case rt_depthDownsample3x3:
            {
                if (downsampling == 1 && passId != rt_depthDownsample1x1)
                {
                    skipPass = true;
                    return;
                }
                if (downsampling == 2 && passId != rt_depthDownsample2x2)
                {
                    skipPass = true;
                    return;
                }
                if (downsampling == 3 && passId != rt_depthDownsample3x3)
                {
                    skipPass = true;
                    return;
                }

                GpuProgramParameters parameters = material.Techniques[0].Passes[0].FragmentProgramParameters;
                if (parameters != null)
                {
                    parameters.SetNamedAutoConstant("viewportSize", GpuProgramParameters.AutoConstantType.ViewportSize);

                    Vec4 v = new Vec4(EngineApp.Instance.IsKeyPressed(EKeys.Z) ? 1 : -1, 0, 0, 0);
                    parameters.SetNamedConstant("temp", v);
                }
            }
            break;

            case rt_occlusion:
            {
                GpuProgramParameters parameters = material.Techniques[0].Passes[0].FragmentProgramParameters;
                if (parameters != null)
                {
                    parameters.SetNamedAutoConstant("farClipDistance",
                                                    GpuProgramParameters.AutoConstantType.FarClipDistance);
                    parameters.SetNamedAutoConstant("viewportSize",
                                                    GpuProgramParameters.AutoConstantType.ViewportSize);
                    parameters.SetNamedAutoConstant("fov",
                                                    GpuProgramParameters.AutoConstantType.FOV);

                    parameters.SetNamedConstant("downscaleTextureSize",
                                                new Vec4(downscaleTextureSize.X, downscaleTextureSize.Y,
                                                         1.0f / (float)downscaleTextureSize.X, 1.0f / (float)downscaleTextureSize.Y));

                    parameters.SetNamedConstant("sampleLength", sampleLength);
                    parameters.SetNamedConstant("offsetScale", offsetScale);
                    parameters.SetNamedConstant("defaultAccessibility", defaultAccessibility);

                    //parameters.SetNamedConstant( "parameters",
                    //   new Vec4( sampleLength, offsetScale, defaultAccessibility, 0 ) );

                    Range range = new Range(maxDistance, maxDistance * 1.2f);
                    parameters.SetNamedConstant("fadingByDistanceRange",
                                                new Vec4(range.Minimum, 1.0f / (range.Maximum - range.Minimum), 0, 0));
                }
            }
            break;

            case rt_blurHorizontal:
            case rt_blurVertical:
            {
                // horizontal and vertical blur
                bool horizontal = passId == rt_blurHorizontal;

                float[] sampleOffsets = new float[15];
                Vec4[]  sampleWeights = new Vec4[15];

                Vec2I textureSize = Owner.DimensionsInPixels.Size;
                CalculateBlurSampleOffsets(horizontal ? textureSize.X : textureSize.Y, sampleOffsets, sampleWeights, 3, 1);

                //convert to Vec4 array
                Vec4[] vec4Offsets = new Vec4[15];
                for (int n = 0; n < 15; n++)
                {
                    float offset = sampleOffsets[n] * blurSpread;

                    if (horizontal)
                    {
                        vec4Offsets[n] = new Vec4(offset, 0, 0, 0);
                    }
                    else
                    {
                        vec4Offsets[n] = new Vec4(0, offset, 0, 0);
                    }
                }

                GpuProgramParameters parameters = material.GetBestTechnique().
                                                  Passes[0].FragmentProgramParameters;
                parameters.SetNamedAutoConstant("farClipDistance",
                                                GpuProgramParameters.AutoConstantType.FarClipDistance);
                parameters.SetNamedConstant("sampleOffsets", vec4Offsets);
                parameters.SetNamedConstant("sampleWeights", sampleWeights);

                //parameters.SetNamedConstant( "horizontal", passId == rt_blurHorizontal ? 1.0f : -1.0f );
            }
            break;

            case rt_targetOutput:
            {
                GpuProgramParameters parameters = material.GetBestTechnique().
                                                  Passes[0].FragmentProgramParameters;
                parameters.SetNamedConstant("intensity", intensity);

                //parameters.SetNamedConstant( "fixEdges", fixEdges ? 1.0f : -1.0f );
                parameters.SetNamedConstant("showAO", showAO ? 1.0f : -1.0f);

                parameters.SetNamedConstant("downscaleTextureSize",
                                            new Vec4(downscaleTextureSize.X, downscaleTextureSize.Y,
                                                     1.0f / (float)downscaleTextureSize.X, 1.0f / (float)downscaleTextureSize.Y));
            }
            break;
            }
        }
Esempio n. 12
0
        void SetProgramAutoConstants_Main_Vertex( GpuProgramParameters parameters, int lightCount )
        {
            bool shadowMap = SceneManager.Instance.IsShadowTechniqueShadowmapBased() && ReceiveShadows &&
                lightCount != 0;

            parameters.SetNamedAutoConstant( "worldMatrix",
                GpuProgramParameters.AutoConstantType.WorldMatrix );
            parameters.SetNamedAutoConstant( "viewProjMatrix",
                GpuProgramParameters.AutoConstantType.ViewProjMatrix );
            parameters.SetNamedAutoConstant( "cameraPositionObjectSpace",
                GpuProgramParameters.AutoConstantType.CameraPositionObjectSpace );
            parameters.SetNamedAutoConstant( "cameraPosition",
                GpuProgramParameters.AutoConstantType.CameraPosition );

            if( lightCount != 0 )
            {
                if( shadowMap )
                {
                    parameters.SetNamedAutoConstant( "textureViewProjMatrix0",
                    GpuProgramParameters.AutoConstantType.TextureViewProjMatrix, 0 );
                    parameters.SetNamedAutoConstant( "textureViewProjMatrix1",
                        GpuProgramParameters.AutoConstantType.TextureViewProjMatrix, 1 );
                    parameters.SetNamedAutoConstant( "textureViewProjMatrix2",
                        GpuProgramParameters.AutoConstantType.TextureViewProjMatrix, 2 );
                    parameters.SetNamedAutoConstant( "shadowFarDistance",
                        GpuProgramParameters.AutoConstantType.ShadowFarDistance );
                    parameters.SetNamedAutoConstant( "shadowTextureSizes",
                        GpuProgramParameters.AutoConstantType.ShadowTextureSizes );
                    if( SceneManager.Instance.IsShadowTechniquePSSM() )
                    {
                        parameters.SetNamedAutoConstant( "shadowDirectionalLightSplitDistances",
                            GpuProgramParameters.AutoConstantType.ShadowDirectionalLightSplitDistances );
                    }
                }

                parameters.SetNamedAutoConstant( "lightPositionArray",
                    GpuProgramParameters.AutoConstantType.LightPositionArray, lightCount );
                parameters.SetNamedAutoConstant( "lightPositionObjectSpaceArray",
                    GpuProgramParameters.AutoConstantType.LightPositionObjectSpaceArray, lightCount );
                parameters.SetNamedAutoConstant( "lightDirectionArray",
                    GpuProgramParameters.AutoConstantType.LightDirectionArray, lightCount );
                parameters.SetNamedAutoConstant( "lightAttenuationArray",
                    GpuProgramParameters.AutoConstantType.LightAttenuationArray, lightCount );
                parameters.SetNamedAutoConstant( "spotLightParamsArray",
                    GpuProgramParameters.AutoConstantType.SpotLightParamsArray, lightCount );
                parameters.SetNamedAutoConstant( "lightCustomShaderParameterArray",
                    GpuProgramParameters.AutoConstantType.LightCustomShaderParameterArray, lightCount );
            }

            //instancing
            if( RenderSystem.Instance.HasShaderModel3() &&
                RenderSystem.Instance.Capabilities.HardwareInstancing )
            {
                parameters.SetNamedAutoConstant( "instancing", GpuProgramParameters.AutoConstantType.Instancing );
            }

            //1 hour interval for better precision.
            parameters.SetNamedAutoConstantFloat( "time",
                GpuProgramParameters.AutoConstantType.Time0X, 3600.0f );
        }
Esempio n. 13
0
        void SetProgramAutoConstants_Main_Fragment( GpuProgramParameters parameters, int lightCount )
        {
            bool shadowMap = SceneManager.Instance.IsShadowTechniqueShadowmapBased() && ReceiveShadows &&
                lightCount != 0;

            parameters.SetNamedAutoConstant( "worldMatrix", GpuProgramParameters.AutoConstantType.WorldMatrix );
            parameters.SetNamedAutoConstant( "cameraPosition", GpuProgramParameters.AutoConstantType.CameraPosition );

            parameters.SetNamedAutoConstant( "farClipDistance",
                GpuProgramParameters.AutoConstantType.FarClipDistance );

            if( shadowMap )
            {
                parameters.SetNamedAutoConstant( "drawShadowDebugging",
                    GpuProgramParameters.AutoConstantType.DrawShadowDebugging );
            }

            //viewportSize
            if( SoftParticles )
            {
                parameters.SetNamedAutoConstant( "viewportSize",
                    GpuProgramParameters.AutoConstantType.ViewportSize );
            }

            //Light
            parameters.SetNamedAutoConstant( "ambientLightColor",
                GpuProgramParameters.AutoConstantType.AmbientLightColor );

            if( lightCount != 0 )
            {
                if( shadowMap )
                {
                    parameters.SetNamedAutoConstant( "lightShadowFarClipDistance",
                        GpuProgramParameters.AutoConstantType.LightShadowFarClipDistance, 0 );
                    parameters.SetNamedAutoConstant( "shadowFarDistance",
                        GpuProgramParameters.AutoConstantType.ShadowFarDistance );
                    parameters.SetNamedAutoConstant( "shadowColorIntensity",
                        GpuProgramParameters.AutoConstantType.ShadowColorIntensity );
                    parameters.SetNamedAutoConstant( "shadowTextureSizes",
                        GpuProgramParameters.AutoConstantType.ShadowTextureSizes );
                    if( SceneManager.Instance.IsShadowTechniquePSSM() )
                    {
                        parameters.SetNamedAutoConstant( "shadowDirectionalLightSplitDistances",
                            GpuProgramParameters.AutoConstantType.ShadowDirectionalLightSplitDistances );
                    }
                }

                parameters.SetNamedAutoConstant( "lightPositionArray",
                    GpuProgramParameters.AutoConstantType.LightPositionArray, lightCount );
                parameters.SetNamedAutoConstant( "lightDirectionArray",
                    GpuProgramParameters.AutoConstantType.LightDirectionArray, lightCount );
                parameters.SetNamedAutoConstant( "lightAttenuationArray",
                    GpuProgramParameters.AutoConstantType.LightAttenuationArray, lightCount );
                parameters.SetNamedAutoConstant( "lightDiffuseColorPowerScaledArray",
                    GpuProgramParameters.AutoConstantType.LightDiffuseColorPowerScaledArray, lightCount );
                parameters.SetNamedAutoConstant( "lightSpecularColorPowerScaledArray",
                    GpuProgramParameters.AutoConstantType.LightSpecularColorPowerScaledArray, lightCount );
                parameters.SetNamedAutoConstant( "spotLightParamsArray",
                    GpuProgramParameters.AutoConstantType.SpotLightParamsArray, lightCount );
                parameters.SetNamedAutoConstant( "lightCastShadowsArray",
                    GpuProgramParameters.AutoConstantType.LightCastShadowsArray, lightCount );
                parameters.SetNamedAutoConstant( "lightCustomShaderParameterArray",
                    GpuProgramParameters.AutoConstantType.LightCustomShaderParameterArray, lightCount );
            }

            //Fog
            if( allowFog && SceneManager.Instance.GetFogMode() != FogMode.None )
            {
                parameters.SetNamedAutoConstant( "fogParams",
                    GpuProgramParameters.AutoConstantType.FogParams );
                parameters.SetNamedAutoConstant( "fogColor",
                    GpuProgramParameters.AutoConstantType.FogColor );
            }

            //lightmap
            if( LightmapTexCoordIndex != -1 )
            {
                parameters.SetNamedAutoConstant( "lightmapUVTransform",
                    GpuProgramParameters.AutoConstantType.LightmapUVTransform );
            }

            //clip planes
            if( RenderSystem.Instance.IsOpenGL() )
            {
                for( int n = 0; n < 6; n++ )
                {
                    parameters.SetNamedAutoConstant( "clipPlane" + n.ToString(),
                        GpuProgramParameters.AutoConstantType.ClipPlane, n );
                }
            }

            if( RenderSystem.Instance.IsOpenGLES() )
            {
                parameters.SetNamedAutoConstant( "alphaRejectValue",
                    GpuProgramParameters.AutoConstantType.AlphaRejectValue );
            }

            //1 hour interval for better precision.
            parameters.SetNamedAutoConstantFloat( "time",
                GpuProgramParameters.AutoConstantType.Time0X, 3600.0f );
        }
Esempio n. 14
0
            public static void TranslateProgramParameters(ScriptCompiler compiler, GpuProgramParameters parameters,
                                                          ObjectAbstractNode obj)
            {
                var animParametricsCount = 0;

                foreach (var i in obj.Children)
                {
                    if (!(i is PropertyAbstractNode))
                    {
                        continue;
                    }

                    var prop = (PropertyAbstractNode)i;
                    switch ((Keywords)prop.Id)
                    {
                        #region ID_SHARED_PARAMS_REF

                    case Keywords.ID_SHARED_PARAMS_REF:
                    {
                        if (prop.Values.Count != 1)
                        {
                            compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line,
                                              "shared_params_ref requires a single parameter");
                            continue;
                        }

                        var i0 = getNodeAt(prop.Values, 0);
                        if (!(i0 is AtomAbstractNode))
                        {
                            compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line,
                                              "shared parameter set name expected");
                            continue;
                        }
                        var atom0 = (AtomAbstractNode)i0;

                        try
                        {
                            parameters.AddSharedParameters(atom0.Value);
                        }
                        catch (AxiomException e)
                        {
                            compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line, e.Message);
                        }
                    }
                    break;

                        #endregion ID_SHARED_PARAMS_REF

                        #region ID_PARAM_INDEXED || ID_PARAM_NAMED

                    case Keywords.ID_PARAM_INDEXED:
                    case Keywords.ID_PARAM_NAMED:
                    {
                        if (prop.Values.Count >= 3)
                        {
                            var named = (prop.Id == (uint)Keywords.ID_PARAM_NAMED);
                            var i0    = getNodeAt(prop.Values, 0);
                            var i1    = getNodeAt(prop.Values, 1);
                            var k     = getNodeAt(prop.Values, 2);

                            if (!(i0 is AtomAbstractNode) || !(i1 is AtomAbstractNode))
                            {
                                compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line,
                                                  "name or index and parameter type expected");
                                return;
                            }

                            var atom0 = (AtomAbstractNode)i0;
                            var atom1 = (AtomAbstractNode)i1;
                            if (!named && !atom0.IsNumber)
                            {
                                compiler.AddError(CompileErrorCode.NumberExpected, prop.File, prop.Line, "parameter index expected");
                                return;
                            }

                            var name  = string.Empty;
                            var index = 0;
                            // Assign the name/index
                            if (named)
                            {
                                name = atom0.Value;
                            }
                            else
                            {
                                index = (int)atom0.Number;
                            }

                            // Determine the type
                            if (atom1.Value == "matrix4x4")
                            {
                                Matrix4 m;
                                if (getMatrix4(prop.Values, 2, out m))
                                {
                                    try
                                    {
                                        if (named)
                                        {
                                            parameters.SetNamedConstant(name, m);
                                        }
                                        else
                                        {
                                            parameters.SetConstant(index, m);
                                        }
                                    }
                                    catch
                                    {
                                        compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line,
                                                          "setting matrix4x4 parameter failed");
                                    }
                                }
                                else
                                {
                                    compiler.AddError(CompileErrorCode.NumberExpected, prop.File, prop.Line, "incorrect matrix4x4 declaration");
                                }
                            }
                            else
                            {
                                // Find the number of parameters
                                var isValid = true;
                                var type    = GpuProgramParameters.ElementType.Real;
                                var count   = 0;
                                if (atom1.Value.Contains("float"))
                                {
                                    type = GpuProgramParameters.ElementType.Real;
                                    if (atom1.Value.Length >= 6)
                                    {
                                        count = int.Parse(atom1.Value.Substring(5));
                                    }
                                    else
                                    {
                                        count = 1;
                                    }
                                }
                                else if (atom1.Value.Contains("int"))
                                {
                                    type = GpuProgramParameters.ElementType.Int;
                                    if (atom1.Value.Length >= 4)
                                    {
                                        count = int.Parse(atom1.Value.Substring(3));
                                    }
                                    else
                                    {
                                        count = 1;
                                    }
                                }
                                else
                                {
                                    compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line,
                                                      "incorrect type specified; only variants of int and float allowed");
                                    isValid = false;
                                }

                                if (isValid)
                                {
                                    // First, clear out any offending auto constants
                                    if (named)
                                    {
                                        parameters.ClearNamedAutoConstant(name);
                                    }
                                    else
                                    {
                                        parameters.ClearAutoConstant(index);
                                    }

                                    var roundedCount = count % 4 != 0 ? count + 4 - (count % 4) : count;
                                    if (type == GpuProgramParameters.ElementType.Int)
                                    {
                                        var vals = new int[roundedCount];
                                        if (getInts(prop.Values, 2, out vals, roundedCount))
                                        {
                                            try
                                            {
                                                if (named)
                                                {
                                                    parameters.SetNamedConstant(name, vals, count, 1);
                                                }
                                                else
                                                {
                                                    parameters.SetConstant(index, vals, roundedCount / 4);
                                                }
                                            }
                                            catch
                                            {
                                                compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line, "setting of constant failed");
                                            }
                                        }
                                        else
                                        {
                                            compiler.AddError(CompileErrorCode.NumberExpected, prop.File, prop.Line,
                                                              "incorrect integer constant declaration");
                                        }
                                    }
                                    else
                                    {
                                        var vals = new float[roundedCount];
                                        if (getFloats(prop.Values, 2, out vals, roundedCount))
                                        {
                                            try
                                            {
                                                if (named)
                                                {
                                                    parameters.SetNamedConstant(name, vals, count, 1);
                                                }
                                                else
                                                {
                                                    parameters.SetConstant(index, vals, roundedCount / 4);
                                                }
                                            }
                                            catch
                                            {
                                                compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line, "setting of constant failed");
                                            }
                                        }
                                        else
                                        {
                                            compiler.AddError(CompileErrorCode.NumberExpected, prop.File, prop.Line,
                                                              "incorrect float constant declaration");
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line,
                                              "param_named and param_indexed properties requires at least 3 arguments");
                        }
                    }
                    break;

                        #endregion ID_PARAM_INDEXED || ID_PARAM_NAMED

                        #region ID_PARAM_INDEXED_AUTO || ID_PARAM_NAMED_AUTO

                    case Keywords.ID_PARAM_INDEXED_AUTO:
                    case Keywords.ID_PARAM_NAMED_AUTO:
                    {
                        var named = (prop.Id == (uint)Keywords.ID_PARAM_NAMED_AUTO);
                        var name  = string.Empty;
                        var index = 0;

                        if (prop.Values.Count >= 2)
                        {
                            var i0 = getNodeAt(prop.Values, 0);
                            var i1 = getNodeAt(prop.Values, 1);
                            var i2 = getNodeAt(prop.Values, 2);
                            var i3 = getNodeAt(prop.Values, 3);

                            if (!(i0 is AtomAbstractNode) || !(i1 is AtomAbstractNode))
                            {
                                compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line,
                                                  "name or index and auto constant type expected");
                                return;
                            }
                            var atom0 = (AtomAbstractNode)i0;
                            var atom1 = (AtomAbstractNode)i1;

                            if (!named && !atom0.IsNumber)
                            {
                                compiler.AddError(CompileErrorCode.NumberExpected, prop.File, prop.Line, "parameter index expected");
                                return;
                            }

                            if (named)
                            {
                                name = atom0.Value;
                            }
                            else
                            {
                                index = int.Parse(atom0.Value);
                            }

                            // Look up the auto constant
                            atom1.Value = atom1.Value.ToLower();

                            GpuProgramParameters.AutoConstantDefinition def;
                            var defFound = GpuProgramParameters.GetAutoConstantDefinition(atom1.Value, out def);

                            if (defFound)
                            {
                                switch (def.DataType)
                                {
                                    #region None

                                case GpuProgramParameters.AutoConstantDataType.None:
                                    // Set the auto constant
                                    try
                                    {
                                        if (named)
                                        {
                                            parameters.SetNamedAutoConstant(name, def.AutoConstantType);
                                        }
                                        else
                                        {
                                            parameters.SetAutoConstant(index, def.AutoConstantType);
                                        }
                                    }
                                    catch
                                    {
                                        compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line, "setting of constant failed");
                                    }
                                    break;

                                    #endregion None

                                    #region Int

                                case GpuProgramParameters.AutoConstantDataType.Int:
                                    if (def.AutoConstantType == GpuProgramParameters.AutoConstantType.AnimationParametric)
                                    {
                                        try
                                        {
                                            if (named)
                                            {
                                                parameters.SetNamedAutoConstant(name, def.AutoConstantType, animParametricsCount++);
                                            }
                                            else
                                            {
                                                parameters.SetAutoConstant(index, def.AutoConstantType, animParametricsCount++);
                                            }
                                        }
                                        catch
                                        {
                                            compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line, "setting of constant failed");
                                        }
                                    }
                                    else
                                    {
                                        // Only certain texture projection auto params will assume 0
                                        // Otherwise we will expect that 3rd parameter
                                        if (i2 == null)
                                        {
                                            if (def.AutoConstantType == GpuProgramParameters.AutoConstantType.TextureViewProjMatrix ||
                                                def.AutoConstantType == GpuProgramParameters.AutoConstantType.TextureWorldViewProjMatrix ||
                                                def.AutoConstantType == GpuProgramParameters.AutoConstantType.SpotLightViewProjMatrix ||
                                                def.AutoConstantType == GpuProgramParameters.AutoConstantType.SpotLightWorldViewProjMatrix)
                                            {
                                                try
                                                {
                                                    if (named)
                                                    {
                                                        parameters.SetNamedAutoConstant(name, def.AutoConstantType, 0);
                                                    }
                                                    else
                                                    {
                                                        parameters.SetAutoConstant(index, def.AutoConstantType, 0);
                                                    }
                                                }
                                                catch
                                                {
                                                    compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line, "setting of constant failed");
                                                }
                                            }
                                            else
                                            {
                                                compiler.AddError(CompileErrorCode.NumberExpected, prop.File, prop.Line,
                                                                  "extra parameters required by constant definition " + atom1.Value);
                                            }
                                        }
                                        else
                                        {
                                            var success   = false;
                                            var extraInfo = 0;
                                            if (i3 == null)
                                            {
                                                // Handle only one extra value
                                                if (getInt(i2, out extraInfo))
                                                {
                                                    success = true;
                                                }
                                            }
                                            else
                                            {
                                                // Handle two extra values
                                                var extraInfo1 = 0;
                                                var extraInfo2 = 0;
                                                if (getInt(i2, out extraInfo1) && getInt(i3, out extraInfo2))
                                                {
                                                    extraInfo = extraInfo1 | (extraInfo2 << 16);
                                                    success   = true;
                                                }
                                            }

                                            if (success)
                                            {
                                                try
                                                {
                                                    if (named)
                                                    {
                                                        parameters.SetNamedAutoConstant(name, def.AutoConstantType, extraInfo);
                                                    }
                                                    else
                                                    {
                                                        parameters.SetAutoConstant(index, def.AutoConstantType, extraInfo);
                                                    }
                                                }
                                                catch
                                                {
                                                    compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line, "setting of constant failed");
                                                }
                                            }
                                            else
                                            {
                                                compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line,
                                                                  "invalid auto constant extra info parameter");
                                            }
                                        }
                                    }
                                    break;

                                    #endregion Int

                                    #region Real

                                case GpuProgramParameters.AutoConstantDataType.Real:
                                    if (def.AutoConstantType == GpuProgramParameters.AutoConstantType.Time ||
                                        def.AutoConstantType == GpuProgramParameters.AutoConstantType.FrameTime)
                                    {
                                        Real f = 1.0f;
                                        if (i2 != null)
                                        {
                                            getReal(i2, out f);
                                        }

                                        try
                                        {
                                            if (named)
                                            {
                                                parameters.SetNamedAutoConstantReal(name, def.AutoConstantType, f);
                                            }
                                            else
                                            {
                                                parameters.SetAutoConstantReal(index, def.AutoConstantType, f);
                                            }
                                        }
                                        catch
                                        {
                                            compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line, "setting of constant failed");
                                        }
                                    }
                                    else
                                    {
                                        if (i2 != null)
                                        {
                                            Real extraInfo = 0.0f;
                                            if (getReal(i2, out extraInfo))
                                            {
                                                try
                                                {
                                                    if (named)
                                                    {
                                                        parameters.SetNamedAutoConstantReal(name, def.AutoConstantType, extraInfo);
                                                    }
                                                    else
                                                    {
                                                        parameters.SetAutoConstantReal(index, def.AutoConstantType, extraInfo);
                                                    }
                                                }
                                                catch
                                                {
                                                    compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line, "setting of constant failed");
                                                }
                                            }
                                            else
                                            {
                                                compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line,
                                                                  "incorrect float argument definition in extra parameters");
                                            }
                                        }
                                        else
                                        {
                                            compiler.AddError(CompileErrorCode.NumberExpected, prop.File, prop.Line,
                                                              "extra parameters required by constant definition " + atom1.Value);
                                        }
                                    }
                                    break;

                                    #endregion Real
                                }
                            }
                            else
                            {
                                compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line);
                            }
                        }
                        else
                        {
                            compiler.AddError(CompileErrorCode.InvalidParameters, prop.File, prop.Line);
                        }
                    }
                    break;

                        #endregion ID_PARAM_INDEXED_AUTO || ID_PARAM_NAMED_AUTO

                    default:
                        compiler.AddError(CompileErrorCode.UnexpectedToken, prop.File, prop.Line,
                                          "token \"" + prop.Name + "\" is not recognized");
                        break;
                    }
                }
            }
Esempio n. 15
0
        /// <summary>
        ///
        /// </summary>
        private void UpdateShaders()
        {
            if (!mShadersSupported)
            {
                return;
            }

            int i = 0;

            foreach (BatchedGeometry.SubBatch it in mBatch.SubBatches.Values)
            {
                BatchedGeometry.SubBatch subBatch = it;
                Material mat = mUnfadedMaterials[i++];

                //check ig lighting should be enabled
                bool lightningEnabled = false;
                for (int t = 0; t < mat.TechniqueCount; t++)
                {
                    Technique tech = mat.GetTechnique(t);
                    for (int p = 0; p < tech.PassCount; p++)
                    {
                        Pass pass = tech.GetPass(p);
                        if (pass.LightingEnabled)
                        {
                            lightningEnabled = true;
                            break;
                        }
                        if (lightningEnabled)
                        {
                            break;
                        }
                    }
                }

                //Compile the CG shader script based on various material / fade options
                string tmpName = string.Empty;

                tmpName += "BatchPage_";
                if (mFadeEnabled)
                {
                    tmpName += "fade_";
                }
                if (lightningEnabled)
                {
                    tmpName += "lit_";
                }

                tmpName += "vp";

                string vertexProgName = tmpName;

                //If the shader hasn't been created yet, create it
                if (HighLevelGpuProgramManager.Instance.GetByName(tmpName) == null)
                {
                    string vertexProgSource =
                        "void main( \n" +
                        "	float4 iPosition : POSITION, \n"+
                        "	float3 normal    : NORMAL,	\n"+
                        "	float2 iUV       : TEXCOORD0,	\n"+
                        "	float4 iColor    : COLOR, \n"+

                        "	out float4 oPosition : POSITION, \n"+
                        "	out float2 oUV       : TEXCOORD0,	\n"+
                        "	out float4 oColor : COLOR, \n"+
                        "	out float4 oFog : FOG,	\n";

                    if (lightningEnabled)
                    {
                        vertexProgSource +=
                            "	uniform float4 objSpaceLight,	\n"+
                            "	uniform float4 lightDiffuse,	\n"+
                            "	uniform float4 lightAmbient,	\n";
                    }

                    if (mFadeEnabled)
                    {
                        vertexProgSource +=
                            "	uniform float3 camPos, \n";
                    }

                    vertexProgSource +=
                        "	uniform float4x4 worldViewProj,	\n"+
                        "	uniform float fadeGap, \n"+
                        "   uniform float invisibleDist )\n" +
                        "{	\n";

                    if (lightningEnabled)
                    {
                        vertexProgSource +=
                            //Perform lighting calculations (no specular)
                            "	float3 light = normalize(objSpaceLight.xyz - (iPosition.xyz * objSpaceLight.w)); \n"+
                            "	float diffuseFactor = max(dot(normal, light), 0); \n"+
                            "	oColor = (lightAmbient + diffuseFactor * lightDiffuse) * iColor; \n";
                    }
                    else
                    {
                        vertexProgSource +=
                            "	oColor = iColor; \n";
                    }

                    if (mFadeEnabled)
                    {
                        vertexProgSource +=
                            //Fade out in the distance
                            "	float dist = distance(camPos.xz, iPosition.xz);	\n"+
                            "	oColor.a *= (invisibleDist - dist) / fadeGap;   \n";
                    }

                    vertexProgSource +=
                        "	oUV = iUV;	\n"+
                        "	oPosition = mul(worldViewProj, iPosition);  \n"+
                        "	oFog.x = oPosition.z; \n"+
                        "}";

                    HighLevelGpuProgram vertexShader = HighLevelGpuProgramManager.Instance.CreateProgram(
                        vertexProgName,
                        ResourceGroupManager.DefaultResourceGroupName,
                        "cg", GpuProgramType.Vertex);

                    vertexShader.Source = vertexProgSource;
                    vertexShader.SetParam("profiles", "vs_1_1 arbvp1");
                    vertexShader.SetParam("entry_point", "main");
                    vertexShader.Load();
                }

                //Now that the shader is ready to be applied, apply it
                string materialSignature = string.Empty;
                materialSignature += "BatchMat|";
                materialSignature += mat.Name + "|";
                if (mFadeEnabled)
                {
                    materialSignature += mVisibleDist + "|";
                    materialSignature += mInvisibleDist + "|";
                }
                //Search for the desired material
                Material generatedMaterial = (Material)MaterialManager.Instance.GetByName(materialSignature);
                if (generatedMaterial == null)
                {
                    //Clone the material
                    generatedMaterial = mat.Clone(materialSignature);

                    //And apply the fade shader
                    for (int t = 0; t < generatedMaterial.TechniqueCount; t++)
                    {
                        Technique tech = generatedMaterial.GetTechnique(t);
                        for (int p = 0; p < tech.PassCount; p++)
                        {
                            Pass pass = tech.GetPass(p);
                            //Setup vertex program
                            if (pass.VertexProgramName == "")
                            {
                                pass.VertexProgramName = vertexProgName;
                            }
                            try
                            {
                                GpuProgramParameters gparams = pass.VertexProgramParameters;
                                if (lightningEnabled)
                                {
                                    gparams.SetNamedAutoConstant("objSpaceLight", GpuProgramParameters.AutoConstantType.LightPositionObjectSpace, 0);
                                    gparams.SetNamedAutoConstant("lightDiffuse", GpuProgramParameters.AutoConstantType.LightDiffuseColor, 0);
                                    gparams.SetNamedAutoConstant("lightAmbient", GpuProgramParameters.AutoConstantType.AmbientLightColor, 0);
                                }

                                gparams.SetNamedAutoConstant("worldViewProj", GpuProgramParameters.AutoConstantType.WorldViewProjMatrix, 0);

                                if (mFadeEnabled)
                                {
                                    gparams.SetNamedAutoConstant("camPos", GpuProgramParameters.AutoConstantType.CameraPositionObjectSpace, 0);

                                    //set fade ranges
                                    gparams.SetNamedAutoConstant("invisibleDist", GpuProgramParameters.AutoConstantType.Custom, 0);
                                    gparams.SetNamedConstant("invisibleDist", mInvisibleDist);
                                    gparams.SetNamedAutoConstant("fadeGap", GpuProgramParameters.AutoConstantType.Custom, 0);
                                    gparams.SetNamedConstant("fadeGap", mInvisibleDist - mVisibleDist);

                                    if (pass.AlphaRejectFunction == CompareFunction.AlwaysPass)
                                    {
                                        pass.SetSceneBlending(SceneBlendType.TransparentAlpha);
                                    }
                                }
                            }
                            catch
                            {
                                throw new Exception("Error configuring batched geometry transitions." +
                                                    "If you're using materials with custom vertex shaders, they will need to implement fade transitions to be compatible with BatchPage.");
                            }
                        }
                    }
                }

                //Apply the material
                subBatch.Material = generatedMaterial;
            }
        }
        protected virtual void OnSetProgramAutoConstants(
            GpuProgramParameters parameters, int lightCount)
        {
            parameters.SetNamedAutoConstant( "worldMatrix",
                GpuProgramParameters.AutoConstantType.WorldMatrix );
            parameters.SetNamedAutoConstant( "worldViewMatrix",
                GpuProgramParameters.AutoConstantType.WorldViewMatrix );
            parameters.SetNamedAutoConstant( "worldViewProjMatrix",
                GpuProgramParameters.AutoConstantType.WorldViewProjMatrix );
            parameters.SetNamedAutoConstant( "viewProjMatrix",
                GpuProgramParameters.AutoConstantType.ViewProjMatrix );
            parameters.SetNamedAutoConstant( "cameraPositionObjectSpace",
                GpuProgramParameters.AutoConstantType.CameraPositionObjectSpace );
            parameters.SetNamedAutoConstant( "cameraPosition",
                GpuProgramParameters.AutoConstantType.CameraPosition );
            parameters.SetNamedAutoConstant( "farClipDistance",
                GpuProgramParameters.AutoConstantType.FarClipDistance );

            parameters.SetNamedAutoConstant( "texelOffsets",
                GpuProgramParameters.AutoConstantType.TexelOffsets );
            parameters.SetNamedAutoConstant( "alphaRejectValue",
                GpuProgramParameters.AutoConstantType.AlphaRejectValue );

            parameters.SetNamedAutoConstant( "disableFetch4ForBrokenDrivers",
                GpuProgramParameters.AutoConstantType.DisableFetch4ForBrokenDrivers );

            //Light
            parameters.SetNamedAutoConstant( "ambientLightColor",
                GpuProgramParameters.AutoConstantType.AmbientLightColor );

            if( lightCount != 0 )
            {
                parameters.SetNamedAutoConstant( "textureViewProjMatrix0",
                    GpuProgramParameters.AutoConstantType.TextureViewProjMatrix, 0 );
                parameters.SetNamedAutoConstant( "textureViewProjMatrix1",
                    GpuProgramParameters.AutoConstantType.TextureViewProjMatrix, 1 );
                parameters.SetNamedAutoConstant( "textureViewProjMatrix2",
                    GpuProgramParameters.AutoConstantType.TextureViewProjMatrix, 2 );
                parameters.SetNamedAutoConstant( "lightShadowFarClipDistance",
                    GpuProgramParameters.AutoConstantType.LightShadowFarClipDistance, 0 );
                parameters.SetNamedAutoConstant( "shadowFarDistance",
                    GpuProgramParameters.AutoConstantType.ShadowFarDistance );
                parameters.SetNamedAutoConstant( "shadowColorIntensity",
                    GpuProgramParameters.AutoConstantType.ShadowColorIntensity );
                parameters.SetNamedAutoConstant( "shadowTextureSizes",
                    GpuProgramParameters.AutoConstantType.ShadowTextureSizes );
                parameters.SetNamedAutoConstant( "shadowDirectionalLightSplitDistances",
                    GpuProgramParameters.AutoConstantType.ShadowDirectionalLightSplitDistances );
                parameters.SetNamedAutoConstant( "lightPositionArray",
                    GpuProgramParameters.AutoConstantType.LightPositionArray, lightCount );
                parameters.SetNamedAutoConstant( "lightPositionObjectSpaceArray",
                    GpuProgramParameters.AutoConstantType.LightPositionObjectSpaceArray, lightCount );
                parameters.SetNamedAutoConstant( "lightDirectionArray",
                    GpuProgramParameters.AutoConstantType.LightDirectionArray, lightCount );
                parameters.SetNamedAutoConstant( "lightDirectionObjectSpaceArray",
                    GpuProgramParameters.AutoConstantType.LightDirectionObjectSpaceArray, lightCount );
                parameters.SetNamedAutoConstant( "lightAttenuationArray",
                    GpuProgramParameters.AutoConstantType.LightAttenuationArray, lightCount );
                parameters.SetNamedAutoConstant( "lightDiffuseColorPowerScaledArray",
                    GpuProgramParameters.AutoConstantType.LightDiffuseColorPowerScaledArray, lightCount );
                parameters.SetNamedAutoConstant( "lightSpecularColorPowerScaledArray",
                    GpuProgramParameters.AutoConstantType.LightSpecularColorPowerScaledArray, lightCount );
                parameters.SetNamedAutoConstant( "spotLightParamsArray",
                    GpuProgramParameters.AutoConstantType.SpotLightParamsArray, lightCount );
                parameters.SetNamedAutoConstant( "lightCastShadowsArray",
                    GpuProgramParameters.AutoConstantType.LightCastShadowsArray, lightCount );
            }

            //Fog
            parameters.SetNamedAutoConstant( "fogParams",
                GpuProgramParameters.AutoConstantType.FogParams );
            parameters.SetNamedAutoConstant( "fogColor",
                GpuProgramParameters.AutoConstantType.FogColor );

            //Time
            //1 hour interval. for better precision
            parameters.SetNamedAutoConstantFloat( "time",
                GpuProgramParameters.AutoConstantType.Time0X, 3600.0f );

            //lightmap
            parameters.SetNamedAutoConstant( "lightmapUVTransform",
                GpuProgramParameters.AutoConstantType.LightmapUVTransform );

            //clip planes
            for( int n = 0; n < 6; n++ )
            {
                parameters.SetNamedAutoConstant( "clipPlane" + n.ToString(),
                    GpuProgramParameters.AutoConstantType.ClipPlane, n );
            }

            parameters.SetNamedAutoConstant( "instancing",
                GpuProgramParameters.AutoConstantType.Instancing );
        }
Esempio n. 17
0
        void SetProgramAutoConstants_ShadowCaster_Fragment( GpuProgramParameters parameters )
        {
            parameters.SetNamedAutoConstant( "farClipDistance",
                GpuProgramParameters.AutoConstantType.FarClipDistance );
            parameters.SetNamedAutoConstant( "shadowDirectionalLightBias",
                GpuProgramParameters.AutoConstantType.ShadowDirectionalLightBias );
            parameters.SetNamedAutoConstant( "shadowSpotLightBias",
                GpuProgramParameters.AutoConstantType.ShadowSpotLightBias );
            parameters.SetNamedAutoConstant( "shadowPointLightBias",
                GpuProgramParameters.AutoConstantType.ShadowPointLightBias );

            parameters.SetNamedAutoConstant( "alphaRejectValue",
                GpuProgramParameters.AutoConstantType.AlphaRejectValue );

            //1 hour interval for better precision.
            parameters.SetNamedAutoConstantFloat( "time",
                GpuProgramParameters.AutoConstantType.Time0X, 3600.0f );
        }
Esempio n. 18
0
        void SetProgramAutoConstants_ShadowCaster_Vertex( GpuProgramParameters parameters )
        {
            parameters.SetNamedAutoConstant( "worldMatrix",
                GpuProgramParameters.AutoConstantType.WorldMatrix );
            parameters.SetNamedAutoConstant( "viewProjMatrix",
                GpuProgramParameters.AutoConstantType.ViewProjMatrix );
            parameters.SetNamedAutoConstant( "cameraPosition",
                GpuProgramParameters.AutoConstantType.CameraPosition );
            parameters.SetNamedAutoConstant( "texelOffsets",
                GpuProgramParameters.AutoConstantType.TexelOffsets );

            if( RenderSystem.Instance.HasShaderModel3() &&
                RenderSystem.Instance.Capabilities.HardwareInstancing )
            {
                parameters.SetNamedAutoConstant( "instancing", GpuProgramParameters.AutoConstantType.Instancing );
            }

            //1 hour interval for better precision.
            parameters.SetNamedAutoConstantFloat( "time",
                GpuProgramParameters.AutoConstantType.Time0X, 3600.0f );
        }
        void SetProgramAutoConstants(GpuProgramParameters parameters, int lightCount)
        {
            parameters.SetNamedAutoConstant("worldMatrix",
                                            GpuProgramParameters.AutoConstantType.WorldMatrix);
            parameters.SetNamedAutoConstant("worldViewProjMatrix",
                                            GpuProgramParameters.AutoConstantType.WorldViewProjMatrix);
            parameters.SetNamedAutoConstant("cameraPosition",
                                            GpuProgramParameters.AutoConstantType.CameraPosition);
            parameters.SetNamedAutoConstant("farClipDistance",
                                            GpuProgramParameters.AutoConstantType.FarClipDistance);

            parameters.SetNamedAutoConstant("ambientLightColor",
                                            GpuProgramParameters.AutoConstantType.AmbientLightColor);
            parameters.SetNamedAutoConstant("ambientLightColor2",
                                            GpuProgramParameters.AutoConstantType.AmbientLightColor2);
            parameters.SetNamedAutoConstant("ambientLightColor3",
                                            GpuProgramParameters.AutoConstantType.AmbientLightColor3);

            if (lightCount != 0)
            {
                parameters.SetNamedAutoConstant("lightPositionArray",
                                                GpuProgramParameters.AutoConstantType.LightPositionArray, lightCount);
                parameters.SetNamedAutoConstant("lightPositionObjectSpaceArray",
                                                GpuProgramParameters.AutoConstantType.LightPositionObjectSpaceArray, lightCount);
                parameters.SetNamedAutoConstant("lightDirectionArray",
                                                GpuProgramParameters.AutoConstantType.LightDirectionArray, lightCount);
                parameters.SetNamedAutoConstant("lightDirectionObjectSpaceArray",
                                                GpuProgramParameters.AutoConstantType.LightDirectionObjectSpaceArray, lightCount);
                parameters.SetNamedAutoConstant("lightAttenuationArray",
                                                GpuProgramParameters.AutoConstantType.LightAttenuationArray, lightCount);
                parameters.SetNamedAutoConstant("lightDiffuseColorPowerScaledArray",
                                                GpuProgramParameters.AutoConstantType.LightDiffuseColorPowerScaledArray, lightCount);
                parameters.SetNamedAutoConstant("spotLightParamsArray",
                                                GpuProgramParameters.AutoConstantType.SpotLightParamsArray, lightCount);
            }
        }
        public static void UpdateAll(Vector3 cameraDirection)
        {
            if (mSelfInstances > 0)//selfInstances will only be greater than 0 if one or more StaticBillboardSet's are using BB_METHOD_ACCELERATED
            //Set shader parameter so material will face camera
            {
                Vector3 forward = cameraDirection;
                Vector3 vRight  = forward.Cross(Vector3.UnitY);
                Vector3 vUp     = forward.Cross(vRight);
                vRight.Normalize();
                vUp.Normalize();

                //Even if camera is upside down, the billboards should remain upright
                if (vUp.y < 0)
                {
                    vUp *= -1;
                }

                //For each material in use by the billboard system..
                foreach (SBMaterialRef it in SBMaterialRef.SelfList.Values)
                {
                    Material        mat      = it.Material;
                    BillboardOrigin bbOrigin = it.Origin;

                    Vector3 vPoint0 = Vector3.Zero;
                    Vector3 vPoint1 = Vector3.Zero;
                    Vector3 vPoint2 = Vector3.Zero;
                    Vector3 vPoint3 = Vector3.Zero;

                    if (bbOrigin == BillboardOrigin.Center)
                    {
                        vPoint0 = (-vRight + vUp);
                        vPoint1 = (vRight + vUp);
                        vPoint2 = (-vRight - vUp);
                        vPoint3 = (vRight - vUp);
                    }
                    else if (bbOrigin == BillboardOrigin.BottomCenter)
                    {
                        vPoint0 = (-vRight + vUp + vUp);
                        vPoint1 = (vRight + vUp + vUp);
                        vPoint2 = (-vRight);
                        vPoint3 = (vRight);
                    }
                    //single prerotated quad oriented towards the camera
                    float[] preRotatedQuad =
                    {
                        vPoint0.x, vPoint0.y, vPoint0.z, 0.0f,
                        vPoint1.x, vPoint1.y, vPoint1.z, 0.0f,
                        vPoint2.x, vPoint2.y, vPoint2.z, 0.0f,
                        vPoint3.x, vPoint3.y, vPoint3.z, 0.0f
                    };

                    Pass p = mat.GetTechnique(0).GetPass(0);
                    if (!p.HasVertexProgram)
                    {
                        p.SetVertexProgram("Sprite_vp");
                        GpuProgramParameters gparams = p.VertexProgramParameters;
                        gparams.SetNamedAutoConstant("worldViewProj", GpuProgramParameters.AutoConstantType.WorldViewProjMatrix, 0);
                        gparams.SetNamedAutoConstant("uScroll", GpuProgramParameters.AutoConstantType.Custom, 0);
                        gparams.SetNamedAutoConstant("vScroll", GpuProgramParameters.AutoConstantType.Custom, 0);
                        gparams.SetNamedAutoConstant("preRotatedQuad[0]", GpuProgramParameters.AutoConstantType.Custom, 0);
                        gparams.SetNamedAutoConstant("preRotatedQuad[1]", GpuProgramParameters.AutoConstantType.Custom, 0);
                        gparams.SetNamedAutoConstant("preRotatedQuad[2]", GpuProgramParameters.AutoConstantType.Custom, 0);
                        gparams.SetNamedAutoConstant("preRotatedQuad[3]", GpuProgramParameters.AutoConstantType.Custom, 0);
                    }
                    //Update the vertex shader parameters
                    GpuProgramParameters gparams2 = p.VertexProgramParameters;
                    for (int i = 0; i < preRotatedQuad.Length; i++)
                    {
                        gparams2.SetNamedConstant(string.Format("preRotatedQuad[{0}]", i), (Real)preRotatedQuad[i]);
                    }
                    //gparams2.SetNamedConstant("preRotatedQuad[0]", preRotatedQuad);
                    gparams2.SetNamedConstant("uScroll", p.GetTextureUnitState(0).TextureScrollU);
                    gparams2.SetNamedConstant("vScroll", p.GetTextureUnitState(0).TextureScrollV);
                }
            }
        }