Beispiel #1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ShadowBuilder"/> class.
 /// </summary>
 /// <param name="renderer">The renderer.</param>
 /// <param name="effect">The gaussian blur effect to use in order to soften the shadows.</param>
 /// <param name="sprite1">The first sprite to draw.</param>
 /// <param name="sprite2">The second sprite to draw.</param>
 public ShadowBuilder(Gorgon2D renderer, Gorgon2DGaussBlurEffect effect, GorgonSprite sprite1, GorgonSprite sprite2)
 {
     _renderer  = renderer;
     _gaussBlur = effect;
     _sprite1   = sprite1;
     _sprite2   = sprite2;
 }
Beispiel #2
0
        /// <summary>
        /// Function called to initialize the application.
        /// </summary>
        private void Initialize()
        {
            GorgonExample.ResourceBaseDirectory = new DirectoryInfo(Settings.Default.ResourceLocation);

            // Resize and center the screen.
            var screen = Screen.FromHandle(Handle);

            ClientSize = Settings.Default.Resolution;
            Location   = new Point(screen.Bounds.Left + (screen.WorkingArea.Width / 2) - (ClientSize.Width / 2),
                                   screen.Bounds.Top + (screen.WorkingArea.Height / 2) - (ClientSize.Height / 2));

            // Initialize our graphics.
            IReadOnlyList <IGorgonVideoAdapterInfo> videoAdapters = GorgonGraphics.EnumerateAdapters(log: GorgonApplication.Log);

            if (videoAdapters.Count == 0)
            {
                throw new GorgonException(GorgonResult.CannotCreate,
                                          "Gorgon requires at least a Direct3D 11.4 capable video device.\nThere is no suitable device installed on the system.");
            }

            // Find the best video device.
            _graphics = new GorgonGraphics(videoAdapters.OrderByDescending(item => item.FeatureSet).First());

            // Build our "screen".
            _screen = new GorgonSwapChain(_graphics,
                                          this,
                                          new GorgonSwapChainInfo
            {
                Width  = ClientSize.Width,
                Height = ClientSize.Height,
                Format = BufferFormat.R8G8B8A8_UNorm
            });

            if (!Settings.Default.IsWindowed)
            {
                // Go full screen by using borderless windowed mode.
                _screen.EnterFullScreen();
            }

            // Build up our 2D renderer.
            _renderer = new Gorgon2D(_graphics);

            // Load in the logo texture from our resources.
            GorgonExample.LoadResources(_graphics);

            // Create fonts.
            _textFont = GorgonExample.Fonts.GetFont(new GorgonFontInfo("GiGi", 24.0f, FontHeightMode.Points, "GiGi_24pt")
            {
                AntiAliasingMode = FontAntiAliasMode.AntiAlias,
                TextureWidth     = 512,
                TextureHeight    = 256
            });

            // Use the form font for this one.
            _helpFont = GorgonExample.Fonts.GetFont(new GorgonFontInfo(Font.FontFamily.Name,
                                                                       Font.Size,
                                                                       Font.Unit == GraphicsUnit.Pixel ? FontHeightMode.Pixels : FontHeightMode.Points,
                                                                       "Form Font")
            {
                AntiAliasingMode = FontAntiAliasMode.AntiAlias,
                FontStyle        = FontStyle.Bold
            });

            // Create our file system and mount the resources.
            _fileSystem = new GorgonFileSystem(GorgonApplication.Log);
            _fileSystem.Mount(GorgonExample.GetResourcePath(@"FileSystems\FolderSystem").FullName);

            // In the previous versions of Gorgon, we used to load the image first, and then the sprites.
            // But in this version, we have an extension that will load the sprite textures for us.
            _sprites = new GorgonSprite[3];

            // The sprites are in the v2 format.
            IEnumerable <IGorgonSpriteCodec> v2Codec  = new[] { new GorgonV2SpriteCodec(_renderer) };
            IEnumerable <IGorgonImageCodec>  pngCodec = new[] { new GorgonCodecPng() };

            _sprites[0] = _fileSystem.LoadSpriteFromFileSystem(_renderer, "/Sprites/base.gorSprite", spriteCodecs: v2Codec, imageCodecs: pngCodec);
            _sprites[1] = _fileSystem.LoadSpriteFromFileSystem(_renderer, "/Sprites/Mother.gorSprite", spriteCodecs: v2Codec, imageCodecs: pngCodec);
            _sprites[2] = _fileSystem.LoadSpriteFromFileSystem(_renderer, "/Sprites/Mother2c.gorSprite", spriteCodecs: v2Codec, imageCodecs: pngCodec);

            // This is how you would get the sprites in v2 of Gorgon:

            /*_spriteImage = _graphics.Textures.FromMemory<GorgonTexture2D>("0_HardVacuum", LoadFile("/Images/0_HardVacuum.png"), new GorgonCodecPNG());
             *
             *      // Get the sprites.
             *      // The sprites in the file system are from version 1.0 of Gorgon.
             *      // This version is backwards compatible and can load any version
             *      // of the sprites produced by older versions of Gorgon.
             *      _sprites = new GorgonSprite[3];
             *      _sprites[0] = _renderer.Renderables.FromMemory<GorgonSprite>("Base", LoadFile("/Sprites/base.gorSprite"));
             *      _sprites[1] = _renderer.Renderables.FromMemory<GorgonSprite>("Mother", LoadFile("/Sprites/Mother.gorSprite"));
             *      _sprites[2] = _renderer.Renderables.FromMemory<GorgonSprite>("Mother2c", LoadFile("/Sprites/Mother2c.gorSprite"));
             */

            // Get poetry.
            _textPosition = new DX.Vector2(0, ClientSize.Height + _textFont.LineHeight);

            _poetry = new GorgonTextSprite(_textFont, Encoding.UTF8.GetString(LoadFile("/SomeText.txt")))
            {
                Position = _textPosition,
                Color    = Color.Black
            };

            // Set up help text.
            _helpText = new GorgonTextSprite(_helpFont, "F1 - Show/hide this help text.\nS - Show frame statistics.\nESC - Exit.")
            {
                Color    = Color.Blue,
                Position = new DX.Vector2(3, 3)
            };

            // Unlike the old example, we'll blend to render targets, ping-ponging back and forth, for a much better quality image and smoother transition.
            _blurEffect = new Gorgon2DGaussBlurEffect(_renderer, 3)
            {
                BlurRenderTargetsSize = new DX.Size2((int)_sprites[2].Size.Width * 2, (int)_sprites[2].Size.Height * 2),
                PreserveAlpha         = false
            };
            _blurEffect.Precache();

            _blurredTarget[0] = GorgonRenderTarget2DView.CreateRenderTarget(_graphics, new GorgonTexture2DInfo("Blurred RTV")
            {
                Width   = _blurEffect.BlurRenderTargetsSize.Width,
                Height  = _blurEffect.BlurRenderTargetsSize.Height,
                Binding = TextureBinding.ShaderResource,
                Format  = BufferFormat.R8G8B8A8_UNorm,
                Usage   = ResourceUsage.Default
            });
            _blurredTarget[1] = GorgonRenderTarget2DView.CreateRenderTarget(_graphics, _blurredTarget[0]);
            _blurredImage[0]  = _blurredTarget[0].GetShaderResourceView();
            _blurredImage[1]  = _blurredTarget[1].GetShaderResourceView();

            GorgonApplication.IdleMethod = Idle;
        }
