/// <summary>
        /// Creates a circular solid colored brush that we can apply to a visual
        /// </summary>
        private CompositionEffectBrush CreateCircleBrushWithColor(Windows.UI.Color color)
        {
            var colorBrush = _compositor.CreateColorBrush(color);

            //
            // Because Windows.UI.Composition does not have a Circle visual, we will
            // work around by using a circular opacity mask
            // Create a simple Composite Effect, using DestinationIn (S * DA),
            // with a color source and a named parameter source.
            //
            var effect = new CompositeEffect
            {
                Mode    = CanvasComposite.DestinationIn,
                Sources =
                {
                    new ColorSourceEffect()
                    {
                        Color = color
                    },
                    new CompositionEffectSourceParameter("mask")
                }
            };
            var factory = _compositor.CreateEffectFactory(effect);
            var brush   = factory.CreateBrush();

            //
            // Create the mask brush using the circle mask
            //
            CompositionSurfaceBrush maskBrush = _compositor.CreateSurfaceBrush();

            maskBrush.Surface = _circleMaskSurface.Surface;
            brush.SetSourceParameter("mask", maskBrush);

            return(brush);
        }
Exemple #2
0
        public void UpdateLightingEffect_DistantDiffuse(float AmbientAmount  = 0, float DiffuseAmount    = .5f,
                                                        float SpecularAmount = 0, string NormalMapSource = "NormalMap", bool forceUpdate = false, BrushType brushType = BrushType.Flat)
        {
            //_currentBrushType = brushType;
            var sceneLightingEffect = new SceneLightingEffect()
            {
                AmbientAmount   = AmbientAmount,
                DiffuseAmount   = DiffuseAmount,
                SpecularAmount  = SpecularAmount,
                NormalMapSource = new CompositionEffectSourceParameter(NormalMapSource),
            };

            IGraphicsEffect graphicsEffect = new CompositeEffect()
            {
                Mode    = CanvasComposite.Add,
                Sources =
                {
                    new CompositionEffectSourceParameter("ImageSource"),
                    sceneLightingEffect
                }
            };

            _effectFactory = _compositor.CreateEffectFactory(graphicsEffect);


            if (forceUpdate)
            {
                UpdateEffectBrush(_currentBrushType);
            }
        }
        public static GameObject CreateUnsafe(string effectName, string instanceId = null)
        {
            string targetingSphereJson = Get(effectName)?.Effect;

            if (targetingSphereJson == null)
            {
                return(null);
            }
            Talespire.GameObjects.InvalidateFound();
            CompositeEffect compositeEffect = CompositeEffect.CreateFrom(targetingSphereJson);
            GameObject      gameObject      = compositeEffect.CreateOrFindUnsafe(instanceId);

            compositeEffect.RefreshIfNecessary(gameObject);

            if (gameObject != null)
            {
                Talespire.Log.Debug($"gameObject: {gameObject.name}");
            }
            else
            {
                Talespire.Log.Error($"CreateOrFindUnsafe returned null!");
            }

            if (gameObject != null)
            {
                gameObject.name = effectName;
            }
            return(gameObject);
        }
Exemple #4
0
        void DrawShadow(CanvasControl canvasCtrl, CanvasDrawingSession drawSession, List <ShadowParam> shadowParams)
        {
            var    canvasCommandList = new CanvasCommandList(canvasCtrl);
            var    content           = _contentPresenter.Content as FrameworkElement;
            var    contentWidth      = content.ActualWidth + content.Margin.Left + content.Margin.Right;
            var    contentHeight     = content.ActualHeight + content.Margin.Top + content.Margin.Bottom;
            var    radius            = GetActualCornerRadius(contentWidth);
            double maxOffset_Y       = shadowParams.Max(param => param.Offset_Y);

            _shadowCanvas.VerticalAlignment   = content.VerticalAlignment;
            _shadowCanvas.HorizontalAlignment = content.HorizontalAlignment;

            using (var ds = canvasCommandList.CreateDrawingSession())
            {
                ds.FillRoundedRectangle(new Rect(0, 0, contentWidth, contentHeight), radius, radius, Color.FromArgb(255, 0, 0, 0));
            }

            CompositeEffect compositeEffect = CreateEffects(shadowParams, canvasCommandList);

            var    bound        = compositeEffect.GetBounds(drawSession);
            double shadowWidth  = Math.Abs(bound.X);
            double shadowHeight = Math.Abs(bound.Y);

            UpdateLayout(maxOffset_Y, bound, shadowWidth, shadowHeight);

            DrawEffect(drawSession, compositeEffect, shadowWidth, shadowHeight);
        }
Exemple #5
0
        /// <summary>
        /// Function is responsible for creating the circular alpha masked profile brush
        /// </summary>
        /// <returns></returns>
        private CompositionEffectBrush InitializeCompositeEffect()
        {
            //
            // Create a simple Composite Effect, using DestinationIn (S * DA), and two named sources - image and mask.
            //
            var effect = new CompositeEffect
            {
                Mode    = CanvasComposite.DestinationIn,
                Sources =
                {
                    new CompositionEffectSourceParameter("image"),
                    new CompositionEffectSourceParameter("mask")
                }
            };
            var factory = _compositor.CreateEffectFactory(effect);
            var brush   = factory.CreateBrush();

            //
            // Load in the profile picture as a brush using the Composition Toolkit.
            //
            _profilePictureSurface = ImageLoader.Instance.LoadFromUri(new Uri("ms-appx:///Samples/SDK 10586/Z-Order Scrolling/teched3ae5a27b-4f78-e111-94ad-001ec953730b.jpg"));
            brush.SetSourceParameter("image", _profilePictureSurface.Brush);

            //
            // Load in the circular mask picture asx a brush using the composition Toolkit.
            //
            _circleMaskSurface = ImageLoader.Instance.LoadCircle(200, Colors.White);
            brush.SetSourceParameter("mask", _circleMaskSurface.Brush);

            return(brush);
        }
        public static GameObject Create(string effectName, string instanceId = null)
        {
            Talespire.Log.Indent($"KnownEffects.Create(\"{effectName}\")");
            try
            {
                string effectJson = Get(effectName)?.Effect;
                if (effectJson == null)
                {
                    Talespire.Log.Error($"effectJson == null");
                    return(null);
                }

                Talespire.GameObjects.InvalidateFound();
                CompositeEffect compositeEffect = CompositeEffect.CreateFrom(effectJson);
                GameObject      gameObject      = compositeEffect.CreateOrFindUnsafe(instanceId);
                compositeEffect.RefreshIfNecessary(gameObject);

                if (gameObject != null)
                {
                    gameObject.name = effectName;
                }
                return(gameObject);
            }
            finally
            {
                Talespire.Log.Unindent();
            }
        }
Exemple #7
0
        private ICanvasImage CreateComposite()
        {
            var compositeEffect = new CompositeEffect {
                Mode = CanvasComposite.SourceOver
            };

            var transformEffects = new List <Transform3DEffect>();

            const int petalCount = 12;

            for (int i = 0; i < petalCount; i++)
            {
                var transformEffect = new Transform3DEffect
                {
                    Source = bitmapTiger
                };

                compositeEffect.Sources.Add(transformEffect);
                transformEffects.Add(transformEffect);
            }

            // Animation rotates each copy of the image at a different speed.
            animationFunction = elapsedTime =>
            {
                for (int i = 0; i < petalCount; i++)
                {
                    transformEffects[i].TransformMatrix = Matrix4x4.CreateRotationZ(elapsedTime * i / 3);
                }
            };

            currentEffectSize = Vector2.Zero;

            return(compositeEffect);
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            _compositor       = ElementCompositionPreview.GetElementVisual(this)?.Compositor;
            _visual           = ElementCompositionPreview.GetElementVisual(Image);
            _pointLight       = _compositor.CreatePointLight();
            _pointLight.Color = Colors.White;

            var graphicsEffect = new CompositeEffect
            {
                Mode    = CanvasComposite.Add,
                Sources =
                {
                    new CompositionEffectSourceParameter("ImageSource"),
                    new SceneLightingEffect()
                    {
                        AmbientAmount  = 0,
                        DiffuseAmount  = .75f,
                        SpecularAmount = 0,
                    }
                }
            };

            _effectFactory = _compositor.CreateEffectFactory(graphicsEffect);

            var lightRootVisual = ElementCompositionPreview.GetElementVisual(this);

            _pointLight.CoordinateSpace = lightRootVisual;
            _pointLight.Targets.Add(lightRootVisual);

            var brush = _effectFactory.CreateBrush();

            PointerMoved += Lighting_PointerMoved;
        }
Exemple #9
0
        private IGraphicsEffect _createRevealBorderEffect()
        {
            var sceneLightingEffect = new Windows.UI.Composition.Effects.SceneLightingEffect();

            sceneLightingEffect.AmbientAmount  = 0f;
            sceneLightingEffect.DiffuseAmount  = sc_diffuseAmountBorder;
            sceneLightingEffect.SpecularAmount = sc_specularAmountBorder;
            sceneLightingEffect.SpecularShine  = sc_specularShineBorder;

            var colorMatrixEffect = new ColorMatrixEffect();

            colorMatrixEffect.ColorMatrix = sc_revealInvertedBorderColorMatrix;
            colorMatrixEffect.AlphaMode   = Microsoft.Graphics.Canvas.CanvasAlphaMode.Straight;
            colorMatrixEffect.Source      = sceneLightingEffect;

            var baseColorEffect = new ColorSourceEffect();

            baseColorEffect.Name  = "BaseColorEffect";
            baseColorEffect.Color = Color.FromArgb(0, 0, 0, 0);

            var compositeEffect = new CompositeEffect();

            compositeEffect.Mode = Microsoft.Graphics.Canvas.CanvasComposite.SourceOver;
            //	Union of source and destination bitmaps. Equation: O = S + (1 - SA) * D.
            compositeEffect.Sources.Add(baseColorEffect);   //Destination
            compositeEffect.Sources.Add(colorMatrixEffect); //Source
            return(compositeEffect);
        }
Exemple #10
0
        protected override void OnConnected()
        {
            if (DesignMode.DesignModeEnabled)
            {
                return;
            }
            compositor = ElementCompositionPreview.GetElementVisual(Window.Current.Content as UIElement).Compositor;
            var compositeEffect = new CompositeEffect()
            {
                Mode = CanvasComposite.Add
            };

            compositeEffect.Sources.Add(new BorderEffect()
            {
                Source  = new CompositionEffectSourceParameter("backdrop"),
                ExtendX = CanvasEdgeBehavior.Clamp,
                ExtendY = CanvasEdgeBehavior.Clamp
            });
            compositeEffect.Sources.Add(new BorderEffect()
            {
                Source  = new CompositionEffectSourceParameter("color"),
                ExtendX = CanvasEdgeBehavior.Clamp,
                ExtendY = CanvasEdgeBehavior.Clamp
            });

            var Brush = compositor.CreateEffectFactory(compositeEffect).CreateBrush();

            Brush.SetSourceParameter("backdrop", compositor.CreateBackdropBrush());
            Brush.SetSourceParameter("color", compositor.CreateColorBrush(Color));
            CompositionBrush = Brush;

            XamlLight.AddTargetBrush(Lights.RevealAmbientLight.GetIdStatic(), this);
            XamlLight.AddTargetBrush(Lights.RevealBorderSpotLight.GetIdStatic(), this);
        }
        async Task CreateTintEffectBrushAsync(Uri uri)
        {
            Xamarin.Forms.Image element = this.Element as Xamarin.Forms.Image;

            if (Control == null || Element == null || element.Width < 0 || element.Height < 0)
            {
                return;
            }

            SetupCompositor();

            spriteVisual      = compositor.CreateSpriteVisual();
            spriteVisual.Size = new Vector2((float)element.Width, (float)element.Height);

            imageSurface = await generator.CreateImageSurfaceAsync(uri, new Windows.Foundation.Size(element.Width, element.Height), ImageSurfaceOptions.DefaultOptimized);

            CompositionSurfaceBrush surfaceBrush = compositor.CreateSurfaceBrush(imageSurface.Surface);

            CompositionBrush targetBrush = surfaceBrush;

            if (this.TintColor == Color.Transparent)
            {
                // Don't apply tint effect
                effectBrush = null;
            }
            else
            {
                // Set target brush to tint effect brush

                Windows.UI.Color nativeColor = GetNativeColor(this.TintColor);

                IGraphicsEffect graphicsEffect = new CompositeEffect
                {
                    Mode    = CanvasComposite.DestinationIn,
                    Sources =
                    {
                        new ColorSourceEffect
                        {
                            Name  = "colorSource",
                            Color = nativeColor
                        },
                        new CompositionEffectSourceParameter("mask")
                    }
                };

                CompositionEffectFactory effectFactory = compositor.CreateEffectFactory(graphicsEffect,
                                                                                        new[] { "colorSource.Color" });

                effectBrush = effectFactory.CreateBrush();
                effectBrush.SetSourceParameter("mask", surfaceBrush);

                SetTint(nativeColor);

                targetBrush = effectBrush;
            }

            spriteVisual.Brush = targetBrush;
            ElementCompositionPreview.SetElementChildVisual(Control, spriteVisual);
        }
