protected override void OnMaterialRender(uint passId, Material material, ref bool skipPass)
        {
            base.OnMaterialRender(passId, material, ref skipPass);

            //update texture name
            if (passId == 100)
            {
                TextureUnitState textureUnit = material.Techniques[0].Passes[0].TextureUnitStates[1];

                //we can't change texture by means call SetTextureName() for compositor materials. use _Internal_SetTexture
                Texture texture = null;
                if (!string.IsNullOrEmpty(TextureName))
                {
                    texture = TextureManager.Instance.Load(TextureName, Texture.Type.Type2D);
                }
                if (texture == null)
                {
                    texture = TextureManager.Instance.Load("Base\\FullScreenEffects\\ColorCorrectionLUT\\Textures\\NoEffect.png");
                }
                textureUnit._Internal_SetTexture(texture);
                //if( textureUnit.TextureName != TextureName )
                //   textureUnit.SetTextureName( TextureName );

                GpuProgramParameters parameters = material.Techniques[0].Passes[0].FragmentProgramParameters;
                parameters.SetNamedConstant("multiply", multiply);
                parameters.SetNamedConstant("add", add);
            }
        }
예제 #2
0
        /// <summary>
        ///
        /// </summary>
        public override void FrameUpdate()
        {
            long currentTime = mWindTimer.Milliseconds;
            long elapsedTime = currentTime - mLastTime;

            mLastTime = currentTime;
            float elapsed = elapsedTime / 1000.0f;

            //Update the vertex shader parameters
            foreach (GrassLayer it in mLayerList)
            {
                GrassLayer layer = it;
                layer.UpdateShaders();

                GpuProgramParameters gparams = layer.Material.GetTechnique(0).GetPass(0).VertexProgramParameters;
                if (layer.IsAnimationEnabled)
                {
                    //Increment animation frame
                    layer.WaveCount += elapsed * (float)(layer.SwaySpeed * System.Math.PI);
                    if (layer.WaveCount > System.Math.PI * 2)
                    {
                        layer.WaveCount -= (float)System.Math.PI * 2;
                    }

                    //Set vertex shader parameters
                    gparams.SetNamedConstant("time", layer.WaveCount);
                    gparams.SetNamedConstant("frequency", layer.SwayDistribution);

                    Vector3 direction = mWindDir * layer.SwayLength;
                    gparams.SetNamedConstant("direction", new Vector4(direction.x, direction.y, direction.z, 0));
                }
            }
        }
예제 #3
0
        protected override void OnMaterialRender(uint passId, Material material, ref bool skipPass)
        {
            base.OnMaterialRender(passId, material, ref skipPass);

            if (passId == 700 || passId == 701)
            {
                bool horizontal = passId == 700;

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

                // calculate gaussian texture offsets & weights
                Vec2i textureSize = Owner.DimensionsInPixels.Size;
                float texelSize   = 1.0f / (float)(horizontal ? textureSize.X : textureSize.Y);

                texelSize *= fuzziness;

                // central sample, no offset
                sampleOffsets[0] = Vec2.Zero;
                {
                    float distribution = GaussianDistribution(0, 0, 3);
                    sampleWeights[0] = new Vec4(distribution, distribution, distribution, 0);
                }

                // 'pre' samples
                for (int n = 1; n < 8; n++)
                {
                    float distribution = GaussianDistribution(n, 0, 3);
                    sampleWeights[n] = new Vec4(distribution, distribution, distribution, 1);

                    if (horizontal)
                    {
                        sampleOffsets[n] = new Vec2((float)n * texelSize, 0);
                    }
                    else
                    {
                        sampleOffsets[n] = new Vec2(0, (float)n * texelSize);
                    }
                }
                // 'post' samples
                for (int n = 8; n < 15; n++)
                {
                    sampleWeights[n] = sampleWeights[n - 7];
                    sampleOffsets[n] = -sampleOffsets[n - 7];
                }

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

                GpuProgramParameters parameters = material.GetBestTechnique().
                                                  Passes[0].FragmentProgramParameters;
                parameters.SetNamedConstant("sampleOffsets", vec4Offsets);
                parameters.SetNamedConstant("sampleWeights", sampleWeights);
            }
        }
