public override void SetupShaders(EffectMesh effectMesh) { var permutationKey = new MaterialShaderPluginPermutationKey(effectMesh.MeshData); // Determines the max number of bones from the currect graphics profile int defaultSkinningMaxBones = GraphicsDevice.Features.Profile <= GraphicsProfile.Level_9_3 ? 56 : 200; if (permutationKey.SkinningPosition) { DefaultShaderPass.Macros.Add(new ShaderMacro("SkinningMaxBones", defaultSkinningMaxBones)); BasicShaderPlugin.ApplyMixinClass(DefaultShaderPass.Shader, new ShaderClassSource("TransformationSkinning"), true); } if (permutationKey.SkinningNormal) { BasicShaderPlugin.ApplyMixinClass(DefaultShaderPass.Shader, new ShaderClassSource("NormalSkinning"), true); } if (permutationKey.SkinningTangent) { BasicShaderPlugin.ApplyMixinClass(DefaultShaderPass.Shader, new ShaderClassSource("TangentSkinning"), true); } if (permutationKey.AlbedoMaterial != null) { BasicShaderPlugin.ApplyMixinClass(DefaultShaderPass.Shader, permutationKey.AlbedoMaterial, true); } }
public override void SetupPasses(EffectMesh effectMesh) { Effect.Parameters.RegisterParameter(LightKeys.LightColor); Effect.Parameters.RegisterParameter(LightKeys.LightPosition); Effect.Parameters.RegisterParameter(LightKeys.LightIntensity); Effect.Parameters.RegisterParameter(LightKeys.LightRadius); }
public void AddMesh(EffectMesh mesh) { if (!graph.ContainsVertex(mesh)) { graph.AddVertex(mesh); } }
public override void SetupResources(EffectMesh effectMesh) { 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; // "LightPrePassAdditiveBlend" Effect.Parameters.Set(BlendStateKey, BlendState.New(GraphicsDevice, blendStateDesc)); if (Debug) { var rasterizer = RasterizerState.New(GraphicsDevice, new RasterizerStateDescription() { FillMode = FillMode.Wireframe }); rasterizer.Name = "LightPrePassWireFrame"; Effect.Parameters.Set(RasterizerStateKey, rasterizer); } Effect.PrepareMesh += SetupMeshResources; Effect.UpdateMeshData += UpdateMeshResources; }
public override void SetupPasses(EffectMesh effectMesh) { var parameters = RenderPass != null && RenderPass.Parameters != null ? RenderPass.Parameters : RenderPassPlugin != null ? RenderPassPlugin.Parameters : null; //DefaultShaderPass = CreateShaderPass(null, "PostEffect", parameters); throw new System.NotImplementedException(); }
/// <param name="effectMesh"></param> /// <inheritdoc/> /// <inheritdoc/> public override void SetupShaders(EffectMesh effectMesh) { // Create shader from base shader var postEffect = new ShaderClassSource("PostEffectBase"); DefaultShaderPass.Shader.Mixins.Add(postEffect); }
private static void SetupParticles(EngineContext engineContext) { // Create particle system var particleSystem = new SiliconStudio.Xenko.Particles.ParticleSystem(); // Set particle default size to 10.0f particleSystem.GetOrCreateFieldWithDefault(ParticleFields.Size, 10.0f); // Add particle plugins particleSystem.Plugins.Add(new ResetAcceleration()); particleSystem.Plugins.Add(new SimpleEmitter()); particleSystem.Plugins.Add(new RemoveOldParticles(10.0f)); particleSystem.Plugins.Add(new Gravity()); particleSystem.Plugins.Add(new UpdateVelocity()); // Create particle system mesh for rendering. var particleEffect = engineContext.RenderContext.Effects.First(x => x.Name == "DefaultParticle"); var particleMesh = new EffectMesh(particleEffect); particleMesh.Parameters.Set(ParticleRendererPlugin.ParticleSystemKey, particleSystem); // Load particle texture var smokeVolTexture = (Texture2D)engineContext.AssetManager.Load <Texture>("/global_data/gdc_demo/fx/smokevol.dds"); particleMesh.Parameters.Set(TexturingKeys.DiffuseTexture, smokeVolTexture); // Register it to rendering engineContext.RenderContext.GlobalMeshes.AddMesh(particleMesh); }
public override void SetupShaders(EffectMesh effectMesh) { // Duplicate the main shader throw new System.NotImplementedException(); EffectShaderPass mainShaderPass; //var mainShaderPass = FindShaderPassFromPlugin(RenderPassPlugin.MainTargetPlugin); DefaultShaderPass.Shader = (ShaderMixinSource)mainShaderPass.Shader.Clone(); DefaultShaderPass.Macros.AddRange(mainShaderPass.Macros); DefaultShaderPass.SubMeshDataKey = mainShaderPass.SubMeshDataKey; // G-Buffer construction // ExtractGBuffer: Extract POSITION + NORMAL DefaultShaderPass.Shader.Mixins.Add("GBuffer"); DefaultShaderPass.Shader.Mixins.Add("NormalVSStream"); mainShaderPass.Shader.Mixins.Remove("PositionVSStream"); mainShaderPass.Shader.Mixins.Remove("NormalVSStream"); mainShaderPass.Shader.Mixins.Add("NormalVSGBuffer"); mainShaderPass.Shader.Mixins.Add("SpecularPowerGBuffer"); mainShaderPass.Shader.Mixins.Add("PositionVSGBuffer"); // Apply Mixin if (Mixin != null) { BasicShaderPlugin.ApplyMixinClass(DefaultShaderPass.Shader, Mixin, true); } }
public override void SetupPasses(EffectMesh effectMesh) { Effect.Parameters.RegisterParameter(LightKeys.LightColor); Effect.Parameters.RegisterParameter(LightKeys.LightPosition); Effect.Parameters.RegisterParameter(LightKeys.LightIntensity); Effect.Parameters.RegisterParameter(LightKeys.LightRadius); }
public override void SetupResources(EffectMesh effectMesh) { if (effectMesh.MeshData.Material.Parameters.Get(EffectData.NeedAlphaBlending)) { effectMesh.Parameters.Set(BlendStateKey, GraphicsDevice.BlendStates.NonPremultiplied); } }
/// <param name="effectMesh"></param> /// <inheritdoc/> public override void SetupPasses(EffectMesh effectMesh) { // Special case: We have 2 shader passes that are sharing the same Shader, but with different parameters throw new System.NotImplementedException(); //maxPass = CreateShaderPass(RenderPassPlugin.RenderPass, "MaxPass", RenderPassPlugin.Parameters); //minPass = CreateShaderPass(RenderPassPlugin.RenderPass, "MinPass", RenderPassPlugin.Parameters); DefaultShaderPass = maxPass; }
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); } }
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); } }
public override void SetupShaders(EffectMesh effectMesh) { // Merge only this shader on the main throw new System.NotImplementedException(); EffectShaderPass mainShaderPass; //var mainShaderPass = FindShaderPassFromPlugin(RenderPassPlugin.GBufferPlugin.MainPlugin); mainShaderPass.Shader.Mixins.Add(new ShaderClassSource("LightDeferredShading")); }
public override void SetupShaders(EffectMesh effectMesh) { // Use the standard or debug shader var lightPrepassShader = new ShaderClassSource(string.Format("LightPrepass{0}", Debug ? "Debug" : string.Empty)); DefaultShaderPass.Shader.Mixins.Add(lightPrepassShader); DefaultShaderPass.Shader.Compositions.Add("DiffuseColor", new ShaderClassSource("ComputeBRDFColorFresnel")); DefaultShaderPass.Shader.Compositions.Add("DiffuseLighting", new ShaderClassSource("ComputeBRDFDiffuseLambert")); DefaultShaderPass.Shader.Compositions.Add("SpecularColor", new ShaderClassSource("ComputeBRDFColor")); DefaultShaderPass.Shader.Compositions.Add("SpecularLighting", new ShaderClassSource("ComputeBRDFColorSpecularBlinnPhong")); }
public override void SetupPasses(EffectMesh effectMesh) { var effectSystem = Services.GetSafeServiceAs <IEffectSystemOld>(); throw new NotImplementedException(); EffectShaderPass mainShaderPass; //DefaultShaderPass = FindShaderPassFromPlugin(MainTargetPlugin); //effectSystemOld.RegisterPermutation(DefaultShaderPass, this, ShadowMapPermutationArray.Key, SetupShadersPermutationReceiver); //effectSystemOld.RegisterPermutation(DefaultShaderPass, this, ShadowMapPermutationArray.Key, SetupShadersPermutationCaster); //effectSystemOld.RegisterPermutation(DefaultShaderPass, this, LightingPermutation.Key, SetupLighting); }
public override void SetupShaders(EffectMesh effectMesh) { // Duplicate the main shader throw new System.NotImplementedException(); EffectShaderPass mainShaderPass; //var mainShaderPass = FindShaderPassFromPlugin(MainPlugin); DefaultShaderPass.Shader = (ShaderMixinSource)mainShaderPass.Shader.Clone(); DefaultShaderPass.Macros.AddRange(mainShaderPass.Macros); DefaultShaderPass.SubMeshDataKey = mainShaderPass.SubMeshDataKey; BasicShaderPlugin.ApplyMixinClass(DefaultShaderPass.Shader, new ShaderClassSource("PickingRasterizer"), true); }
public void AddLink(EffectMesh source, ParameterKey <RenderTarget> sourceKey, EffectMesh target, ParameterKey <Texture> targetKey, TextureDescription?textureDescription = null) { if (!graph.ContainsVertex(source)) { graph.AddVertex(source); } if (!graph.ContainsVertex(target)) { graph.AddVertex(target); } graph.AddEdge(new PostEffectEdge(source, sourceKey, target, targetKey, textureDescription)); }
public override void SetupShaders(EffectMesh effectMesh) { // Duplicate the main shader throw new System.NotImplementedException(); EffectShaderPass mainShaderPass; //var mainShaderPass = FindShaderPassFromPlugin(MainTargetPlugin); DefaultShaderPass.Shader = (ShaderMixinSource)mainShaderPass.Shader.Clone(); DefaultShaderPass.Macros.AddRange(mainShaderPass.Macros); DefaultShaderPass.SubMeshDataKey = mainShaderPass.SubMeshDataKey; // Wireframe are white! var wireframeShader = new ShaderClassSource("Wireframe"); DefaultShaderPass.Shader.Mixins.Add(wireframeShader); }
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); }
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); } }; }
public override void SetupResources(EffectMesh effectMesh) { if (UseBlendState) { Effect.Parameters.RegisterParameter(BlendStateKey); } if (UseRasterizerState) { Effect.Parameters.RegisterParameter(RasterizerStateKey); } if (UseDepthStencilState) { Effect.Parameters.RegisterParameter(DepthStencilStateKey); } }
private static void InvokeMeshPass(EffectMesh mesh, ThreadContext context, bool skipEffectPass = false) { var effectPass = mesh.EffectPass; // Execute EffectPass - StartPass if (!skipEffectPass) { effectPass.StartPass.Invoke(context); } // Execute MeshPass - StartPass - EndPass context.EffectMesh = mesh; mesh.Render.Invoke(context); context.EffectMesh = null; // Execute EffectPass - EndPass if (!skipEffectPass) { effectPass.EndPass.Invoke(context); } }
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) } }; }
public override void SetupShaders(EffectMesh effectMesh) { var permutationKey = new TessellationPluginPermutationKey(effectMesh.MeshData); if (permutationKey != null && permutationKey.Tessellation != null) { int inputControlPointCount = 3; BasicShaderPlugin.ApplyMixinClass(DefaultShaderPass.Shader, permutationKey.Tessellation, true); // Apply Displacement AEN plugin if both AEN is available and displacement is active if (permutationKey.TessellationAEN) { BasicShaderPlugin.ApplyMixinClass(DefaultShaderPass.Shader, new ShaderClassSource("TessellationDisplacementAEN"), true); DefaultShaderPass.SubMeshDataKey = "TessellationAEN"; inputControlPointCount = 12; } DefaultShaderPass.Macros.Add(new ShaderMacro("InputControlPointCount", inputControlPointCount)); DefaultShaderPass.Macros.Add(new ShaderMacro("OutputControlPointCount", 3)); } }
public override void SetupResources(EffectMesh effectMesh) { base.SetupResources(effectMesh); throw new System.NotImplementedException(); EffectShaderPass effectShaderPass; //var effectShaderPass = FindShaderPassFromPlugin(RenderPassPlugin); var rasterizer = RasterizerState.New(GraphicsDevice, new RasterizerStateDescription(CullMode.None) { FillMode = FillMode.Wireframe, DepthBias = -1000 }); rasterizer.Name = "WireFrame"; effectShaderPass.Parameters.Set(RasterizerStateKey, rasterizer); var depthStencilState = DepthStencilState.New(GraphicsDevice, new DepthStencilStateDescription(true, false) { DepthBufferFunction = CompareFunction.LessEqual }); effectShaderPass.Parameters.Set(DepthStencilStateKey, depthStencilState); }
private Entity GetPickedEntity(EngineContext engineContext, EffectMesh pickedEffectMesh) { if (pickedEffectMesh == null) { return(null); } // Find Entity from EffectMesh var pickedEntity = pickedEffectMesh.Get(PickingPlugin.AssociatedEntity); if (pickedEntity == null) { // Iterate over both scene entities and editor entities (i.e. gizmo) var entities = engineContext.EntityManager.Entities.AsEnumerable(); if (editorEntitySystem != null) { entities = entities.Concat(editorEntitySystem.Entities); } foreach (var entity in entities) { var meshComponent = entity.Get(ModelComponent.Key); if (meshComponent == null) { continue; } if (!meshComponent.InstantiatedSubMeshes.Any(x => x.Value == pickedEffectMesh)) { continue; } pickedEntity = entity; break; } } return(pickedEntity); }
public override void SetupResources(EffectMesh effectMesh) { base.SetupResources(effectMesh); Effect.Parameters.RegisterParameter(BlendStateKey); Effect.Parameters.RegisterParameter(RasterizerStateKey); // Create blendstate for min calculation var bbBlendDesc = new BlendStateDescription(); bbBlendDesc.SetDefaults(); bbBlendDesc.AlphaToCoverageEnable = false; bbBlendDesc.IndependentBlendEnable = false; bbBlendDesc.RenderTargets[0].BlendEnable = true; bbBlendDesc.RenderTargets[0].ColorSourceBlend = Blend.One; bbBlendDesc.RenderTargets[0].ColorDestinationBlend = Blend.One; bbBlendDesc.RenderTargets[0].ColorBlendFunction = BlendFunction.Max; bbBlendDesc.RenderTargets[0].ColorWriteChannels = ColorWriteChannels.Red; var blendMinState = BlendState.New(GraphicsDevice, bbBlendDesc); blendMinState.Name = "MinBlend"; // Create blendstate for max calculation bbBlendDesc.RenderTargets[0].ColorBlendFunction = BlendFunction.Max; bbBlendDesc.RenderTargets[0].ColorWriteChannels = ColorWriteChannels.Green; var blendMaxState = BlendState.New(GraphicsDevice, bbBlendDesc); blendMaxState.Name = "MaxBlend"; maxPass.Parameters.Set(RasterizerStateKey, GraphicsDevice.RasterizerStates.CullFront); maxPass.Parameters.Set(BlendStateKey, blendMaxState); minPass.Parameters.Set(RasterizerStateKey, GraphicsDevice.RasterizerStates.CullBack); minPass.Parameters.Set(BlendStateKey, blendMinState); }
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); }
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(); }); } }
private static void SetupParticles(EngineContext engineContext) { // Create particle system var particleSystem = new SiliconStudio.Xenko.Particles.ParticleSystem(); // Set particle default size to 10.0f particleSystem.GetOrCreateFieldWithDefault(ParticleFields.Size, 10.0f); // Add particle plugins particleSystem.Plugins.Add(new ResetAcceleration()); particleSystem.Plugins.Add(new SimpleEmitter()); particleSystem.Plugins.Add(new RemoveOldParticles(10.0f)); particleSystem.Plugins.Add(new Gravity()); particleSystem.Plugins.Add(new UpdateVelocity()); // Create particle system mesh for rendering. var particleEffect = engineContext.RenderContext.Effects.First(x => x.Name == "DefaultParticle"); var particleMesh = new EffectMesh(particleEffect); particleMesh.Parameters.Set(ParticleRendererPlugin.ParticleSystemKey, particleSystem); // Load particle texture var smokeVolTexture = (Texture2D)engineContext.AssetManager.Load<Texture>("/global_data/gdc_demo/fx/smokevol.dds"); particleMesh.Parameters.Set(TexturingKeys.DiffuseTexture, smokeVolTexture); // Register it to rendering engineContext.RenderContext.GlobalMeshes.AddMesh(particleMesh); }
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); } }
public override void SetupPasses(EffectMesh effectMesh) { var parameters = RenderPass != null && RenderPass.Parameters != null ? RenderPass.Parameters : RenderPassPlugin != null ? RenderPassPlugin.Parameters : null; //DefaultShaderPass = CreateShaderPass(null, "PostEffect", parameters); throw new System.NotImplementedException(); }
static void Main(string[] args) { EngineContext.Setup(); EngineContext.RenderSystem = new DefaultRenderSystem(); EngineContext.RenderSystem.Init(EngineContext.RenderContext); var effect = EngineContext.RenderContext.BuildEffect().Using<RenderTargetFeature>().Using<TransformationFeature>().Using<TextureFeature>().Compile(); var vfs = new VirtualFileStorage(); vfs.MountFileSystem("/global_data", "..\\deps\\data\\"); vfs.MountFileSystem("/global_data2", "..\\data\\"); var packageVfs = vfs.MountPackage("/testpackage", "/global_data/factory3.dat").Result; var contentManager = new ContentManager(vfs, packageVfs); contentManager.RegisterSerializer(new SimpleContentSerializer<MeshData>()); contentManager.RegisterSerializer(new TextureSerializer()); contentManager.RegisterSerializer(new GpuTextureSerializer(EngineContext.RenderContext.GraphicsDevice)); var meshData = contentManager.Load<MeshData>("/testpackage/guid/" + packageVfs.Objects[2].Header.ObjectId.Guid); var effectMesh = new EffectMesh(effect, meshData); //effect.InstantiateMesh(effectMesh); //effect.UpdateMeshData(effectMesh, meshData); //effectMesh.AddRenderQueue(); var projectionMatrix = Matrix.PerspectiveFovLH((float)Math.PI * 0.5f, 1024.0f / 768.0f, 1.0f, 4000.0f); EngineContext.RenderContext.ParameterGroups.Get(TransformationFeature.TransformationGroup).SetAs(TransformationFeature.Projection, projectionMatrix); var factoryTexture = (ITexture2D)contentManager.Load<ITexture>("/global_data2/media/factory.png"); effectMesh.Parameters.Set(TextureFeature.Texture, factoryTexture); var world = Matrix.Scaling(0.1f) * Matrix.Translation(new Vector3(-30.0f, -30.0f, 0.0f)); effectMesh.Parameters.Set(TransformationFeature.World, world); var depth = EngineContext.RenderContext.GraphicsDevice.DepthStencilBuffer.New(DepthFormat.Depth32, EngineContext.RenderContext.Width, EngineContext.RenderContext.Height); EngineContext.RenderContext.ParameterGroups.GetGroup(RenderTargetFeature.Group).Set(RenderTargetFeature.RenderTarget, EngineContext.RenderContext.RenderTarget); EngineContext.RenderContext.ParameterGroups.GetGroup(RenderTargetFeature.Group).Set(RenderTargetFeature.DepthStencil, depth); float time = 0.0f; while (true) { var eyeVector = new Vector4(-800.0f * (float)Math.Cos(time), 800.0f * (float)Math.Sin(time), 500.0f, 1.0f); time += 0.0001f; var viewMatrix = Matrix.LookAtLH(new Vector3(eyeVector.X, eyeVector.Y, eyeVector.Z), new Vector3(0.0f, 0.0f, 50.0f), new Vector3(0.0f, 0.0f, 1.0f)); EngineContext.RenderContext.ParameterGroups.Get(TransformationFeature.TransformationGroup).SetAs(TransformationFeature.View, viewMatrix); Scheduler.Step(); WinFormsHelper.UpdateWindow(); EngineContext.Render(); if (Win32Interop._kbhit() != 0) { var key = Console.ReadKey(true).KeyChar; switch (key) { default: break; } if (key == 'q') break; } } EngineContext.Stop(); }
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 PARADOX_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); }
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); } }
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; } } } }
private Entity GetPickedEntity(EngineContext engineContext, EffectMesh pickedEffectMesh) { if (pickedEffectMesh == null) return null; // Find Entity from EffectMesh var pickedEntity = pickedEffectMesh.Get(PickingPlugin.AssociatedEntity); if (pickedEntity == null) { // Iterate over both scene entities and editor entities (i.e. gizmo) var entities = engineContext.EntityManager.Entities.AsEnumerable(); if (editorEntitySystem != null) entities = entities.Concat(editorEntitySystem.Entities); foreach (var entity in entities) { var meshComponent = entity.Get(ModelComponent.Key); if (meshComponent == null) continue; if (!meshComponent.InstantiatedSubMeshes.Any(x => x.Value == pickedEffectMesh)) continue; pickedEntity = entity; break; } } return pickedEntity; }
public override void Load() { base.Load(); if (OfflineCompilation) return; var renderTargets = new RenderTarget[2]; DepthStencilBuffer depthStencilBuffer = null; Texture2D depthStencilTexture = null; Parameters.AddSources(MainPlugin.ViewParameters); Parameters.RegisterParameter(EffectPlugin.BlendStateKey); var filteredPasses = new FastList<RenderPass>(); RenderPass.UpdatePasses += updatePassesAction = (RenderPass currentRenderPass, ref FastList<RenderPass> currentPasses) => { var originalPasses = currentPasses; filteredPasses.Clear(); currentPasses = filteredPasses; Parameters.Set(PickingFrameIndex, ++currentPickingFrameIndex); Request[] requests; lock (pendingRequests) { // No picking request or no mesh to pick? if (pendingRequests.Count == 0) return; requests = pendingRequests.ToArray(); pendingRequests.Clear(); } foreach (var request in requests) { requestResults.Add(request); } if (originalPasses == null) return; // Count mesh passes int meshIndex = 0; foreach (var pass in originalPasses) { meshIndex += pass.Passes.Count; } // No mesh to pick? if (meshIndex == 0) return; // Copy mesh passes and assign indices var meshPasses = new EffectMesh[meshIndex]; meshIndex = 0; foreach (var pass in RenderPass.Passes) { throw new NotImplementedException(); //foreach (var effectMeshPass in pass.Meshes) //{ // meshPasses[meshIndex] = (EffectMesh)effectMeshPass; // // Prefix increment so that 0 means no rendering. // effectMeshPass.Parameters.Set(PickingMeshIndex, ++meshIndex); //} } // For now, it generates one rendering per picking. // It would be quite easy to optimize it by make Picking shader works on multiple picking points at a time. foreach (var request in requests) { var pickingRenderPass = new RenderPass("Picking"); pickingRenderPass.StartPass.AddFirst = (threadContext) => { threadContext.GraphicsDevice.Clear(renderTargets[0], Color.Black); threadContext.GraphicsDevice.Clear(renderTargets[1], Color.Black); threadContext.Parameters.Set(PickingScreenPosition, request.Location); threadContext.GraphicsDevice.SetViewport(new Viewport(0, 0, renderTargets[0].Description.Width, renderTargets[0].Description.Height)); threadContext.GraphicsDevice.Clear(depthStencilBuffer, DepthStencilClearOptions.DepthBuffer); threadContext.GraphicsDevice.SetRenderTargets(depthStencilBuffer, renderTargets); }; pickingRenderPass.EndPass.AddLast = (threadContext) => { threadContext.Parameters.Reset(PickingScreenPosition); threadContext.GraphicsDevice.Copy(renderTargets[0].Texture, request.ResultTextures[0]); threadContext.GraphicsDevice.Copy(renderTargets[1].Texture, request.ResultTextures[1]); }; //pickingRenderPass.PassesInternal = originalPasses; throw new NotImplementedException(); request.MeshPasses = meshPasses; currentPasses.Add(pickingRenderPass); request.HasResults = true; // Wait 2 frames before pulling the results. request.FrameCounter = 2; } }; RenderSystem.GlobalPass.EndPass.AddLast = CheckPickingResults; var backBuffer = GraphicsDevice.BackBuffer; int pickingArea = 1 + PickingDistance * 2; renderTargets[0] = Texture.New2D(GraphicsDevice, pickingArea, pickingArea, PixelFormat.R32_UInt, TextureFlags.ShaderResource | TextureFlags.RenderTarget).ToRenderTarget().KeepAliveBy(ActiveObjects); renderTargets[1] = Texture.New2D(GraphicsDevice, pickingArea, pickingArea, PixelFormat.R32G32B32A32_Float, TextureFlags.ShaderResource | TextureFlags.RenderTarget).ToRenderTarget().KeepAliveBy(ActiveObjects); depthStencilTexture = Texture.New2D(GraphicsDevice, pickingArea, pickingArea, PixelFormat.D32_Float, TextureFlags.ShaderResource | TextureFlags.DepthStencil).KeepAliveBy(ActiveObjects); depthStencilBuffer = depthStencilTexture.ToDepthStencilBuffer(false); Parameters.AddDynamic(PickingMatrix, ParameterDynamicValue.New(PickingScreenPosition, (ref Vector2 pickingPosition, ref Matrix picking) => { // Move center to picked position, and zoom (it is supposed to stay per-pixel according to render target size) picking = Matrix.Translation(1.0f - (pickingPosition.X) / backBuffer.Width * 2.0f, -1.0f + (pickingPosition.Y) / backBuffer.Height * 2.0f, 0.0f) * Matrix.Scaling((float)backBuffer.Width / (float)pickingArea, (float)backBuffer.Height / (float)pickingArea, 1.0f); })); }
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; }
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]); } } }
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; }
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++; // } // } //} }
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); }
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++; } } } }
private static void InvokeMeshPass(EffectMesh mesh, ThreadContext context, bool skipEffectPass = false) { var effectPass = mesh.EffectPass; // Execute EffectPass - StartPass if (!skipEffectPass) effectPass.StartPass.Invoke(context); // Execute MeshPass - StartPass - EndPass context.EffectMesh = mesh; mesh.Render.Invoke(context); context.EffectMesh = null; // Execute EffectPass - EndPass if (!skipEffectPass) effectPass.EndPass.Invoke(context); }
private void CreatePrePassMesh(RenderPass renderPass, bool debug) { var lightDeferredEffect = lightDeferredEffects[debug ? 1 : 0]; Tiles = new List<LightingPrepassShaderPlugin.LightData>[TileCountX * TileCountY]; for (int i = 0; i < Tiles.Length; ++i) { Tiles[i] = new List<LightingPrepassShaderPlugin.LightData>(); } renderPass.StartPass.AddLast = (threadContext) => { // TODO THIS IS NOT ACCURATE TO TAKE THE CURRENT BACKBUFFER var mainBackBuffer = graphicsDeviceService.GraphicsDevice.BackBuffer; threadContext.GraphicsDevice.SetViewport(new Viewport(0, 0, mainBackBuffer.Width, mainBackBuffer.Height)); if (threadContext.FirstContext) { if (debug) { threadContext.GraphicsDevice.SetRenderTarget(GBufferPlugin.MainTargetPlugin.RenderTarget); } else { threadContext.GraphicsDevice.Clear(LightTexture, new Color(0.0f, 0.0f, 0.0f, 0.0f)); threadContext.GraphicsDevice.SetRenderTarget(LightTexture); } } for (int i = 0; i < Tiles.Length; ++i) Tiles[i].Clear(); var lights = Lights; var lightAttenuationCutoff = 0.1f; Matrix viewMatrix; var mainParameters = GBufferPlugin.MainPlugin.ViewParameters; mainParameters.Get(TransformationKeys.View, out viewMatrix); Matrix projMatrix; mainParameters.Get(TransformationKeys.Projection, out projMatrix); for (int index = 0; index < lights.Meshes.Count; index++) { LightingPrepassShaderPlugin.LightData lightData; var lightMesh = lights.Meshes[index]; Vector3 lightPos; lightMesh.Parameters.TryGet(LightKeys.LightPosition, out lightPos); Vector3.TransformCoordinate(ref lightPos, ref viewMatrix, out lightData.LightPosVS); lightMesh.Parameters.TryGet(LightKeys.LightColor, out lightData.DiffuseColor); lightMesh.Parameters.TryGet(LightKeys.LightIntensity, out lightData.LightIntensity); lightMesh.Parameters.TryGet(LightKeys.LightRadius, out lightData.LightRadius); // ------------------------------------------------------------------------------------------ // TEMPORARY FIX FOR DEFERRED LIGHTS // ------------------------------------------------------------------------------------------ //lightData2[index].DiffuseColor.Pow(1 / 4.0f); //lightData2[index].LightIntensity = (float)Math.Pow(lightData2[index].LightIntensity, 1.0f / 2.2f); // ------------------------------------------------------------------------------------------ // Linearize color lightData.DiffuseColor.Pow(Color.DefaultGamma); lightData.LightIntensity = (float)Math.Pow(lightData.LightIntensity, Color.DefaultGamma); float lightDistanceMax = CalculateMaxDistance(lightData.LightIntensity, lightData.LightRadius, lightAttenuationCutoff); var clipRegion = ComputeClipRegion(lightData.LightPosVS, lightDistanceMax, ref projMatrix); var tileStartX = (int)((clipRegion.X * 0.5f + 0.5f) * TileCountX); var tileEndX = (int)((clipRegion.Z * 0.5f + 0.5f) * TileCountX); var tileStartY = (int)((clipRegion.Y * 0.5f + 0.5f) * TileCountY); var tileEndY = (int)((clipRegion.W * 0.5f + 0.5f) * TileCountY); // Check if this light is really visible (not behind us) if (lightData.LightPosVS.Z + lightDistanceMax < 0.0f) continue; for (int y = tileStartY; y <= tileEndY; ++y) { if (y < 0 || y >= TileCountY) continue; for (int x = tileStartX; x <= tileEndX; ++x) { if (x < 0 || x >= TileCountX) continue; Tiles[y * TileCountX + x].Add(lightData); } } } }; var lightDeferredMesh = new EffectMesh(lightDeferredEffect).KeepAliveBy(ActiveObjects); RenderSystem.GlobalMeshes.AddMesh(lightDeferredMesh); renderPass.EndPass.AddLast = (context) => { // Clear thread context overridden variables. context.Parameters.Reset(LightingPrepassShaderPlugin.LightCount); context.Parameters.Reset(LightingPrepassShaderPlugin.LightInfos); context.Parameters.Reset(LightingPrepassShaderPlugin.TileIndex); context.Parameters.Reset(TransformationKeys.Projection); context.Parameters.Reset(RenderTargetKeys.DepthStencilSource); }; var tileRenderPasses = new RenderPass[TileCountX * TileCountY]; for (int i = 0; i < tileRenderPasses.Length; ++i) { int tileIndex = i; tileRenderPasses[i] = new RenderPass("Lighting Tile"); tileRenderPasses[i].StartPass.AddLast = (context) => { context.Parameters.Set(LightingPrepassShaderPlugin.TileIndex, tileIndex); }; throw new NotImplementedException(); //tileRenderPasses[i].Meshes.Add(lightDeferredMesh); } throw new NotImplementedException(); //renderPass.UpdatePasses += (RenderPass currentRenderPass, ref FastList<RenderPass> currentPasses) => // { // lightDeferredEffect.Passes[0].Passes.Clear(); // lightDeferredEffect.Passes[0].Passes.AddRange(tileRenderPasses); // }; }
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); }
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); }
public override void Load() { base.Load(); if (OfflineCompilation) return; // Declare post render pass PostPass = new RenderPass("PostPass").KeepAliveBy(ActiveObjects); RenderPass.AddPass(PostPass); var depthStencilTexture = Texture.New2D(GraphicsDevice, AtlasSize, AtlasSize, PixelFormat.D32_Float, TextureFlags.DepthStencil | TextureFlags.ShaderResource).KeepAliveBy(ActiveObjects); var depthStencilBuffer = depthStencilTexture.ToDepthStencilBuffer(false); ShadowMapDepth = depthStencilBuffer; //MainTargetPlugin.Parameters.Set(ShadowMapKeys.Texture0, ShadowMapDepth); // Setup clear of this target var renderTargetPlugin = new RenderTargetsPlugin { Services = Services, EnableClearDepth = true, EnableSetTargets = false, RenderPass = RenderPass, RenderTarget = null, DepthStencil = depthStencilBuffer, }; renderTargetPlugin.Apply(); // Use Default ZTest for GBuffer depthStencilStateZStandard = DepthStencilState.New(GraphicsDevice, new DepthStencilStateDescription().Default()).KeepAliveBy(ActiveObjects); depthStencilStateZStandard.Name = "ZStandard"; Parameters.Set(EffectPlugin.DepthStencilStateKey, depthStencilStateZStandard); casterRasterizerState = RasterizerState.New(GraphicsDevice, new RasterizerStateDescription(CullMode.Back)).KeepAliveBy(ActiveObjects); // Variance Shadow Mapping // Create the blur temporary texture var shadowMapTextureDesc = ShadowMapDepth.Description; var shadowMapBlurH = Texture.New2D(GraphicsDevice, shadowMapTextureDesc.Width, shadowMapTextureDesc.Height, PixelFormat.R32G32_Float, TextureFlags.ShaderResource | TextureFlags.RenderTarget).KeepAliveBy(ActiveObjects); var shadowMapBlurV = Texture.New2D(GraphicsDevice, shadowMapTextureDesc.Width, shadowMapTextureDesc.Height, PixelFormat.R32G32_Float, TextureFlags.ShaderResource | TextureFlags.RenderTarget).KeepAliveBy(ActiveObjects); Texture2D textureSourceH = ShadowMapDepth.Texture; Texture2D textureSourceV = shadowMapBlurH; RenderTarget renderTargetH = shadowMapBlurH.ToRenderTarget(); RenderTarget renderTargetV = shadowMapBlurV.ToRenderTarget(); var blurQuadMesh = new EffectMesh[2]; for (int j = 0; j < BlurCount; j++) { for (int i = 0; i < 2; ++i) { blurQuadMesh[i] = new EffectMesh(j > 0 ? blurEffects[1] : blurEffects[i]).KeepAliveBy(ActiveObjects); blurQuadMesh[i].Parameters.Set(PostEffectBlurKeys.Coefficients, new[] { 0.2270270270f, 0.3162162162f, 0.3162162162f, 0.0702702703f, 0.0702702703f }); var unit = i == 0 ? Vector2.UnitX : Vector2.UnitY; blurQuadMesh[i].Parameters.Set(PostEffectBlurKeys.Offsets, new[] { Vector2.Zero, unit * -1.3846153846f, unit * +1.3846153846f, unit * -3.2307692308f, unit * +3.2307692308f }); PostPass.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); textureSourceH = shadowMapBlurV; textureSourceV = shadowMapBlurH; } ShadowMapVsm = shadowMapBlurV; // Final texture for VSM is result of blur //MainTargetPlugin.Parameters.Set(ShadowMapKeys.Texture0, shadowMapBlurV); }
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(); }