Пример #1
0
        public static async Task LoadDude(EngineContext engineContext)
        {
            var       mainPlugin = engineContext.RenderContext.RenderPassPlugins.OfType <MainPlugin>().FirstOrDefault();
            EffectOld effect     = engineContext.RenderContext.BuildEffect("SimpleSkinning")
                                   .Using(new BasicShaderPlugin("ShaderBase")
            {
                RenderPassPlugin = mainPlugin
            })
                                   .Using(new BasicShaderPlugin("TransformationWVP")
            {
                RenderPassPlugin = mainPlugin
            })
                                   .Using(new BasicShaderPlugin(new ShaderMixinSource()
            {
                new ShaderClassSource("AlbedoDiffuseBase"),
                new ShaderComposition("albedoDiffuse", new ShaderClassSource("ComputeColorTexture", TexturingKeys.DiffuseTexture, "TEXCOORD")),
                new ShaderComposition("albedoSpecular", new ShaderClassSource("ComputeColor")),             // TODO: Default values!
            })
            {
                RenderPassPlugin = mainPlugin
            })
                                   .Using(new BasicShaderPlugin("AlbedoFlatShading")
            {
                RenderPassPlugin = mainPlugin
            })
            ;

            var characterEntity = await AnimScript.LoadFBXModel(engineContext, "/global_data/fbx/test_mesh.hotei#");

            await AnimScript.AnimateFBXModel(engineContext, characterEntity);
        }
Пример #2
0
 public void DisposeEffects()
 {
     if (EffectUpdater != null)
     {
         EffectUpdater.Release();
         EffectUpdater = null;
     }
 }
Пример #3
0
        public static async Task Run(EngineContext engineContext)
        {
#if PARADOX_YEBIS
            YebisPlugin yebisPlugin;
            if (engineContext.DataContext.RenderPassPlugins.TryGetValueCast("YebisPlugin", out yebisPlugin))
            {
                yebisPlugin.Glare.Enable                = false;
                yebisPlugin.DepthOfField.Enable         = false;
                yebisPlugin.ToneMap.AutoExposure.Enable = false;
                yebisPlugin.ToneMap.Exposure            = 1.0f;
                yebisPlugin.ToneMap.Gamma               = 2.2f;
            }
#endif

            EffectOld effect = engineContext.RenderContext.Effects.First(x => x.Name == "Multicore");
            //Effect effect = engineContext.RenderContext.BuildEffect("Multicore")
            //    .Using(new BasicShaderPlugin("ShaderBase") { RenderPassPlugin = renderingSetup.MainDepthReadOnlyPlugin })
            //    .Using(new BasicShaderPlugin("TransformationWVP") { RenderPassPlugin = renderingSetup.MainDepthReadOnlyPlugin })
            //    .Using(new BasicShaderPlugin(new ShaderMixinSource()
            //                        {
            //                            "NormalVSStream",
            //                            "PositionVSStream",
            //                            new ShaderComposition("albedoDiffuse", new ShaderClassSource("ComputeColorStream")),
            //                            new ShaderComposition("albedoSpecular", new ShaderClassSource("ComputeColor")), // TODO: Default values!
            //                            "BRDFDiffuseLambert",
            //                            "BRDFSpecularBlinnPhong",
            //                        }) { RenderPassPlugin = renderingSetup.MainDepthReadOnlyPlugin })
            //    .Using(new BasicShaderPlugin("AlbedoFlatShading") { RenderPassPlugin = renderingSetup.MainDepthReadOnlyPlugin })
            //    .Using(new LightingShaderPlugin { RenderPassPlugin = renderingSetup.LightingPlugin })
            //    //.Using(new BasicShaderPlugin("LightDirectionalShading") { RenderPassPlugin = renderingSetup.MainDepthReadOnlyPlugin })
            //    ;

            //effect.Permutations.Set(LightingPermutation.Key, new LightingPermutation { Lights = new Light[] { new DirectionalLight { LightColor = new Color3(1.0f), LightDirection = new R32G32B32_Float(-1.0f, -1.0f, 1.0f) } } });

            var rand         = new Random();
            var cubeMeshData = Enumerable.Range(0, 10).Select(x => MeshDataHelper.CreateBox(10, 10, 10, new Color((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), 1.0f))).ToArray();

            var effectMeshGroup = new RenderPassListEnumerator();
            engineContext.RenderContext.RenderPassEnumerators.Add(effectMeshGroup);

            int objectSqrtCount = 31;
            int meshCount       = objectSqrtCount * objectSqrtCount * objectSqrtCount;

            for (int j = 0; j < meshCount; ++j)
            {
                var effectMesh = new EffectMesh(effect, cubeMeshData[(j / 25) % 10]);
                effectMesh.KeepAliveBy(engineContext.SimpleComponentRegistry);
                effectMeshGroup.AddMesh(effectMesh);

                var w2 = Matrix.Scaling(1.0f)
                         * Matrix.Translation(new Vector3(
                                                  (j % objectSqrtCount - objectSqrtCount / 2) * 30.0f - 30.0f,
                                                  (((j / objectSqrtCount) % objectSqrtCount) - objectSqrtCount / 2) * 30.0f - 30.0f,
                                                  (j / (objectSqrtCount * objectSqrtCount) - objectSqrtCount / 2) * 30.0f - 30.0f));

                effectMesh.Parameters.Set(TransformationKeys.World, w2);
            }
        }
Пример #4
0
        public LightProcessor(LightingPlugin lightingPlugin, RenderTargetsPlugin renderTargetsPlugin, EffectOld lightEffect, bool enableIcons)
            : base(new PropertyKey[] { LightComponent.Key, TransformationComponent.Key })
        {
            this.enableIcons         = enableIcons;
            this.lightingPlugin      = lightingPlugin;
            this.lightEffect         = lightEffect;
            this.renderTargetsPlugin = renderTargetsPlugin;

            renderPassEnumerator = new RenderPassListEnumerator();
        }
Пример #5
0
        private void InitializeIconsRenderer()
        {
            var graphicsDevice = graphicsDeviceService.GraphicsDevice;

            var lightIconEffectBuilder = this.effectSystemOld.BuildEffect("LightIcon")
                                         .Using(new BasicShaderPlugin(
                                                    new ShaderMixinSource
            {
                Mixins = new List <ShaderClassSource>()
                {
                    "ShaderBase",
                    "TransformationZero",
                    "TransformationWVP",
                    "EditorIcon",
                },
                Compositions = new Dictionary <string, ShaderSource>()
                {
                    { "color", new ShaderClassSource("ComputeColorTexture", TexturingKeys.Texture0.Name, "TEXCOORD") }
                }
            })
            {
                RenderPassPlugin = renderTargetsPlugin
            })
                                         .Using(new StateShaderPlugin {
                UseBlendState = true, UseDepthStencilState = true, RenderPassPlugin = renderTargetsPlugin
            });

            lightIconEffectBuilder.PickingPassMainPlugin = renderTargetsPlugin;
            lightIconEffect = lightIconEffectBuilder;

            lightIconEffect.Parameters.Set(EffectPlugin.BlendStateKey, BlendState.New(graphicsDevice, new BlendStateDescription(Blend.SourceAlpha, Blend.InverseSourceAlpha)));
            lightIconEffect.Parameters.Set(EffectPlugin.DepthStencilStateKey, graphicsDevice.DepthStencilStates.Default);

            throw new NotImplementedException();
            //lightIconEffect.Passes[0].UpdatePasses += (RenderPass currentRenderPass, ref FastList<RenderPass> currentPasses) =>
            //    {
            //        if (currentRenderPass.Passes != null)
            //        {
            //            var meshComparer = new MeshComparer(renderTargetsPlugin.Parameters);
            //            currentRenderPass.Passes.Sort(meshComparer);
            //        }
            //    };

            // Generates a quad for post effect rendering (should be utility function)
            var vertices = new[]
            {
                0.0f, 1.0f,
                1.0f, 1.0f,
                0.0f, 0.0f,
                1.0f, 0.0f,
            };

            lightBulbTexture = (Texture2D)assetManager.Load <Texture>("/global_data/editor/light_bulb.png");
        }
Пример #6
0
        public override void Load()
        {
            base.Load();

            Effect.Services = Services;
            instantiatedEffect = Effect.InstantiatePermutation();

            // Create mesh
            effectMesh = new EffectMesh(instantiatedEffect, null, "PostEffectMesh").KeepAliveBy(this);
            effectMesh.Parameters.Set(TexturingKeys.Texture0, RenderSource);
            effectMesh.Parameters.Set(RenderTargetKeys.RenderTarget, RenderTarget);

            effectMesh.EffectPass.RenderPass = RenderPass;

            // Register mesh for rendering
            RenderSystem.GlobalMeshes.AddMesh(effectMesh);
        }
Пример #7
0
        public override void Load()
        {
            base.Load();

            Effect.Services    = Services;
            instantiatedEffect = Effect.InstantiatePermutation();

            // Create mesh
            effectMesh = new EffectMesh(instantiatedEffect, null, "PostEffectMesh").KeepAliveBy(this);
            effectMesh.Parameters.Set(TexturingKeys.Texture0, RenderSource);
            effectMesh.Parameters.Set(RenderTargetKeys.RenderTarget, RenderTarget);

            effectMesh.EffectPass.RenderPass = RenderPass;

            // Register mesh for rendering
            RenderSystem.GlobalMeshes.AddMesh(effectMesh);
        }
        private void UpdateMeshResources(EffectOld effect, EffectMesh effectMesh)
        {
            var oldStartPass = effectMesh.Render;

            // TODO: Integrate StageStatus.Apply in API
            // Temporarely, use AddEnd as StageStatus.Apply is appended to AddStart after this code is executed
            effectMesh.Render.Set = (context) =>
            {
                int tileIndex = context.Parameters.Get(TileIndex);
                var tiles     = RenderPassPlugin.Tiles[tileIndex];

                var mainParameters = RenderPassPlugin.GBufferPlugin.MainPlugin.ViewParameters;

                Matrix projMatrix;
                mainParameters.Get(TransformationKeys.Projection, out projMatrix);
                context.Parameters.Set(TransformationKeys.Projection, projMatrix);

                // Use depth buffer generated by GBuffer pass
                context.Parameters.Set(RenderTargetKeys.DepthStencilSource, RenderPassPlugin.GBufferPlugin.DepthStencil.Texture);

                if (currentTiles == null)
                {
                    currentTiles = new LightData[LightingPrepassPlugin.MaxLightsPerTileDrawCall];
                }

                //((Paradox.Framework.Graphics.Direct3D.GraphicsDevice)context.GraphicsDevice).NativeDeviceContext.InputAssembler.InputLayout = null;

                for (int i = 0; i < (tiles.Count + LightingPrepassPlugin.MaxLightsPerTileDrawCall - 1) / LightingPrepassPlugin.MaxLightsPerTileDrawCall; ++i)
                {
                    int lightCount = Math.Min(tiles.Count - i * LightingPrepassPlugin.MaxLightsPerTileDrawCall, LightingPrepassPlugin.MaxLightsPerTileDrawCall);
                    //effectMesh.Parameters.Set(LightCount, lightCount);
                    //effectMesh.Parameters.Set(LightInfos, RenderPassPlugin.Tiles[tileIndex].Skip(i * LightingPrepassPlugin.MaxLightsPerTileDrawCall).Take(lightCount).ToArray());

                    var startLightIndex = i * LightingPrepassPlugin.MaxLightsPerTileDrawCall;
                    for (int lightIndex = 0; lightIndex < lightCount; ++lightIndex)
                    {
                        currentTiles[lightIndex] = RenderPassPlugin.Tiles[tileIndex][startLightIndex + lightIndex];
                    }
                    context.Parameters.Set(LightCount, lightCount);
                    context.Parameters.Set(LightInfos, currentTiles);

                    // Render this tile
                    oldStartPass.Invoke(context);
                }
            };
        }
Пример #9
0
        void SetupMeshResources(EffectOld effect, EffectMesh effectMesh)
        {
            // Generates a quad for post effect rendering (should be utility function)
            var vertices = new[]
            {
                -1.0f, 1.0f,
                1.0f, 1.0f,
                -1.0f, -1.0f,
                1.0f, -1.0f,
            };

            // Use the quad for this effectMesh
            effectMesh.MeshData.Draw = new MeshDraw
            {
                DrawCount     = 4,
                PrimitiveType = PrimitiveType.TriangleStrip,
                VertexBuffers = new[]
                {
                    new VertexBufferBinding(Buffer.Vertex.New(GraphicsDevice, vertices), new VertexDeclaration(VertexElement.Position <Vector2>()), 4)
                }
            };

            // TODO: unbind render targets
            var previousRender = effectMesh.Render;

            effectMesh.Render += (threadContext) =>
            {
                // Setup render target
                var renderTarget = effectMesh.Parameters.Get(RenderTargetKeys.RenderTarget);
                var desc         = renderTarget.Description;
                threadContext.GraphicsDevice.SetViewport(new Viewport(0, 0, desc.Width, desc.Height));
                threadContext.GraphicsDevice.SetRenderTarget(renderTarget);

                // Draw
                previousRender.Invoke(threadContext);

                // Unbind RenderTargets
                threadContext.GraphicsDevice.UnsetRenderTargets();
            };
        }
        private void SetupMeshResources(EffectOld effect, EffectMesh effectMesh)
        {
            // Generates a quad for post effect rendering (should be utility function)
            var vertices = new[]
            {
                -1.0f, 1.0f,
                1.0f, 1.0f,
                -1.0f, -1.0f,
                1.0f, -1.0f,
            };

            // Use the quad for this effectMesh
            effectMesh.MeshData.Draw = new MeshDraw
            {
                DrawCount     = 4,
                PrimitiveType = PrimitiveType.TriangleStrip,
                VertexBuffers = new[]
                {
                    new VertexBufferBinding(Buffer.Vertex.New(GraphicsDevice, vertices), new VertexDeclaration(VertexElement.Position <Vector2>()), 4)
                }
            };
        }