예제 #4
0
        protected override void OnMaterialRender(uint passId, Material material, ref bool skipPass)
        {
            base.OnMaterialRender(passId, material, ref skipPass);

            if (passId == 555)
            {
                GpuProgramParameters parameters = material.Techniques[0].Passes[0].FragmentProgramParameters;
                parameters.SetNamedConstant("intensity", intensity);
                parameters.SetNamedConstant("radius", radius);
            }
        }
        /// <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);
        }
예제 #6
0
        protected override void OnMaterialRender(uint passId, Material material, ref bool skipPass)
        {
            base.OnMaterialRender(passId, material, ref skipPass);

            if (passId == 123)
            {
                GpuProgramParameters parameters = material.Techniques[0].Passes[0].FragmentProgramParameters;
                if (parameters != null)
                {
                    parameters.SetNamedConstant("center", new Vec4(center.X, center.Y, 0, 0));
                    parameters.SetNamedConstant("blurFactor", blurFactor);
                }
            }
        }
예제 #7
0
        public override void UpdateGpuProgramsParams(IRenderable rend, Pass pass, AutoParamDataSource source,
                                                     Core.Collections.LightList lightList)
        {
            if (this.isTableDataUpdated == false)
            {
                this.isTableDataUpdated = true;
                for (int j = 0; j < TextureAtlasSampler.MaxTextures; j++)
                {
                    if (this.isAtlasTextureUnits[j] == true)
                    {
                        //Update the information of the size of the atlas textures
                        //TODO: Replace -1, -1 with actual dimensions
                        var texSizeInt = new Math.Tuple <int, int>(-1, -1);
                        // = pass.GetTextureUnitState(j).Dimensions;
                        var texSize = new Vector2(texSizeInt.First, texSizeInt.Second);
                        this.psTextureSizes[j].SetGpuParameter(texSize);

                        //Update the information of which texture exists where in the atlas
                        GpuProgramParameters vsGpuParams = pass.VertexProgramParameters;
                        var buffer = new List <float>(this.atlasTableDatas[j].Count * 4);
                        for (int i = 0; i < this.atlasTableDatas[j].Count; i++)
                        {
                            buffer[i * 4]     = this.atlasTableDatas[j][i].posU;
                            buffer[i * 4 + 1] = this.atlasTableDatas[j][i].posV;
                            buffer[i * 4 + 2] =
                                (float)Axiom.Math.Utility.Log2((int)this.atlasTableDatas[j][i].width * (int)texSize.x);
                            buffer[i * 4 + 3] =
                                (float)Axiom.Math.Utility.Log2((int)this.atlasTableDatas[j][i].height * (int)texSize.y);
                        }
                        vsGpuParams.SetNamedConstant(this.vsTextureTable[j].Name, buffer.ToArray(),
                                                     this.atlasTableDatas[j].Count);
                    }
                }
            }
        }
예제 #8
0
        protected void UpdateMaterial()
        {
            if (useShaders && config.UseParams)
            {
                GpuProgramParameters vertexParams = material.GetTechnique(0).GetPass(0).VertexProgramParameters;
                vertexParams.SetNamedConstant("seaLevel", new Vector3(config.SeaLevel, 0, 0));
                vertexParams.SetNamedConstant("waveAmp", new Vector3(config.WaveHeight, 0, 0));
                vertexParams.SetNamedConstant("BumpScale", new Vector3(config.BumpScale, 0, 0));
                vertexParams.SetNamedConstant("bumpSpeed", new Vector3(config.BumpSpeedX, config.BumpSpeedZ, 0));
                vertexParams.SetNamedConstant("textureScale", new Vector3(config.TextureScaleX, config.TextureScaleZ, 0));

                GpuProgramParameters fragmentParams = material.GetTechnique(0).GetPass(0).FragmentProgramParameters;
                fragmentParams.SetNamedConstant("deepColor", config.DeepColor);
                fragmentParams.SetNamedConstant("shallowColor", config.ShallowColor);
            }
        }