Beispiel #3
0
        /// <summary>
        /// Function to initialize the effects and the effect compositor.
        /// </summary>
        private static void InitializeEffects()
        {
            // The blur effect.
            _blurEffect = new Gorgon2DGaussBlurEffect(_renderer)
            {
                PreserveAlpha = true
            };
            _blurEffect.Precache();

            // The grayscale effect.
            _grayScaleEffect = new Gorgon2DGrayScaleEffect(_renderer);

            // The posterize effect.
            _posterizeEffect = new Gorgon2DPosterizedEffect(_renderer)
            {
                Bits = 10
            };

            // The 1 bit effect.
            _1BitEffect = new Gorgon2D1BitEffect(_renderer)
            {
                Threshold           = new GorgonRangeF(0.5f, 1.0f),
                ConvertAlphaChannel = false
            };

            // The burn effect.
            _burnEffect = new Gorgon2DBurnDodgeEffect(_renderer)
            {
                UseDodge = false
            };

            // The dodge effect.
            _dodgeEffect = new Gorgon2DBurnDodgeEffect(_renderer)
            {
                UseDodge = true
            };

            // The invert effect.
            _invertEffect = new Gorgon2DInvertEffect(_renderer);

            // The sharpen effect.
            _sharpenEffect = new Gorgon2DSharpenEmbossEffect(_renderer)
            {
                UseEmbossing = false,
                Amount       = 1.0f
            };
            // The emboss effect.
            _embossEffect = new Gorgon2DSharpenEmbossEffect(_renderer)
            {
                UseEmbossing = true,
                Amount       = 1.0f
            };

            // The sobel edge detection effect.
            _sobelEffect = new Gorgon2DSobelEdgeDetectEffect(_renderer)
            {
                LineThickness = 2.5f,
                EdgeThreshold = 0.80f
            };

            // An old film effect.
            _oldFilmEffect = new Gorgon2DOldFilmEffect(_renderer)
            {
                ScrollSpeed = 0.05f
            };
            // A HDR bloom effect.
            _bloomEffect = new Gorgon2DBloomEffect(_renderer)
            {
                Threshold      = 1.11f,
                BloomIntensity = 35.0f,
                BlurAmount     = 6.0f,
                ColorIntensity = 1.15f
            };
            // A chromatic aberration effect.
            _chromatic = new Gorgon2DChromaticAberrationEffect(_renderer)
            {
                Intensity = 0.25f
            };

            _compositor = new Gorgon2DCompositor(_renderer);
            // Set up each pass for the compositor.
            // As you can see, we're not strictly limited to using our 2D effect objects, we can define custom passes as well.
            // And, we can also define how existing effects are rendered for things like animation and such.
            _compositor.EffectPass("Chromatic Aberration", _chromatic)
            .EffectPass("1-Bit Color", _1BitEffect)
            .EffectPass("Blur", _blurEffect)
            .EffectPass("Grayscale", _grayScaleEffect)
            .EffectPass("Posterize", _posterizeEffect)
            .EffectPass("Burn", _burnEffect)
            .EffectPass("Dodge", _dodgeEffect)
            .EffectPass("Invert", _invertEffect)
            .EffectPass("Sharpen", _sharpenEffect)
            .EffectPass("Emboss", _embossEffect)
            .EffectPass("Bloom", _bloomEffect)
            .Pass(new Gorgon2DCompositionPass("Sobel Edge Detection", _sobelEffect)
            {
                BlendOverride = GorgonBlendState.Default,
                ClearColor    = GorgonColor.White
            })
            .RenderPass("Sobel Blend Pass",
                        (sobelTexture, pass, passCount, size) =>
            {
                // This is a custom pass that does nothing but rendering.  No effect is applied here, just straight rendering to
                // the currently active render target.
                var rectPosition = new DX.RectangleF(0, 0, size.Width, size.Height);
                var texCoords    = new DX.RectangleF(0, 0, 1, 1);
                _renderer.DrawFilledRectangle(rectPosition, GorgonColor.White, _images[_currentImage], texCoords);
                _renderer.DrawFilledRectangle(rectPosition, GorgonColor.White, sobelTexture, texCoords);
            })
            .Pass(new Gorgon2DCompositionPass("Olde Film", _oldFilmEffect)
            {
                BlendOverride = GorgonBlendState.Additive,
                RenderMethod  = (prevEffect, passIndex, passCount, size) =>
                {
                    // Here we can override the method used to render to the effect.
                    // In this case, we're animating our old film content to shake and darken at defined intervals.
                    // If we do not override this, the compositor would just blit the previous texture to the
                    // current render target.
                    var rectPosition  = new DX.RectangleF(0, 0, size.Width, size.Height);
                    var texCoords     = new DX.RectangleF(0, 0, 1, 1);
                    GorgonColor color = GorgonColor.White;

                    if ((GorgonTiming.SecondsSinceStart % 10) >= 4)
                    {
                        rectPosition.Inflate(GorgonRandom.RandomSingle(1, 5), GorgonRandom.RandomSingle(1, 5));
                        float value = GorgonRandom.RandomSingle(0.5f, 0.89f);
                        color       = new GorgonColor(value, value, value, 1.0f);
                    }

                    _renderer.DrawFilledRectangle(rectPosition, color, prevEffect, texCoords);
                }
            })
            .InitialClearColor(GorgonColor.White)
            .FinalClearColor(GorgonColor.White);

            _compositor.Passes["Chromatic Aberration"].Enabled = false;
            _compositor.Passes["Bloom"].Enabled       = false;
            _compositor.Passes["Posterize"].Enabled   = false;
            _compositor.Passes["Grayscale"].Enabled   = false;
            _compositor.Passes["1-Bit Color"].Enabled = false;
            _compositor.Passes["Emboss"].Enabled      = false;
            _compositor.Passes["Dodge"].Enabled       = false;
            _compositor.Passes["Olde Film"].Enabled   = false;
        }