Exemple #12
0
        public void ProcessFrame(ProcessVideoFrameContext context)
        {
            var inputSurface  = context.InputFrame.Direct3DSurface;
            var outputSurface = context.OutputFrame.Direct3DSurface;

            using (var inputBitmap = CanvasBitmap.CreateFromDirect3D11Surface(canvasDevice, inputSurface))
                using (var renderTarget = CanvasRenderTarget.CreateFromDirect3D11Surface(canvasDevice, outputSurface))
                    using (var ds = renderTarget.CreateDrawingSession())
                        using (var brush = new CanvasImageBrush(canvasDevice, inputBitmap))
                            using (var textCommandList = new CanvasCommandList(canvasDevice))
                            {
                                using (var clds = textCommandList.CreateDrawingSession())
                                {
                                    clds.DrawText(
                                        "Win2D\nMediaClip",
                                        (float)inputBitmap.Size.Width / 2,
                                        (float)inputBitmap.Size.Height / 2,
                                        brush,
                                        new CanvasTextFormat()
                                    {
                                        FontSize   = (float)inputBitmap.Size.Width / 5,
                                        FontWeight = new FontWeight()
                                        {
                                            Weight = 999
                                        },
                                        HorizontalAlignment = CanvasHorizontalAlignment.Center,
                                        VerticalAlignment   = CanvasVerticalAlignment.Center
                                    });
                                }

                                var background = new GaussianBlurEffect()
                                {
                                    BlurAmount = 10,
                                    BorderMode = EffectBorderMode.Hard,
                                    Source     = new BrightnessEffect()
                                    {
                                        BlackPoint = new Vector2(0.5f, 0.7f),
                                        Source     = new SaturationEffect()
                                        {
                                            Saturation = 0,
                                            Source     = inputBitmap
                                        }
                                    }
                                };

                                var shadow = new ShadowEffect()
                                {
                                    Source     = textCommandList,
                                    BlurAmount = 10
                                };

                                var composite = new CompositeEffect()
                                {
                                    Sources = { background, shadow, textCommandList }
                                };

                                ds.DrawImage(composite);
                            }
        }
        //@Static
        /// <summary>
        /// Render layers.
        /// </summary>
        /// <param name="resourceCreator"> The resource-creator. </param>
        /// <param name="layerages"> The layerage. </param>
        /// <returns> The render image. </returns>
        public static ICanvasImage Render(ICanvasResourceCreator resourceCreator, IList <Layerage> layerages)
        {
            ICanvasImage previousImage = null;

            for (int i = layerages.Count - 1; i >= 0; i--)
            {
                Layerage currentLayerage = layerages[i];
                ILayer   currentLayer    = currentLayerage.Self;

                if (currentLayer.Visibility == Visibility.Collapsed)
                {
                    continue;
                }
                if (currentLayer.Opacity == 0)
                {
                    continue;
                }


                //Layer
                ICanvasImage currentImage = currentLayer.GetActualRender(resourceCreator, currentLayerage.Children);
                if (currentImage == null)
                {
                    continue;
                }
                if (previousImage == null)
                {
                    previousImage = currentImage;
                    continue;
                }


                //Blend
                if (currentLayer.BlendMode is BlendEffectMode blendMode)
                {
                    previousImage = new BlendEffect
                    {
                        Background = currentImage,
                        Foreground = previousImage,
                        Mode       = blendMode
                    };
                    continue;
                }

                //Composite
                previousImage = new CompositeEffect
                {
                    Sources =
                    {
                        previousImage,
                        currentImage,
                    }
                };
                continue;
            }

            return(previousImage);
        }
Exemple #14
0
        public void LinkLayerEffects(Layer nextLayer)
        {
            IGraphicsEffect source = _inputEffect;

            _chainedEffect = null;

            // Link the effect chain
            foreach (var effect in Effects)
            {
                if (effect.Enabled)
                {
                    effect.GraphicsEffect.GetType().GetProperties().FirstOrDefault(x => x.Name == "Source").SetValue(effect.GraphicsEffect, source);
                    source         = effect.GraphicsEffect;
                    _chainedEffect = effect.GraphicsEffect;
                }
            }

            if (nextLayer != null)
            {
                IGraphicsEffect layerEffect = EffectRoot;
                IGraphicsEffect blendEffect;

                blendEffect = Helpers.GetEffectFromBlendMode(_blendMode);

                if (blendEffect is BlendEffect)
                {
                    BlendEffect blend = (BlendEffect)blendEffect;
                    blend.Foreground = nextLayer.GenerateEffectGraph(false);
                    blend.Background = layerEffect;
                    _blendEffect     = blend;
                }
                else if (blendEffect is CompositeEffect)
                {
                    CompositeEffect composite = (CompositeEffect)blendEffect;
                    composite.Sources.Add(nextLayer.GenerateEffectGraph(false));
                    composite.Sources.Add(layerEffect);
                    _blendEffect = composite;
                }
                else if (blendEffect is ArithmeticCompositeEffect)
                {
                    ArithmeticCompositeEffect arith = (ArithmeticCompositeEffect)blendEffect;
                    arith.Source1 = layerEffect;
                    arith.Source2 = nextLayer.GenerateEffectGraph(false);
                    _blendEffect  = arith;
                }
                else
                {
                    Debug.Assert(false);
                }
            }
            else
            {
                _blendEffect = null;
            }
        }
Exemple #15
0
        private ICanvasImage CreateChromaKey()
        {
            textLabel = requiresWin10;

            var chromaKeyEffect = new ChromaKeyEffect
            {
                Source  = bitmapTiger,
                Color   = Color.FromArgb(255, 162, 125, 73),
                Feather = true
            };

            // Composite the chromakeyed image on top of a background checker pattern.
            Color[] twoByTwoChecker =
            {
                Colors.LightGray, Colors.DarkGray,
                Colors.DarkGray,  Colors.LightGray,
            };

            var compositeEffect = new CompositeEffect
            {
                Sources =
                {
                    // Create the checkered background by scaling up a tiled 2x2 bitmap.
                    new CropEffect
                    {
                        Source = new DpiCompensationEffect
                        {
                            Source = new ScaleEffect
                            {
                                Source = new BorderEffect
                                {
                                    Source  = CanvasBitmap.CreateFromColors(canvas, twoByTwoChecker, 2, 2),
                                    ExtendX = CanvasEdgeBehavior.Wrap,
                                    ExtendY = CanvasEdgeBehavior.Wrap
                                },
                                Scale             = new Vector2(8, 8),
                                InterpolationMode = CanvasImageInterpolation.NearestNeighbor
                            }
                        },
                        SourceRectangle = bitmapTiger.Bounds
                    },

                    // Composite the chromakey result on top of the background.
                    chromaKeyEffect
                }
            };

            // Animation changes the chromakey matching tolerance.
            animationFunction = elapsedTime =>
            {
                chromaKeyEffect.Tolerance = 0.1f + (float)Math.Sin(elapsedTime) * 0.1f;
            };

            return(compositeEffect);
        }
Exemple #16
0
        public void UpdateLightingEffect_SpotLightSpecular(float AmbientAmount1    = 0.6f, float DiffuseAmount1        = 1f,
                                                           float SpecularAmount1   = 0, string NormalMapSource1        = "NormalMap", float AmbientAmount2 = 0,
                                                           float DiffuseAmount2    = 0f, float SpecularAmount2         = 1, float SpecularShine2           = 100f,
                                                           string NormalMapSource2 = "NormalMap", float InnerConeAngle = 15,
                                                           float OuterConeAngle    = 10, bool forceUpdate = false, BrushType brushType = BrushType.Flat)
        {
            //_currentBrushType = brushType;
            IGraphicsEffect graphicsEffect = new CompositeEffect()
            {
                Mode    = CanvasComposite.DestinationIn,
                Sources =
                {
                    new ArithmeticCompositeEffect()
                    {
                        Source1Amount  = 1,
                        Source2Amount  = 1,
                        MultiplyAmount = 0,

                        Source1 = new ArithmeticCompositeEffect()
                        {
                            MultiplyAmount = 1,
                            Source1Amount  = 0,
                            Source2Amount  = 0,
                            Source1        = new CompositionEffectSourceParameter("ImageSource"),
                            Source2        = new SceneLightingEffect()
                            {
                                AmbientAmount   = AmbientAmount1,
                                DiffuseAmount   = DiffuseAmount1,
                                SpecularAmount  = SpecularAmount1,
                                NormalMapSource = new CompositionEffectSourceParameter(NormalMapSource1),
                            }
                        },
                        Source2 = new SceneLightingEffect()
                        {
                            AmbientAmount   = AmbientAmount2,
                            DiffuseAmount   = DiffuseAmount2,
                            SpecularAmount  = SpecularAmount2,
                            SpecularShine   = SpecularShine2,
                            NormalMapSource = new CompositionEffectSourceParameter(NormalMapSource2),
                        }
                    },
                    new CompositionEffectSourceParameter("NormalMap"),
                }
            };

            _effectFactory = _compositor.CreateEffectFactory(graphicsEffect);

            _spotLight.InnerConeAngle = (float)(Math.PI / InnerConeAngle);
            _spotLight.OuterConeAngle = (float)(Math.PI / OuterConeAngle);

            if (forceUpdate)
            {
                UpdateEffectBrush(_currentBrushType);
            }
        }
        private void UpdateBrush()
        {
            if (m_isDisabledByPolicy && m_brush is CompositionEffectBrush)
            {
                m_brush.Dispose();
                m_brush = null;
            }

            if (m_brush == null)
            {
                if (m_isDisabledByPolicy)
                {
                    m_brush          = Window.Current.Compositor.CreateColorBrush(FallbackColor);
                    CompositionBrush = m_brush;
                }
                else
                {
                    var gaussianBlur = new GaussianBlurEffect
                    {
                        Name         = "Blur",
                        BlurAmount   = 30,
                        Optimization = EffectOptimization.Speed,
                        BorderMode   = EffectBorderMode.Hard,
                        Source       = new CompositionEffectSourceParameter("Backdrop")
                    };

                    var saturationEffect = new SaturationEffect
                    {
                        Name       = "Saturation",
                        Saturation = 1.7f,
                        Source     = gaussianBlur
                    };

                    var tintColorEffect = new ColorSourceEffect
                    {
                        Name  = "TintColor",
                        Color = Color.FromArgb(52, 0, 0, 0)
                    };

                    var compositeEffect = new CompositeEffect();
                    compositeEffect.Mode = CanvasComposite.SourceOver;
                    compositeEffect.Sources.Add(saturationEffect);
                    compositeEffect.Sources.Add(tintColorEffect);

                    var effectFactory = Window.Current.Compositor.CreateEffectFactory(compositeEffect);
                    var backdrop      = Window.Current.Compositor.CreateBackdropBrush();

                    var brush = effectFactory.CreateBrush();
                    brush.SetSourceParameter("Backdrop", backdrop);

                    m_brush          = brush;
                    CompositionBrush = m_brush;
                }
            }
        }
Exemple #18
0
        public static ICanvasImage RenderTransform(Layer l, ICanvasImage ci)
        {
            if (l.Visual == true && l.Opacity != 0) //图层可视且透明度大于零
            {
                if (l.Opacity == 100)               //无透明度渲染
                {
                    //图层无混合模式
                    if (l.BlendIndex == 0)
                    {
                        ci = new CompositeEffect
                        {
                            Sources = { ci, GetTransform(l.CanvasRenderTarget, l.Vect) }
                        }
                    }
                    ; //结合接口
                    //图层有混合模式
                    else
                    {
                        ci = new BlendEffect()
                        {
                            Background = GetTransform(l.CanvasRenderTarget, l.Vect), Foreground = ci, Mode = l.BlendMode,
                        }
                    };                   //混合接口
                }
                else if (l.Opacity == 0) //透明度渲染
                {
                    return(ci);
                }
                else// if (l.Opacity < 100)//有透明度渲染
                {
                    ICanvasImage oci = new OpacityEffect {
                        Source = GetTransform(l.CanvasRenderTarget, l.Vect), Opacity = (float)(l.Opacity / 100)
                    };                                                                                                                               //透明度接口

                    //图层无混合模式
                    if (l.BlendIndex == 0)
                    {
                        ci = new CompositeEffect {
                            Sources = { ci, oci }
                        }
                    }
                    ;                                                                         //结合接口
                                                                                              //图层有混合模式
                    else
                    {
                        ci = new BlendEffect()
                        {
                            Background = oci, Foreground = ci, Mode = l.BlendMode,
                        }
                    };                                                                                     //混合接口
                }
            }
            return(ci);
        }
Exemple #19
0
        private CompositeEffect CreateEffects(List <ShadowParam> shadowParams, CanvasCommandList canvasCommandList)
        {
            CompositeEffect compositeEffect = new CompositeEffect();

            shadowParams.ForEach(param =>
            {
                var shadowEffect = CreateShadowEffect(canvasCommandList, param);
                compositeEffect.Sources.Add(shadowEffect);
            });
            return(compositeEffect);
        }
Exemple #20
0
        /// <summary>
        /// Creates a custom shaped Effect Brush using BackdropBrush and a Mask
        /// </summary>
        /// <param name="compositor">Compositor</param>
        /// <param name="mask">IMaskSurface</param>
        /// <param name="blendColor">Color to blend in the BackdropBrush</param>
        /// <param name="blurAmount">Blur Amount of the Backdrop Brush</param>
        /// <param name="backdropBrush">Backdrop Brush (optional). If not provided, then compositor creates it.</param>
        /// <returns>CompositionEffectBrush</returns>
        public static CompositionEffectBrush CreateMaskedBackdropBrush(this Compositor compositor, IMaskSurface mask,
                                                                       Color blendColor, float blurAmount, CompositionBackdropBrush backdropBrush = null)
        {
            // Blur Effect
            var blurEffect = new GaussianBlurEffect()
            {
                Name         = "Blur",
                BlurAmount   = blurAmount,
                BorderMode   = EffectBorderMode.Hard,
                Optimization = EffectOptimization.Balanced,
                Source       = new CompositionEffectSourceParameter("backdrop"),
            };

            // Blend Effect
            var blendEffect = new BlendEffect
            {
                Foreground = new ColorSourceEffect
                {
                    Name  = "Color",
                    Color = blendColor
                },
                Background = blurEffect,
                Mode       = BlendEffectMode.Multiply
            };

            // Composite Effect
            var effect = new CompositeEffect
            {
                Mode    = CanvasComposite.DestinationIn,
                Sources =
                {
                    blendEffect,
                    new CompositionEffectSourceParameter("mask")
                }
            };

            // Create Effect Factory
            var factory = compositor.CreateEffectFactory(effect, new[] { "Blur.BlurAmount", "Color.Color" });
            // Create Effect Brush
            var brush = factory.CreateBrush();

            // Set the BackDropBrush
            // If no backdrop brush is provided, create one
            brush.SetSourceParameter("backdrop", backdropBrush ?? compositor.CreateBackdropBrush());

            // Set the Mask
            // Create SurfaceBrush from IMaskSurface
            var maskBrush = compositor.CreateSurfaceBrush(mask.Surface);

            brush.SetSourceParameter("mask", maskBrush);

            return(brush);
        }
Exemple #21
0
        /// <summary>
        /// Creates a custom shaped Frosted Glass Effect Brush using BackdropBrush and a Mask
        /// </summary>
        /// <param name="compositor">Compositor</param>
        /// <param name="mask">IMaskSurface</param>
        /// <param name="blendColor">Color to blend in the BackdropBrush</param>
        /// <param name="blurAmount">Blur Amount of the Backdrop Brush</param>
        /// <param name="backdropBrush">Backdrop Brush (optional). If not provided, then compositor creates it.</param>
        /// <param name="multiplyAmount">MultiplyAmount of the ArithmeticCompositeEffect</param>
        /// <param name="colorAmount">Source1Amount of the ArithmeticCompositeEffect</param>
        /// <param name="backdropAmount">Source2Amount of the ArithmeticCompositeEffect</param>
        /// <returns>CompositionEffectBrush</returns>
        public static CompositionEffectBrush CreateFrostedGlassBrush(this Compositor compositor, IMaskSurface mask,
                                                                     Color blendColor, float blurAmount, CompositionBackdropBrush backdropBrush = null,
                                                                     float multiplyAmount = 0, float colorAmount = 0.5f, float backdropAmount = 0.5f)
        {
            // Create a frosty glass effect
            var frostEffect = new GaussianBlurEffect
            {
                Name       = "Blur",
                BlurAmount = blurAmount,
                BorderMode = EffectBorderMode.Hard,
                Source     = new ArithmeticCompositeEffect
                {
                    Name           = "Source",
                    MultiplyAmount = multiplyAmount,
                    Source1Amount  = backdropAmount,
                    Source2Amount  = colorAmount,
                    Source1        = new CompositionEffectSourceParameter("backdrop"),
                    Source2        = new ColorSourceEffect
                    {
                        Name  = "BlendColor",
                        Color = blendColor
                    }
                }
            };

            // Composite Effect
            var effect = new CompositeEffect
            {
                Mode    = CanvasComposite.DestinationIn,
                Sources =
                {
                    frostEffect,
                    new CompositionEffectSourceParameter("mask")
                }
            };

            // Create Effect Factory
            var factory = compositor.CreateEffectFactory(effect, new[] { "Blur.BlurAmount", "BlendColor.Color" });
            // Create Effect Brush
            var brush = factory.CreateBrush();

            // Set the BackDropBrush
            // If no backdrop brush is provided, create one
            brush.SetSourceParameter("backdrop", backdropBrush ?? compositor.CreateBackdropBrush());

            // Set the Mask
            // Create SurfaceBrush from CompositionMask
            var maskBrush = compositor.CreateSurfaceBrush(mask.Surface);

            brush.SetSourceParameter("mask", maskBrush);

            return(brush);
        }