예제 #9
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);
                }
            }
        }
        protected override void OnMaterialRender(uint passId, Material material, ref bool skipPass)
        {
            base.OnMaterialRender(passId, material, ref skipPass);

            if (passId == 123)
            {
                GpuProgramParameters parameters = material.Techniques[0].
                                                  Passes[0].FragmentProgramParameters;

                if (parameters != null)
                {
                    // randomFractions
                    parameters.SetNamedConstant("randomFractions",
                                                new Vec4(random.NextFloat(), random.NextFloat(), 0, 0));

                    // depthModulator
                    if ((Math.Abs(current - end) <= .001f))
                    {
                        // take a new value to reach
                        end   = .95f + random.NextFloat() * .05f;
                        start = current;
                    }
                    else
                    {
                        float step = RendererWorld.Instance.FrameRenderTimeStep;
                        if (step > .3f)
                        {
                            step = 0;
                        }

                        if (current > end)
                        {
                            current -= step;
                        }
                        else
                        {
                            current += step;
                        }
                    }
                    parameters.SetNamedConstant("depthModulator", current);
                }
            }
        }
예제 #11
0
        protected override void OnMaterialRender(uint passId, Material material, ref bool skipPass)
        {
            base.OnMaterialRender(passId, material, ref skipPass);

            if (passId == 333) //Incin framerate?
            {
                Vec4 multiplier = new Vec4(Red, Green, Blue, alpha);

                GpuProgramParameters parameters = material.Techniques[0].Passes[0].FragmentProgramParameters;
                parameters.SetNamedConstant("multiplier", multiplier);
            }
        }
        public void UpdateMaterial(Material material)
        {
            if (useParams)
            {
                Pass pass = material.GetTechnique(0).GetPass(0);
                pass.GetTextureUnitState(0).SetTextureName(sandTextureName);
                pass.GetTextureUnitState(1).SetTextureName(grassTextureName);
                pass.GetTextureUnitState(2).SetTextureName(rockTextureName);
                pass.GetTextureUnitState(3).SetTextureName(snowTextureName);
                GpuProgramParameters vertexParams = pass.VertexProgramParameters;
                vertexParams.SetNamedConstant("splatConfig", new Vector3(sandToGrassHeight, grassToRockHeight, rockToSnowHeight));
                vertexParams.SetNamedConstant("textureTileSize", new Vector3(textureTileSize, 0, 0));

                if (useGeneratedShadeMask)
                {
                    Page.SetShadeMask(material, 4);
                }
                else
                {
                    pass.GetTextureUnitState(4).SetTextureName(shadeMaskTextureName);
                }
            }
        }
예제 #13
0
        protected override void OnMaterialRender(uint passId, Material material, ref bool skipPass)
        {
            base.OnMaterialRender(passId, material, ref skipPass);

            if (passId == 666)
            {
                GpuProgramParameters parameters = material.Techniques[0].
                                                  Passes[0].FragmentProgramParameters;
                if (parameters != null)
                {
                    parameters.SetNamedConstant("blur", Blur);
                }
            }
        }
예제 #14
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);
                }
            }
        }
        public void UpdateMaterial(Material material)
        {
            if (useParams)
            {
                // Note: If we change the number of alpha map mosaics, we may need to update the GPU
                // shader to support
                Pass pass = material.GetTechnique(0).GetPass(0);
                GpuProgramParameters vertexParams = pass.VertexProgramParameters;
                vertexParams.SetNamedConstant("textureTileSize", new Vector3(textureTileSize, 0, 0));

                // set splatting textures
                int offset = alphaMapMosaicNames.Length;
                for (int i = 0; i < layerTextureNames.Length; i++)
                {
                    pass.GetTextureUnitState(offset + i).SetTextureName(layerTextureNames[i]);
                }

                pass.GetTextureUnitState(10).SetTextureName(detailTextureName);
            }
        }