Пример #11
0
        public override void Initialize()
        {
            base.Initialize();

            boundingBoxPass = new RenderPass("BoundingBoxPass");
            minMaxPass = new RenderPass("MinmaxPass");
            lightShaftPass = new RenderPass("LightShaftPass");
            filterUpscalePass = new RenderPass("UpscalePass");
            RenderPass.AddPass(boundingBoxPass, minMaxPass, lightShaftPass, filterUpscalePass);

            var useUpScaling = false;

            var bbRenderTargetPlugin = new RenderTargetsPlugin("BoundingBoxRenderTargetPlugin")
                {
                    EnableSetTargets = true,
                    EnableClearTarget = true,
                    RenderPass = boundingBoxPass,
                    Services = Services,
                };

            var minMaxEffectBuilder = this.EffectSystemOld.BuildEffect("MinMax")
                .Using(new MinMaxShaderPlugin("MinMaxShaderPlugin") { RenderPassPlugin = bbRenderTargetPlugin })
                .Using(new BasicShaderPlugin("TransformationWVP") { RenderPassPlugin = bbRenderTargetPlugin });


            var minmaxEffectBuilder = this.EffectSystemOld.BuildEffect("LightShaftsMinMax")
                .Using(new PostEffectSeparateShaderPlugin() { RenderPass = minMaxPass })
                .Using(new BasicShaderPlugin("ForwardShadowMapBase") { RenderPass = minMaxPass })
                .Using(new BasicShaderPlugin(new ShaderClassSource("PostEffectMinMax", "ShadowMapUtils.shadowMapTexture", "PointSampler", 4, 4, 0.0, 1.0)) { RenderPass = minMaxPass });

            var lightShaftsEffectBuilder = this.EffectSystemOld.BuildEffect("LightShafts")
                .Using(new PostEffectSeparateShaderPlugin() { RenderPass = lightShaftPass })
                .Using(new StateShaderPlugin() { UseBlendState = !useUpScaling, RenderPass = lightShaftPass })
                //.Using(new BasicShaderPlugin(new ShaderClassSource("PostEffectLightShafts", Debug ? 1 : 0, RenderContext.IsZReverse ? 1 : 0, StepCount)) { RenderPass = lightShaftPass });
                .Using(new BasicShaderPlugin(new ShaderClassSource("PostEffectLightShafts", Debug ? 1 : 0, false ? 1 : 0, StepCount)) { RenderPass = lightShaftPass });

            if (OfflineCompilation)
            {
                minMaxEffectBuilder.InstantiatePermutation();
                minmaxEffectBuilder.InstantiatePermutation();
                lightShaftsEffectBuilder.InstantiatePermutation();
                return;
            }

            Parameters.AddSources(ViewParameters);
            Parameters.Set(RenderTargetKeys.DepthStencilSource, DepthStencil.Texture);
            Parameters.Set(TexturingKeys.Sampler, GraphicsDevice.SamplerStates.PointClamp);

            // BoundingBox prepass
            var gbufferDesc = RenderTarget.Description;
            var bbRenderTarget = Texture.New2D(GraphicsDevice, gbufferDesc.Width / 8, gbufferDesc.Height / 8, PixelFormat.R32G32_Float, TextureFlags.ShaderResource | TextureFlags.RenderTarget);

            // Use MinMax Plugin
            bbRenderTargetPlugin.RenderTarget = bbRenderTarget.ToRenderTarget();
            bbRenderTargetPlugin.Parameters.AddSources(Parameters);
            bbRenderTargetPlugin.Apply();

            EffectOld minMaxEffect = minMaxEffectBuilder.InstantiatePermutation();
           
            // Add meshes
            foreach (var bbMeshData in BoundingBoxes)
            {
                // Mesh for MinPass
                var bbMesh = new EffectMesh(minMaxEffect, bbMeshData).KeepAliveBy(this);
                // Add mesh
                // boundingBoxPass.AddPass(bbMesh.EffectMeshPasses[0].EffectPass);
                RenderSystem.GlobalMeshes.AddMesh(bbMesh);
            }

            // MinMax render target
            var minMaxRenderTarget = Texture.New2D(GraphicsDevice, 256, 256, PixelFormat.R32G32_Float, TextureFlags.ShaderResource | TextureFlags.RenderTarget);
            minMaxPass.Parameters = new ParameterCollection(null);
            minMaxPass.Parameters.AddSources(ShadowMap.Parameters);
            minMaxPass.Parameters.AddSources(Parameters);
            minMaxPass.Parameters.AddDynamic(PostEffectMinMaxKeys.MinMaxCoords, ParameterDynamicValue.New(LightingPlugin.CascadeTextureCoords, (ref Vector4[] cascadeTextureCoords, ref Vector4 output) =>
                {
                    output = cascadeTextureCoords[0];
                }, autoCheckDependencies: false));

            EffectOld minmaxEffect = minmaxEffectBuilder.InstantiatePermutation();

            var minMaxMesh = new EffectMesh(minmaxEffect).KeepAliveBy(this);
            minMaxMesh.Parameters.Set(RenderTargetKeys.RenderTarget, minMaxRenderTarget.ToRenderTarget());
            RenderSystem.GlobalMeshes.AddMesh(minMaxMesh);

            // Light Shafts effect
            var blendStateDesc = new BlendStateDescription();
            blendStateDesc.SetDefaults();
            blendStateDesc.AlphaToCoverageEnable = false;
            blendStateDesc.IndependentBlendEnable = false;
            blendStateDesc.RenderTargets[0].BlendEnable = true;

            blendStateDesc.RenderTargets[0].AlphaBlendFunction = BlendFunction.Add;
            blendStateDesc.RenderTargets[0].AlphaSourceBlend = Blend.One;
            blendStateDesc.RenderTargets[0].AlphaDestinationBlend = Blend.One;

            blendStateDesc.RenderTargets[0].ColorBlendFunction = BlendFunction.Add;
            blendStateDesc.RenderTargets[0].ColorSourceBlend = Blend.One;
            blendStateDesc.RenderTargets[0].ColorDestinationBlend = Blend.One;

            blendStateDesc.RenderTargets[0].ColorWriteChannels = ColorWriteChannels.All;

            var additiveBlending = BlendState.New(GraphicsDevice, blendStateDesc);
            additiveBlending.Name = "LightShaftAdditiveBlend";

            var shaftRenderTarget = useUpScaling ? Texture.New2D(GraphicsDevice, gbufferDesc.Width / 2, gbufferDesc.Height / 2, PixelFormat.R16G16B16A16_Float, TextureFlags.ShaderResource | TextureFlags.RenderTarget).ToRenderTarget() : RenderTarget;
            

            lightShaftPass.Parameters = new ParameterCollection();
            lightShaftPass.Parameters.AddSources(ShadowMap.Parameters);
            lightShaftPass.Parameters.AddSources(Parameters);

            this.lightShaftsEffect = lightShaftsEffectBuilder.InstantiatePermutation();


            var mesh = new EffectMesh(lightShaftsEffect).KeepAliveBy(this);
            mesh.Parameters.Set(TexturingKeys.Texture0, minMaxRenderTarget);
            mesh.Parameters.Set(TexturingKeys.Texture1, bbRenderTarget);
            mesh.Parameters.Set(RenderTargetKeys.RenderTarget, shaftRenderTarget);

            if (!useUpScaling)
            {
                mesh.Parameters.Set(EffectPlugin.BlendStateKey, additiveBlending);
            }
            RenderSystem.GlobalMeshes.AddMesh(mesh);

            // Bilateral Gaussian filtering for up-sampling
            if (useUpScaling)
            {
                var bbRenderTargetUpScaleH = Texture.New2D(GraphicsDevice, gbufferDesc.Width, gbufferDesc.Height / 2, PixelFormat.R16G16B16A16_Float, TextureFlags.ShaderResource | TextureFlags.RenderTarget);
                var bbRenderTargetUpScaleV = RenderTarget;
                //var bbRenderTargetUpScaleV = GraphicsDevice.RenderTarget2D.New(gbufferDesc.Width, gbufferDesc.Height, PixelFormat.HalfVector4);

                var blurEffects = new EffectOld[] {
                                                   this.EffectSystemOld.BuildEffect("BilateralGaussianFiltering")
                                                       .Using(new PostEffectSeparateShaderPlugin())
                                                       .Using(new BasicShaderPlugin( new ShaderClassSource("PostEffectBilateralGaussian", 0))),
                                                   this.EffectSystemOld.BuildEffect("BilateralGaussianFiltering")
                                                       .Using(new StateShaderPlugin() { UseBlendState = true })
                                                       .Using(new PostEffectSeparateShaderPlugin())
                                                       .Using(new BasicShaderPlugin( new ShaderClassSource("PostEffectBilateralGaussian", 1))),
                                               };

                Texture2D textureSourceH = (Texture2D)shaftRenderTarget.Texture;
                Texture2D textureSourceV = bbRenderTargetUpScaleH;
                RenderTarget renderTargetH = bbRenderTargetUpScaleH.ToRenderTarget();
                RenderTarget renderTargetV = bbRenderTargetUpScaleV;

                var blurQuadMesh = new EffectMesh[2];
                for (int i = 0; i < 2; ++i)
                {
                    blurQuadMesh[i] = new EffectMesh(blurEffects[i]).KeepAliveBy(this);
                    filterUpscalePass.AddPass(blurQuadMesh[i].EffectPass);
                    RenderSystem.GlobalMeshes.AddMesh(blurQuadMesh[i]);
                }

                blurQuadMesh[0].Parameters.Set(TexturingKeys.Texture0, textureSourceH);
                blurQuadMesh[1].Parameters.Set(TexturingKeys.Texture0, textureSourceV);
                blurQuadMesh[0].Parameters.Set(RenderTargetKeys.RenderTarget, renderTargetH);
                blurQuadMesh[1].Parameters.Set(RenderTargetKeys.RenderTarget, renderTargetV);

                // Additive blending for 2nd render target
                blurQuadMesh[1].Parameters.Set(EffectPlugin.BlendStateKey, additiveBlending);
            }
        }