Exemple #22
0
            CompositionEffectBrush EffectBrush()
            {
                var compositeEffect = new CompositeEffect();

                compositeEffect.Mode = CanvasComposite.DestinationIn;
                compositeEffect.Sources.Add(new CompositionEffectSourceParameter("destination"));
                compositeEffect.Sources.Add(new CompositionEffectSourceParameter("source"));
                var effectFactory = _c.CreateEffectFactory(compositeEffect);
                var result        = effectFactory.CreateBrush();

                result.SetSourceParameter("destination", SurfaceBrush_0());
                result.SetSourceParameter("source", SurfaceBrush_1());
                return(result);
            }
        async Task CreateTintEffectBrushAsync(Uri uri)
        {
            if (Control == null || Element == null || Element.Width < 0 || Element.Height < 0)
            {
                return;
            }

            Debug.WriteLine("Creating Tint Effect Brush");

            SetupCompositor();

            spriteVisual      = compositor.CreateSpriteVisual();
            spriteVisual.Size = new Vector2((float)Element.Width, (float)Element.Height);

            imageSurface = await generator.CreateImageSurfaceAsync(uri, new Size(Element.Width, Element.Height), ImageSurfaceOptions.DefaultOptimized);

            CompositionSurfaceBrush surfaceBrush = compositor.CreateSurfaceBrush(imageSurface.Surface);

            Windows.UI.Color nativeColor = GetNativeColor(((TintedImage)Element).TintColor);

            IGraphicsEffect graphicsEffect = new CompositeEffect
            {
                Mode    = CanvasComposite.DestinationIn,
                Sources =
                {
                    new ColorSourceEffect
                    {
                        Name  = "colorSource",
                        Color = nativeColor
                    },
                    new CompositionEffectSourceParameter("mask")
                }
            };

            CompositionEffectFactory effectFactory = compositor.CreateEffectFactory(graphicsEffect, new[] { "colorSource.Color" });

            effectBrush = effectFactory.CreateBrush();
            effectBrush.SetSourceParameter("mask", surfaceBrush);

            SetTint(nativeColor);

            spriteVisual.Brush = effectBrush;
            ElementCompositionPreview.SetElementChildVisual(Control, spriteVisual);
        }
Exemple #24
0
        private ICanvasImage CreateShadow()
        {
            var renderTarget = new CanvasRenderTarget(canvas, 360, 150);

            using (var ds = renderTarget.CreateDrawingSession())
            {
                ds.Clear(Color.FromArgb(0, 0, 0, 0));

                ds.DrawText("This text is drawn onto a rendertarget", 10, 10, Colors.White);
                ds.DrawText("with a different color per line,", 10, 40, Colors.Red);
                ds.DrawText("after which a drop shadow is", 10, 70, Colors.Green);
                ds.DrawText("generated using image effects.", 10, 100, Colors.Blue);
            }

            var shadowEffect = new Transform2DEffect
            {
                Source = new ShadowEffect
                {
                    Source     = renderTarget,
                    BlurAmount = 2
                },
                TransformMatrix = Matrix3x2.CreateTranslation(3, 3)
            };

            var whiteBackground = new CropEffect
            {
                Source = new ColorSourceEffect {
                    Color = Colors.White
                },
                SourceRectangle = renderTarget.Bounds
            };

            var compositeEffect = new CompositeEffect
            {
                Sources = { whiteBackground, shadowEffect, renderTarget }
            };

            animationFunction = elapsedTime => { };

            currentEffectSize = renderTarget.Size.ToVector2();

            return(compositeEffect);
        }
        public static CompositionEffectBrush CreateCompositeImageBrush(this Compositor compositor, List<Tuple<string, string>> images)
        {
            var effect = new CompositeEffect { Mode = CanvasComposite.DestinationIn };

            foreach (var image in images)
            {
                var param = new CompositionEffectSourceParameter(image.Item1);
                effect.Sources.Add(param);
            }

            var effectFactory = compositor.CreateEffectFactory(effect);
            var brush = effectFactory.CreateBrush();

            foreach (var image in images)
            {
                brush.SetSourceParameter(image.Item1, compositor.CreateImageBrush(image.Item2));
            }

            return brush;
        }
Exemple #26
0
        private void RenderImage(UIElement uiElement, Uri imageUri, Vector2 size, Vector3 offset, Color imageColor, float Opacity = 1)
        {
            var compositor = ElementCompositionPreview.GetElementVisual(uiElement).Compositor;
            var visual     = compositor.CreateSpriteVisual();

            visual.Size   = size;
            visual.Offset = offset;

            var _imageLoader = new ImageLoader();

            _imageLoader.Initialize(compositor);

            var surface = _imageLoader.LoadImageFromUri(imageUri);
            var brush   = compositor.CreateSurfaceBrush(surface);

            IGraphicsEffect graphicsEffect = new CompositeEffect
            {
                Mode    = Microsoft.Graphics.Canvas.CanvasComposite.DestinationIn,
                Sources =
                {
                    new ColorSourceEffect
                    {
                        Name  = "colorSource",
                        Color = Color.FromArgb(255, 255, 255, 255)
                    },
                    new CompositionEffectSourceParameter("mask")
                }
            };

            var _effectFactory = compositor.CreateEffectFactory(graphicsEffect, new string[] { "colorSource.Color" });
            var effectBrush    = _effectFactory.CreateBrush();

            effectBrush.SetSourceParameter("mask", brush);

            visual.Brush = effectBrush;

            effectBrush.Properties.InsertColor("colorSource.Color", imageColor);

            ElementCompositionPreview.SetElementChildVisual(uiElement, visual);
            uiElement.Opacity = Opacity;
        }
Exemple #27
0
        CompositionEffectBrush GetCompositionEffectBrush(CompositionEffectBrush obj)
        {
            if (GetExisting(obj, out CompositionEffectBrush result))
            {
                return(result);
            }

            var effectBase = obj.GetEffect();

            switch (effectBase.Type)
            {
            case GraphicsEffectType.CompositeEffect:
                var compositeEffect = (CompositeEffect)effectBase;

                var newCompositeEffect = new CompositeEffect
                {
                    Mode = compositeEffect.Mode,
                };

                var effectFactory        = _c.CreateEffectFactory(newCompositeEffect);
                var compositeEffectBrush = effectFactory.CreateBrush();

                result = CacheAndInitializeCompositionObject(obj, compositeEffectBrush);

                foreach (var source in compositeEffect.Sources)
                {
                    newCompositeEffect.Sources.Add(new CompositionEffectSourceParameter(source.Name));

                    result.SetSourceParameter(source.Name, GetCompositionBrush(obj.GetSourceParameter(source.Name)));
                }

                break;

            default:
                throw new InvalidOperationException();
            }

            StartAnimationsAndFreeze(obj, result);
            return(result);
        }
Exemple #28
0
        public ICanvasImage Apply(ICanvasImage image)
        {
            if (IsEnabled)
            {
                var  originalImage = image;
                Rect?bounds        = null;

                // Apply all our effects in turn.
                foreach (var effect in Effects)
                {
                    image = effect.Apply(image, ref bounds);
                }

                // Mask so these effects only alter a specific region of the image?
                if (regionMask != null)
                {
                    var selectedRegion = new CompositeEffect
                    {
                        Sources = { image, GetRegionMask() },
                        Mode    = CanvasComposite.DestinationIn
                    };

                    image = new CompositeEffect
                    {
                        Sources = { originalImage, selectedRegion }
                    };

                    if (bounds.HasValue)
                    {
                        image = new CropEffect
                        {
                            Source          = image,
                            SourceRectangle = bounds.Value
                        };
                    }
                }
            }

            return(image);
        }
Exemple #29
0
        /// <summary>
        /// Function is responsible for creating the circular alpha masked profile brush
        /// </summary>
        /// <returns></returns>
        private CompositionEffectBrush InitializeCompositeEffect()
        {
            //
            // Create a simple Composite Effect, using DestinationIn (S * DA), and two named sources - image and mask.
            //
            var effect = new CompositeEffect
            {
                Mode    = CanvasComposite.DestinationIn,
                Sources =
                {
                    new CompositionEffectSourceParameter("image"),
                    new CompositionEffectSourceParameter("mask")
                }
            };
            var factory = _compositor.CreateEffectFactory(effect);
            var brush   = factory.CreateBrush();

            //
            // Load in the profile picture as a brush using the Composition Toolkit.
            //
            CompositionSurfaceBrush profileBrush = _compositor.CreateSurfaceBrush();
            var image = _imageFactory.CreateImageFromUri(new Uri("ms-appx:///Assets/teched3ae5a27b-4f78-e111-94ad-001ec953730b.jpg"));

            profileBrush.Surface = image.Surface;
            brush.SetSourceParameter("image", profileBrush);

            //
            // Load in the circular mask picture asx a brush using the composition Toolkit.
            //
            CompositionSurfaceBrush maskBrush = _compositor.CreateSurfaceBrush();

            image             = _imageFactory.CreateImageFromUri(new Uri("ms-appx:///Assets/CircleMask.png"));
            maskBrush.Surface = image.Surface;
            brush.SetSourceParameter("mask", maskBrush);

            return(brush);
        }
Exemple #30
0
        private void DrawTextPosition(CanvasDrawingSession drawingSession, Matrix3x2 transform, IDictionary <TrackPoint, Vector2> points, Func <TrackPoint, string> textGetter)
        {
            var nearestPoint = FindNearest(points, (float)_progression);

            var trackPoint    = nearestPoint.Key;
            var pointPosition = Multiply(transform, nearestPoint.Value);

            var whiteBrush = new CanvasSolidColorBrush(drawingSession, Colors.White);

            drawingSession.FillCircle(pointPosition, 3, whiteBrush);

            var textPosition = new Vector2(pointPosition.X + 10, pointPosition.Y - 10);

            var renderTarget = new CanvasRenderTarget(drawingSession, 100, 50);

            using (var ds = renderTarget.CreateDrawingSession())
            {
                ds.DrawText(textGetter(trackPoint), 0, 0, Colors.White);
            }

            var shadowEffect = new Transform2DEffect
            {
                Source = new ShadowEffect
                {
                    Source     = renderTarget,
                    BlurAmount = 2
                },
            };

            var compositeEffect = new CompositeEffect
            {
                Inputs = { shadowEffect, renderTarget }
            };

            drawingSession.DrawImage(compositeEffect, textPosition);
        }