예제 #16
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="gpup"></param>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <param name="updateGroundPasses"></param>
        public void SetGpuProgramParameter(GpuProgram gpup, string name, Vector3 value, bool updateGroundPasses)
        {
            if (!this.SkyX.MeshManager.IsCreated)
            {
                return;
            }

            GpuProgramParameters parameters = null;

            switch (gpup)
            {
            case GpuProgram.Vertex:
            {
                using (MaterialPtr mat = (MaterialPtr)MaterialManager.Singleton.GetByName(this.SkyX.MeshManager.MaterialName)) {
                    //parameters = mat.GetTechnique(0).GetPass(0).VertexProgramParameters;
                    parameters = mat.GetTechnique(0).GetPass(0).GetVertexProgramParameters();
                }
            }
            break;

            case GpuProgram.Fragment:
            {
                using (MaterialPtr mat = (MaterialPtr)MaterialManager.Singleton.GetByName(this.SkyX.MeshManager.MaterialName)) {
                    //parameters = mat.GetTechnique(0).GetPass(0).FragmentProgramParameters;
                    parameters = mat.GetTechnique(0).GetPass(0).GetFragmentProgramParameters();
                }
            }
            break;

            default:
            {
                throw new NotSupportedException("this type is not supported");
            }
            }

            parameters.SetNamedConstant(name, value);

            if (!updateGroundPasses)
            {
                return;
            }

            foreach (Pass iter in _groundPasses)
            {
                switch (gpup)
                {
                case GpuProgram.Vertex:
                {
                    //parameters = iter.VertexProgramParameters;
                    parameters = iter.GetVertexProgramParameters();
                }
                break;

                case GpuProgram.Fragment:
                {
                    //parameters = iter.FragmentProgramParameters;
                    parameters = iter.GetFragmentProgramParameters();
                }
                break;
                }

                parameters.SetNamedConstant(name, value);
            }
        }