Пример #12
0
        public override void Initialize()
        {
            base.Initialize();

            boundingBoxPass   = new RenderPass("BoundingBoxPass");
            minMaxPass        = new RenderPass("MinmaxPass");
            lightShaftPass    = new RenderPass("LightShaftPass");
            filterUpscalePass = new RenderPass("UpscalePass");
            RenderPass.AddPass(boundingBoxPass, minMaxPass, lightShaftPass, filterUpscalePass);

            var useUpScaling = false;

            var bbRenderTargetPlugin = new RenderTargetsPlugin("BoundingBoxRenderTargetPlugin")
            {
                EnableSetTargets  = true,
                EnableClearTarget = true,
                RenderPass        = boundingBoxPass,
                Services          = Services,
            };

            var minMaxEffectBuilder = this.EffectSystemOld.BuildEffect("MinMax")
                                      .Using(new MinMaxShaderPlugin("MinMaxShaderPlugin")
            {
                RenderPassPlugin = bbRenderTargetPlugin
            })
                                      .Using(new BasicShaderPlugin("TransformationWVP")
            {
                RenderPassPlugin = bbRenderTargetPlugin
            });


            var minmaxEffectBuilder = this.EffectSystemOld.BuildEffect("LightShaftsMinMax")
                                      .Using(new PostEffectSeparateShaderPlugin()
            {
                RenderPass = minMaxPass
            })
                                      .Using(new BasicShaderPlugin("ForwardShadowMapBase")
            {
                RenderPass = minMaxPass
            })
                                      .Using(new BasicShaderPlugin(new ShaderClassSource("PostEffectMinMax", "ShadowMapUtils.shadowMapTexture", "PointSampler", 4, 4, 0.0, 1.0))
            {
                RenderPass = minMaxPass
            });

            var lightShaftsEffectBuilder = this.EffectSystemOld.BuildEffect("LightShafts")
                                           .Using(new PostEffectSeparateShaderPlugin()
            {
                RenderPass = lightShaftPass
            })
                                           .Using(new StateShaderPlugin()
            {
                UseBlendState = !useUpScaling, RenderPass = lightShaftPass
            })
                                           //.Using(new BasicShaderPlugin(new ShaderClassSource("PostEffectLightShafts", Debug ? 1 : 0, RenderContext.IsZReverse ? 1 : 0, StepCount)) { RenderPass = lightShaftPass });
                                           .Using(new BasicShaderPlugin(new ShaderClassSource("PostEffectLightShafts", Debug ? 1 : 0, false ? 1 : 0, StepCount))
            {
                RenderPass = lightShaftPass
            });

            if (OfflineCompilation)
            {
                minMaxEffectBuilder.InstantiatePermutation();
                minmaxEffectBuilder.InstantiatePermutation();
                lightShaftsEffectBuilder.InstantiatePermutation();
                return;
            }

            Parameters.AddSources(ViewParameters);
            Parameters.Set(RenderTargetKeys.DepthStencilSource, DepthStencil.Texture);
            Parameters.Set(TexturingKeys.Sampler, GraphicsDevice.SamplerStates.PointClamp);

            // BoundingBox prepass
            var gbufferDesc    = RenderTarget.Description;
            var bbRenderTarget = Texture2D.New(GraphicsDevice, gbufferDesc.Width / 8, gbufferDesc.Height / 8, PixelFormat.R32G32_Float, TextureFlags.ShaderResource | TextureFlags.RenderTarget);

            // Use MinMax Plugin
            bbRenderTargetPlugin.RenderTarget = bbRenderTarget.ToRenderTarget();
            bbRenderTargetPlugin.Parameters.AddSources(Parameters);
            bbRenderTargetPlugin.Apply();

            EffectOld minMaxEffect = minMaxEffectBuilder.InstantiatePermutation();

            // Add meshes
            foreach (var bbMeshData in BoundingBoxes)
            {
                // Mesh for MinPass
                var bbMesh = new EffectMesh(minMaxEffect, bbMeshData).KeepAliveBy(this);
                // Add mesh
                // boundingBoxPass.AddPass(bbMesh.EffectMeshPasses[0].EffectPass);
                RenderSystem.GlobalMeshes.AddMesh(bbMesh);
            }

            // MinMax render target
            var minMaxRenderTarget = Texture2D.New(GraphicsDevice, 256, 256, PixelFormat.R32G32_Float, TextureFlags.ShaderResource | TextureFlags.RenderTarget);

            minMaxPass.Parameters = new ParameterCollection(null);
            minMaxPass.Parameters.AddSources(ShadowMap.Parameters);
            minMaxPass.Parameters.AddSources(Parameters);
            minMaxPass.Parameters.AddDynamic(PostEffectMinMaxKeys.MinMaxCoords, ParameterDynamicValue.New(LightingPlugin.CascadeTextureCoords, (ref Vector4[] cascadeTextureCoords, ref Vector4 output) =>
            {
                output = cascadeTextureCoords[0];
            }, autoCheckDependencies: false));

            EffectOld minmaxEffect = minmaxEffectBuilder.InstantiatePermutation();

            var minMaxMesh = new EffectMesh(minmaxEffect).KeepAliveBy(this);

            minMaxMesh.Parameters.Set(RenderTargetKeys.RenderTarget, minMaxRenderTarget.ToRenderTarget());
            RenderSystem.GlobalMeshes.AddMesh(minMaxMesh);

            // Light Shafts effect
            var blendStateDesc = new BlendStateDescription();

            blendStateDesc.SetDefaults();
            blendStateDesc.AlphaToCoverageEnable        = false;
            blendStateDesc.IndependentBlendEnable       = false;
            blendStateDesc.RenderTargets[0].BlendEnable = true;

            blendStateDesc.RenderTargets[0].AlphaBlendFunction    = BlendFunction.Add;
            blendStateDesc.RenderTargets[0].AlphaSourceBlend      = Blend.One;
            blendStateDesc.RenderTargets[0].AlphaDestinationBlend = Blend.One;

            blendStateDesc.RenderTargets[0].ColorBlendFunction    = BlendFunction.Add;
            blendStateDesc.RenderTargets[0].ColorSourceBlend      = Blend.One;
            blendStateDesc.RenderTargets[0].ColorDestinationBlend = Blend.One;

            blendStateDesc.RenderTargets[0].ColorWriteChannels = ColorWriteChannels.All;

            var additiveBlending = BlendState.New(GraphicsDevice, blendStateDesc);

            additiveBlending.Name = "LightShaftAdditiveBlend";

            var shaftRenderTarget = useUpScaling ? Texture2D.New(GraphicsDevice, gbufferDesc.Width / 2, gbufferDesc.Height / 2, PixelFormat.R16G16B16A16_Float, TextureFlags.ShaderResource | TextureFlags.RenderTarget).ToRenderTarget() : RenderTarget;


            lightShaftPass.Parameters = new ParameterCollection();
            lightShaftPass.Parameters.AddSources(ShadowMap.Parameters);
            lightShaftPass.Parameters.AddSources(Parameters);

            this.lightShaftsEffect = lightShaftsEffectBuilder.InstantiatePermutation();


            var mesh = new EffectMesh(lightShaftsEffect).KeepAliveBy(this);

            mesh.Parameters.Set(TexturingKeys.Texture0, minMaxRenderTarget);
            mesh.Parameters.Set(TexturingKeys.Texture1, bbRenderTarget);
            mesh.Parameters.Set(RenderTargetKeys.RenderTarget, shaftRenderTarget);

            if (!useUpScaling)
            {
                mesh.Parameters.Set(EffectPlugin.BlendStateKey, additiveBlending);
            }
            RenderSystem.GlobalMeshes.AddMesh(mesh);

            // Bilateral Gaussian filtering for up-sampling
            if (useUpScaling)
            {
                var bbRenderTargetUpScaleH = Texture2D.New(GraphicsDevice, gbufferDesc.Width, gbufferDesc.Height / 2, PixelFormat.R16G16B16A16_Float, TextureFlags.ShaderResource | TextureFlags.RenderTarget);
                var bbRenderTargetUpScaleV = RenderTarget;
                //var bbRenderTargetUpScaleV = GraphicsDevice.RenderTarget2D.New(gbufferDesc.Width, gbufferDesc.Height, PixelFormat.HalfVector4);

                var blurEffects = new EffectOld[] {
                    this.EffectSystemOld.BuildEffect("BilateralGaussianFiltering")
                    .Using(new PostEffectSeparateShaderPlugin())
                    .Using(new BasicShaderPlugin(new ShaderClassSource("PostEffectBilateralGaussian", 0))),
                    this.EffectSystemOld.BuildEffect("BilateralGaussianFiltering")
                    .Using(new StateShaderPlugin()
                    {
                        UseBlendState = true
                    })
                    .Using(new PostEffectSeparateShaderPlugin())
                    .Using(new BasicShaderPlugin(new ShaderClassSource("PostEffectBilateralGaussian", 1))),
                };

                Texture2D    textureSourceH = (Texture2D)shaftRenderTarget.Texture;
                Texture2D    textureSourceV = bbRenderTargetUpScaleH;
                RenderTarget renderTargetH  = bbRenderTargetUpScaleH.ToRenderTarget();
                RenderTarget renderTargetV  = bbRenderTargetUpScaleV;

                var blurQuadMesh = new EffectMesh[2];
                for (int i = 0; i < 2; ++i)
                {
                    blurQuadMesh[i] = new EffectMesh(blurEffects[i]).KeepAliveBy(this);
                    filterUpscalePass.AddPass(blurQuadMesh[i].EffectPass);
                    RenderSystem.GlobalMeshes.AddMesh(blurQuadMesh[i]);
                }

                blurQuadMesh[0].Parameters.Set(TexturingKeys.Texture0, textureSourceH);
                blurQuadMesh[1].Parameters.Set(TexturingKeys.Texture0, textureSourceV);
                blurQuadMesh[0].Parameters.Set(RenderTargetKeys.RenderTarget, renderTargetH);
                blurQuadMesh[1].Parameters.Set(RenderTargetKeys.RenderTarget, renderTargetV);

                // Additive blending for 2nd render target
                blurQuadMesh[1].Parameters.Set(EffectPlugin.BlendStateKey, additiveBlending);
            }
        }
Пример #13
0
        public static async Task Run(EngineContext engineContext)
        {
            var renderingSetup = new RenderingSetup();

            renderingSetup.Initialize(engineContext);
            var device = engineContext.RenderContext.GraphicsDevice;

            var effectMeshGroup = new RenderPassListEnumerator();

            engineContext.RenderContext.RenderPassEnumerators.Add(effectMeshGroup);


            EffectOld linearEffect = engineContext.RenderContext.BuildEffect("LinearColor")
                                     .Using(new PostEffectShaderPlugin())
                                     .Using(new BasicShaderPlugin(new ShaderClassSource("ComputeToneMap", "0")));
            var linearMesh = new EffectMesh(linearEffect);

            renderingSetup.LinearColorPlugin.RenderPass.AddPass(linearMesh.EffectMeshPasses[0].EffectPass);
            var linearTexture = Texture2D.New(engineContext.RenderContext.GraphicsDevice, 512, 512, PixelFormat.R16G16B16A16_Float, TextureFlags.RenderTarget);

            linearMesh.Parameters.Set(RenderTargetKeys.RenderTarget, linearTexture.ToRenderTarget());
            effectMeshGroup.AddMesh(linearMesh);

            EffectOld reinhardColor = engineContext.RenderContext.BuildEffect("ReinhardColor")
                                      .Using(new PostEffectShaderPlugin())
                                      .Using(new BasicShaderPlugin(new ShaderClassSource("ComputeToneMap", "1")));
            var reinhardMesh = new EffectMesh(reinhardColor);

            renderingSetup.ReinhardColorPlugin.RenderPass.AddPass(reinhardMesh.EffectMeshPasses[0].EffectPass);
            var reinhardTexture = Texture2D.New(engineContext.RenderContext.GraphicsDevice, 512, 512, PixelFormat.R16G16B16A16_Float, TextureFlags.RenderTarget);

            reinhardMesh.Parameters.Set(RenderTargetKeys.RenderTarget, reinhardTexture.ToRenderTarget());
            effectMeshGroup.AddMesh(reinhardMesh);

            var yebisTexture = Texture2D.New(engineContext.RenderContext.GraphicsDevice, 512, 512, PixelFormat.R8G8B8A8_UNorm, TextureFlags.RenderTarget);

#if XENKO_YEBIS
            var yebisPlugin = renderingSetup.YebisPlugin;

            yebisPlugin.RenderSource = reinhardTexture;
            yebisPlugin.RenderTarget = yebisTexture.ToRenderTarget();

            yebisPlugin.Glare.Enable           = false;
            yebisPlugin.Lens.Vignette.Enable   = false;
            yebisPlugin.Lens.Distortion.Enable = false;

            yebisPlugin.ToneMap.Exposure = 1.0f;
            yebisPlugin.ToneMap.Gamma    = 2.2f;
            yebisPlugin.ToneMap.Type     = ToneMapType.Reinhard;
            engineContext.RenderContext.Register(yebisPlugin);
#endif

            EffectOld filmicEffect = engineContext.RenderContext.BuildEffect("FilmicColor")
                                     .Using(new PostEffectShaderPlugin())
                                     .Using(new BasicShaderPlugin(new ShaderClassSource("ComputeToneMap", "2")));
            var filmicMesh = new EffectMesh(filmicEffect);
            renderingSetup.FilmicColorPlugin.RenderPass.AddPass(filmicMesh.EffectMeshPasses[0].EffectPass);
            var filmicTexture = Texture2D.New(engineContext.RenderContext.GraphicsDevice, 512, 512, PixelFormat.R16G16B16A16_Float, TextureFlags.ShaderResource | TextureFlags.RenderTarget);
            filmicTexture.Name = "FilmicTexture";
            filmicMesh.Parameters.Set(RenderTargetKeys.RenderTarget, filmicTexture.ToRenderTarget());
            effectMeshGroup.AddMesh(filmicMesh);

            EffectOld mainEffect = engineContext.RenderContext.BuildEffect("ComposeToneMap")
                                   .Using(new PostEffectShaderPlugin())
                                   .Using(new BasicShaderPlugin(new ShaderClassSource("ComposeToneMap")));
            var mainMesh = new EffectMesh(mainEffect);
            renderingSetup.MainPlugin.RenderPass.AddPass(mainMesh.EffectMeshPasses[0].EffectPass);

            mainMesh.Parameters.Set(TexturingKeys.Texture0, linearTexture);
            mainMesh.Parameters.Set(TexturingKeys.Texture2, yebisTexture);
            mainMesh.Parameters.Set(TexturingKeys.Texture3, filmicTexture);
            mainMesh.Parameters.Set(RenderTargetKeys.RenderTarget, engineContext.RenderContext.RenderTarget);
            effectMeshGroup.AddMesh(mainMesh);
        }