Beispiel #4
0
        /// <summary>
        /// Function to initialize the example.
        /// </summary>
        /// <returns>The main window for the application.</returns>
        private static FormMain Initialize()
        {
            GorgonExample.ResourceBaseDirectory = new DirectoryInfo(Settings.Default.ResourceLocation);
            GorgonExample.ShowStatistics        = false;

            FormMain window = GorgonExample.Initialize(new DX.Size2(Settings.Default.Resolution.Width, Settings.Default.Resolution.Height), "The Shadow Gn0s");

            try
            {
                // Create our primary graphics interface.
                IReadOnlyList <IGorgonVideoAdapterInfo> adapters = GorgonGraphics.EnumerateAdapters(log: GorgonApplication.Log);

                if (adapters.Count == 0)
                {
                    throw new GorgonException(GorgonResult.CannotCreate, "This example requires a Direct3D 11.4 capable video card.\nThe application will now close.");
                }

                _graphics = new GorgonGraphics(adapters[0], log: GorgonApplication.Log);

                // Create our "screen".
                _screen = new GorgonSwapChain(_graphics, window, new GorgonSwapChainInfo("TheShadowGn0s Screen Swap chain")
                {
                    Width  = Settings.Default.Resolution.Width,
                    Height = Settings.Default.Resolution.Height,
                    Format = BufferFormat.R8G8B8A8_UNorm
                });

                BuildRenderTargets(new DX.Size2(_screen.Width, _screen.Height));


                _backgroundTexture = GorgonTexture2DView.FromFile(_graphics,
                                                                  Path.Combine(GorgonExample.GetResourcePath(@"Textures\TheShadowGn0s\").FullName,
                                                                               "VBBack.jpg"),
                                                                  new GorgonCodecJpeg(),
                                                                  new GorgonTexture2DLoadOptions
                {
                    Name    = "Background Texture",
                    Binding = TextureBinding.ShaderResource,
                    Usage   = ResourceUsage.Immutable
                });

                // Create our 2D renderer.
                _renderer = new Gorgon2D(_graphics);

                _spriteTexture = GorgonTexture2DView.FromFile(_graphics,
                                                              Path.Combine(GorgonExample.GetResourcePath(@"Textures\TheShadowGn0s\").FullName,
                                                                           "0_HardVacuum.png"),
                                                              new GorgonCodecPng(),
                                                              new GorgonTexture2DLoadOptions
                {
                    Name    = "/Images/0_HardVacuum.png",
                    Binding = TextureBinding.ShaderResource,
                    Usage   = ResourceUsage.Immutable
                });

                var spriteCodec = new GorgonV2SpriteCodec(_renderer);
                _sprite1 = spriteCodec.FromFile(Path.Combine(GorgonExample.GetResourcePath(@"Sprites\TheShadowGn0s\").FullName, "Mother.gorSprite"));
                _sprite2 = spriteCodec.FromFile(Path.Combine(GorgonExample.GetResourcePath(@"Sprites\TheShadowGn0s\").FullName, "Mother2c.gorSprite"));

                _gaussBlur = new Gorgon2DGaussBlurEffect(_renderer, 9)
                {
                    BlurRenderTargetsSize = new DX.Size2(_screen.Width / 2, _screen.Height / 2)
                };

                var shadowBuilder = new ShadowBuilder(_renderer, _gaussBlur, _sprite1, _sprite2);
                (GorgonSprite[] shadowSprites, GorgonTexture2DView shadowTexture) = shadowBuilder.Build();
                _shadowSprites = shadowSprites;
                _shadowTexture = shadowTexture;

                var batchStateBuilder = new Gorgon2DBatchStateBuilder();
                var blendStateBuilder = new GorgonBlendStateBuilder();
                _rtvBlendState = batchStateBuilder
                                 .BlendState(blendStateBuilder
                                             .ResetTo(GorgonBlendState.Default)
                                             .DestinationBlend(alpha: Blend.InverseSourceAlpha))
                                 .Build();

                _sprite2.Position = new DX.Vector2((int)(_screen.Width / 2.0f), (int)(_screen.Height / 4.0f));
                _sprite1.Position = new DX.Vector2((int)(_screen.Width / 4.0f), (int)(_screen.Height / 5.0f));

                _bgSprite = _sprite2;
                _fgSprite = _sprite1;

                _screen.BeforeSwapChainResized += (sender, args) =>
                {
                    _blurTexture?.Dispose();
                    _blurTarget?.Dispose();
                    _layer1Texture?.Dispose();
                    _layer1Target?.Dispose();
                };

                window.MouseMove  += Window_MouseMove;
                window.MouseUp    += Window_MouseUp;
                window.MouseWheel += Window_MouseWheel;
                window.KeyUp      += Window_KeyUp;

                _screen.AfterSwapChainResized += (sender, args) => BuildRenderTargets(args.Size);

                GorgonExample.LoadResources(_graphics);

                _helpFont = GorgonExample.Fonts.GetFont(new GorgonFontInfo("Segoe UI", 12.0f, FontHeightMode.Points, "Segoe UI 12pt Bold, Outlined")
                {
                    FontStyle     = FontStyle.Bold,
                    OutlineColor2 = GorgonColor.Black,
                    OutlineColor1 = GorgonColor.Black,
                    OutlineSize   = 2,
                    TextureWidth  = 512,
                    TextureHeight = 256
                });

                return(window);
            }
            finally
            {
                GorgonExample.EndInit();
            }
        }
Beispiel #5
0
        /// <summary>
        /// Function to initialize the application.
        /// </summary>
        private static void Initialize()
        {
            GorgonExample.ShowStatistics = false;

            _window = GorgonExample.Initialize(new DX.Size2(Settings.Default.ScreenWidth, Settings.Default.ScreenHeight), "Balls");

            try
            {
                // Create the graphics interface.
                IReadOnlyList <IGorgonVideoAdapterInfo> adapters = GorgonGraphics.EnumerateAdapters();

                if (adapters.Count == 0)
                {
                    throw new GorgonException(GorgonResult.CannotCreate,
                                              "Gorgon requires at least a Direct3D 11.4 capable video device.\nThere is no suitable device installed on the system.");
                }

                // Find the best video device.
                _graphics = new GorgonGraphics(adapters.OrderByDescending(item => item.FeatureSet).First());

                // Create the primary swap chain.
                _mainScreen = new GorgonSwapChain(_graphics,
                                                  _window,
                                                  new GorgonSwapChainInfo("Main Screen")
                {
                    Width  = Settings.Default.ScreenWidth,
                    Height = Settings.Default.ScreenHeight,
                    Format = BufferFormat.R8G8B8A8_UNorm
                });

                // Center the display.
                if (_mainScreen.IsWindowed)
                {
                    _window.Location =
                        new Point((Screen.PrimaryScreen.Bounds.Width / 2) - (_window.Width / 2) + Screen.PrimaryScreen.Bounds.Left,
                                  (Screen.PrimaryScreen.Bounds.Height / 2) - (_window.Height / 2) + Screen.PrimaryScreen.Bounds.Top);
                }

                // Load the ball texture.
                _ballTexture = GorgonTexture2DView.FromFile(_graphics,
                                                            GetResourcePath(@"Textures\Balls\BallsTexture.dds"),
                                                            new GorgonCodecDds(),
                                                            new GorgonTexture2DLoadOptions
                {
                    Usage = ResourceUsage.Immutable,
                    Name  = "Ball Texture"
                });

                // Create the 2D interface.
                _2D = new Gorgon2D(_graphics);

                // Create the wall sprite.
                _wall = new GorgonSprite
                {
                    Size          = new DX.Size2F(63, 63),
                    Texture       = _ballTexture,
                    TextureRegion = new DX.RectangleF(0, 0, 0.5f, 0.5f)
                };

                // Create the ball sprite.
                _ball = new GorgonSprite
                {
                    Size          = new DX.Size2F(64, 64),
                    Texture       = _ballTexture,
                    TextureRegion = new DX.RectangleF(0, 0, 0.5f, 0.5f),
                    Anchor        = new DX.Vector2(0.5f, 0.5f)
                };

                // Create the ball render target.
                _ballTarget = GorgonRenderTarget2DView.CreateRenderTarget(_graphics,
                                                                          new GorgonTexture2DInfo("Ball Target")
                {
                    Width  = Settings.Default.ScreenWidth,
                    Height = Settings.Default.ScreenHeight,
                    Format = BufferFormat.R8G8B8A8_UNorm
                });
                _ballTargetView = _ballTarget.GetShaderResourceView();

                // Create our blur effect.
                _blur = new Gorgon2DGaussBlurEffect(_2D, 15)
                {
                    BlurRenderTargetsSize = new DX.Size2(512, 512),
                    BlurRadius            = 0
                };

                _mainScreen.BeforeSwapChainResized += (sender, args) =>
                {
                    _ballTargetView.Dispose();
                    _ballTarget.Dispose();
                };

                // Ensure that our secondary camera gets updated.
                _mainScreen.AfterSwapChainResized += (sender, args) =>
                {
                    // Fix any objects caught outside of the main target.
                    for (int i = 0; i < _ballCount; i++)
                    {
                        _ballList[i].Position.X = _ballList[i].Position.X.Max(0).Min(args.Size.Width);
                        _ballList[i].Position.Y = _ballList[i].Position.Y.Max(0).Min(args.Size.Height);
                    }

                    _ballTarget = GorgonRenderTarget2DView.CreateRenderTarget(_graphics,
                                                                              new GorgonTexture2DInfo("Ball Target")
                    {
                        Width  = args.Size.Width,
                        Height = args.Size.Height,
                        Format = BufferFormat.R8G8B8A8_UNorm
                    });
                    _ballTargetView = _ballTarget.GetShaderResourceView();

                    DX.Size2 newTargetSize;
                    newTargetSize.Width =
                        (int)((512.0f * (args.Size.Width / (float)Settings.Default.ScreenWidth)).Min(512));
                    newTargetSize.Height =
                        (int)((512.0f * (args.Size.Height / (float)Settings.Default.ScreenHeight)).Min(512));

                    _blur.BlurRenderTargetsSize = newTargetSize;
                };

                // Generate the ball list.
                GenerateBalls(Settings.Default.BallCount);

                // Assign event handlers.
                _window.KeyDown += Form_KeyDown;

                var stateBuilder      = new Gorgon2DBatchStateBuilder();
                var blendStateBuilder = new GorgonBlendStateBuilder();

                _blurBlend = stateBuilder.BlendState(blendStateBuilder.ResetTo(GorgonBlendState.Default)
                                                     .SourceBlend(alpha: Blend.InverseDestinationAlpha)
                                                     .DestinationBlend(alpha: Blend.One)
                                                     .Build())
                             .Build();

                GorgonExample.LoadResources(_graphics);

                _ballFont = GorgonExample.Fonts.GetFont(new GorgonFontInfo("Arial", 9.0f, FontHeightMode.Points, "Arial 9pt Bold")
                {
                    FontStyle     = FontStyle.Bold,
                    Characters    = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890()_.-+:\u2191\u2193",
                    OutlineSize   = 1,
                    OutlineColor1 = GorgonColor.Black,
                    OutlineColor2 = GorgonColor.Black
                });

                // Statistics text buffer.
                _fpsText = new StringBuilder(64);

                // Create statistics render target.
                _statsTexture = GorgonTexture2DView.CreateTexture(_graphics,
                                                                  new GorgonTexture2DInfo("Stats Render Target")
                {
                    Width = (int)_ballFont
                            .MeasureText(string.Format(Resources.FPSLine,
                                                       999999,
                                                       999999.999,
                                                       _ballCount,
                                                       9999),
                                         true).Width,
                    Height  = (int)((_ballFont.FontHeight * 4) + _ballFont.Descent),
                    Format  = BufferFormat.R8G8B8A8_UNorm,
                    Binding = TextureBinding.RenderTarget
                });

                using (GorgonRenderTarget2DView rtv = _statsTexture.Texture.GetRenderTargetView())
                {
                    // Draw our stats window frame.
                    rtv.Clear(new GorgonColor(0, 0, 0, 0.5f));
                    _graphics.SetRenderTarget(rtv);
                    _2D.Begin();
                    _2D.DrawRectangle(new DX.RectangleF(0, 0, rtv.Width, rtv.Height), new GorgonColor(0.86667f, 0.84314f, 0.7451f, 1.0f));
                    _2D.End();
                }

                _helpTextSprite = new GorgonTextSprite(_ballFont,
                                                       string.Format(Resources.HelpText,
                                                                     _graphics.VideoAdapter.Name,
                                                                     _graphics.VideoAdapter.FeatureSet,
                                                                     _graphics.VideoAdapter.Memory.Video.FormatMemory()))
                {
                    Color    = Color.Yellow,
                    Position = new DX.Vector2(3, (_statsTexture.Height + 8.0f).FastFloor()),
                    DrawMode = TextDrawMode.OutlinedGlyphs
                };

                // Set our main render target.
                _graphics.SetRenderTarget(_mainScreen.RenderTargetView);
            }
            finally
            {
                GorgonExample.EndInit();
            }
        }
Beispiel #6
0
        /// <summary>
        /// Function to initialize the application.
        /// </summary>
        /// <returns>The main window for the application.</returns>
        private static FormMain Initialize()
        {
            GorgonExample.ResourceBaseDirectory = new DirectoryInfo(Settings.Default.ResourceLocation);
            FormMain window = GorgonExample.Initialize(new DX.Size2(Settings.Default.Resolution.Width, Settings.Default.Resolution.Height), "Effects");

            try
            {
                IReadOnlyList <IGorgonVideoAdapterInfo> videoDevices = GorgonGraphics.EnumerateAdapters(log: GorgonApplication.Log);

                if (videoDevices.Count == 0)
                {
                    throw new GorgonException(GorgonResult.CannotCreate,
                                              "Gorgon requires at least a Direct3D 11.4 capable video device.\nThere is no suitable device installed on the system.");
                }

                // Find the best video device.
                _graphics = new GorgonGraphics(videoDevices.OrderByDescending(item => item.FeatureSet).First());

                _screen = new GorgonSwapChain(_graphics,
                                              window,
                                              new GorgonSwapChainInfo("Gorgon2D Effects Example Swap Chain")
                {
                    Width  = Settings.Default.Resolution.Width,
                    Height = Settings.Default.Resolution.Height,
                    Format = BufferFormat.R8G8B8A8_UNorm
                });
                _screen.BeforeSwapChainResized += Screen_BeforeSwapChainResized;
                _screen.AfterSwapChainResized  += Screen_AfterSwapChainResized;
                // Tell the graphics API that we want to render to the "screen" swap chain.
                _graphics.SetRenderTarget(_screen.RenderTargetView);

                // Initialize the renderer so that we are able to draw stuff.
                _renderer = new Gorgon2D(_graphics);

                // Create the displacement effect used for the "cloaking" effect.
                _displacement = new Gorgon2DDisplacementEffect(_renderer)
                {
                    Strength = 0
                };

                // Create the old film effect for that old timey look.
                _oldFilm = new Gorgon2DOldFilmEffect(_renderer)
                {
                    ScrollSpeed = 0.05f
                };

                // Create the gaussian blur effect for that "soft" look.
                _gaussBlur = new Gorgon2DGaussBlurEffect(_renderer, 9)
                {
                    BlurRenderTargetsSize = new DX.Size2(_screen.Width / 2, _screen.Height / 2),
                    BlurRadius            = 1
                };
                // The higher # of taps on the blur shader will introduce a stutter on first render, so precache its setup data.
                _gaussBlur.Precache();

                // Load our texture with our space background in it.
                _background = GorgonTexture2DView.FromFile(_graphics,
                                                           Path.Combine(GorgonExample.GetResourcePath(@"Textures\").FullName, "HotPocket.dds"),
                                                           new GorgonCodecDds(),
                                                           new GorgonTexture2DLoadOptions
                {
                    Usage   = ResourceUsage.Immutable,
                    Binding = TextureBinding.ShaderResource
                });

                // Load up our super space ship image.
                _spaceShipTexture = GorgonTexture2DView.FromFile(_graphics,
                                                                 Path.Combine(GorgonExample.GetResourcePath(@"Textures\Effects\").FullName, "ship.png"),
                                                                 new GorgonCodecPng(),
                                                                 new GorgonTexture2DLoadOptions
                {
                    Usage   = ResourceUsage.Immutable,
                    Binding = TextureBinding.ShaderResource
                });
                _shipSprite = new GorgonSprite
                {
                    Texture       = _spaceShipTexture,
                    TextureRegion = new DX.RectangleF(0, 0, 1, 1),
                    Anchor        = new DX.Vector2(0.5f, 0.5f),
                    Position      = new DX.Vector2(_screen.Width / 2.0f, _screen.Height / 2.0f),
                    Size          = new DX.Size2F(_spaceShipTexture.Width, _spaceShipTexture.Height)
                };

                BuildRenderTargets();
                InitializeBackgroundTexturePositioning();

                GorgonExample.LoadResources(_graphics);

                window.MouseMove  += Window_MouseMove;
                window.MouseWheel += Window_MouseWheel;
                window.KeyUp      += Window_KeyUp;

                return(window);
            }
            finally
            {
                GorgonExample.EndInit();
            }
        }