예제 #17
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;
                }
            }
        }
        protected override void OnMaterialRender(uint passId, Material material, ref bool skipPass)
        {
            base.OnMaterialRender(passId, material, ref skipPass);

            //update material scheme
            {
                string materialScheme = RendererWorld.Instance.DefaultViewport.MaterialScheme;

                foreach (CompositionTechnique technique in Compositor.Techniques)
                {
                    foreach (CompositionTargetPass pass in technique.TargetPasses)
                    {
                        pass.MaterialScheme = materialScheme;
                    }
                    if (technique.OutputTargetPass != null)
                    {
                        technique.OutputTargetPass.MaterialScheme = materialScheme;
                    }
                }
            }

            const int rt_luminance0       = 994;
            const int rt_luminance1       = 993;
            const int rt_luminance2       = 992;
            const int rt_luminance3       = 991;
            const int rt_luminance4       = 990;
            const int rt_brightPass       = 800;
            const int rt_bloomBlur        = 700;
            const int rt_bloomHorizontal  = 701;
            const int rt_bloomVertical    = 702;
            const int rt_adaptedLuminance = 500;
            const int rt_targetOutput     = 600;

            //Skip adaptation passes if adaptation switched off.
            if (!Adaptation)
            {
                if (passId == rt_luminance0 || passId == rt_luminance1 || passId == rt_luminance2 ||
                    passId == rt_luminance3 || passId == rt_luminance4)
                {
                    skipPass = true;
                    return;
                }
            }

            //Skip bloom passes if bloom switched off
            if (BloomScale == 0)
            {
                if (passId == rt_brightPass || passId == rt_bloomBlur || passId == rt_bloomHorizontal ||
                    passId == rt_bloomVertical)
                {
                    skipPass = true;
                    return;
                }
            }

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

                // Initialize the sample offsets for the initial luminance pass.
                int textureSize = Technique.GetTextureDefinition("rt_luminance0").Size.X;

                float tu = 1.0f / (3.0f * textureSize);

                int index = 0;
                for (int x = -1; x <= 1; x++)
                {
                    for (int y = -1; y <= 1; y++)
                    {
                        sampleOffsets[index] = new Vec2(x, y) * tu;
                        index++;
                    }
                }

                GpuProgramParameters parameters = material.GetBestTechnique().
                                                  Passes[0].FragmentProgramParameters;

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

                parameters.SetNamedConstant("sampleOffsets", vec4Offsets);
            }
            break;

            case rt_luminance1:
            case rt_luminance2:
            case rt_luminance3:
            case rt_luminance4:
            {
                Vec2[] sampleOffsets = new Vec2[16];

                string textureSizeFrom = null;
                switch (passId)
                {
                case rt_luminance1: textureSizeFrom = "rt_luminance0"; break;

                case rt_luminance2: textureSizeFrom = "rt_luminance1"; break;

                case rt_luminance3: textureSizeFrom = "rt_luminance2"; break;

                case rt_luminance4: textureSizeFrom = "rt_luminance3"; break;

                default: Trace.Assert(false); break;
                }
                Vec2I textureSize = Technique.GetTextureDefinition(textureSizeFrom).Size;
                CalculateDownScale4x4SampleOffsets(textureSize, 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;

            //BrightPass
            case rt_brightPass:
            {
                Vec2[] sampleOffsets = new Vec2[16];

                Vec2I textureSize = Owner.DimensionsInPixels.Size;
                CalculateDownScale4x4SampleOffsets(textureSize, 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("brightThreshold", BloomBrightThreshold);
                parameters.SetNamedConstant("sampleOffsets", vec4Offsets);
            }
            break;

            case rt_bloomBlur:
            {
                Vec2[] sampleOffsets = new Vec2[13];
                Vec4[] sampleWeights = new Vec4[13];

                Vec2I textureSize = brightPassTextureSize;
                CalculateGaussianBlur5x5SampleOffsets(textureSize, sampleOffsets, sampleWeights, 1);

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

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

            case rt_bloomHorizontal:
            case rt_bloomVertical:
            {
                // horizontal and vertical bloom
                bool horizontal = passId == rt_bloomHorizontal;

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

                Vec2I textureSize = bloomTextureSize;
                CalculateBloomSampleOffsets(horizontal ? textureSize.X : textureSize.Y,
                                            sampleOffsets, sampleWeights, 3, 2);

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

                    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_adaptedLuminance:
            {
                float elapsedTime;
                {
                    float currentTime = RendererWorld.Instance.FrameRenderTime;
                    if (lastLuminanceCalculationTime != -1)
                    {
                        elapsedTime = currentTime - lastLuminanceCalculationTime;
                    }
                    else
                    {
                        elapsedTime = 1000;
                    }
                    lastLuminanceCalculationTime = currentTime;
                }

                GpuProgramParameters parameters = material.GetBestTechnique().
                                                  Passes[0].FragmentProgramParameters;
                parameters.SetNamedConstant("adaptationMinimum", Adaptation ? AdaptationMinimum : 1);
                parameters.SetNamedConstant("adaptationMaximum", Adaptation ? AdaptationMaximum : 1);
                parameters.SetNamedConstant("adaptationVelocity", AdaptationVelocity);
                parameters.SetNamedConstant("elapsedTime", elapsedTime);
            }
            break;

            //Final pass
            case rt_targetOutput:
            {
                GpuProgramParameters parameters = material.GetBestTechnique().
                                                  Passes[0].FragmentProgramParameters;
                parameters.SetNamedConstant("adaptationMiddleBrightness",
                                            Adaptation ? AdaptationMiddleBrightness : 1);
                parameters.SetNamedConstant("bloomScale", BloomScale);
            }
            break;
            }
        }
        protected override void OnMaterialRender(uint passId, Material material, ref bool skipPass)
        {
            base.OnMaterialRender(passId, material, ref skipPass);

            Camera camera = Owner.ViewportCamera;

            Sun  sun = null;
            Vec2 screenLightPosition = Vec2.Zero;

            if (Map.Instance != null && Map.Instance.IsPostCreated && Sun.Instances.Count > 0)
            {
                //get first sun entity on the map.
                sun = Sun.Instances[0];

                Vec3 direction;
                if (sun.BillboardOverridePosition != Vec3.Zero)
                {
                    direction = sun.BillboardOverridePosition.GetNormalize();
                }
                else
                {
                    direction = -sun.Rotation.GetForward();
                }

                Vec3 sunPosition = camera.Position + direction * 100000;

                if (!camera.ProjectToScreenCoordinates(sunPosition, out screenLightPosition))
                {
                    //don't see the sun.
                    sun = null;
                }
            }

            //calculate intensity factor by the sun position on the screen.
            float needIntensityFactor = 0;

            if (sun != null)
            {
                const float screenFadingBorder = .1f;

                float minDistance = 1;

                for (int axis = 0; axis < 2; axis++)
                {
                    if (screenLightPosition[axis] < screenFadingBorder)
                    {
                        float d = screenLightPosition[axis];
                        if (d < minDistance)
                        {
                            minDistance = d;
                        }
                    }
                    else if (screenLightPosition[axis] > 1.0f - screenFadingBorder)
                    {
                        float d = 1.0f - screenLightPosition[axis];
                        if (d < minDistance)
                        {
                            minDistance = d;
                        }
                    }
                }
                needIntensityFactor = minDistance / screenFadingBorder;
                MathFunctions.Saturate(ref needIntensityFactor);

                //clamp screenLightPosition
                if (!new Rect(0, 0, 1, 1).IsContainsPoint(screenLightPosition))
                {
                    Vec2 intersectPoint1;
                    Vec2 intersectPoint2;
                    if (MathUtils.IntersectRectangleLine(new Rect(.0001f, .0001f, .9999f, .9999f),
                                                         new Vec2(.5f, .5f), screenLightPosition, out intersectPoint1, out intersectPoint2) != 0)
                    {
                        screenLightPosition = intersectPoint1;
                    }
                }
            }

            //update smooth intensity factor
            if (sun != null)
            {
                if (smoothIntensityFactorLastUpdate != RendererWorld.Instance.FrameRenderTime)
                {
                    smoothIntensityFactorLastUpdate = RendererWorld.Instance.FrameRenderTime;

                    const float smoothSpeed = 3;
                    float       step        = RendererWorld.Instance.FrameRenderTimeStep * smoothSpeed;

                    if (needIntensityFactor > smoothIntensityFactor)
                    {
                        smoothIntensityFactor += step;
                        if (smoothIntensityFactor > needIntensityFactor)
                        {
                            smoothIntensityFactor = needIntensityFactor;
                        }
                    }
                    else
                    {
                        smoothIntensityFactor -= step;
                        if (smoothIntensityFactor < needIntensityFactor)
                        {
                            smoothIntensityFactor = needIntensityFactor;
                        }
                    }
                }
            }
            else
            {
                smoothIntensityFactor = 0;
            }

            //get result intensity
            float resultIntensity = intensity * smoothIntensityFactor;


            const int rt_scattering = 100;
            const int rt_blur       = 200;
            const int rt_final      = 300;

            //skip passes for disabled effect
            if (resultIntensity == 0)
            {
                if (passId == rt_scattering || passId == rt_blur)
                {
                    skipPass = true;
                    return;
                }
            }

            //set gpu parameters

            switch (passId)
            {
            case rt_scattering:
            {
                GpuProgramParameters parameters = material.Techniques[0].Passes[0].
                                                  FragmentProgramParameters;
                parameters.SetNamedConstant("color", new Vec4(color.Red, color.Green, color.Blue, 0));
                parameters.SetNamedConstant("screenLightPosition",
                                            new Vec4(screenLightPosition.X, screenLightPosition.Y, 0, 0));
                parameters.SetNamedConstant("decay", decay);
                parameters.SetNamedConstant("density", density);
            }
            break;

            case rt_blur:
            {
                GpuProgramParameters parameters = material.Techniques[0].Passes[0].
                                                  FragmentProgramParameters;
                parameters.SetNamedConstant("color", new Vec4(color.Red, color.Green, color.Blue, 0));
                parameters.SetNamedConstant("screenLightPosition",
                                            new Vec4(screenLightPosition.X, screenLightPosition.Y, 0, 0));
                parameters.SetNamedConstant("intensity", resultIntensity);
                parameters.SetNamedConstant("blurFactor", blurFactor);
            }
            break;

            case rt_final:
            {
                GpuProgramParameters parameters = material.Techniques[0].Passes[0].
                                                  FragmentProgramParameters;
                parameters.SetNamedConstant("intensity", resultIntensity);
            }
            break;
            }
        }
예제 #20
0
        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);
                }
            }
        }