Exemple #31
0
 private void DrawEffect(CanvasDrawingSession drawSession, CompositeEffect compositeEffect, double shadowWidth, double shadowHeight)
 {
     drawSession.DrawImage(compositeEffect, (float)shadowWidth, (float)shadowHeight);
 }
        private ICanvasImage CreateAlphaMask()
        {
            if (!AlphaMaskEffect.IsSupported)
            {
                return CreateNotSupportedMessage(requiresWin10_14393);
            }

            textLabel = requiresWin10_14393;

            // Draw an alpha gradient into a command list.
            var alphaGradientBrush = new CanvasRadialGradientBrush(canvas, Colors.Black, Colors.Transparent)
            {
                Center = bitmapTiger.Size.ToVector2() / 2,

                RadiusX = (float)bitmapTiger.Size.Width,
                RadiusY = (float)bitmapTiger.Size.Height
            };

            var alphaMask = new CanvasCommandList(canvas);

            using (var drawingSession = alphaMask.CreateDrawingSession())
            {
                drawingSession.FillRectangle(bitmapTiger.Bounds, alphaGradientBrush);
            }

            // Apply the alpha mask to the tiger bitmap.
            var alphaMaskEffect = new AlphaMaskEffect
            {
                Source = bitmapTiger,
                AlphaMask = alphaMask
            };

            // Composite the alpha masked image on top of a background checker pattern.
            var compositeEffect = new CompositeEffect
            {
                Sources = { CreateCheckeredBackground(), alphaMaskEffect }
            };

            animationFunction = elapsedTime => { };

            return compositeEffect;
        }
        private async void UpdateEffect()
        {
            if (_compositor != null)
            {
                ComboBoxItem item = EffectSelection.SelectedValue as ComboBoxItem;
                IGraphicsEffect graphicsEffect = null;
                CompositionBrush secondaryBrush = null;
                string[] animatableProperties = null;

                //
                // Create the appropriate effect graph and resources
                //

                switch ((EffectTypes)item.Tag)
                {
                    case EffectTypes.Desaturation:
                        {
                            graphicsEffect = new SaturationEffect()
                            {
                                Saturation = 0.0f,
                                Source = new CompositionEffectSourceParameter("ImageSource")
                            };
                        }
                        break;

                    case EffectTypes.Hue:
                        {
                            graphicsEffect = new HueRotationEffect()
                            {
                                Name = "Hue",
                                Angle = 3.14f,
                                Source = new CompositionEffectSourceParameter("ImageSource")
                            };
                            animatableProperties = new[] { "Hue.Angle" };
                        }
                        break;

                    case EffectTypes.VividLight:
                        {
                            graphicsEffect = new BlendEffect()
                            {
                                Mode = BlendEffectMode.VividLight,
                                Foreground = new ColorSourceEffect()
                                {
                                    Name = "Base",
                                    Color = Color.FromArgb(255,80,40,40)
                                },
                                Background = new CompositionEffectSourceParameter("ImageSource"),
                            };
                            animatableProperties = new[] { "Base.Color" };
                        }
                        break;
                    case EffectTypes.Mask:
                        {
                            graphicsEffect = new CompositeEffect()
                            {
                                Mode = CanvasComposite.DestinationOver,
                                Sources =
                                {
                                    new CompositeEffect()
                                    {
                                        Mode = CanvasComposite.DestinationIn,
                                        Sources =
                                        {

                                            new CompositionEffectSourceParameter("ImageSource"),
                                            new CompositionEffectSourceParameter("SecondSource")
                                        }
                                    },
                                    new ColorSourceEffect()
                                    {
                                        Color = Color.FromArgb(200,255,255,255)
                                    },
                                }
                            };

                            CompositionDrawingSurface backgroundSurface = await SurfaceLoader.LoadFromUri(new Uri("ms-appx:///Samples/SDK Insider/ForegroundFocusEffects/mask.png"));

                            CompositionSurfaceBrush maskBrush = _compositor.CreateSurfaceBrush(backgroundSurface);
                            maskBrush.Stretch = CompositionStretch.UniformToFill;
                            maskBrush.CenterPoint = backgroundSurface.Size.ToVector2() / 2;
                            secondaryBrush = maskBrush;
                        }
                        break;
                    case EffectTypes.Blur:
                        {
                            graphicsEffect = new GaussianBlurEffect()
                            {
                                BlurAmount = 20,
                                Source = new CompositionEffectSourceParameter("ImageSource"),
                                Optimization = EffectOptimization.Balanced,
                                BorderMode = EffectBorderMode.Hard,
                            };
                        }
                        break;
                    case EffectTypes.LightenBlur:
                        {
                            graphicsEffect = new ArithmeticCompositeEffect()
                            {
                                Source1Amount = .4f,
                                Source2Amount = .6f,
                                MultiplyAmount = 0,
                                Source1 = new ColorSourceEffect()
                                {
                                    Name = "Base",
                                    Color = Color.FromArgb(255, 255, 255, 255),
                                },
                                Source2 = new GaussianBlurEffect()
                                {
                                    BlurAmount = 20,
                                    Source = new CompositionEffectSourceParameter("ImageSource"),
                                    Optimization = EffectOptimization.Balanced,
                                    BorderMode = EffectBorderMode.Hard,
                                }
                            };
                        }
                        break;
                    case EffectTypes.DarkenBlur:
                        {
                            graphicsEffect = new ArithmeticCompositeEffect()
                            {
                                Source1Amount = .4f,
                                Source2Amount = .6f,
                                MultiplyAmount = 0,
                                Source1 = new ColorSourceEffect()
                                {
                                    Name = "Base",
                                    Color = Color.FromArgb(255, 0, 0, 0),
                                },
                                Source2 = new GaussianBlurEffect()
                                {
                                    BlurAmount = 20,
                                    Source = new CompositionEffectSourceParameter("ImageSource"),
                                    Optimization = EffectOptimization.Balanced,
                                    BorderMode= EffectBorderMode.Hard,
                                }
                            };
                        }
                        break;
                    case EffectTypes.RainbowBlur:
                        {
                            graphicsEffect = new ArithmeticCompositeEffect()
                            {
                                Source1Amount = .3f,
                                Source2Amount = .7f,
                                MultiplyAmount = 0,
                                Source1 = new ColorSourceEffect()
                                {
                                    Name = "Base",
                                    Color = Color.FromArgb(255, 0, 0, 0),
                                },
                                Source2 = new GaussianBlurEffect()
                                {
                                    BlurAmount = 20,
                                    Source = new CompositionEffectSourceParameter("ImageSource"),
                                    Optimization = EffectOptimization.Balanced,
                                    BorderMode = EffectBorderMode.Hard,
                                }
                            };
                            animatableProperties = new[] { "Base.Color" };
                        }
                        break;
                    default:
                        break;
                }

                // Create the effect factory and instantiate a brush
                CompositionEffectFactory _effectFactory = _compositor.CreateEffectFactory(graphicsEffect, animatableProperties);
                CompositionEffectBrush brush = _effectFactory.CreateBrush();

                // Set the destination brush as the source of the image content
                brush.SetSourceParameter("ImageSource", _compositor.CreateBackdropBrush());

                // If his effect uses a secondary brush, set it now
                if (secondaryBrush != null)
                {
                    brush.SetSourceParameter("SecondSource", secondaryBrush);
                }

                // Update the destination layer with the fully configured brush
                _destinationSprite.Brush = brush;
            }
        }
        /// <summary>
        /// Initializes the Composition elements
        /// </summary>
        private void InitComposition()
        {
            // Compositor
            _compositor = ElementCompositionPreview.GetElementVisual(this).Compositor;
            // CompositionGenerator
            _generator = CompositionGeneratorFactory.GetCompositionGenerator(_compositor);
            
            // Fade Out Animation
            _fadeOutAnimation = _compositor.CreateScalarKeyFrameAnimation();
            _fadeOutAnimation.InsertKeyFrame(1f, 0);
            _fadeOutAnimation.Duration = TransitionDuration;
            // Fade In Animation
            _fadeInAnimation = _compositor.CreateScalarKeyFrameAnimation();
            _fadeInAnimation.InsertKeyFrame(1f, 1);
            _fadeInAnimation.Duration = TransitionDuration;
            // Color Animation
            _colorAnimation = _compositor.CreateColorKeyFrameAnimation();
            _colorAnimation.Duration = TransitionDuration;
            // Offset Animation
            _offsetAnimation = _compositor.CreateVector3KeyFrameAnimation();
            _offsetAnimation.Target = "Offset";
            _offsetAnimation.Duration = TransitionDuration;
            _offsetAnimation.InsertKeyFrame(1f, Vector3.Zero);
            // Alignment animations
            _alignXAnimation = _compositor.CreateScalarKeyFrameAnimation();
            _alignXAnimation.Duration = AlignmentTransitionDuration;
            _alignYAnimation = _compositor.CreateScalarKeyFrameAnimation();
            _alignYAnimation.Duration = AlignmentTransitionDuration;

            // ZoomIn Animation Group
            _scaleAnimation = _compositor.CreateVector3KeyFrameAnimation();
            _scaleAnimation.Target = "Scale";
            _scaleAnimation.InsertKeyFrame(1f, Vector3.One);
            _scaleAnimation.Duration = TransitionDuration;
            _zoomInAnimationGroup = _compositor.CreateAnimationGroup();
            _zoomInAnimationGroup.Add(_scaleAnimation);
            _zoomInAnimationGroup.Add(_offsetAnimation);

            // Visuals
            _rootContainer = _compositor.CreateContainerVisual();
            _frameLayer = _compositor.CreateLayerVisual();
            _frameBackgroundVisual = _compositor.CreateSpriteVisual();
            _frameContentVisual = _compositor.CreateSpriteVisual();
            _placeholderContentVisual = _compositor.CreateSpriteVisual();
            _placeholderBackgroundVisual = _compositor.CreateSpriteVisual();
            _nextVisualContent = _compositor.CreateSpriteVisual();

            _frameLayer.Children.InsertAtTop(_frameBackgroundVisual);
            _frameLayer.Children.InsertAtTop(_frameContentVisual);
            _frameLayer.Children.InsertAtTop(_placeholderBackgroundVisual);
            _frameLayer.Children.InsertAtTop(_placeholderContentVisual);
            _frameLayer.Children.InsertAtTop(_nextVisualContent);

            // Placeholder content
            _placeholderContentMask = _generator.CreateGeometrySurface(PlaceholderSize, GetPlaceHolderGeometry(),
                PlaceholderColor, PlaceholderBackground);
            _placeholderContentBrush = _compositor.CreateSurfaceBrush(_placeholderContentMask.Surface);
            _placeholderContentVisual.Brush = _placeholderContentBrush;
            // Placeholder background
            _placeholderBackgroundVisual.Brush = _compositor.CreateColorBrush(PlaceholderBackground);

            // By default placeholder visual will not be visible
            HidePlaceholder();

            // Shadow visual
            _shadowVisual = _compositor.CreateSpriteVisual();

            _rootContainer.Children.InsertAtBottom(_shadowVisual);
            _rootContainer.Children.InsertAtTop(_frameLayer);

            _frameBackgroundVisual.Brush = _compositor.CreateColorBrush(FrameBackground);

            // Create the effect to create the opacity mask
            var layerEffect = new CompositeEffect
            {
                // CanvasComposite.DestinationIn - Intersection of source and mask. 
                // Equation: O = MA * S
                // where O - Output pixel, MA - Mask Alpha, S - Source pixel.
                Mode = CanvasComposite.DestinationIn,
                Sources =
                        {
                            new CompositionEffectSourceParameter("source"),
                            new CompositionEffectSourceParameter("mask")
                        }
            };

            var layerEffectFactory = _compositor.CreateEffectFactory(layerEffect);
            _layerEffectBrush = layerEffectFactory.CreateBrush();

            // The mask for the imageFrame
            _frameLayerMask = _generator.CreateMaskSurface(new Size(0, 0), null);
            _layerEffectBrush.SetSourceParameter("mask", _compositor.CreateSurfaceBrush(_frameLayerMask.Surface));
            // Apply the mask effect to the frameLayer
            _frameLayer.Effect = _layerEffectBrush;

            ElementCompositionPreview.SetElementChildVisual(this, _rootContainer);
        }
        private void MainGridLoaded(object sender, RoutedEventArgs e)
        {
            m_compositor = ElementCompositionPreview.GetElementVisual(MainGrid).Compositor;
            m_root = m_compositor.CreateContainerVisual();
            ElementCompositionPreview.SetElementChildVisual(MainGrid, m_root);

            Size imageSize;
            m_noEffectBrush = CreateBrushFromAsset(
                "Bruno'sFamily2015 (13)-X2.jpg",
                out imageSize);
            m_imageAspectRatio = (imageSize.Width == 0 && imageSize.Height == 0) ? 1 : imageSize.Width / imageSize.Height;

            m_sprite = m_compositor.CreateSpriteVisual();
            ResizeImage(new Size(MainGrid.ActualWidth, MainGrid.ActualHeight));
            m_root.Children.InsertAtTop(m_sprite);

            // Image with alpha channel as an mask.
            var alphaMaskEffectDesc = new CompositeEffect
            {
                Mode = CanvasComposite.DestinationIn,
                Sources =
                {
                    new CompositionEffectSourceParameter("Image"),
                    new Transform2DEffect
                    {
                        Name = "MaskTransform",
                        Source = new CompositionEffectSourceParameter("Mask")
                    }
                }
            };
            m_alphaMaskEffectBrush = m_compositor.CreateEffectFactory(
                alphaMaskEffectDesc,
                new[] { "MaskTransform.TransformMatrix" }
            ).CreateBrush();
            m_alphaMaskEffectBrush.SetSourceParameter(
                "Image",
                m_noEffectBrush);
            m_alphaMaskEffectBrush.SetSourceParameter(
                "Mask",
                CreateBrushFromAsset("CircleMask.png"));

            // Arithmetic operations between two images.
            var arithmeticEffectDesc = new ArithmeticCompositeEffect
            {
                Name = "effect",
                ClampOutput = false,
                Source1 = new CompositionEffectSourceParameter("Source1"),
                Source2 = new CompositionEffectSourceParameter("Source2")
            };
            m_arithmeticEffectBrush = m_compositor.CreateEffectFactory(
                arithmeticEffectDesc,
                new[]
                {
                    "effect.MultiplyAmount",
                    "effect.Source1Amount",
                    "effect.Source2Amount",
                    "effect.Offset"
                }
            ).CreateBrush();
            m_arithmeticEffectBrush.SetSourceParameter(
                "Source1",
                m_noEffectBrush);
            m_arithmeticEffectBrush.SetSourceParameter(
                "Source2",
                CreateBrushFromAsset("_P2A8041.jpg"));

            // Creates a blend effect that combines two images.
            var foregroundBrush = CreateBrushFromAsset("Checkerboard_100x100.png");
            m_blendEffectBrushes = new CompositionEffectBrush[m_supportedBlendModes.Length];
            for (int i = 0; i < m_supportedBlendModes.Length; i++)
            {
                var blendEffectDesc = new BlendEffect
                {
                    Mode = m_supportedBlendModes[i],
                    Background = new CompositionEffectSourceParameter("Background"),
                    Foreground = new CompositionEffectSourceParameter("Foreground")
                };
                m_blendEffectBrushes[i] = m_compositor.CreateEffectFactory(
                    blendEffectDesc
                ).CreateBrush();
                m_blendEffectBrushes[i].SetSourceParameter(
                    "Background",
                    m_noEffectBrush);
                m_blendEffectBrushes[i].SetSourceParameter(
                    "Foreground",
                    foregroundBrush);
            }

            // Generates an image containing a solid color.
            var colorSourceEffectDesc = new ColorSourceEffect // FloodEffect
            {
                Name = "effect"
            };
            m_colorSourceEffectBrush = m_compositor.CreateEffectFactory(
                colorSourceEffectDesc,
                new[] { "effect.Color" }
            ).CreateBrush();

            // Changes the contrast of an image.
            var contrastEffectDesc = new ContrastEffect
            {
                Name = "effect",
                Source = new CompositionEffectSourceParameter("Image")
            };
            m_contrastEffectBrush = m_compositor.CreateEffectFactory(
                contrastEffectDesc,
                new[] { "effect.Contrast" }
            ).CreateBrush();
            m_contrastEffectBrush.SetSourceParameter(
                "Image",
                m_noEffectBrush);

            // Changes the exposure of an image.
            var exposureEffectDesc = new ExposureEffect
            {
                Name = "effect",
                Source = new CompositionEffectSourceParameter("Image")
            };
            m_exposureEffectBrush = m_compositor.CreateEffectFactory(
                exposureEffectDesc,
                new[] { "effect.Exposure" }
            ).CreateBrush();
            m_exposureEffectBrush.SetSourceParameter(
                "Image",
                m_noEffectBrush);

            // Alters the colors of an image by applying a per-channel gamma transfer function.
            var gammaTransferEffectDesc = new GammaTransferEffect
            {
                Name = "effect",
                RedDisable = false,
                GreenDisable = false,
                BlueDisable = false,
                AlphaDisable = false,
                Source = new CompositionEffectSourceParameter("Image")
            };
            m_gammaTransferEffectBrush = m_compositor.CreateEffectFactory(
                gammaTransferEffectDesc,
                new[]
                {
                    "effect.RedAmplitude",
                    "effect.RedExponent",
                    "effect.RedOffset",
                    "effect.GreenAmplitude",
                    "effect.GreenExponent",
                    "effect.GreenOffset",
                    "effect.BlueAmplitude",
                    "effect.BlueExponent",
                    "effect.BlueOffset"
                }
            ).CreateBrush();
            m_gammaTransferEffectBrush.SetSourceParameter(
                "Image",
                m_noEffectBrush);

            // Converts an image to monochromatic gray.
            var grayscaleEffectDesc = new GrayscaleEffect
            {
                Name = "effect",
                Source = new CompositionEffectSourceParameter("Image")
            };
            m_grayscaleEffectBrush = m_compositor.CreateEffectFactory(
                grayscaleEffectDesc
            ).CreateBrush();
            m_grayscaleEffectBrush.SetSourceParameter(
                "Image",
                m_noEffectBrush);

            // Alters the color of an image by rotating its hue values.
            var hueRotationEffectDesc = new HueRotationEffect
            {
                Name = "effect",
                Source = new CompositionEffectSourceParameter("Image")
            };
            m_hueRotationEffectBrush = m_compositor.CreateEffectFactory(
                hueRotationEffectDesc,
                new[] { "effect.Angle" }
            ).CreateBrush();
            m_hueRotationEffectBrush.SetSourceParameter(
                "Image",
                m_noEffectBrush);

            // Inverts the colors of an image.
            var invertEffectDesc = new InvertEffect
            {
                Name = "effect",
                Source = new CompositionEffectSourceParameter("Image")
            };
            m_invertEffectBrush = m_compositor.CreateEffectFactory(
                invertEffectDesc
            ).CreateBrush();
            m_invertEffectBrush.SetSourceParameter(
                "Image",
                m_noEffectBrush);

            // Alters the saturation of an image.
            var saturationEffectDesc = new SaturationEffect
            {
                Name = "effect",
                Source = new CompositionEffectSourceParameter("Image")
            };
            m_saturateEffectBrush = m_compositor.CreateEffectFactory(
                saturationEffectDesc,
                new[] { "effect.Saturation" }
            ).CreateBrush();
            m_saturateEffectBrush.SetSourceParameter(
                "Image",
                m_noEffectBrush);

            // Converts an image to sepia tones.
            var supportedAlphaModes = new[]
            {
                CanvasAlphaMode.Premultiplied,
                CanvasAlphaMode.Straight
            };
            m_sepiaEffectBrushes = new CompositionEffectBrush[supportedAlphaModes.Length];
            for (int i = 0; i < supportedAlphaModes.Length; i++)
            {
                var sepiaEffectDesc = new SepiaEffect
                {
                    Name = "effect",
                    AlphaMode = supportedAlphaModes[i],
                    Source = new CompositionEffectSourceParameter("Image")
                };
                m_sepiaEffectBrushes[i] = m_compositor.CreateEffectFactory(
                    sepiaEffectDesc,
                    new[] { "effect.Intensity" }
                ).CreateBrush();
                m_sepiaEffectBrushes[i].SetSourceParameter(
                    "Image",
                    m_noEffectBrush);
            }

            // Adjusts the temperature and/or tint of an image.
            var temperatureAndTintEffectDesc = new TemperatureAndTintEffect
            {
                Name = "effect",
                Source = new CompositionEffectSourceParameter("Image")
            };
            m_temperatureAndTintEffectBrush = m_compositor.CreateEffectFactory(
                temperatureAndTintEffectDesc,
                new[]
                {
                    "effect.Temperature",
                    "effect.Tint"
                }
            ).CreateBrush();
            m_temperatureAndTintEffectBrush.SetSourceParameter(
                "Image",
                m_noEffectBrush);

            // Applies a 2D affine transform matrix to an image.
            var transform2DEffectDesc = new Transform2DEffect
            {
                TransformMatrix = new Matrix3x2(
                    -1, 0,
                    0, 1,
                    m_sprite.Size.X, 0),
                Source = new CompositionEffectSourceParameter("Image")
            };
            m_transform2DEffectBrush = m_compositor.CreateEffectFactory(
                transform2DEffectDesc
            ).CreateBrush();
            m_transform2DEffectBrush.SetSourceParameter(
                "Image",
                m_noEffectBrush);

            // For simplying UI states switch, put effect parameter grids in an array
            m_effectParamsGrids = new Grid[(int)EffectType.NumEffectTypes];
            m_effectParamsGrids[(int)EffectType.NoEffect] = null;
            m_effectParamsGrids[(int)EffectType.AlphaMask] = AlphaMaskParams;
            m_effectParamsGrids[(int)EffectType.Arithmetic] = ArithmeticParams;
            m_effectParamsGrids[(int)EffectType.Blend] = BlendParams;
            m_effectParamsGrids[(int)EffectType.ColorSource] = ColorSourceParams;
            m_effectParamsGrids[(int)EffectType.Contrast] = ContrastParams;
            m_effectParamsGrids[(int)EffectType.Exposure] = ExposureParams;
            m_effectParamsGrids[(int)EffectType.GammaTransfer] = GammaTransferParams;
            m_effectParamsGrids[(int)EffectType.Grayscale] = null;
            m_effectParamsGrids[(int)EffectType.HueRotation] = HueRotationParams;
            m_effectParamsGrids[(int)EffectType.Invert] = null;
            m_effectParamsGrids[(int)EffectType.Saturation] = SaturationParams;
            m_effectParamsGrids[(int)EffectType.Sepia] = SepiaParams;
            m_effectParamsGrids[(int)EffectType.TemperatureAndTint] = TemperatureAndTintParams;
            m_effectParamsGrids[(int)EffectType.Transform2D] = null;

            // Same as grids
            m_effectBrushes = new CompositionBrush[(int)EffectType.NumEffectTypes];
            m_effectBrushes[(int)EffectType.NoEffect] = m_noEffectBrush;
            m_effectBrushes[(int)EffectType.AlphaMask] = m_alphaMaskEffectBrush;
            m_effectBrushes[(int)EffectType.Arithmetic] = m_arithmeticEffectBrush;
            m_effectBrushes[(int)EffectType.Blend] = m_blendEffectBrushes[m_activeBlendMode];
            m_effectBrushes[(int)EffectType.ColorSource] = m_colorSourceEffectBrush;
            m_effectBrushes[(int)EffectType.Contrast] = m_contrastEffectBrush;
            m_effectBrushes[(int)EffectType.Exposure] = m_exposureEffectBrush;
            m_effectBrushes[(int)EffectType.GammaTransfer] = m_gammaTransferEffectBrush;
            m_effectBrushes[(int)EffectType.Grayscale] = m_grayscaleEffectBrush;
            m_effectBrushes[(int)EffectType.HueRotation] = m_hueRotationEffectBrush;
            m_effectBrushes[(int)EffectType.Invert] = m_invertEffectBrush;
            m_effectBrushes[(int)EffectType.Saturation] = m_saturateEffectBrush;
            m_effectBrushes[(int)EffectType.Sepia] = m_sepiaEffectBrushes[m_activeSepiaAlphaMode];
            m_effectBrushes[(int)EffectType.TemperatureAndTint] = m_temperatureAndTintEffectBrush;
            m_effectBrushes[(int)EffectType.Transform2D] = m_transform2DEffectBrush;

            this.InitializeValues();
        }
        /// <summary>
        /// Creates a circular solid colored brush that we can apply to a visual
        /// </summary>
        private CompositionEffectBrush CreateCircleBrushWithColor(Windows.UI.Color color)
        {

            var colorBrush = _compositor.CreateColorBrush(color);

            //
            // Because Windows.UI.Composition does not have a Circle visual, we will 
            // work around by using a circular opacity mask
            // Create a simple Composite Effect, using DestinationIn (S * DA), 
            // with a color source and a named parameter source.
            //
            var effect = new CompositeEffect
            {
                Mode = CanvasComposite.DestinationIn,
                Sources =
                {
                    new ColorSourceEffect()
                    {
                        Color = color
                    },
                    new CompositionEffectSourceParameter("mask")
                }

            };
            var factory = _compositor.CreateEffectFactory(effect);
            var brush = factory.CreateBrush();

            //
            // Create the mask brush using the circle mask
            //
            CompositionSurfaceBrush maskBrush = _compositor.CreateSurfaceBrush();
            maskBrush.Surface = _circleMaskSurface.Surface;
            brush.SetSourceParameter("mask", maskBrush);

            return brush;

        }
        private ICanvasImage CreateChromaKey()
        {
            textLabel = requiresWin10;

            var chromaKeyEffect = new ChromaKeyEffect
            {
                Source = bitmapTiger,
                Color = Color.FromArgb(255, 162, 125, 73),
                Feather = true
            };

            // Composite the chromakeyed image on top of a background checker pattern.
            Color[] twoByTwoChecker =
            {
                Colors.LightGray, Colors.DarkGray,
                Colors.DarkGray,  Colors.LightGray,
            };

            var compositeEffect = new CompositeEffect
            {
                Sources =
                {
                    // Create the checkered background by scaling up a tiled 2x2 bitmap.
                    new CropEffect
                    {
                        Source = new DpiCompensationEffect
                        {
                            Source = new ScaleEffect
                            {
                                Source = new BorderEffect
                                {
                                    Source = CanvasBitmap.CreateFromColors(canvas, twoByTwoChecker, 2, 2),
                                    ExtendX = CanvasEdgeBehavior.Wrap,
                                    ExtendY = CanvasEdgeBehavior.Wrap
                                },
                                Scale = new Vector2(8, 8),
                                InterpolationMode = CanvasImageInterpolation.NearestNeighbor
                            }
                        },
                        SourceRectangle = bitmapTiger.Bounds
                    },

                    // Composite the chromakey result on top of the background.
                    chromaKeyEffect
                }
            };

            // Animation changes the chromakey matching tolerance.
            animationFunction = elapsedTime =>
            {
                chromaKeyEffect.Tolerance = 0.1f + (float)Math.Sin(elapsedTime) * 0.1f;
            };

            return compositeEffect;
        }