Пример #14
0
        public static async Task GenerateSimpleCubeEffect(EngineContext engineContext)
        {
            var renderingSetup = RenderingSetup.Singleton;

            renderingSetup.RegisterLighting(engineContext);

#if XENKO_YEBIS
            YebisPlugin yebisPlugin;
            if (engineContext.DataContext.RenderPassPlugins.TryGetValueCast("YebisPlugin", out yebisPlugin))
            {
                yebisPlugin.Glare.Enable                = false;
                yebisPlugin.DepthOfField.Enable         = false;
                yebisPlugin.ToneMap.AutoExposure.Enable = false;
                yebisPlugin.ToneMap.Exposure            = 1.0f;
                yebisPlugin.ToneMap.Gamma               = 2.2f;
            }
#endif
            var lightPrepassPlugin = (LightingPrepassPlugin)engineContext.DataContext.RenderPassPlugins.TryGetValue("LightingPrepassPlugin");
            var gbufferPlugin      = (GBufferPlugin)engineContext.DataContext.RenderPassPlugins.TryGetValue("GBufferPlugin");

            EffectOld effect = engineContext.RenderContext.BuildEffect("SimpleCube")
                               .Using(new BasicShaderPlugin("ShaderBase")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin("TransformationWVP")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin("AlbedoSpecularBase")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin("AlbedoDiffuseBase")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin("NormalVSGBuffer")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin("SpecularPowerPerMesh")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin("PositionVSGBuffer")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin("BRDFDiffuseLambert")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin("BRDFSpecularBlinnPhong")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin(new ShaderMixinSource()
            {
                new ShaderComposition("albedoDiffuse", new ShaderClassSource("ComputeColorStream"))
            })
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin(new ShaderMixinSource()
            {
                new ShaderComposition("albedoSpecular", new ShaderClassSource("ComputeColorSynthetic"))
            })
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new GBufferShaderPlugin {
                RenderPassPlugin = gbufferPlugin
            })
                               .Using(new DeferredLightingShaderPlugin()
            {
                RenderPassPlugin = lightPrepassPlugin
            })
                               .Using(new BasicShaderPlugin("LightDirectionalShading")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
            ;

            EffectOld effect2 = engineContext.RenderContext.BuildEffect("SimpleSkinning")
                                .Using(new BasicShaderPlugin("ShaderBase")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                                .Using(new BasicShaderPlugin("TransformationWVP")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                                .Using(new BasicShaderPlugin("TransformationSkinning")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                                .Using(new BasicShaderPlugin("AlbedoSpecularBase")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                                .Using(new BasicShaderPlugin("AlbedoDiffuseBase")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                                .Using(new BasicShaderPlugin("NormalVSGBuffer")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                                .Using(new BasicShaderPlugin("SpecularPowerPerMesh")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                                .Using(new BasicShaderPlugin("PositionVSGBuffer")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                                .Using(new BasicShaderPlugin("BRDFDiffuseLambert")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                                .Using(new BasicShaderPlugin("BRDFSpecularBlinnPhong")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                                .Using(new BasicShaderPlugin(new ShaderMixinSource()
            {
                new ShaderClassSource("AlbedoDiffuseBase"),
                new ShaderComposition("albedoDiffuse", new ShaderClassSource("ComputeColorTexture", TexturingKeys.DiffuseTexture.Name, "TEXCOORD")),
                new ShaderComposition("albedoSpecular", new ShaderClassSource("ComputeColor")),
            })
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                                .Using(new GBufferShaderPlugin {
                RenderPassPlugin = gbufferPlugin
            })
                                .Using(new DeferredLightingShaderPlugin()
            {
                RenderPassPlugin = (LightingPrepassPlugin)engineContext.DataContext.RenderPassPlugins.TryGetValue("LightingPrepassPlugin")
            })
                                .Using(new BasicShaderPlugin("LightDirectionalShading")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
            ;
        }
Пример #15
0
        public static async Task Run(EngineContext engineContext)
        {
            var renderingSetup = RenderingSetup.Singleton;

            renderingSetup.Initialize(engineContext);
            renderingSetup.RegisterLighting(engineContext);

#if XENKO_YEBIS
            YebisPlugin yebisPlugin;
            if (engineContext.DataContext.RenderPassPlugins.TryGetValueCast("YebisPlugin", out yebisPlugin))
            {
                yebisPlugin.Glare.Enable     = true;
                yebisPlugin.ToneMap.Exposure = 1.0f;
                yebisPlugin.ToneMap.Gamma    = 2.2f;
            }
#endif

            var lightPrepassPlugin = (LightingPrepassPlugin)engineContext.DataContext.RenderPassPlugins.TryGetValue("LightingPrepassPlugin");
            var gbufferPlugin      = (GBufferPlugin)engineContext.DataContext.RenderPassPlugins.TryGetValue("GBufferPlugin");

            EffectOld effect = engineContext.RenderContext.BuildEffect("SimpleCube")
                               .Using(new BasicShaderPlugin("ShaderBase")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin("TransformationWVP")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin("AlbedoSpecularBase")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin("AlbedoDiffuseBase")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin("NormalVSGBuffer")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin("SpecularPowerPerMesh")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin("PositionVSGBuffer")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin("BRDFDiffuseLambert")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin("BRDFSpecularBlinnPhong")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin(new ShaderMixinSource()
            {
                new ShaderComposition("albedoDiffuse", new ShaderClassSource("ComputeColorStream"))
            })
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin(new ShaderMixinSource()
            {
                new ShaderComposition("albedoSpecular", new ShaderClassSource("ComputeColorSynthetic"))
            })
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new GBufferShaderPlugin {
                RenderPassPlugin = gbufferPlugin
            })
                               .Using(new DeferredLightingShaderPlugin()
            {
                RenderPassPlugin = lightPrepassPlugin
            })
                               .Using(new LightingShaderPlugin()
            {
                RenderPassPlugin = (LightingPlugin)engineContext.DataContext.RenderPassPlugins.TryGetValue("LightingPlugin")
            })
                               .Using(new BasicShaderPlugin("LightDirectionalShading")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
            ;

            var shadowMap1 = new ShadowMap(new DirectionalLight()
            {
                LightColor = new Color3(1.0f, 1.0f, 1.0f), LightDirection = new Vector3(1.0f, 1.0f, 1.0f)
            });
            effect.Permutations.Set(ShadowMapPermutationArray.Key, new ShadowMapPermutationArray {
                ShadowMaps = { shadowMap1 }
            });

            var r = new Random(0);


            VirtualFileSystem.MountFileSystem("/global_data", "..\\..\\deps\\data\\");
            VirtualFileSystem.MountFileSystem("/global_data2", "..\\..\\data\\");

            SkyBoxPlugin skyBoxPlugin;
            if (engineContext.DataContext.RenderPassPlugins.TryGetValueCast("SkyBoxPlugin", out skyBoxPlugin))
            {
                var skyBoxTexture = (Texture2D)await engineContext.AssetManager.LoadAsync <Texture>("/global_data/gdc_demo/bg/GDC2012_map_sky.dds");

                skyBoxPlugin.Texture = skyBoxTexture;
            }

            var effectMeshGroup = new RenderPassListEnumerator();
            engineContext.RenderContext.RenderPassEnumerators.Add(effectMeshGroup);

            var groundMesh = new EffectMesh(effect, MeshDataHelper.CreateBox(10000, 10000, 1, Color.White));
            groundMesh.KeepAliveBy(engineContext.SimpleComponentRegistry);
            effectMeshGroup.AddMesh(groundMesh);
            groundMesh.Parameters.Set(TransformationKeys.World, Matrix.Translation(new Vector3(0, 0, 0)));

            // Lights
            for (int i = 0; i < 1024; ++i)
            {
                Color3 color = (Color3)Color.White;

                switch (i % 4)
                {
                case 0: color = (Color3)Color.DarkOrange; break;

                case 1: color = (Color3)Color.DarkGoldenrod; break;

                case 2: color = (Color3)Color.DarkSalmon; break;

                case 3: color = (Color3)Color.DarkRed; break;
                }
                var effectMesh = new EffectMesh(lightPrepassPlugin.Lights);
                effectMesh.Parameters.Set(LightKeys.LightRadius, (float)r.NextDouble() * 200 + 200.0f);
                effectMesh.Parameters.Set(LightKeys.LightColor, color);
                effectMesh.KeepAliveBy(engineContext.SimpleComponentRegistry);

                effectMeshGroup.AddMesh(effectMesh);
            }

            EffectOld effectLight = lightPrepassPlugin.Lights;

            var lightInfo = new LightInfo[effectLight != null ? effectLight.Meshes.Count : 0];
            for (int i = 0; i < lightInfo.Length; ++i)
            {
                lightInfo[i].Radius = (float)r.NextDouble() * 7000.0f + 500.0f;
                lightInfo[i].Phase  = (float)(r.NextDouble() * Math.PI * 2.0);
                lightInfo[i].Z      = (float)r.NextDouble() * 3000.0f;;
            }
            float time = 0.0f;


            // Meshes (quad) that will later be generated by the engine (light pre pass, SSAO, etc...)
            // Lights
            //var effectMesh = new EffectMesh(setup.LightingPrepassPlugin.Lights);
            //effectMesh.Parameters.Set(LightKeys.LightRadius, 1000.0f);
            //effectMesh.Parameters.Set(LightKeys.LightColor, new R32G32B32_Float(1.0f, 1.0f, 1.0f));
            //effectMesh.Parameters.Set(LightKeys.LightPosition, new R32G32B32_Float(0, 0, 1200));

            //effectMesh.KeepAliveBy(engineContext.SimpleComponentRegistry);
            //effectMeshGroup.AddMesh(effectMesh);

            //var boxMesh = new EffectMesh(effect, MeshDataHelper.CreateBox(300, R8G8B8A8.LightBlue));
            //boxMesh.KeepAliveBy(engineContext.SimpleComponentRegistry);
            //boxMesh.Parameters.Set(TransformationKeys.World, Matrix.Translation(new R32G32B32_Float(0, 0, 200)));
            //effectMeshGroup.AddMesh(boxMesh);


            var clock = new Stopwatch();
            clock.Start();


            int sizeX = 10;
            int sizeY = 10;

            var spheres = new Sphere[sizeY, sizeX];

            Random random = new Random(0);

            int size     = 200;
            var meshData = MeshDataHelper.CreateSphere(size, 30, 30, Color.Gray);

            for (int iy = 0; iy < sizeY; iy++)
            {
                for (int ix = 0; ix < sizeX; ix++)
                {
                    var sphere = new Sphere();

                    sphere.Mesh  = new EffectMesh(effect, meshData);
                    sphere.Phase = (float)random.NextDouble();
                    sphere.Speed = (float)random.NextDouble();

                    spheres[iy, ix] = sphere;
                    effectMeshGroup.AddMesh(sphere.Mesh);
                }
            }


            while (true)
            {
                await Scheduler.Current.NextFrame();


                for (int iy = 0; iy < sizeY; iy++)
                {
                    for (int ix = 0; ix < sizeX; ix++)
                    {
                        var iFactor = (float)(iy * sizeY + ix) / (sizeX * sizeY);

                        var sphere        = spheres[iy, ix];
                        var sphereMesh    = sphere.Mesh;
                        var specularColor = Color.SmoothStep(Color.GreenYellow, Color.Gray, iFactor);

                        // Matrix.RotationX((float)Math.PI/2.0f) * M
                        sphereMesh.Parameters.Set(
                            TransformationKeys.World,
                            Matrix.Translation(
                                new Vector3(
                                    (ix - sizeX / 2) * (size * 1.2f) * 2.0f,
                                    (iy - sizeY / 2) * (size * 1.2f) * 2.0f,
                                    (float)(2000 * (0.5 + 0.5 * Math.Sin(clock.ElapsedMilliseconds / 1000.0f * sphere.Speed * 0.5f + Math.PI * sphere.Phase))))));
                        sphereMesh.Parameters.Set(MaterialKeys.SpecularPower, iFactor * 0.9f);
                        sphereMesh.Parameters.Set(MaterialKeys.SpecularColor, specularColor);
                    }
                }

                time = clock.ElapsedMilliseconds / 1000.0f;

                if (lightInfo.Length > 0)
                {
                    int index = 0;
                    foreach (var mesh in effectLight.Meshes)
                    {
                        mesh.Parameters.Set(LightKeys.LightPosition, new Vector3(lightInfo[index].Radius * (float)Math.Cos(-time * 0.17f + lightInfo[index].Phase), lightInfo[index].Radius * (float)Math.Sin(-time * 0.05f + lightInfo[index].Phase), lightInfo[index].Z * (0.5f + 0.5f * (float)Math.Sin(-time * 0.1f + lightInfo[index].Phase * 2.0f))));
                        index++;
                    }
                }
            }
        }
Пример #16
0
        public static async Task SetupPostEffects(EngineContext engineContext)
        {
            var config = AppConfig.GetConfiguration <Config>("Script1");

            var renderingSetup = RenderingSetup.Singleton;

            renderingSetup.Initialize(engineContext);

            bool bloom = config.Bloom;
            bool fxaa  = config.FXAA;

            bool useHBAO             = false;
            bool doBlur              = true;
            bool mixAOWithColorImage = false;
            bool halfResAO           = true;

            var effectMeshGroup = new RenderPassListEnumerator();

            engineContext.RenderContext.RenderPassEnumerators.Add(effectMeshGroup);

            PostEffectPlugin postEffectPlugin;

            if (engineContext.DataContext.RenderPassPlugins.TryGetValueCast("PostEffectPlugin", out postEffectPlugin) &&
                (bloom || fxaa || useHBAO))
            {
                if (bloom)
                {
                    // Create various effects required by the bloom effect
                    EffectOld brightPassFilter = engineContext.RenderContext.BuildEffect("BrightPass")
                                                 .Using(new PostEffectShaderPlugin()
                    {
                        RenderPassPlugin = postEffectPlugin
                    })
                                                 .Using(new BasicShaderPlugin("ShadingTexturing"))
                                                 .Using(new BasicShaderPlugin("PostEffectBrightFilter"));

                    EffectOld blurEffect = engineContext.RenderContext.BuildEffect("Blur")
                                           .Using(new PostEffectShaderPlugin()
                    {
                        RenderPassPlugin = postEffectPlugin
                    })
                                           .Using(new BasicShaderPlugin("PostEffectBlur"));

                    EffectOld downsampleEffect = engineContext.RenderContext.BuildEffect("DownSample")
                                                 .Using(new PostEffectShaderPlugin()
                    {
                        RenderPassPlugin = postEffectPlugin
                    })
                                                 .Using(new BasicShaderPlugin("ShadingTexturing"));

                    EffectOld mixEffect = engineContext.RenderContext.BuildEffect("Mix")
                                          .Using(new PostEffectShaderPlugin()
                    {
                        RenderPassPlugin = postEffectPlugin
                    })
                                          .Using(new BasicShaderPlugin("ShadingTexturing"))
                                          .Using(new BasicShaderPlugin("PosteffectTexturing2"));

                    EffectOld fxaaEffect = engineContext.RenderContext.BuildEffect("Fxaa")
                                           .Using(new PostEffectShaderPlugin()
                    {
                        RenderPassPlugin = postEffectPlugin
                    })
                                           .Using(new BasicShaderPlugin("PostEffectFXAA.xksl"));


                    // Create post effect meshes: downsampling and blurs
                    int bloomLevels      = 6;
                    var downsampleMeshes = new EffectMesh[bloomLevels];
                    var lastBlurs        = new EffectMesh[bloomLevels];
                    for (int i = 0; i < bloomLevels; ++i)
                    {
                        downsampleMeshes[i] = new EffectMesh(i == 0 ? brightPassFilter : downsampleEffect, name: "Downsample " + i);
                        postEffectPlugin.AddEffectMesh(downsampleMeshes[i]);

                        // Blur effect
                        var blurQuadMesh = new EffectMesh[2];
                        for (int j = 0; j < 2; ++j)
                        {
                            blurQuadMesh[j] = new EffectMesh(blurEffect, name: string.Format("Blur level {0}:{1}", i, j));
                            blurQuadMesh[j].Parameters.Set(PostEffectBlurKeys.Coefficients, new[] { 0.30f, 0.20f, 0.20f, 0.15f, 0.15f });
                            var unit = j == 0 ? Vector2.UnitX : Vector2.UnitY;
                            blurQuadMesh[j].Parameters.Set(PostEffectBlurKeys.Offsets, new[] { Vector2.Zero, unit * -1.3862832f, unit * +1.3862832f, unit * -3.2534592f, unit * +3.2534592f });
                            postEffectPlugin.AddEffectMesh(blurQuadMesh[j]);
                        }
                        lastBlurs[i] = blurQuadMesh[1];
                        postEffectPlugin.AddLink(downsampleMeshes[i], RenderTargetKeys.RenderTarget, blurQuadMesh[0], TexturingKeys.Texture0, new TextureDescription {
                            Width = 1024 >> (i + 1), Height = 768 >> (i + 1), Format = PixelFormat.R8G8B8A8_UNorm
                        });
                        postEffectPlugin.AddLink(blurQuadMesh[0], RenderTargetKeys.RenderTarget, blurQuadMesh[1], TexturingKeys.Texture0);
                        if (i > 0)
                        {
                            postEffectPlugin.AddLink(downsampleMeshes[i - 1], RenderTargetKeys.RenderTarget, downsampleMeshes[i], TexturingKeys.Texture0);
                        }
                    }

                    // Create post effect meshes: mix
                    EffectMesh lastMix = null;
                    for (int i = 0; i < bloomLevels; ++i)
                    {
                        var mixMesh = new EffectMesh(mixEffect, name: "Mix " + (bloomLevels - 1 - i));
                        mixMesh.Parameters.Set(PostEffectKeys.MixCoefficients, (i < bloomLevels - 1) ? new[] { 0.10f, 0.90f } : new[] { 1.0f, 3.0f });
                        postEffectPlugin.AddEffectMesh(mixMesh);


                        if (i < bloomLevels - 1)
                        {
                            postEffectPlugin.AddLink(lastBlurs[bloomLevels - 2 - i], RenderTargetKeys.RenderTarget, mixMesh, TexturingKeys.Texture0);
                        }
                        postEffectPlugin.AddLink(lastMix ?? lastBlurs[bloomLevels - 1], RenderTargetKeys.RenderTarget, mixMesh, TexturingKeys.Texture2);

                        lastMix = mixMesh;
                    }

                    EffectMesh lastEffectMesh = lastMix;

                    //add fxaa?
                    if (fxaa)
                    {
                        var fxaaQuadMesh = new EffectMesh(fxaaEffect, name: "FXAA level");
                        postEffectPlugin.AddEffectMesh(fxaaQuadMesh);
                        postEffectPlugin.AddLink(lastMix, RenderTargetKeys.RenderTarget, fxaaQuadMesh, TexturingKeys.Texture0, new TextureDescription {
                            Width = 1024, Height = 768, Format = PixelFormat.R8G8B8A8_UNorm
                        });
                        lastEffectMesh = fxaaQuadMesh;
                    }

                    engineContext.RenderContext.GraphicsResizeContext.SetupResize((resizeContext) =>
                    {
                        var renderTarget = renderingSetup.MainTargetPlugin.RenderTarget;
                        //blurQuadMesh[0].Parameters.Set(TextureFeature.Texture0, renderTarget);
                        //blurQuadMesh[1].Parameters.Set(RenderTargetKeys.RenderTarget, renderTarget);
                        downsampleMeshes[0].Parameters.SetWithResize(resizeContext, TexturingKeys.Texture0, (Texture2D)renderTarget.Texture);
                        lastMix.Parameters.SetWithResize(resizeContext, TexturingKeys.Texture0, (Texture2D)renderTarget.Texture);
                        lastMix.Parameters.SetWithResize(resizeContext, RenderTargetKeys.RenderTarget, engineContext.RenderContext.RenderTarget);

                        lastEffectMesh.Parameters.SetWithResize(resizeContext, RenderTargetKeys.RenderTarget, engineContext.RenderContext.RenderTarget);
                    });
                }
                else if (fxaa)
                {
                    //fxaa effect setup (fxaa only, no bloom effect)
                    EffectOld fxaaEffect = engineContext.RenderContext.BuildEffect("Fxaa")
                                           .Using(new PostEffectShaderPlugin()
                    {
                        RenderPassPlugin = postEffectPlugin
                    })
                                           .Using(new BasicShaderPlugin("..\\..\\sources\\shaders\\posteffect_fxaa.xksl"));

                    var fxaaQuadMesh = new EffectMesh(fxaaEffect, name: "FXAA level");

                    fxaaQuadMesh.Parameters.Set(TexturingKeys.Texture0, (Texture2D)renderingSetup.MainTargetPlugin.RenderTarget.Texture);
                    fxaaQuadMesh.Parameters.Set(RenderTargetKeys.RenderTarget, engineContext.RenderContext.RenderTarget);
                    //fxaaQuadMesh.Parameters.Set(PostEffectFXAAKeys.FxaaQualitySubpix, 0);

                    postEffectPlugin.AddEffectMesh(fxaaQuadMesh);

                    //TODO, application will crashes if we resize or move the window!!
                }

                foreach (var mesh in postEffectPlugin.Meshes)
                {
                    effectMeshGroup.AddMesh(mesh);
                }

                //engineContext.RenderContext.RootRenderPass.AddPass(postEffectPlugin.RenderPass);

                engineContext.RenderContext.GraphicsResizeContext.SetupResize((resizeContext) =>
                {
                    // Link post effects (this will create intermediate surfaces)
                    postEffectPlugin.Resolve();
                });
            }
        }
Пример #17
0
        public override void Load()
        {
            base.Load();

            if (string.IsNullOrEmpty(StructureName) || StructureSize == 0)
                throw new InvalidOperationException("StructureName and StructureSize must be setup on ParticlePlugin");

            // Add passes to the render pass
            RenderPass.AddPass(updatePasses, copyPass, sortPass, renderPass);

            // Create effect to copy from particle buffer to sort buffer
            effectCopyToSortBuffer = this.EffectSystemOld.BuildEffect("CopyToSortBuffer").Using(
                new ComputeShaderPlugin(new ShaderClassSource("ParticleSortInitializer"), MaximumThreadPerGroup, 1, 1)
                    {
                        RenderPass = copyPass,
                        Macros = { new ShaderMacro("PARTICLE_STRUCT", StructureName) }
                    });
            effectCopyToSortBuffer.KeepAliveBy(ActiveObjects);
            effectCopyToSortBuffer.Parameters.AddSources(MainPlugin.ViewParameters);
            effectMeshCopyToSortBuffer = new EffectMesh(effectCopyToSortBuffer);

            // Clear the sort buffer
            copyPass.StartPass.AddFirst = (context) =>
                {
                    if (CapacityCount > 0)
                    {
                        // TODO handle progressive sorting
                        context.GraphicsDevice.ClearReadWrite(sortBuffer, new UInt4(0xFF7FFFFF)); // 0xFF7FFFFF = - float.MaxValue
                    }
                };

            // Create effect for bitonic sort 1 - pass 1
            effectBitonicSort1Pass1 = this.EffectSystemOld.BuildEffect("ParticleBitonicSort1-Pass1").Using(
                new ComputeShaderPlugin(new ShaderClassSource("ParticleBitonicSort1"), MaximumThreadPerGroup, 1, 1)
                {
                    RenderPass = bitonicSort1Pass1,
                    Macros = { new ShaderMacro("PARTICLE_STRUCT", StructureName),
                                new ShaderMacro("PARTICLE_SORT_PASS", 0)
                    }
                });
            effectBitonicSort1Pass1.KeepAliveBy(this);
            effectMeshSort1Pass1 = new EffectMesh(effectBitonicSort1Pass1);

            // Create effect for bitonic sort 1 - pass 2
            effectBitonicSort1Pass2 = this.EffectSystemOld.BuildEffect("ParticleBitonicSort1-Pass2").Using(
                new ComputeShaderPlugin(new ShaderClassSource("ParticleBitonicSort1"), MaximumThreadPerGroup, 1, 1)
                {
                    RenderPass = bitonicSort1Pass2,
                    Macros = { new ShaderMacro("PARTICLE_STRUCT", StructureName),
                                new ShaderMacro("PARTICLE_SORT_PASS", 1)
                    }
                });
            effectBitonicSort1Pass2.KeepAliveBy(this);
            effectMeshSort1Pass2 = new EffectMesh(effectBitonicSort1Pass2);

            // Creates Effect for bitonic sort 2
            var currentDepth = MaximumDepthLevel;
            for (int i = 0; i < bitonicSort2Passes.Length; i++)
            {
                var bitonicShader = new RenderPass(string.Format("Bitonic-{0}", currentDepth));
                bitonicSort2Passes[i] = bitonicShader;

                // Compile the new shader for this count
                effectBitonicSort2[i] = this.EffectSystemOld.BuildEffect("ParticleBitonicSort2-" + currentDepth).Using(
                    new ComputeShaderPlugin(new ShaderClassSource("ParticleBitonicSort2", currentDepth), MaximumThreadPerGroup, 1, 1)
                        {
                            RenderPass = bitonicShader,
                            Macros = { new ShaderMacro("PARTICLE_STRUCT", StructureName) }
                        });
                effectBitonicSort2[i].KeepAliveBy(this);

                currentDepth /= 2;
            }
            effectMeshBitonicSort2 = new EffectMesh[bitonicSort2Passes.Length];
            for (int i = 0; i < effectMeshBitonicSort2.Length; i++)
                effectMeshBitonicSort2[i] = new EffectMesh(effectBitonicSort2[i]);

            // Creates Effect for rendering
            EffectOld particleRenderEffect = this.EffectSystemOld.BuildEffect("ParticleRender")
                .Using(new StateShaderPlugin() { UseBlendState = true, UseDepthStencilState = true, RenderPass = renderPass })
                .Using(new BasicShaderPlugin(RenderShader)
                        {
                            RenderPass = renderPass,
                            Macros = { new ShaderMacro("PARTICLE_STRUCT", StructureName) }
                        });
            particleRenderEffect.KeepAliveBy(this);

            particleRenderEffect.Parameters.AddSources(this.Parameters);
            particleRenderEffect.Parameters.AddSources(MainPlugin.ViewParameters);
            particleRenderEffect.Parameters.Set(EffectPlugin.BlendStateKey, graphicsDeviceService.GraphicsDevice.BlendStates.AlphaBlend);
            particleRenderEffect.Parameters.Set(EffectPlugin.DepthStencilStateKey, MainTargetPlugin.DepthStencilState);
            particleRenderEffect.Parameters.Set(RenderTargetKeys.DepthStencilSource, MainTargetPlugin.DepthStencil.Texture);

            effectMeshRender = new EffectMesh(particleRenderEffect);

            effectMeshRender.Render += (context) =>
            {
                if (currentParticleCount > 0)
                {
                    context.GraphicsDevice.SetVertexArrayObject(null);
                    context.GraphicsDevice.SetViewport(MainTargetPlugin.Viewport);
                    //context.GraphicsDevice.SetRenderTargets(MainTargetPlugin.DepthStencil, 0, MainTargetPlugin.RenderTarget);
                    
                    context.GraphicsDevice.SetRenderTargets((MainTargetPlugin.DepthStencilReadOnly != null) ? MainTargetPlugin.DepthStencilReadOnly : MainTargetPlugin.DepthStencil, RenderTarget);

                    // TODO HANDLE dynamic count
                    //context.GraphicsDevice.Draw(PrimitiveType.PointList, CapacityCount);
                    context.GraphicsDevice.Draw(PrimitiveType.PointList, currentParticleCount);
                }
                //context.GraphicsDevice.SetRenderTargets(null, 0, new ITexture2D[] { null } );
            };

            if (OfflineCompilation)
                return;

            // Allocate global buffers at register time
            // Buffers can also be reallocated at runtime
            OnCapacityCountChange();

            // Add our local meshes to render RenderContext.RenderPassEnumerators
            RenderSystem.RenderPassEnumerators.Add(meshesToRender);

            // Register update per frame
            RenderSystem.GlobalPass.StartPass += OnFrameUpdate;

            // Register sort pass
            sortPass.EndPass.Set = ComputeBitonicSort;
        }
Пример #18
0
        public override void Load()
        {
            base.Load();

            if (string.IsNullOrEmpty(StructureName) || StructureSize == 0)
            {
                throw new InvalidOperationException("StructureName and StructureSize must be setup on ParticlePlugin");
            }

            // Add passes to the render pass
            RenderPass.AddPass(updatePasses, copyPass, sortPass, renderPass);

            // Create effect to copy from particle buffer to sort buffer
            effectCopyToSortBuffer = this.EffectSystemOld.BuildEffect("CopyToSortBuffer").Using(
                new ComputeShaderPlugin(new ShaderClassSource("ParticleSortInitializer"), MaximumThreadPerGroup, 1, 1)
            {
                RenderPass = copyPass,
                Macros     = { new ShaderMacro("PARTICLE_STRUCT", StructureName) }
            });
            effectCopyToSortBuffer.KeepAliveBy(ActiveObjects);
            effectCopyToSortBuffer.Parameters.AddSources(MainPlugin.ViewParameters);
            effectMeshCopyToSortBuffer = new EffectMesh(effectCopyToSortBuffer);

            // Clear the sort buffer
            copyPass.StartPass.AddFirst = (context) =>
            {
                if (CapacityCount > 0)
                {
                    // TODO handle progressive sorting
                    context.GraphicsDevice.ClearReadWrite(sortBuffer, new UInt4(0xFF7FFFFF));     // 0xFF7FFFFF = - float.MaxValue
                }
            };

            // Create effect for bitonic sort 1 - pass 1
            effectBitonicSort1Pass1 = this.EffectSystemOld.BuildEffect("ParticleBitonicSort1-Pass1").Using(
                new ComputeShaderPlugin(new ShaderClassSource("ParticleBitonicSort1"), MaximumThreadPerGroup, 1, 1)
            {
                RenderPass = bitonicSort1Pass1,
                Macros     = { new ShaderMacro("PARTICLE_STRUCT", StructureName),
                               new ShaderMacro("PARTICLE_SORT_PASS", 0) }
            });
            effectBitonicSort1Pass1.KeepAliveBy(this);
            effectMeshSort1Pass1 = new EffectMesh(effectBitonicSort1Pass1);

            // Create effect for bitonic sort 1 - pass 2
            effectBitonicSort1Pass2 = this.EffectSystemOld.BuildEffect("ParticleBitonicSort1-Pass2").Using(
                new ComputeShaderPlugin(new ShaderClassSource("ParticleBitonicSort1"), MaximumThreadPerGroup, 1, 1)
            {
                RenderPass = bitonicSort1Pass2,
                Macros     = { new ShaderMacro("PARTICLE_STRUCT", StructureName),
                               new ShaderMacro("PARTICLE_SORT_PASS", 1) }
            });
            effectBitonicSort1Pass2.KeepAliveBy(this);
            effectMeshSort1Pass2 = new EffectMesh(effectBitonicSort1Pass2);

            // Creates Effect for bitonic sort 2
            var currentDepth = MaximumDepthLevel;

            for (int i = 0; i < bitonicSort2Passes.Length; i++)
            {
                var bitonicShader = new RenderPass(string.Format("Bitonic-{0}", currentDepth));
                bitonicSort2Passes[i] = bitonicShader;

                // Compile the new shader for this count
                effectBitonicSort2[i] = this.EffectSystemOld.BuildEffect("ParticleBitonicSort2-" + currentDepth).Using(
                    new ComputeShaderPlugin(new ShaderClassSource("ParticleBitonicSort2", currentDepth), MaximumThreadPerGroup, 1, 1)
                {
                    RenderPass = bitonicShader,
                    Macros     = { new ShaderMacro("PARTICLE_STRUCT", StructureName) }
                });
                effectBitonicSort2[i].KeepAliveBy(this);

                currentDepth /= 2;
            }
            effectMeshBitonicSort2 = new EffectMesh[bitonicSort2Passes.Length];
            for (int i = 0; i < effectMeshBitonicSort2.Length; i++)
            {
                effectMeshBitonicSort2[i] = new EffectMesh(effectBitonicSort2[i]);
            }

            // Creates Effect for rendering
            EffectOld particleRenderEffect = this.EffectSystemOld.BuildEffect("ParticleRender")
                                             .Using(new StateShaderPlugin()
            {
                UseBlendState = true, UseDepthStencilState = true, RenderPass = renderPass
            })
                                             .Using(new BasicShaderPlugin(RenderShader)
            {
                RenderPass = renderPass,
                Macros     = { new ShaderMacro("PARTICLE_STRUCT", StructureName) }
            });

            particleRenderEffect.KeepAliveBy(this);

            particleRenderEffect.Parameters.AddSources(this.Parameters);
            particleRenderEffect.Parameters.AddSources(MainPlugin.ViewParameters);
            particleRenderEffect.Parameters.Set(EffectPlugin.BlendStateKey, graphicsDeviceService.GraphicsDevice.BlendStates.AlphaBlend);
            particleRenderEffect.Parameters.Set(EffectPlugin.DepthStencilStateKey, MainTargetPlugin.DepthStencilState);
            particleRenderEffect.Parameters.Set(RenderTargetKeys.DepthStencilSource, MainTargetPlugin.DepthStencil.Texture);

            effectMeshRender = new EffectMesh(particleRenderEffect);

            effectMeshRender.Render += (context) =>
            {
                if (currentParticleCount > 0)
                {
                    context.GraphicsDevice.SetVertexArrayObject(null);
                    context.GraphicsDevice.SetViewport(MainTargetPlugin.Viewport);
                    //context.GraphicsDevice.SetRenderTargets(MainTargetPlugin.DepthStencil, 0, MainTargetPlugin.RenderTarget);

                    context.GraphicsDevice.SetRenderTargets((MainTargetPlugin.DepthStencilReadOnly != null) ? MainTargetPlugin.DepthStencilReadOnly : MainTargetPlugin.DepthStencil, RenderTarget);

                    // TODO HANDLE dynamic count
                    //context.GraphicsDevice.Draw(PrimitiveType.PointList, CapacityCount);
                    context.GraphicsDevice.Draw(PrimitiveType.PointList, currentParticleCount);
                }
                //context.GraphicsDevice.SetRenderTargets(null, 0, new ITexture2D[] { null } );
            };

            if (OfflineCompilation)
            {
                return;
            }

            // Allocate global buffers at register time
            // Buffers can also be reallocated at runtime
            OnCapacityCountChange();

            // Add our local meshes to render RenderContext.RenderPassEnumerators
            RenderSystem.RenderPassEnumerators.Add(meshesToRender);

            // Register update per frame
            RenderSystem.GlobalPass.StartPass += OnFrameUpdate;

            // Register sort pass
            sortPass.EndPass.Set = ComputeBitonicSort;
        }
Пример #19
0
 public void DisposeEffects()
 {
     if (EffectUpdater != null)
     {
         EffectUpdater.Release();
         EffectUpdater = null;
     }
 }
Пример #20
0
        public static async Task Run(EngineContext engineContext)
        {
            var renderingSetup = RenderingSetup.Singleton;
            //engineContext.RenderContext.Register(renderingSetup.LightingPlugin);
            //renderingSetup.RegisterLighting(engineContext);

            var shadowMapPlugin = new LightingPlugin {
                MainPlugin = renderingSetup.MainPlugin, RenderPass = engineContext.DataContext.RenderPasses.TryGetValue("ShadowMapPass")
            };

            shadowMapPlugin.RenderContext = engineContext.RenderContext;

            var shadowMap1 = new ShadowMap(new DirectionalLight())
            {
                Level = CascadeShadowMapLevel.X1, ShadowMapSize = 1024, ShadowDistance = 2000.0f
            }
            .SetFilter(sm => new ShadowMapFilterDefault(sm));
            var shadowMap2 = new ShadowMap(new DirectionalLight())
            {
                Level = CascadeShadowMapLevel.X2, ShadowMapSize = 1024, ShadowDistance = 2000.0f
            }
            .SetFilter(sm => new ShadowMapFilterVsm(sm));

            shadowMapPlugin.AddShadowMap(shadowMap1);
            shadowMapPlugin.AddShadowMap(shadowMap2);

            shadowMap1.DirectionalLight.LightDirection = new Vector3(-1.0f, -1.0f, -1.0f);
            shadowMap1.DirectionalLight.LightColor     = new Color3(1.0f, 0.5f, 0.5f);
            shadowMap2.DirectionalLight.LightDirection = new Vector3(-1.0f, 1.0f, -1.0f);
            shadowMap2.DirectionalLight.LightColor     = new Color3(0.5f, 0.5f, 1.0f);

            engineContext.RenderContext.Register(shadowMapPlugin);

            EffectOld effect = engineContext.RenderContext.BuildEffect("Permutation")
                               .Using(new BasicShaderPlugin("ShaderBase")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin("TransformationWVP")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin(new ShaderMixinSource()
            {
                "NormalVSStream",
                "PositionVSStream",
                new ShaderComposition("albedoDiffuse", new ShaderClassSource("ComputeColorStream")),
                new ShaderComposition("albedoSpecular", new ShaderClassSource("ComputeColor")),                         // TODO: Default values!
                "BRDFDiffuseLambert",
                "BRDFSpecularBlinnPhong",
                "ShadingBase",
            })
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new LightingShaderPlugin()
            {
                RenderPassPlugin = shadowMapPlugin
            })
            ;

            var sphereMeshData = MeshDataHelper.CreateSphere(10.0f, 20, 20, Color.White);

            var effectMeshGroup = new RenderPassListEnumerator();

            engineContext.RenderContext.RenderPassEnumerators.Add(effectMeshGroup);

            int objectSqrtCount = 1;
            int meshCount       = objectSqrtCount * objectSqrtCount * objectSqrtCount;

            var shadowMapPermutation1 = new ShadowMapPermutationArray {
                ShadowMaps = { shadowMap1 }
            };
            var shadowMapPermutation2 = new ShadowMapPermutationArray {
                ShadowMaps = { shadowMap2 }
            };
            var shadowMapPermutation3 = new ShadowMapPermutationArray {
                ShadowMaps = { shadowMap1, shadowMap2 }
            };

            effect.Permutations.Set(ShadowMapPermutationArray.Key, shadowMapPermutation1);

            var groups2     = new[] { shadowMapPermutation1, shadowMapPermutation2, shadowMapPermutation3 };
            int groupIndex2 = 0;

            var effectMeshes = new List <EffectMesh>();

            for (int j = 0; j < meshCount; ++j)
            {
                var effectMesh = new EffectMesh(effect, sphereMeshData);
                effectMesh.KeepAliveBy(engineContext.SimpleComponentRegistry);

                effect.Permutations.Set(ShadowMapPermutationArray.Key, groups2[2]);

                var w2 = Matrix.Scaling(1.0f)
                         * Matrix.Translation(new Vector3(
                                                  (j % objectSqrtCount - objectSqrtCount / 2) * 30.0f - 30.0f,
                                                  (((j / objectSqrtCount) % objectSqrtCount) - objectSqrtCount / 2) * 30.0f - 30.0f,
                                                  (j / (objectSqrtCount * objectSqrtCount)) * 30.0f + 30.0f));

                effectMesh.Parameters.Set(TransformationKeys.World, w2);
                effectMeshes.Add(effectMesh);
            }

            var groundMesh = new EffectMesh(effect, MeshDataHelper.CreateBox(1000, 1000, 1, Color.White));

            groundMesh.KeepAliveBy(engineContext.SimpleComponentRegistry);
            effectMeshGroup.AddMesh(groundMesh);
            groundMesh.Parameters.Set(TransformationKeys.World, Matrix.Translation(0.0f, 0.0f, 0.0f));

            var groups     = new[] { new int[] { 0, 1 }, new int[] { 0 }, new int[] { 1 } };
            int groupIndex = 0;

            await TaskEx.Delay(1000);

            foreach (var effectMesh in effectMeshes)
            {
                effectMeshGroup.AddMesh(effectMesh);
            }

            while (true)
            {
                await engineContext.Scheduler.NextFrame();

                if (engineContext.InputManager.IsKeyPressed(Keys.F8))
                {
                    var permutation = new LightingPermutation {
                        LightBindings = { new Light() }
                    };
                    effect.Permutations.Set(LightingPermutation.Key, permutation);
                }
                if (engineContext.InputManager.IsKeyPressed(Keys.F9))
                {
                    effect.Permutations.Set(ShadowMapPermutationArray.Key, groups2[(groupIndex2++) % groups2.Length]);
                }
            }
        }
Пример #21
0
        public static async Task Run(EngineContext engineContext)
        {
            var renderingSetup = RenderingSetup.Singleton;

            renderingSetup.Initialize(engineContext);
            renderingSetup.RegisterLighting(engineContext);


#if PARADOX_YEBIS
            YebisPlugin yebisPlugin;
            if (engineContext.DataContext.RenderPassPlugins.TryGetValueCast("YebisPlugin", out yebisPlugin))
            {
                yebisPlugin.Glare.Enable     = true;
                yebisPlugin.ToneMap.Exposure = 1.0f;
                yebisPlugin.ToneMap.Gamma    = 2.2f;
            }
#endif

            EffectOld effect = engineContext.RenderContext.BuildEffect("SimpleCube")
                               .Using(new BasicShaderPlugin("ShaderBase")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin("TransformationWVP")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin("AlbedoSpecularBase")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin("AlbedoDiffuseBase")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin("NormalVSGBuffer")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin("SpecularPowerPerMesh")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin("PositionVSGBuffer")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin("BRDFDiffuseLambert")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin("BRDFSpecularBlinnPhong")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin(new ShaderMixinSource()
            {
                new ShaderComposition("albedoDiffuse", new ShaderClassSource("ComputeColorStream"))
            })
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin(new ShaderMixinSource()
            {
                new ShaderComposition("albedoSpecular", new ShaderClassSource("ComputeColorSynthetic"))
            })
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new GBufferShaderPlugin {
                RenderPassPlugin = (GBufferPlugin)engineContext.DataContext.RenderPassPlugins.TryGetValue("GBufferPlugin")
            })
                               .Using(new LightingShaderPlugin()
            {
                RenderPassPlugin = (LightingPlugin)engineContext.DataContext.RenderPassPlugins.TryGetValue("LightingPlugin")
            })
                               .Using(new BasicShaderPlugin("LightDirectionalShading")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
            ;

            var shadowMap1 = new ShadowMap(new DirectionalLight()
            {
                LightColor = new Color3(1.0f, 1.0f, 1.0f), LightDirection = new Vector3(1.0f, 1.0f, 1.0f)
            });
            effect.Permutations.Set(ShadowMapPermutationArray.Key, new ShadowMapPermutationArray {
                ShadowMaps = { shadowMap1 }
            });

            var r = new Random(0);


            VirtualFileSystem.MountFileSystem("/global_data", "..\\..\\deps\\data\\");
            VirtualFileSystem.MountFileSystem("/global_data2", "..\\..\\data\\");

            SkyBoxPlugin skyBoxPlugin;
            if (engineContext.DataContext.RenderPassPlugins.TryGetValueCast("SkyBoxPlugin", out skyBoxPlugin))
            {
                var skyBoxTexture = (Texture2D)await engineContext.AssetManager.LoadAsync <Texture>("/global_data/gdc_demo/bg/GDC2012_map_sky.dds");

                skyBoxPlugin.Texture = skyBoxTexture;
            }

            var effectMeshGroup = new RenderPassListEnumerator();
            engineContext.RenderContext.RenderPassEnumerators.Add(effectMeshGroup);

            var groundMesh = new EffectMesh(effect, MeshDataHelper.CreateBox(10000, 10000, 1, Color.White));
            groundMesh.KeepAliveBy(engineContext.SimpleComponentRegistry);
            effectMeshGroup.AddMesh(groundMesh);
            groundMesh.Parameters.Set(TransformationKeys.World, Matrix.Translation(new Vector3(0, 0, 0)));

            var meshData   = MeshDataHelper.CreateSphere(200, 30, 30, Color.Gray);
            var sphereMesh = new EffectMesh(effect, meshData);
            sphereMesh.Parameters.Set(TransformationKeys.World, Matrix.Translation(new Vector3(0, 0, 50)));
            sphereMesh.Parameters.Set(MaterialKeys.SpecularPower, 0f);
            sphereMesh.Parameters.Set(MaterialKeys.SpecularColor, Color.White);
            effectMeshGroup.AddMesh(sphereMesh);

            //while (true)
            //{
            //    await Scheduler.Current.WaitFrame();


            //    for (int iy = 0; iy < sizeY; iy++)
            //    {
            //        for (int ix = 0; ix < sizeX; ix++)
            //        {
            //            var iFactor = (float)(iy * sizeY + ix) / (sizeX * sizeY);

            //            var sphere = spheres[iy, ix];
            //            var sphereMesh = sphere.Mesh;
            //            var specularColor = R8G8B8A8.SmoothStep(R8G8B8A8.GreenYellow, R8G8B8A8.Gray, iFactor);

            //            // Matrix.RotationX((float)Math.PI/2.0f) * M
            //            sphereMesh.Parameters.Set(
            //                TransformationKeys.World,
            //                Matrix.Translation(
            //                    new R32G32B32_Float(
            //                        (ix - sizeX / 2) * (size * 1.2f) * 2.0f,
            //                        (iy - sizeY / 2) * (size * 1.2f) * 2.0f,
            //                        (float)(2000 * (0.5 + 0.5 * Math.Sin(clock.ElapsedMilliseconds / 1000.0f * sphere.Speed * 0.5f + Math.PI * sphere.Phase))))));
            //            sphereMesh.Parameters.Set(MaterialKeys.SpecularPower, iFactor * 0.9f);
            //            sphereMesh.Parameters.Set(MaterialKeys.SpecularColor, specularColor);
            //        }
            //    }

            //    time = clock.ElapsedMilliseconds / 1000.0f;

            //    if (lightInfo.Length > 0)
            //    {
            //        int index = 0;
            //        foreach (var mesh in effectLight.Meshes)
            //        {
            //            mesh.Parameters.Set(LightKeys.LightPosition, new R32G32B32_Float(lightInfo[index].Radius * (float)Math.Cos(-time * 0.17f + lightInfo[index].Phase), lightInfo[index].Radius * (float)Math.Sin(-time * 0.05f + lightInfo[index].Phase), lightInfo[index].Z * (0.5f + 0.5f * (float)Math.Sin(-time * 0.1f + lightInfo[index].Phase * 2.0f))));
            //            index++;
            //        }
            //    }
            //}
        }
Пример #22
0
        public override void Load()
        {
            base.Load();

            skyboxEffect = this.EffectSystemOld.BuildEffect("Skybox")
                           .Using(new StateShaderPlugin()
            {
                RenderPassPlugin = this, UseDepthStencilState = true
            })
                           .Using(new BasicShaderPlugin(
                                      new ShaderMixinSource()
            {
                Mixins = new List <ShaderClassSource>()
                {
                    new ShaderClassSource("SkyBox")
                },
                Compositions = new Dictionary <string, ShaderSource>()
                {
                    { "color", SkyBoxColor }
                }
            })
            {
                RenderPassPlugin = this
            })
                           .InstantiatePermutation();

            if (OfflineCompilation)
            {
                return;
            }

            Parameters.AddSources(MainPlugin.ViewParameters);

            var zBackgroundValue = MainTargetPlugin.ClearDepth;
            // Generates a quad for post effect rendering (should be utility function)
            var vertices = new[]
            {
                -1.0f, 1.0f, zBackgroundValue, 1.0f,
                1.0f, 1.0f, zBackgroundValue, 1.0f,
                -1.0f, -1.0f, zBackgroundValue, 1.0f,
                1.0f, -1.0f, zBackgroundValue, 1.0f,
            };

            Parameters.RegisterParameter(EffectPlugin.DepthStencilStateKey);
            Parameters.Set(TexturingKeys.Sampler, GraphicsDevice.SamplerStates.LinearWrap);

            // Use the quad for this effectMesh
            var quadData = new Mesh();

            quadData.Draw = new MeshDraw
            {
                DrawCount     = 4,
                PrimitiveType = PrimitiveType.TriangleStrip,
                VertexBuffers = new[]
                {
                    new VertexBufferBinding(Buffer.Vertex.New(GraphicsDevice, vertices), new VertexDeclaration(VertexElement.Position <Vector4>()), 4)
                }
            };

            RenderPass.StartPass += (context) =>
            {
                // Setup the Viewport
                context.GraphicsDevice.SetViewport(MainTargetPlugin.Viewport);

                // Setup the depth stencil and main render target.
                context.GraphicsDevice.SetRenderTarget(MainTargetPlugin.DepthStencil, MainTargetPlugin.RenderTarget);
            };

            RenderPass.EndPass += (context) => context.GraphicsDevice.UnsetRenderTargets();

            var skyboxMesh = new EffectMesh(skyboxEffect, quadData).KeepAliveBy(this);

            // If the main target plugin is not clearing anything, we assume that this is the job of the skybox plugin
            if (!MainTargetPlugin.EnableClearTarget && !MainTargetPlugin.EnableClearDepth)
            {
                var description = new DepthStencilStateDescription().Default();
                description.DepthBufferFunction = CompareFunction.Always;
                var alwaysWrite = DepthStencilState.New(GraphicsDevice, description);
                skyboxMesh.Parameters.Set(EffectPlugin.DepthStencilStateKey, alwaysWrite);
            }
            else
            {
                skyboxMesh.Parameters.Set(EffectPlugin.DepthStencilStateKey, MainTargetPlugin.DepthStencilState);
            }

            skyboxMesh.Parameters.AddSources(this.Parameters);
            RenderSystem.GlobalMeshes.AddMesh(skyboxMesh);
        }
Пример #23
0
        public override void Load()
        {
            base.Load();

            skyboxEffect = this.EffectSystemOld.BuildEffect("Skybox")
                .Using(new StateShaderPlugin() { RenderPassPlugin = this, UseDepthStencilState = true })
                .Using(new BasicShaderPlugin(
                    new ShaderMixinSource() {
                        Mixins = new List<ShaderClassSource>() { new ShaderClassSource("SkyBox")},
                        Compositions = new Dictionary<string, ShaderSource>() { {"color", SkyBoxColor}}
                    }) { RenderPassPlugin = this })
                .InstantiatePermutation();

            if (OfflineCompilation)
                return;

            Parameters.AddSources(MainPlugin.ViewParameters);

            var zBackgroundValue = MainTargetPlugin.ClearDepth;
            // Generates a quad for post effect rendering (should be utility function)
            var vertices = new[]
                {
                    -1.0f, 1.0f, zBackgroundValue, 1.0f, 
                    1.0f, 1.0f, zBackgroundValue, 1.0f, 
                    -1.0f, -1.0f, zBackgroundValue, 1.0f,  
                    1.0f, -1.0f, zBackgroundValue, 1.0f, 
                };

            Parameters.RegisterParameter(EffectPlugin.DepthStencilStateKey);
            Parameters.Set(TexturingKeys.Sampler, GraphicsDevice.SamplerStates.LinearWrap);

            // Use the quad for this effectMesh
            var quadData = new Mesh();
            quadData.Draw = new MeshDraw
                {
                    DrawCount = 4,
                    PrimitiveType = PrimitiveType.TriangleStrip,
                    VertexBuffers = new[]
                                {
                                    new VertexBufferBinding(Buffer.Vertex.New(GraphicsDevice, vertices), new VertexDeclaration(VertexElement.Position<Vector4>()), 4)
                                }
                };

            RenderPass.StartPass += (context) =>
                {
                    // Setup the Viewport
                    context.GraphicsDevice.SetViewport(MainTargetPlugin.Viewport);

                    // Setup the depth stencil and main render target.
                    context.GraphicsDevice.SetRenderTarget(MainTargetPlugin.DepthStencil, MainTargetPlugin.RenderTarget);
                };

            RenderPass.EndPass += (context) => context.GraphicsDevice.UnsetRenderTargets();

            var skyboxMesh = new EffectMesh(skyboxEffect, quadData).KeepAliveBy(this);
            // If the main target plugin is not clearing anything, we assume that this is the job of the skybox plugin
            if (!MainTargetPlugin.EnableClearTarget && !MainTargetPlugin.EnableClearDepth)
            {
                var description = new DepthStencilStateDescription().Default();
                description.DepthBufferFunction = CompareFunction.Always;
                var alwaysWrite = DepthStencilState.New(GraphicsDevice, description);
                skyboxMesh.Parameters.Set(EffectPlugin.DepthStencilStateKey, alwaysWrite);
            }
            else
            {
                skyboxMesh.Parameters.Set(EffectPlugin.DepthStencilStateKey, MainTargetPlugin.DepthStencilState);
            }

            skyboxMesh.Parameters.AddSources(this.Parameters);
            RenderSystem.GlobalMeshes.AddMesh(skyboxMesh);
        }
Пример #24
0
        public override void Load()
        {
            base.Load();

            slideShowEffect = this.EffectSystemOld.BuildEffect("SlideShow")
                .Using(new StateShaderPlugin() { RenderPassPlugin = this, UseDepthStencilState = true})
                .Using(new BasicShaderPlugin(new ShaderClassSource("PostEffectTransition")) { RenderPassPlugin = this })
                .InstantiatePermutation();

            if (OfflineCompilation)
                return;

            RenderPass.StartPass += (context) =>
                {
                    if (RenderPass.Enabled)
                    {
                        // Setup the Viewport
                        context.GraphicsDevice.SetViewport(MainTargetPlugin.Viewport);

                        // Setup the depth stencil and main render target.
                        context.GraphicsDevice.SetRenderTarget(RenderTarget);
                    }
                };

            RenderPass.EndPass += (context) =>
                {
                    if (RenderPass.Enabled)
                    {
                        context.GraphicsDevice.UnsetRenderTargets();
                    }
                };

            // Generates a quad for post effect rendering (should be utility function)
            var vertices = new[]
            {
                -1.0f,  1.0f, 
                 1.0f,  1.0f,
                -1.0f, -1.0f, 
                 1.0f, -1.0f,
            };

            // Use the quad for this effectMesh
            var quadData = new Mesh();
            quadData.Draw = new MeshDraw
            {
                DrawCount = 4,
                PrimitiveType = PrimitiveType.TriangleStrip,
                VertexBuffers = new[]
                            {
                                new VertexBufferBinding(Buffer.Vertex.New(GraphicsDevice, vertices), new VertexDeclaration(VertexElement.Position<Vector2>()), 4)
                            }
            };
            var textureMesh = new EffectMesh(slideShowEffect, quadData).KeepAliveBy(this);
            textureMesh.Parameters.Set(EffectPlugin.DepthStencilStateKey, GraphicsDevice.DepthStencilStates.None);

            textureMesh.Parameters.AddSources(this.Parameters);
            RenderSystem.GlobalMeshes.AddMesh(textureMesh);
        }
Пример #25
0
        public static async Task MoveLights(EngineContext engineContext)
        {
            var r = new Random(0);

            var config = AppConfig.GetConfiguration <Config>("LightScript2");

            LightingPrepassPlugin lightingPrepassPlugin;

            if (!engineContext.DataContext.RenderPassPlugins.TryGetValueCast("LightingPrepassPlugin", out lightingPrepassPlugin))
            {
                return;
            }

            var effectMeshGroup = new RenderPassListEnumerator();

            engineContext.RenderContext.RenderPassEnumerators.Add(effectMeshGroup);

            // Lights
            for (int i = 0; i < 1024; ++i)
            {
                var effectMesh = new EffectMesh(lightingPrepassPlugin.Lights);

                Color3 color = (Color3)Color.White;
                switch (i % 7)
                {
                case 0: color = new Color3(0.7f, 0.0f, 0.0f); break;

                case 1: color = new Color3(0.0f, 0.7f, 0.0f); break;

                case 2: color = new Color3(0.0f, 0.0f, 0.7f); break;

                case 3: color = new Color3(0.7f, 0.7f, 0.0f); break;

                case 4: color = new Color3(0.7f, 0.0f, 0.7f); break;

                case 5: color = new Color3(0.0f, 0.7f, 0.7f); break;

                case 6: color = new Color3(0.7f, 0.7f, 0.7f); break;
                }
                effectMesh.Parameters.Set(LightKeys.LightRadius, 60.0f);
                effectMesh.Parameters.Set(LightKeys.LightColor, color);
                effectMesh.Parameters.Set(LightKeys.LightIntensity, 1.0f);
                effectMesh.KeepAliveBy(engineContext.SimpleComponentRegistry);

                effectMeshGroup.AddMesh(effectMesh);
            }

            bool animatedLights = config.AnimatedLights;

            EffectOld effectLight = null;

            try
            {
                effectLight = engineContext.RenderContext.RenderPassPlugins.OfType <LightingPrepassPlugin>().FirstOrDefault().Lights;
            }
            catch
            {
                return;
            }

            var lightInfo = new LightInfo[effectLight != null ? effectLight.Meshes.Count : 0];

            for (int i = 0; i < lightInfo.Length; ++i)
            {
                lightInfo[i].Radius = (float)r.NextDouble() * 1000.0f + 500.0f;
                lightInfo[i].Phase  = (float)r.NextDouble() * 10.0f;
                lightInfo[i].Z      = (float)r.NextDouble() * 150.0f + 150.0f;
            }
            float time          = 0.0f;
            var   st            = new Stopwatch();
            var   lastTickCount = 0;

            var st2 = new Stopwatch();

            st2.Start();

            bool firstTime = true;

            while (true)
            {
                await Scheduler.NextFrame();

                time += 0.003f;

                if (lightInfo.Length > 0)
                {
                    if (animatedLights || firstTime)
                    {
                        int index = 0;
                        foreach (var mesh in effectLight.Meshes)
                        {
                            mesh.Parameters.Set(LightKeys.LightPosition, new Vector3(lightInfo[index].Radius * (float)Math.Cos(time * 3.0f + lightInfo[index].Phase), lightInfo[index].Radius * (float)Math.Sin(time * 3.0f + lightInfo[index].Phase), lightInfo[index].Z));
                            index++;
                        }

                        firstTime = false;
                    }
                }
            }
        }
Пример #26
0
        public override void Load()
        {
            base.Load();

            var postEffectsPlugin = new PostEffectGraphPlugin("PostEffectPlugin")
            {
                RenderPass = RenderPass
            };
            EffectOld hbaoEffect = this.EffectSystemOld.BuildEffect("HBAO")
                                   .Using(new PostEffectShaderPlugin()
            {
                RenderPassPlugin = postEffectsPlugin
            })
                                   .Using(new BasicShaderPlugin(new ShaderClassSource("PostEffectHBAO")
            {
                GenericArguments = new object[] { UseNormal ? 1 : 0, (int)Quality }
            }))
                                   .KeepAliveBy(ActiveObjects)
                                   .InstantiatePermutation()
                                   .KeepAliveBy(ActiveObjects);

            // Parameters.AddSources(MainPlugin.ViewParameters);

            if (OfflineCompilation)
            {
                return;
            }

            var colorTexture = (Texture2D)GBufferPlugin.MainTargetPlugin.RenderTarget.Texture;

            bool doBlur    = true;
            bool halfResAO = false;

            //=================================================
            //Add hbao pass
            //==========================================
            //HBAO params
            int HBAO_numDir = 16; //TODO: should we recreate the random texture if we change this parameter?

            //==========================================
            //Create random texture
            var rng = new Random(0);

            Vector3[] tab = new Vector3[64 * 64];
            for (int i = 0; i < 64 * 64; i++)
            {
                float   angle  = (float)(2.0 * Math.PI * rng.NextDouble()) / (float)HBAO_numDir;
                Vector3 sample = new Vector3(
                    (float)Math.Cos(angle),
                    (float)Math.Sin(angle),
                    (float)rng.NextDouble()
                    );
                tab[i] = sample;
            }

            var randomTexture = Texture.New2D(GraphicsDevice, 64, 64, PixelFormat.R32G32B32_Float, tab);

            var hbaoQuadMesh = new EffectMesh(hbaoEffect, name: "HBAO level").KeepAliveBy(ActiveObjects);

            //var renderTarget = renderingSetup.MainPlugin.RenderTarget;
            hbaoQuadMesh.Parameters.Set(PostEffectHBAOKeys.RandomTexture, randomTexture);
            hbaoQuadMesh.Parameters.Set(PostEffectHBAOKeys.CountDirection, CountDirection);
            hbaoQuadMesh.Parameters.Set(PostEffectHBAOKeys.CountStepMax, CountStepMax);
            hbaoQuadMesh.Parameters.Set(PostEffectHBAOKeys.Radius, Radius);
            hbaoQuadMesh.Parameters.Set(PostEffectHBAOKeys.Attenuation, Attenuation);
            hbaoQuadMesh.Parameters.Set(PostEffectHBAOKeys.AngleBias, AngleBias * (float)Math.PI / 180.0f);
            hbaoQuadMesh.Parameters.Set(PostEffectHBAOKeys.Contrast, Contrast);
            hbaoQuadMesh.Parameters.Set(PostEffectHBAOKeys.RenderTargetResolutionRatio, halfResAO ? 0.5f : 1.0f);
            hbaoQuadMesh.Parameters.Set(GBufferBaseKeys.GBufferTexture, GBufferPlugin.GBufferTexture);
            hbaoQuadMesh.Parameters.Set(RenderTargetKeys.DepthStencilSource, GBufferPlugin.DepthStencil.Texture);

            if (!doBlur)
            {
                var aoRenderTarget = Texture.New2D(GraphicsDevice, GraphicsDevice.BackBuffer.Width, GraphicsDevice.BackBuffer.Height, PixelFormat.R8_UNorm, TextureFlags.RenderTarget).ToRenderTarget().KeepAliveBy(ActiveObjects);
                aoRenderTarget.Name = "AOTexture";
                hbaoQuadMesh.Parameters.Set(RenderTargetKeys.RenderTarget, aoRenderTarget);
            }
            else
            {
                EffectOld hbaoBlurEffect = this.EffectSystemOld.BuildEffect("HBAO Blur")
                                           .Using(new PostEffectShaderPlugin()
                {
                    RenderPassPlugin = postEffectsPlugin
                })
                                           .Using(new BasicShaderPlugin("PostEffectHBAOBlur"))
                                           .InstantiatePermutation();

                //=====================================================================
                //BlurX
                EffectMesh hbaoBlurQuadMeshX = new EffectMesh(hbaoBlurEffect, name: "HBAO Blur X level");
                hbaoBlurQuadMeshX.Parameters.Set(PostEffectHBAOBlurKeys.BlurDirection, new Vector2(1, 0));
                hbaoBlurQuadMeshX.Parameters.Set(PostEffectHBAOBlurKeys.BlurRadius, BlurRadius);
                hbaoBlurQuadMeshX.Parameters.Set(PostEffectHBAOBlurKeys.BlurSharpness, BlurSharpness);
                hbaoBlurQuadMeshX.Parameters.Set(PostEffectHBAOBlurKeys.ColorTexture, colorTexture);
                hbaoBlurQuadMeshX.Parameters.Set(PostEffectHBAOBlurKeys.MultiplyResultWithColorTarget, false);
                hbaoBlurQuadMeshX.Parameters.Set(RenderTargetKeys.DepthStencilSource, GBufferPlugin.DepthStencil.Texture);

                //TODO: check the format (RGB 8 bits, or Float or half-float?)
                //TODO: check the resolution (can be half!), must update PostEffectSSDOKeys uniforms!
                var backBuffer = GraphicsDevice.BackBuffer;
                postEffectsPlugin.AddLink(
                    hbaoQuadMesh,
                    RenderTargetKeys.RenderTarget,
                    hbaoBlurQuadMeshX,
                    PostEffectHBAOBlurKeys.AmbiantOcclusionTexture,
                    new TextureDescription()
                {
                    Width = backBuffer.Width >> (halfResAO ? 1 : 0), Height = backBuffer.Height >> (halfResAO ? 1 : 0), Format = PixelFormat.R8_UNorm
                });
                //hbaoBlurQuadMeshX.Parameters.Set(RenderTargetKeys.RenderTarget, engineContext.RenderContext.RenderTarget);

                //=====================================================================
                //BlurY
                EffectMesh hbaoBlurQuadMeshY = new EffectMesh(hbaoBlurEffect, name: "HBAO Blur Y level");
                hbaoBlurQuadMeshY.Parameters.Set(PostEffectHBAOBlurKeys.BlurDirection, new Vector2(0, 1));
                hbaoBlurQuadMeshY.Parameters.Set(PostEffectHBAOBlurKeys.BlurRadius, BlurRadius);
                hbaoBlurQuadMeshY.Parameters.Set(PostEffectHBAOBlurKeys.BlurSharpness, BlurSharpness);
                hbaoBlurQuadMeshY.Parameters.Set(PostEffectHBAOBlurKeys.ColorTexture, colorTexture);
                hbaoBlurQuadMeshY.Parameters.Set(PostEffectHBAOBlurKeys.MultiplyResultWithColorTarget, !Debug);
                hbaoBlurQuadMeshY.Parameters.Set(RenderTargetKeys.DepthStencilSource, GBufferPlugin.DepthStencil.Texture);

                //TODO: check the format (RGB 8 bits, or Float or half-float?)
                //TODO: check the resolution (can be half!), must update PostEffectSSDOKeys uniforms!
                postEffectsPlugin.AddLink(
                    hbaoBlurQuadMeshX,
                    RenderTargetKeys.RenderTarget,
                    hbaoBlurQuadMeshY,
                    PostEffectHBAOBlurKeys.AmbiantOcclusionTexture,
                    new TextureDescription {
                    Width = backBuffer.Width, Height = backBuffer.Height, Format = PixelFormat.R8_UNorm
                });

                hbaoBlurQuadMeshY.Parameters.Set(RenderTargetKeys.RenderTarget, RenderTarget);
            }

            var effectMeshGroup = new RenderPassListEnumerator();

            foreach (var mesh in postEffectsPlugin.Meshes)
            {
                RenderSystem.GlobalMeshes.AddMesh(mesh);
            }

            // Link post effects (this will create intermediate surfaces)
            postEffectsPlugin.Resolve();
        }
Пример #27
0
 private void SetupMeshResources(EffectOld effect, EffectMesh effectMesh)
 {
     effectMesh.Parameters.Set(DepthStencilStateKey, RenderPassPlugin.DepthStencilStateZReadOnly);
 }
Пример #28
0
        public override void Load()
        {
            base.Load();

            RenderPass.AddPass(boundingBoxPass, heatShimmerPass, heatShimmerComposePass);

            // Use MinMax Plugin
            var bbRenderTargetPlugin = new RenderTargetsPlugin("BoundingBoxRenderTargetPlugin")
            {
                EnableSetTargets  = true,
                EnableClearTarget = true,
                RenderTarget      = null,
                RenderPass        = boundingBoxPass,
                Services          = Services
            };

            bbRenderTargetPlugin.Apply();

            Parameters.AddSources(ViewParameters);
            Parameters.SetDefault(RenderTargetKeys.DepthStencilSource);
            Parameters.SetDefault(TexturingKeys.Sampler);
            bbRenderTargetPlugin.Parameters.AddSources(Parameters);

            EffectOld minMaxEffect = this.EffectSystemOld.BuildEffect("MinMax")
                                     .Using(new MinMaxShaderPlugin("MinMaxShaderPlugin")
            {
                RenderPassPlugin = bbRenderTargetPlugin
            })
                                     .Using(new BasicShaderPlugin("TransformationWVP")
            {
                RenderPassPlugin = bbRenderTargetPlugin
            })
                                     .KeepAliveBy(ActiveObjects)
                                     .InstantiatePermutation()
                                     .KeepAliveBy(ActiveObjects);

            heatShimmerPass.Parameters = new ParameterCollection();
            heatShimmerPass.Parameters.AddSources(Parameters);
            heatShimmerPass.Parameters.AddSources(NoisePlugin.Parameters);

            EffectOld heatShimmerEffect = this.EffectSystemOld.BuildEffect("HeatShimmer")
                                          .Using(new PostEffectSeparateShaderPlugin()
            {
                RenderPass = heatShimmerPass
            })
                                          .Using(
                new BasicShaderPlugin(
                    new ShaderMixinSource()
            {
                Mixins = new List <ShaderClassSource>()
                {
                    // TODO add support for IsZReverse
                    //new ShaderClassSource("PostEffectHeatShimmer", Debug ? 1 : 0, effectSystemOld.IsZReverse ? 1 : 0, 3),
                    new ShaderClassSource("PostEffectHeatShimmer", Debug ? 1 : 0, false ? 1 : 0, 3)
                },
                Compositions = new Dictionary <string, ShaderSource>()
                {
                    { "NoiseSource", new ShaderClassSource("SimplexNoise") }
                },
            }
                    )
            {
                RenderPass = heatShimmerPass
            })
                                          .KeepAliveBy(ActiveObjects)
                                          .InstantiatePermutation()
                                          .KeepAliveBy(ActiveObjects);

            EffectOld heatShimmerDisplayEffect = this.EffectSystemOld.BuildEffect("HeatShimmer")
                                                 .Using(new PostEffectSeparateShaderPlugin()
            {
                RenderPass = heatShimmerComposePass
            })
                                                 .Using(new BasicShaderPlugin(new ShaderClassSource("PostEffectHeatShimmerDisplay", Debug ? 1 : 0))
            {
                RenderPass = heatShimmerComposePass
            })
                                                 .KeepAliveBy(ActiveObjects)
                                                 .InstantiatePermutation()
                                                 .KeepAliveBy(ActiveObjects);

            if (OfflineCompilation)
            {
                return;
            }

            Parameters.Set(RenderTargetKeys.DepthStencilSource, DepthStencil.Texture);
            Parameters.Set(TexturingKeys.Sampler, GraphicsDevice.SamplerStates.PointClamp);

            // ------------------------------------------
            // BoundingBox prepass
            // ------------------------------------------
            var renderTargetDesc = RenderSource.Description;
            var bbRenderTarget   = Texture.New2D(GraphicsDevice, renderTargetDesc.Width, renderTargetDesc.Height, PixelFormat.R32G32_Float, TextureFlags.ShaderResource | TextureFlags.RenderTarget).KeepAliveBy(ActiveObjects);

            bbRenderTargetPlugin.RenderTarget = bbRenderTarget.ToRenderTarget();

            // Add meshes
            foreach (var bbMeshData in BoundingBoxes)
            {
                // Mesh for MinPass
                var bbMesh = new EffectMesh(minMaxEffect, bbMeshData).KeepAliveBy(ActiveObjects);
                // Add mesh
                // boundingBoxPass.AddPass(bbMesh.EffectMeshPasses[0].EffectPass);
                effectMeshes.Add(bbMesh);
                RenderSystem.GlobalMeshes.AddMesh(bbMesh);
            }

            // ------------------------------------------
            // Heat Compute
            // ------------------------------------------
            var shimmerTexture      = Texture.New2D(GraphicsDevice, renderTargetDesc.Width, renderTargetDesc.Height, PixelFormat.R8_UNorm, TextureFlags.ShaderResource | TextureFlags.RenderTarget);
            var shimmerRenderTarget = shimmerTexture.ToRenderTarget();

            heatShimmerPass.StartPass += context => context.GraphicsDevice.Clear(shimmerRenderTarget, Color.Black);

            var quadMesh = new EffectMesh(heatShimmerEffect).KeepAliveBy(ActiveObjects);

            quadMesh.Parameters.Set(TexturingKeys.Texture1, bbRenderTarget);
            quadMesh.Parameters.Set(RenderTargetKeys.RenderTarget, shimmerRenderTarget);

            effectMeshes.Add(quadMesh);
            RenderSystem.GlobalMeshes.AddMesh(quadMesh);

            // ------------------------------------------
            // Heat display
            // ------------------------------------------
            quadMesh = new EffectMesh(heatShimmerDisplayEffect).KeepAliveBy(ActiveObjects);
            quadMesh.Parameters.Set(TexturingKeys.Texture0, RenderSource);
            quadMesh.Parameters.Set(TexturingKeys.Texture1, shimmerTexture);
            quadMesh.Parameters.Set(RenderTargetKeys.RenderTarget, RenderTarget);

            effectMeshes.Add(quadMesh);
            RenderSystem.GlobalMeshes.AddMesh(quadMesh);
        }
Пример #29
0
        public override void Load()
        {
            base.Load();

            slideShowEffect = this.EffectSystemOld.BuildEffect("SlideShow")
                              .Using(new StateShaderPlugin()
            {
                RenderPassPlugin = this, UseDepthStencilState = true
            })
                              .Using(new BasicShaderPlugin(new ShaderClassSource("PostEffectTransition"))
            {
                RenderPassPlugin = this
            })
                              .InstantiatePermutation();

            if (OfflineCompilation)
            {
                return;
            }

            RenderPass.StartPass += (context) =>
            {
                if (RenderPass.Enabled)
                {
                    // Setup the Viewport
                    context.GraphicsDevice.SetViewport(MainTargetPlugin.Viewport);

                    // Setup the depth stencil and main render target.
                    context.GraphicsDevice.SetRenderTarget(RenderTarget);
                }
            };

            RenderPass.EndPass += (context) =>
            {
                if (RenderPass.Enabled)
                {
                    context.GraphicsDevice.UnsetRenderTargets();
                }
            };

            // Generates a quad for post effect rendering (should be utility function)
            var vertices = new[]
            {
                -1.0f, 1.0f,
                1.0f, 1.0f,
                -1.0f, -1.0f,
                1.0f, -1.0f,
            };

            // Use the quad for this effectMesh
            var quadData = new Mesh();

            quadData.Draw = new MeshDraw
            {
                DrawCount     = 4,
                PrimitiveType = PrimitiveType.TriangleStrip,
                VertexBuffers = new[]
                {
                    new VertexBufferBinding(Buffer.Vertex.New(GraphicsDevice, vertices), new VertexDeclaration(VertexElement.Position <Vector2>()), 4)
                }
            };
            var textureMesh = new EffectMesh(slideShowEffect, quadData).KeepAliveBy(this);

            textureMesh.Parameters.Set(EffectPlugin.DepthStencilStateKey, GraphicsDevice.DepthStencilStates.None);

            textureMesh.Parameters.AddSources(this.Parameters);
            RenderSystem.GlobalMeshes.AddMesh(textureMesh);
        }