예제 #21
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;
            }
        }
예제 #22
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;
                    }
                }
            }
예제 #23
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;
            }
        }
예제 #24
0
 public override void _updateCustomGpuParameter(GpuProgramParameters.AutoConstantEntry_NativePtr constantEntry, GpuProgramParameters @params)
 {
     base._updateCustomGpuParameter(constantEntry, @params);
     @params.SetNamedConstant(_scaleFactorName, ScaleFactor);
     @params.SetNamedConstant(_fineBlockOriginName, FineBlockOrigin);
 }
        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;
            }
        }
예제 #26
0
        protected override void OnMaterialRender(uint passId, Material material, ref bool skipPass)
        {
            base.OnMaterialRender(passId, material, ref skipPass);

            //update material scheme
            {
                string materialScheme = RendererWorld.Instance.DefaultViewport.MaterialScheme;

                foreach (CompositionTechnique technique in Compositor.Techniques)
                {
                    foreach (CompositionTargetPass pass in technique.TargetPasses)
                    {
                        pass.MaterialScheme = materialScheme;
                    }
                    if (technique.OutputTargetPass != null)
                    {
                        technique.OutputTargetPass.MaterialScheme = materialScheme;
                    }
                }
            }

            const int rt_brightPass      = 800;
            const int rt_bloomBlur       = 700;
            const int rt_bloomHorizontal = 701;
            const int rt_bloomVertical   = 702;
            const int rt_targetOutput    = 600;

            //Skip bloom passes if bloom switched off
            if (BloomScale == 0)
            {
                if (passId == rt_brightPass || passId == rt_bloomBlur || passId == rt_bloomHorizontal ||
                    passId == rt_bloomVertical)
                {
                    skipPass = true;
                    return;
                }
            }

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

                Vec2I textureSize = Owner.DimensionsInPixels.Size;
                CalculateDownScale4x4SampleOffsets(textureSize, 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("brightThreshold", BloomBrightThreshold);
                parameters.SetNamedConstant("sampleOffsets", vec4Offsets);
            }
            break;

            case rt_bloomBlur:
            {
                Vec2[] sampleOffsets = new Vec2[13];
                Vec4[] sampleWeights = new Vec4[13];

                Vec2I textureSize = brightPassTextureSize;
                CalculateGaussianBlur5x5SampleOffsets(textureSize, sampleOffsets, sampleWeights, 1);

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

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

            case rt_bloomHorizontal:
            case rt_bloomVertical:
            {
                // horizontal and vertical bloom
                bool horizontal = passId == rt_bloomHorizontal;

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

                Vec2I textureSize = bloomTextureSize;
                CalculateBloomSampleOffsets(horizontal ? textureSize.X : textureSize.Y,
                                            sampleOffsets, sampleWeights, 3, 2);

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

                    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;

            //Final pass
            case rt_targetOutput:
            {
                GpuProgramParameters parameters = material.GetBestTechnique().
                                                  Passes[0].FragmentProgramParameters;
                parameters.SetNamedConstant("bloomScale", BloomScale);
            }
            break;
            }
        }
예제 #27
0
 public void UpdateCustomGpuParameter(GpuProgramParameters.AutoConstantEntry constant, GpuProgramParameters parameters)
 {
     parameters.SetNamedConstant(_scaleFactorName, ScaleFactor);
     parameters.SetNamedConstant(_fineBlockOriginName, FineBlockOrigin);
 }
예제 #28
0
 public override void _updateCustomGpuParameter(GpuProgramParameters.AutoConstantEntry_NativePtr constantEntry, GpuProgramParameters @params)
 {
     base._updateCustomGpuParameter(constantEntry, @params);
     @params.SetNamedConstant(_scaleFactorName, ScaleFactor);
     @params.SetNamedConstant(_fineBlockOriginName, FineBlockOrigin);
 }