Exemple #38
0
        private CompositeEffect CreateEffects(List<ShadowParam> shadowParams, CanvasCommandList canvasCommandList)
        {
            CompositeEffect compositeEffect = new CompositeEffect();

            shadowParams.ForEach(param =>
            {
                var shadowEffect = CreateShadowEffect(canvasCommandList, param);
                compositeEffect.Sources.Add(shadowEffect);
            });
            return compositeEffect;
        }
Exemple #39
0
        public ICanvasImage Apply(ICanvasImage image)
        {
            if (IsEnabled)
            {
                var originalImage = image;
                Rect? bounds = null;

                // Apply all our effects in turn.
                foreach (var effect in Effects)
                {
                    image = effect.Apply(image, ref bounds);
                }

                // Mask so these effects only alter a specific region of the image?
                if (regionMask != null)
                {
                    var selectedRegion = new CompositeEffect
                    {
                        Sources = { image, GetRegionMask() },
                        Mode = CanvasComposite.DestinationIn
                    };

                    image = new CompositeEffect
                    {
                        Sources = { originalImage, selectedRegion }
                    };

                    if (bounds.HasValue)
                    {
                        image = new CropEffect
                        {
                            Source = image,
                            SourceRectangle = bounds.Value
                        };
                    }
                }
            }

            return image;
        }
        /// <summary>
        /// Function is responsible for creating the circular alpha masked profile brush
        /// </summary>
        /// <returns></returns>
        private CompositionEffectBrush InitializeCompositeEffect()
        {
            //
            // Create a simple Composite Effect, using DestinationIn (S * DA), and two named sources - image and mask.
            //
            var effect = new CompositeEffect
            {
                Mode = CanvasComposite.DestinationIn,
                Sources =
                {
                    new CompositionEffectSourceParameter("image"),
                    new CompositionEffectSourceParameter("mask")
                }

            };
            var factory = _compositor.CreateEffectFactory(effect);
            var brush = factory.CreateBrush();

            //
            // Load in the profile picture as a brush using the Composition Toolkit.
            //
            CompositionSurfaceBrush profileBrush = _compositor.CreateSurfaceBrush();
            var image = _imageFactory.CreateImageFromUri(new Uri("ms-appx:///Assets/teched3ae5a27b-4f78-e111-94ad-001ec953730b.jpg"));
            profileBrush.Surface = image.Surface;
            brush.SetSourceParameter("image", profileBrush);

            //
            // Load in the circular mask picture asx a brush using the composition Toolkit.
            //
            CompositionSurfaceBrush maskBrush = _compositor.CreateSurfaceBrush();
            image = _imageFactory.CreateImageFromUri(new Uri("ms-appx:///Assets/CircleMask.png"));
            maskBrush.Surface = image.Surface;
            brush.SetSourceParameter("mask", maskBrush);

            return brush;

        }
        /// <summary>
        /// Creates a reflection of the given Visual
        /// </summary>
        /// <param name="visual">Visual whose reflection has to be created</param>
        /// <param name="reflectionDistance">Distance of the reflection from the visual</param>
        /// <param name="reflectionLength">Normalized Length of the reflected visual that will be visible.</param>
        /// <param name="location"> <see cref="ReflectionLocation"/> - Location of the reflection with respect 
        /// to the Visual - Bottom, Top, Left or Right</param>
        public void CreateReflection(ContainerVisual visual, float reflectionDistance = 0f,
            float reflectionLength = 0.7f, ReflectionLocation location = ReflectionLocation.Bottom)
        {
            // Create the visual layer that will contained the visual's reflection
            var reflectionLayer = _compositor.CreateLayerVisual();
            reflectionLayer.Size = visual.Size;
            reflectionLayer.CenterPoint = new Vector3(visual.Size * 0.5f, 0);

            // Create the effect to create the opacity mask
            var effect = new CompositeEffect
            {
                // CanvasComposite.DestinationIn - Intersection of source and mask. 
                // Equation: O = MA * S
                // where O - Output pixel, MA - Mask Alpha, S - Source pixel.
                Mode = CanvasComposite.DestinationIn,
                Sources =
                        {
                            new CompositionEffectSourceParameter("source"),
                            new CompositionEffectSourceParameter("mask")
                        }
            };

            var effectFactory = _compositor.CreateEffectFactory(effect);
            var effectBrush = effectFactory.CreateBrush();

            // Create the gradient brush for the effect
            var gradientBrush = new CanvasLinearGradientBrush(_canvasDevice,
                                                                Colors.White, Colors.Transparent);

            // Based on the reflection location,
            // Set the Offset, RotationAxis and RotationAngleInDegrees of the reflectionLayer and
            // set the StartPoint and EndPoint of the gradientBrush
            switch (location)
            {
                case ReflectionLocation.Bottom:
                    reflectionLayer.RotationAxis = new Vector3(1, 0, 0);
                    reflectionLayer.RotationAngleInDegrees = 180;
                    reflectionLayer.Offset = new Vector3(0, visual.Size.Y + reflectionDistance, 0);
                    gradientBrush.StartPoint = new Vector2(visual.Size.X * 0.5f, 0);
                    gradientBrush.EndPoint = new Vector2(visual.Size.X * 0.5f, visual.Size.Y * reflectionLength);
                    break;
                case ReflectionLocation.Top:
                    reflectionLayer.RotationAxis = new Vector3(1, 0, 0);
                    reflectionLayer.RotationAngleInDegrees = -180;
                    reflectionLayer.Offset = new Vector3(0, -visual.Size.Y - reflectionDistance, 0);
                    gradientBrush.StartPoint = new Vector2(visual.Size.X * 0.5f, visual.Size.Y);
                    gradientBrush.EndPoint = new Vector2(visual.Size.X * 0.5f, visual.Size.Y * (1f - reflectionLength));
                    break;
                case ReflectionLocation.Left:
                    reflectionLayer.RotationAxis = new Vector3(0, 1, 0);
                    reflectionLayer.RotationAngleInDegrees = -180;
                    reflectionLayer.Offset = new Vector3(-visual.Size.X - reflectionDistance, 0, 0);
                    gradientBrush.StartPoint = new Vector2(visual.Size.X, visual.Size.Y * 0.5f);
                    gradientBrush.EndPoint = new Vector2(visual.Size.X * (1f - reflectionLength), visual.Size.Y * 0.5f);
                    break;
                case ReflectionLocation.Right:
                    reflectionLayer.RotationAxis = new Vector3(0, 1, 0);
                    reflectionLayer.RotationAngleInDegrees = 180;
                    reflectionLayer.Offset = new Vector3(visual.Size.X + reflectionDistance, 0, 0);
                    gradientBrush.StartPoint = new Vector2(0, visual.Size.Y * 0.5f);
                    gradientBrush.EndPoint = new Vector2(visual.Size.X * reflectionLength, visual.Size.Y * 0.5f);
                    break;
            }

            // Create a mask filled with gradientBrush
            var mask = CreateGeometrySurface(visual.Size.ToSize(), null, Colors.Transparent, gradientBrush);

            // Set the 'mask' parameter of the effectBrush
            effectBrush.SetSourceParameter("mask", _compositor.CreateSurfaceBrush(mask.Surface));

            // Set the effect for the reflection layer
            reflectionLayer.Effect = effectBrush;

            // Now we need to duplicate the visual tree of the visual
            ArrangeVisualReflection(visual, reflectionLayer, true);

            visual.Children.InsertAtTop(reflectionLayer);
        }
        /// <summary>
        /// Generate the flame effect graph. This method is called before the text command list
        /// (input) is created.
        /// </summary>
        private void CreateFlameEffect()
        {
            // Thicken the text.
            morphology = new MorphologyEffect
            {
                // The Source property is set by SetupText().
                Mode = MorphologyEffectMode.Dilate,
                Width = 7,
                Height = 1
            };

            // Blur, then colorize the text from black to red to orange as the alpha increases.
            var colorize = new ColorMatrixEffect
            {
                Source = new GaussianBlurEffect
                {
                    Source = morphology,
                    BlurAmount = 3f
                },
                ColorMatrix = new Matrix5x4
                {
                    M11 = 0f, M12 = 0f, M13 = 0f, M14 = 0f,
                    M21 = 0f, M22 = 0f, M23 = 0f, M24 = 0f,
                    M31 = 0f, M32 = 0f, M33 = 0f, M34 = 0f,
                    M41 = 0f, M42 = 1f, M43 = 0f, M44 = 1f,
                    M51 = 1f, M52 = -0.5f, M53 = 0f, M54 = 0f
                }
            };

            // Generate a Perlin noise field (see flamePosition).
            // Animate the noise by modifying flameAnimation's transform matrix at render time.
            flameAnimation = new Transform2DEffect
            {
                Source = new BorderEffect
                {
                    Source = new TurbulenceEffect
                    {
                        Frequency = new Vector2(0.109f, 0.109f),
                        Size = new Vector2(500.0f, 80.0f)
                    },
                    // Use Mirror extend mode to allow us to spatially translate the noise
                    // without any visible seams.
                    ExtendX = CanvasEdgeBehavior.Mirror,
                    ExtendY = CanvasEdgeBehavior.Mirror
                }
            };

            // Give the flame its wavy appearance by generating a displacement map from the noise
            // (see flameAnimation) and applying this to the text.
            // Stretch and position this flame behind the original text.
            flamePosition = new Transform2DEffect
            {
                Source = new DisplacementMapEffect
                {
                    Source = colorize,
                    Displacement = flameAnimation,
                    Amount = 40.0f
                }
                // Set the transform matrix at render time as it depends on window size.
            };

            // Composite the text over the flames.
            composite = new CompositeEffect()
            {
                Sources = { flamePosition, null }
                // Replace null with the text command list when it is created.
            };
        }
        private async void CreateImageAndLights(Vector2 sizeLightBounds)
        {
            //
            // Image and effect setup
            //

            // Create the effect graph.  We will combine the desaturated image with two diffuse lights
            IGraphicsEffect graphicsEffect = new CompositeEffect()
            {
                Mode = Microsoft.Graphics.Canvas.CanvasComposite.Add,
                Sources =
                {
                    new SaturationEffect()
                    {
                        Saturation = 0,
                        Source = new CompositionEffectSourceParameter("ImageSource")
                    },

                    new PointDiffuseEffect()
                    {
                        Name = "Light1",
                        DiffuseAmount = 1f,
                        Source = new CompositionEffectSourceParameter("NormalMap"),
                    },

                    new PointDiffuseEffect()
                    {
                        Name = "Light2",
                        DiffuseAmount = 1f,
                        Source = new CompositionEffectSourceParameter("NormalMap"),
                    },
                }
            };

            // Create the normal map.  For this sample, we want a flat surface with no bumps
            CompositionDrawingSurface normalMap = await SurfaceLoader.LoadFromUri(new Uri("ms-appx:///Samples/SDK Insider/NowPlaying/NormalMap.jpg"));
            CompositionSurfaceBrush surfaceBrush = _compositor.CreateSurfaceBrush(normalMap);
            surfaceBrush.Stretch = CompositionStretch.Fill;

            // Create the effect factory, we're going to animate the light positions and colors
            CompositionEffectFactory effectFactory = _compositor.CreateEffectFactory(graphicsEffect, 
                                new[] { "Light1.LightPosition", "Light1.LightColor",
                                        "Light2.LightPosition", "Light2.LightColor", });

            // Create the effect brush and bind the normal map
            CompositionEffectBrush brush = effectFactory.CreateBrush();         
            brush.SetSourceParameter("NormalMap", surfaceBrush);

            // Update the CompositionImage to use the custom effect brush
            ArtistImage.Brush = brush;


            //
            //  Animation setup
            //
            
            // Setup the first light's position, top and to the left in general
            LinearEasingFunction linear = _compositor.CreateLinearEasingFunction();
            Vector3KeyFrameAnimation positionAnimation = _compositor.CreateVector3KeyFrameAnimation();
            positionAnimation.InsertKeyFrame(0f, new Vector3(0f, 0f, 300f), linear);
            positionAnimation.InsertKeyFrame(.33f, new Vector3(sizeLightBounds.X * .5f, sizeLightBounds.Y * .5f, 100f), linear);
            positionAnimation.InsertKeyFrame(.66f, new Vector3(sizeLightBounds.X * .25f, sizeLightBounds.Y * .95f, 100f), linear);
            positionAnimation.InsertKeyFrame(1f, new Vector3(0f, 0f, 300f), linear);
            positionAnimation.Duration = TimeSpan.FromMilliseconds(20000);
            positionAnimation.IterationBehavior = AnimationIterationBehavior.Forever;
            brush.StartAnimation("Light1.LightPosition", positionAnimation);


            // Setup the first light's color animation, cycling through some brighter tones
            ColorKeyFrameAnimation colorAnimation = _compositor.CreateColorKeyFrameAnimation();
            colorAnimation.InsertKeyFrame(0f, Colors.Orange);
            colorAnimation.InsertKeyFrame(.2f, Colors.Orange);
            colorAnimation.InsertKeyFrame(.3f, Colors.Red);
            colorAnimation.InsertKeyFrame(.5f, Colors.Red);
            colorAnimation.InsertKeyFrame(.6f, Colors.Yellow);
            colorAnimation.InsertKeyFrame(.8f, Colors.Yellow);
            colorAnimation.InsertKeyFrame(.9f, Colors.Orange);
            colorAnimation.InsertKeyFrame(1f, Colors.Orange);
            colorAnimation.Duration = TimeSpan.FromMilliseconds(20000);
            colorAnimation.IterationBehavior = AnimationIterationBehavior.Forever;
            brush.StartAnimation("Light1.LightColor", colorAnimation);


            // Setup the second light's position, down and to the right in general
            positionAnimation = _compositor.CreateVector3KeyFrameAnimation();
            positionAnimation.InsertKeyFrame(0f, new Vector3(sizeLightBounds.X, sizeLightBounds.Y, 200f), linear);
            positionAnimation.InsertKeyFrame(.33f, new Vector3(sizeLightBounds.X * .7f, sizeLightBounds.Y * .9f, 300f), linear);
            positionAnimation.InsertKeyFrame(.66f, new Vector3(sizeLightBounds.X * .95f, sizeLightBounds.Y * .95f, 100f), linear);
            positionAnimation.InsertKeyFrame(1f, new Vector3(sizeLightBounds.X, sizeLightBounds.Y, 200f), linear);
            positionAnimation.Duration = TimeSpan.FromMilliseconds(20000);
            positionAnimation.IterationBehavior = AnimationIterationBehavior.Forever;
            brush.StartAnimation("Light2.LightPosition", positionAnimation);
            
            // Setup the second light's color animation, cycling through some darker tones
            colorAnimation = _compositor.CreateColorKeyFrameAnimation();
            colorAnimation.InsertKeyFrame(0f, Colors.Blue);
            colorAnimation.InsertKeyFrame(.2f, Colors.Blue);
            colorAnimation.InsertKeyFrame(.3f, Colors.DarkGreen);
            colorAnimation.InsertKeyFrame(.5f, Colors.DarkGreen);
            colorAnimation.InsertKeyFrame(.6f, Colors.DarkBlue);
            colorAnimation.InsertKeyFrame(.8f, Colors.DarkBlue);
            colorAnimation.InsertKeyFrame(.9f, Colors.Blue);
            colorAnimation.InsertKeyFrame(1f, Colors.Blue);
            colorAnimation.Duration = TimeSpan.FromMilliseconds(20000);
            colorAnimation.IterationBehavior = AnimationIterationBehavior.Forever;
            brush.StartAnimation("Light2.LightColor", colorAnimation);
        }
        private ICanvasImage CreateChromaKey()
        {
            textLabel = requiresWin10;

            var chromaKeyEffect = new ChromaKeyEffect
            {
                Source = bitmapTiger,
                Color = Color.FromArgb(255, 162, 125, 73),
                Feather = true
            };

            // Composite the chromakeyed image on top of a background checker pattern.
            var compositeEffect = new CompositeEffect
            {
                Sources = { CreateCheckeredBackground(), chromaKeyEffect }
            };

            // Animation changes the chromakey matching tolerance.
            animationFunction = elapsedTime =>
            {
                chromaKeyEffect.Tolerance = 0.1f + (float)Math.Sin(elapsedTime) * 0.1f;
            };

            return compositeEffect;
        }
        void canvas_CreateResources(CanvasControl sender, CanvasCreateResourcesEventArgs args)
        {
            // Fix the source rendertarget at 96 DPI, but let the destination rendertarget inherit
            // its DPI from the CanvasControl. This means their DPI will differ when run on a high
            // DPI display, so we can make sure the region mapping functions handle that correctly.
            sourceRenderTarget = new CanvasRenderTarget(sender, width, height, 96);
            destRenderTarget = new CanvasRenderTarget(sender, width, height);

            // Effect graph applies a subtle blur to the image, and also creates a shadow
            // with a larger blur amount and offset translation.
            blurEffect = new GaussianBlurEffect
            {
                Source = sourceRenderTarget,
                BlurAmount = 2
            };

            shadowEffect = new ShadowEffect
            {
                Source = sourceRenderTarget,
                BlurAmount = 6
            };

            compositeEffect = new CompositeEffect
            {
                Sources =
                {
                    new Transform2DEffect
                    {
                        Source = shadowEffect,
                        TransformMatrix = Matrix3x2.CreateTranslation(16, 16),
                    },

                    blurEffect
                }
            };

            // Arrange a bunch of text characters.
            var textFormat = new CanvasTextFormat
            {
                FontFamily = "Comic Sans MS",
                FontSize = 60,
            };

            characterLayouts = new List<CanvasTextLayout>();
            characterPositions = new List<Vector2>();

            var position = Vector2.Zero;

            for (char character = 'a'; character <= 'z'; character++)
            {
                var textLayout = new CanvasTextLayout(sender, character.ToString(), textFormat, width, height);

                characterLayouts.Add(textLayout);
                characterPositions.Add(position);

                if (character == 'm')
                {
                    position.X = 0;
                    position.Y += (float)textLayout.LayoutBounds.Height;
                }
                else
                {
                    position.X += (float)textLayout.LayoutBounds.Width;
                }
            }
        }
        private ICanvasImage CreateOpacity()
        {
            if (!OpacityEffect.IsSupported)
            {
                return CreateNotSupportedMessage(requiresWin10_14393);
            }

            textLabel = requiresWin10_14393;

            var opacityEffect = new OpacityEffect
            {
                Source = bitmapTiger
            };

            // Composite the fading tiger on top of a background checker pattern.
            var compositeEffect = new CompositeEffect
            {
                Sources = { CreateCheckeredBackground(), opacityEffect }
            };

            // Animation changes the opacity.
            animationFunction = elapsedTime =>
            {
                opacityEffect.Opacity = 0.5f + (float)Math.Sin(elapsedTime * 2) / 2;
            };

            return compositeEffect;
        }
        private ICanvasImage CreateLighting()
        {
            var heightMap = new LuminanceToAlphaEffect
            {
                Source = bitmapTiger
            };

            var distantDiffuseEffect = new DistantDiffuseEffect
            {
                Source = heightMap,
                HeightMapScale = 2
            };

            var distantSpecularEffect = new DistantSpecularEffect
            {
                Source = heightMap,
                SpecularExponent = 16
            };

            var pointDiffuseEffect = new PointDiffuseEffect
            {
                Source = heightMap,
                HeightMapScale = 2
            };

            var pointSpecularEffect = new PointSpecularEffect
            {
                Source = heightMap,
                SpecularExponent = 16
            };

            var spotDiffuseEffect = new SpotDiffuseEffect
            {
                Source = heightMap,
                HeightMapScale = 2,
                LimitingConeAngle = 0.25f,
                LightTarget = new Vector3(bitmapTiger.Size.ToVector2(), 0) / 2
            };

            var spotSpecularEffect = new SpotSpecularEffect
            {
                Source = heightMap,
                SpecularExponent = 16,
                LimitingConeAngle = 0.25f,
                LightTarget = new Vector3(bitmapTiger.Size.ToVector2(), 0) / 2
            };

            // Lay out all the different light types in a grid.
            var xgap = (float)bitmapTiger.Size.Width * 1.1f;
            var ygap = (float)bitmapTiger.Size.Height * 1.1f;

            var compositeEffect = new CompositeEffect
            {
                Sources =
                {
                    AddTextOverlay(distantDiffuseEffect,  -xgap, -ygap),
                    AddTextOverlay(distantSpecularEffect, -xgap,  0),
                    AddTextOverlay(pointDiffuseEffect,    -0,    -ygap),
                    AddTextOverlay(pointSpecularEffect,   -0,     0),
                    AddTextOverlay(spotDiffuseEffect,      xgap, -ygap),
                    AddTextOverlay(spotSpecularEffect,     xgap,  0),

                    CombineDiffuseAndSpecular(distantDiffuseEffect, distantSpecularEffect, -xgap, ygap),
                    CombineDiffuseAndSpecular(pointDiffuseEffect,   pointSpecularEffect,    0,    ygap),
                    CombineDiffuseAndSpecular(spotDiffuseEffect,    spotSpecularEffect,     xgap, ygap),
                }
            };

            ICanvasImage finalEffect = compositeEffect;

            // Check the screen size, and scale down our output if the screen is too small to fit the whole thing as-is.
            var xScaleFactor = (float)canvas.ActualWidth / 750;
            var yScaleFactor = (float)canvas.ActualHeight / 500;

            var scaleFactor = Math.Min(xScaleFactor, yScaleFactor);

            if (scaleFactor < 1)
            {
                finalEffect = new Transform2DEffect
                {
                    Source = compositeEffect,
                    TransformMatrix = Matrix3x2.CreateScale(scaleFactor, bitmapTiger.Size.ToVector2() / 2)
                };
            }

            // Animation changes the light directions.
            animationFunction = elapsedTime =>
            {
                distantDiffuseEffect.Azimuth = 
                distantSpecularEffect.Azimuth = elapsedTime % ((float)Math.PI * 2);

                distantDiffuseEffect.Elevation =
                distantSpecularEffect.Elevation = (float)Math.PI / 4 + (float)Math.Sin(elapsedTime / 2) * (float)Math.PI / 8;

                pointDiffuseEffect.LightPosition = 
                pointSpecularEffect.LightPosition =
                spotDiffuseEffect.LightPosition =
                spotSpecularEffect.LightPosition = new Vector3((float)Math.Cos(elapsedTime), (float)Math.Sin(elapsedTime), 1) * 100;
            };

            return finalEffect;
        }
        private ICanvasImage CreateComposite()
        {
            var compositeEffect = new CompositeEffect { Mode = CanvasComposite.SourceOver };

            var transformEffects = new List<Transform3DEffect>();

            const int petalCount = 12;

            for (int i = 0; i < petalCount; i++)
            {
                var transformEffect = new Transform3DEffect
                {
                    Source = bitmapTiger
                };

                compositeEffect.Sources.Add(transformEffect);
                transformEffects.Add(transformEffect);
            }

            // Animation rotates each copy of the image at a different speed.
            animationFunction = elapsedTime =>
            {
                for (int i = 0; i < petalCount; i++)
                {
                    transformEffects[i].TransformMatrix = Matrix4x4.CreateRotationZ(elapsedTime * i / 3);
                }
            };

            currentEffectSize = Vector2.Zero;

            return compositeEffect;
        }
        public void ProcessFrame(ProcessVideoFrameContext context)
        {
            var inputSurface = context.InputFrame.Direct3DSurface;
            var outputSurface = context.OutputFrame.Direct3DSurface;

            using (var inputBitmap = CanvasBitmap.CreateFromDirect3D11Surface(canvasDevice, inputSurface))
            using (var renderTarget = CanvasRenderTarget.CreateFromDirect3D11Surface(canvasDevice, outputSurface))
            using (var ds = renderTarget.CreateDrawingSession())
            using (var brush = new CanvasImageBrush(canvasDevice, inputBitmap))
            using (var textCommandList = new CanvasCommandList(canvasDevice))
            {
                using (var clds = textCommandList.CreateDrawingSession())
                {
                    clds.DrawText(
                        "Win2D\nMediaClip",
                        (float)inputBitmap.Size.Width / 2,
                        (float)inputBitmap.Size.Height / 2,
                        brush,
                        new CanvasTextFormat()
                        {
                            FontSize = (float)inputBitmap.Size.Width / 5,
                            FontWeight = new FontWeight() { Weight = 999 },
                            HorizontalAlignment = CanvasHorizontalAlignment.Center,
                            VerticalAlignment = CanvasVerticalAlignment.Center
                        });
                }

                var background = new GaussianBlurEffect()
                {
                    BlurAmount = 10,
                    BorderMode = EffectBorderMode.Hard,
                    Source = new BrightnessEffect()
                    {
                        BlackPoint = new Vector2(0.5f, 0.7f),
                        Source = new SaturationEffect()
                        {
                            Saturation = 0,
                            Source = inputBitmap
                        }
                    }
                };

                var shadow = new ShadowEffect()
                {
                    Source = textCommandList,
                    BlurAmount = 10
                };

                var composite = new CompositeEffect()
                {
                    Sources = { background, shadow, textCommandList }
                };

                ds.DrawImage(composite);
            }
        }
        private ICanvasImage CreateShadow()
        {
            var renderTarget = new CanvasRenderTarget(canvas, 360, 150);

            using (var ds = renderTarget.CreateDrawingSession())
            {
                ds.Clear(Color.FromArgb(0, 0, 0, 0));

                ds.DrawText("This text is drawn onto a rendertarget", 10, 10, Colors.White);
                ds.DrawText("with a different color per line,", 10, 40, Colors.Red);
                ds.DrawText("after which a drop shadow is", 10, 70, Colors.Green);
                ds.DrawText("generated using image effects.", 10, 100, Colors.Blue);
            }

            var shadowEffect = new Transform2DEffect
            {
                Source = new ShadowEffect
                {
                    Source = renderTarget,
                    BlurAmount = 2
                },
                TransformMatrix = Matrix3x2.CreateTranslation(3, 3)
            };

            var whiteBackground = new CropEffect
            {
                Source = new ColorSourceEffect { Color = Colors.White },
                SourceRectangle = renderTarget.Bounds
            };

            var compositeEffect = new CompositeEffect
            {
                Sources = { whiteBackground, shadowEffect, renderTarget }
            };

            animationFunction = elapsedTime => { };

            currentEffectSize = renderTarget.Size.ToVector2();

            return compositeEffect;
        }
        private void UpdateLightingEffect()
        {
            _ambientLight.Targets.RemoveAll();
            _pointLight.Targets.RemoveAll();
            _distantLight.Targets.RemoveAll();
            _spotLight.Targets.RemoveAll();

            ComboBoxItem item = LightingSelection.SelectedValue as ComboBoxItem;
            switch ((LightingTypes)item.Tag)
            {
                case LightingTypes.PointDiffuse:
                    {
                        //
                        // Result = Ambient +       Diffuse
                        // Result = (Image) + (.75 * Diffuse color)
                        //

                        IGraphicsEffect graphicsEffect = new CompositeEffect()
                        {
                            Mode = CanvasComposite.Add,
                            Sources =
                            {
                                new CompositionEffectSourceParameter("ImageSource"),
                                new SceneLightingEffect()
                                {
                                    AmbientAmount = 0,
                                    DiffuseAmount = .75f,
                                    SpecularAmount = 0,
                                    NormalMapSource = new CompositionEffectSourceParameter("NormalMap"),
                                }
                            }
                        };

                        _effectFactory = _compositor.CreateEffectFactory(graphicsEffect);

                        // Set the light coordinate space and add the target
                        Visual lightRoot = ElementCompositionPreview.GetElementVisual(ThumbnailList);
                        _pointLight.CoordinateSpace = lightRoot;
                        _pointLight.Targets.Add(lightRoot);
                    }
                    break;

                case LightingTypes.PointSpecular:
                    {
                        //
                        // Result =    Ambient   +       Diffuse           +     Specular
                        // Result = (Image * .6) + (Image * Diffuse color) + (Specular color)
                        //

                        IGraphicsEffect graphicsEffect = new CompositeEffect()
                        {
                            Mode = CanvasComposite.DestinationIn,
                            Sources =
                            {
                                new ArithmeticCompositeEffect()
                                {
                                    Source1Amount = 1,
                                    Source2Amount = 1,
                                    MultiplyAmount = 0,

                                    Source1 = new ArithmeticCompositeEffect()
                                    {
                                        MultiplyAmount = 1,
                                        Source1Amount = 0,
                                        Source2Amount = 0,
                                        Source1 = new CompositionEffectSourceParameter("ImageSource"),
                                        Source2 = new SceneLightingEffect()
                                        {
                                            AmbientAmount = .6f,
                                            DiffuseAmount = 1f,
                                            SpecularAmount = 0f,
                                            NormalMapSource = new CompositionEffectSourceParameter("NormalMap"),
                                        }
                                    },
                                    Source2 = new SceneLightingEffect()
                                    {
                                        AmbientAmount = 0,
                                        DiffuseAmount = 0f,
                                        SpecularAmount = 1f,
                                        SpecularShine = 100,
                                        NormalMapSource = new CompositionEffectSourceParameter("NormalMap"),
                                    }
                                },
                                new CompositionEffectSourceParameter("NormalMap"),
                            }
                        };

                        _effectFactory = _compositor.CreateEffectFactory(graphicsEffect);

                        // Set the light coordinate space and add the target
                        Visual lightRoot = ElementCompositionPreview.GetElementVisual(ThumbnailList);
                        _ambientLight.Targets.Add(lightRoot);
                        _pointLight.CoordinateSpace = lightRoot;
                        _pointLight.Targets.Add(lightRoot);
                    }
                    break;

                case LightingTypes.SpotLightDiffuse:
                    {
                        //
                        // Result = Ambient +      Diffuse
                        // Result =  Image  + (Diffuse color * .75)
                        //

                        IGraphicsEffect graphicsEffect = new CompositeEffect()
                        {
                            Mode = CanvasComposite.Add,
                            Sources =
                            {
                                new CompositionEffectSourceParameter("ImageSource"),
                                new SceneLightingEffect()
                                {
                                    AmbientAmount = 0,
                                    DiffuseAmount = .75f,
                                    SpecularAmount = 0,
                                    NormalMapSource = new CompositionEffectSourceParameter("NormalMap"),
                                }
                            }
                        };

                        _effectFactory = _compositor.CreateEffectFactory(graphicsEffect);

                        // Set the light coordinate space and add the target
                        Visual lightRoot = ElementCompositionPreview.GetElementVisual(ThumbnailList);
                        _spotLight.CoordinateSpace = lightRoot;
                        _spotLight.Targets.Add(lightRoot);
                        _spotLight.InnerConeAngle = (float)(Math.PI / 15);
                        _spotLight.OuterConeAngle = (float)(Math.PI / 10);
                        _spotLight.Direction = new Vector3(0, 0, -1);
                    };
                    break;

                case LightingTypes.SpotLightSpecular:
                    {
                        //
                        // Result =    Ambient   +       Diffuse           +     Specular
                        // Result = (Image * .6) + (Image * Diffuse color) + (Specular color)
                        //

                        IGraphicsEffect graphicsEffect = new CompositeEffect()
                        {
                            Mode = CanvasComposite.DestinationIn,
                            Sources =
                            {
                                new ArithmeticCompositeEffect()
                                {
                                    Source1Amount = 1,
                                    Source2Amount = 1,
                                    MultiplyAmount = 0,

                                    Source1 = new ArithmeticCompositeEffect()
                                    {
                                        MultiplyAmount = 1,
                                        Source1Amount = 0,
                                        Source2Amount = 0,
                                        Source1 = new CompositionEffectSourceParameter("ImageSource"),
                                        Source2 = new SceneLightingEffect()
                                        {
                                            AmbientAmount = .6f,
                                            DiffuseAmount = 1f,
                                            SpecularAmount = 0f,
                                            NormalMapSource = new CompositionEffectSourceParameter("NormalMap"),
                                        }
                                    },
                                    Source2 = new SceneLightingEffect()
                                    {
                                        AmbientAmount = 0,
                                        DiffuseAmount = 0f,
                                        SpecularAmount = 1f,
                                        SpecularShine = 100,
                                        NormalMapSource = new CompositionEffectSourceParameter("NormalMap"),
                                    }
                                },
                                new CompositionEffectSourceParameter("NormalMap"),
                            }
                        };

                        // Create the effect factory
                        _effectFactory = _compositor.CreateEffectFactory(graphicsEffect);

                        // Set the light coordinate space and add the target
                        Visual lightRoot = ElementCompositionPreview.GetElementVisual(ThumbnailList);
                        _ambientLight.Targets.Add(lightRoot);
                        _spotLight.CoordinateSpace = lightRoot;
                        _spotLight.Targets.Add(lightRoot);
                        _spotLight.InnerConeAngle = (float)(Math.PI / 15);
                        _spotLight.OuterConeAngle = (float)(Math.PI / 10);
                        _spotLight.Direction = new Vector3(0, 0, -1);
                    };
                    break;

                case LightingTypes.DistantDiffuse:
                    {
                        //
                        // Result = Ambient +       Diffuse
                        // Result = (Image) + (.5 * Diffuse color)
                        //

                        IGraphicsEffect graphicsEffect = new CompositeEffect()
                        {
                            Mode = CanvasComposite.DestinationIn,
                            Sources =
                            {
                                new CompositeEffect()
                                {
                                    Mode = CanvasComposite.Add,
                                    Sources =
                                    {
                                        new CompositionEffectSourceParameter("ImageSource"),
                                        new SceneLightingEffect()
                                        {
                                            AmbientAmount = 0,
                                            DiffuseAmount = .5f,
                                            SpecularAmount = 0,
                                            NormalMapSource = new CompositionEffectSourceParameter("NormalMap"),
                                        }
                                    }
                                },
                                new CompositionEffectSourceParameter("NormalMap"),
                            }
                        };

                        _effectFactory = _compositor.CreateEffectFactory(graphicsEffect);

                        Visual lightRoot = ElementCompositionPreview.GetElementVisual(ThumbnailList);
                        _distantLight.CoordinateSpace = lightRoot;
                        _distantLight.Targets.Add(lightRoot);
                    };
                    break;

                case LightingTypes.DistantSpecular:
                    {
                        //
                        // Result =          Diffuse        +    Specular
                        // Result = (Image * Diffuse color) + (Specular color)
                        //

                        IGraphicsEffect graphicsEffect = new CompositeEffect()
                        {
                            Mode = CanvasComposite.DestinationIn,
                            Sources =
                            {
                                new ArithmeticCompositeEffect()
                                {
                                    Source1Amount = 1,
                                    Source2Amount = 1,
                                    MultiplyAmount = 0,

                                    Source1 = new ArithmeticCompositeEffect()
                                    {
                                        MultiplyAmount = 1,
                                        Source1Amount = 0,
                                        Source2Amount = 0,
                                        Source1 = new CompositionEffectSourceParameter("ImageSource"),
                                        Source2 = new SceneLightingEffect()
                                        {
                                            AmbientAmount = .6f,
                                            DiffuseAmount = 1f,
                                            SpecularAmount = 0f,
                                            NormalMapSource = new CompositionEffectSourceParameter("NormalMap"),
                                        }
                                    },
                                    Source2 = new SceneLightingEffect()
                                    {
                                        AmbientAmount = 0,
                                        DiffuseAmount = 0f,
                                        SpecularAmount = 1f,
                                        SpecularShine = 100,
                                        NormalMapSource = new CompositionEffectSourceParameter("NormalMap"),
                                    }
                                },
                                new CompositionEffectSourceParameter("NormalMap"),
                            }
                        };

                        _effectFactory = _compositor.CreateEffectFactory(graphicsEffect);

                        Visual lightRoot = ElementCompositionPreview.GetElementVisual(ThumbnailList);
                        _distantLight.CoordinateSpace = lightRoot;
                        _distantLight.Targets.Add(lightRoot);
                    };
                    break;

                default:
                    break;
            }

            // Update the animations
            UpdateAnimations();

            // Update all the image to have the new effect
            UpdateEffectBrush();
        }
        private void MainGridLoaded(object sender, RoutedEventArgs e)
        {
            m_compositor = ElementCompositionPreview.GetElementVisual(MainGrid).Compositor;
            m_root       = m_compositor.CreateContainerVisual();
            ElementCompositionPreview.SetElementChildVisual(MainGrid, m_root);

            Size imageSize;

            m_noEffectBrush = CreateBrushFromAsset(
                "Bruno'sFamily2015 (13)-X2.jpg",
                out imageSize);
            m_imageAspectRatio = (imageSize.Width == 0 && imageSize.Height == 0) ? 1 : imageSize.Width / imageSize.Height;

            m_sprite = m_compositor.CreateSpriteVisual();
            ResizeImage(new Size(MainGrid.ActualWidth, MainGrid.ActualHeight));
            m_root.Children.InsertAtTop(m_sprite);

            // Image with alpha channel as an mask.
            var alphaMaskEffectDesc = new CompositeEffect
            {
                Mode    = CanvasComposite.DestinationIn,
                Sources =
                {
                    new CompositionEffectSourceParameter("Image"),
                    new Transform2DEffect
                    {
                        Name   = "MaskTransform",
                        Source = new CompositionEffectSourceParameter("Mask")
                    }
                }
            };

            m_alphaMaskEffectBrush = m_compositor.CreateEffectFactory(
                alphaMaskEffectDesc,
                new[] { "MaskTransform.TransformMatrix" }
                ).CreateBrush();
            m_alphaMaskEffectBrush.SetSourceParameter(
                "Image",
                m_noEffectBrush);
            m_alphaMaskEffectBrush.SetSourceParameter(
                "Mask",
                CreateBrushFromAsset("CircleMask.png"));

            // Arithmetic operations between two images.
            var arithmeticEffectDesc = new ArithmeticCompositeEffect
            {
                Name        = "effect",
                ClampOutput = false,
                Source1     = new CompositionEffectSourceParameter("Source1"),
                Source2     = new CompositionEffectSourceParameter("Source2")
            };

            m_arithmeticEffectBrush = m_compositor.CreateEffectFactory(
                arithmeticEffectDesc,
                new[]
            {
                "effect.MultiplyAmount",
                "effect.Source1Amount",
                "effect.Source2Amount",
                "effect.Offset"
            }
                ).CreateBrush();
            m_arithmeticEffectBrush.SetSourceParameter(
                "Source1",
                m_noEffectBrush);
            m_arithmeticEffectBrush.SetSourceParameter(
                "Source2",
                CreateBrushFromAsset("_P2A8041.jpg"));

            // Creates a blend effect that combines two images.
            var foregroundBrush = CreateBrushFromAsset("Checkerboard_100x100.png");

            m_blendEffectBrushes = new CompositionEffectBrush[m_supportedBlendModes.Length];
            for (int i = 0; i < m_supportedBlendModes.Length; i++)
            {
                var blendEffectDesc = new BlendEffect
                {
                    Mode       = m_supportedBlendModes[i],
                    Background = new CompositionEffectSourceParameter("Background"),
                    Foreground = new CompositionEffectSourceParameter("Foreground")
                };
                m_blendEffectBrushes[i] = m_compositor.CreateEffectFactory(
                    blendEffectDesc
                    ).CreateBrush();
                m_blendEffectBrushes[i].SetSourceParameter(
                    "Background",
                    m_noEffectBrush);
                m_blendEffectBrushes[i].SetSourceParameter(
                    "Foreground",
                    foregroundBrush);
            }

            // Generates an image containing a solid color.
            var colorSourceEffectDesc = new ColorSourceEffect // FloodEffect
            {
                Name = "effect"
            };

            m_colorSourceEffectBrush = m_compositor.CreateEffectFactory(
                colorSourceEffectDesc,
                new[] { "effect.Color" }
                ).CreateBrush();

            // Changes the contrast of an image.
            var contrastEffectDesc = new ContrastEffect
            {
                Name   = "effect",
                Source = new CompositionEffectSourceParameter("Image")
            };

            m_contrastEffectBrush = m_compositor.CreateEffectFactory(
                contrastEffectDesc,
                new[] { "effect.Contrast" }
                ).CreateBrush();
            m_contrastEffectBrush.SetSourceParameter(
                "Image",
                m_noEffectBrush);

            // Changes the exposure of an image.
            var exposureEffectDesc = new ExposureEffect
            {
                Name   = "effect",
                Source = new CompositionEffectSourceParameter("Image")
            };

            m_exposureEffectBrush = m_compositor.CreateEffectFactory(
                exposureEffectDesc,
                new[] { "effect.Exposure" }
                ).CreateBrush();
            m_exposureEffectBrush.SetSourceParameter(
                "Image",
                m_noEffectBrush);

            // Alters the colors of an image by applying a per-channel gamma transfer function.
            var gammaTransferEffectDesc = new GammaTransferEffect
            {
                Name         = "effect",
                RedDisable   = false,
                GreenDisable = false,
                BlueDisable  = false,
                AlphaDisable = false,
                Source       = new CompositionEffectSourceParameter("Image")
            };

            m_gammaTransferEffectBrush = m_compositor.CreateEffectFactory(
                gammaTransferEffectDesc,
                new[]
            {
                "effect.RedAmplitude",
                "effect.RedExponent",
                "effect.RedOffset",
                "effect.GreenAmplitude",
                "effect.GreenExponent",
                "effect.GreenOffset",
                "effect.BlueAmplitude",
                "effect.BlueExponent",
                "effect.BlueOffset"
            }
                ).CreateBrush();
            m_gammaTransferEffectBrush.SetSourceParameter(
                "Image",
                m_noEffectBrush);

            // Converts an image to monochromatic gray.
            var grayscaleEffectDesc = new GrayscaleEffect
            {
                Name   = "effect",
                Source = new CompositionEffectSourceParameter("Image")
            };

            m_grayscaleEffectBrush = m_compositor.CreateEffectFactory(
                grayscaleEffectDesc
                ).CreateBrush();
            m_grayscaleEffectBrush.SetSourceParameter(
                "Image",
                m_noEffectBrush);

            // Alters the color of an image by rotating its hue values.
            var hueRotationEffectDesc = new HueRotationEffect
            {
                Name   = "effect",
                Source = new CompositionEffectSourceParameter("Image")
            };

            m_hueRotationEffectBrush = m_compositor.CreateEffectFactory(
                hueRotationEffectDesc,
                new[] { "effect.Angle" }
                ).CreateBrush();
            m_hueRotationEffectBrush.SetSourceParameter(
                "Image",
                m_noEffectBrush);

            // Inverts the colors of an image.
            var invertEffectDesc = new InvertEffect
            {
                Name   = "effect",
                Source = new CompositionEffectSourceParameter("Image")
            };

            m_invertEffectBrush = m_compositor.CreateEffectFactory(
                invertEffectDesc
                ).CreateBrush();
            m_invertEffectBrush.SetSourceParameter(
                "Image",
                m_noEffectBrush);

            // Alters the saturation of an image.
            var saturationEffectDesc = new SaturationEffect
            {
                Name   = "effect",
                Source = new CompositionEffectSourceParameter("Image")
            };

            m_saturateEffectBrush = m_compositor.CreateEffectFactory(
                saturationEffectDesc,
                new[] { "effect.Saturation" }
                ).CreateBrush();
            m_saturateEffectBrush.SetSourceParameter(
                "Image",
                m_noEffectBrush);

            // Converts an image to sepia tones.
            var supportedAlphaModes = new[]
            {
                CanvasAlphaMode.Premultiplied,
                CanvasAlphaMode.Straight
            };

            m_sepiaEffectBrushes = new CompositionEffectBrush[supportedAlphaModes.Length];
            for (int i = 0; i < supportedAlphaModes.Length; i++)
            {
                var sepiaEffectDesc = new SepiaEffect
                {
                    Name      = "effect",
                    AlphaMode = supportedAlphaModes[i],
                    Source    = new CompositionEffectSourceParameter("Image")
                };
                m_sepiaEffectBrushes[i] = m_compositor.CreateEffectFactory(
                    sepiaEffectDesc,
                    new[] { "effect.Intensity" }
                    ).CreateBrush();
                m_sepiaEffectBrushes[i].SetSourceParameter(
                    "Image",
                    m_noEffectBrush);
            }

            // Adjusts the temperature and/or tint of an image.
            var temperatureAndTintEffectDesc = new TemperatureAndTintEffect
            {
                Name   = "effect",
                Source = new CompositionEffectSourceParameter("Image")
            };

            m_temperatureAndTintEffectBrush = m_compositor.CreateEffectFactory(
                temperatureAndTintEffectDesc,
                new[]
            {
                "effect.Temperature",
                "effect.Tint"
            }
                ).CreateBrush();
            m_temperatureAndTintEffectBrush.SetSourceParameter(
                "Image",
                m_noEffectBrush);

            // Applies a 2D affine transform matrix to an image.
            var transform2DEffectDesc = new Transform2DEffect
            {
                TransformMatrix = new Matrix3x2(
                    -1, 0,
                    0, 1,
                    m_sprite.Size.X, 0),
                Source = new CompositionEffectSourceParameter("Image")
            };

            m_transform2DEffectBrush = m_compositor.CreateEffectFactory(
                transform2DEffectDesc
                ).CreateBrush();
            m_transform2DEffectBrush.SetSourceParameter(
                "Image",
                m_noEffectBrush);

            // For simplying UI states switch, put effect parameter grids in an array
            m_effectParamsGrids = new Grid[(int)EffectType.NumEffectTypes];
            m_effectParamsGrids[(int)EffectType.NoEffect]           = null;
            m_effectParamsGrids[(int)EffectType.AlphaMask]          = AlphaMaskParams;
            m_effectParamsGrids[(int)EffectType.Arithmetic]         = ArithmeticParams;
            m_effectParamsGrids[(int)EffectType.Blend]              = BlendParams;
            m_effectParamsGrids[(int)EffectType.ColorSource]        = ColorSourceParams;
            m_effectParamsGrids[(int)EffectType.Contrast]           = ContrastParams;
            m_effectParamsGrids[(int)EffectType.Exposure]           = ExposureParams;
            m_effectParamsGrids[(int)EffectType.GammaTransfer]      = GammaTransferParams;
            m_effectParamsGrids[(int)EffectType.Grayscale]          = null;
            m_effectParamsGrids[(int)EffectType.HueRotation]        = HueRotationParams;
            m_effectParamsGrids[(int)EffectType.Invert]             = null;
            m_effectParamsGrids[(int)EffectType.Saturation]         = SaturationParams;
            m_effectParamsGrids[(int)EffectType.Sepia]              = SepiaParams;
            m_effectParamsGrids[(int)EffectType.TemperatureAndTint] = TemperatureAndTintParams;
            m_effectParamsGrids[(int)EffectType.Transform2D]        = null;

            // Same as grids
            m_effectBrushes = new CompositionBrush[(int)EffectType.NumEffectTypes];
            m_effectBrushes[(int)EffectType.NoEffect]           = m_noEffectBrush;
            m_effectBrushes[(int)EffectType.AlphaMask]          = m_alphaMaskEffectBrush;
            m_effectBrushes[(int)EffectType.Arithmetic]         = m_arithmeticEffectBrush;
            m_effectBrushes[(int)EffectType.Blend]              = m_blendEffectBrushes[m_activeBlendMode];
            m_effectBrushes[(int)EffectType.ColorSource]        = m_colorSourceEffectBrush;
            m_effectBrushes[(int)EffectType.Contrast]           = m_contrastEffectBrush;
            m_effectBrushes[(int)EffectType.Exposure]           = m_exposureEffectBrush;
            m_effectBrushes[(int)EffectType.GammaTransfer]      = m_gammaTransferEffectBrush;
            m_effectBrushes[(int)EffectType.Grayscale]          = m_grayscaleEffectBrush;
            m_effectBrushes[(int)EffectType.HueRotation]        = m_hueRotationEffectBrush;
            m_effectBrushes[(int)EffectType.Invert]             = m_invertEffectBrush;
            m_effectBrushes[(int)EffectType.Saturation]         = m_saturateEffectBrush;
            m_effectBrushes[(int)EffectType.Sepia]              = m_sepiaEffectBrushes[m_activeSepiaAlphaMode];
            m_effectBrushes[(int)EffectType.TemperatureAndTint] = m_temperatureAndTintEffectBrush;
            m_effectBrushes[(int)EffectType.Transform2D]        = m_transform2DEffectBrush;

            this.InitializeValues();
        }
        /// <summary>
        /// Function is responsible for creating the circular alpha masked profile brush
        /// </summary>
        /// <returns></returns>
        private CompositionEffectBrush InitializeCompositeEffect()
        {
            //
            // Create a simple Composite Effect, using DestinationIn (S * DA), and two named sources - image and mask.
            //
            var effect = new CompositeEffect
            {
                Mode = CanvasComposite.DestinationIn,
                Sources =
                {
                    new CompositionEffectSourceParameter("image"),
                    new CompositionEffectSourceParameter("mask")
                }

            };
            var factory = _compositor.CreateEffectFactory(effect);
            var brush = factory.CreateBrush();

            //
            // Load in the profile picture as a brush using the Composition Toolkit.
            //
            CompositionSurfaceBrush profileBrush = _compositor.CreateSurfaceBrush();
            _profilePictureSurface = _imageLoader.CreateManagedSurfaceFromUri(new Uri("ms-appx:///Samples/SDK 10586/Z-Order Scrolling/teched3ae5a27b-4f78-e111-94ad-001ec953730b.jpg"));
            profileBrush.Surface = _profilePictureSurface.Surface;
            brush.SetSourceParameter("image", profileBrush);

            //
            // Load in the circular mask picture asx a brush using the composition Toolkit.
            //
            CompositionSurfaceBrush maskBrush = _compositor.CreateSurfaceBrush();
            _circleMaskSurface = _imageLoader.CreateCircleSurface(200, Colors.White);
            maskBrush.Surface = _circleMaskSurface.Surface;
            brush.SetSourceParameter("mask", maskBrush);

            return brush;

        }