Exemple #1
0
        /// <summary>
        /// Raises the <see cref="E:System.Windows.Forms.Form.Load"></see> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            GorgonExample.ShowStatistics = false;
            Cursor.Current = Cursors.WaitCursor;

            try
            {
                Show();
                Application.DoEvents();

                // Initialize Gorgon
                // Set it up so that we won't be rendering in the background, but allow the screensaver to activate.
                IReadOnlyList <IGorgonVideoAdapterInfo> adapters = GorgonGraphics.EnumerateAdapters(log: GorgonApplication.Log);
                if (adapters.Count == 0)
                {
                    throw new GorgonException(GorgonResult.CannotCreate,
                                              "No suitable video adapter found in the system.\nGorgon requires a minimum of a Direct3D 11.4 capable video device.");
                }

                _graphics = new GorgonGraphics(adapters[0]);

                // Set the video mode.
                ClientSize = new Size(640, 400);
                _screen    = new GorgonSwapChain(_graphics,
                                                 this,
                                                 new GorgonSwapChainInfo("FunWithShapes SwapChain")
                {
                    Width  = ClientSize.Width,
                    Height = ClientSize.Height,
                    Format = BufferFormat.R8G8B8A8_UNorm
                });
                _screen.AfterSwapChainResized += Screen_AfterSwapChainResized;
                _graphics.SetRenderTarget(_screen.RenderTargetView);
                _halfSize = new DX.Size2F(_screen.Width / 2.0f, _screen.Height / 2.0f);

                // Create our 2D renderer so we can draw stuff.
                _renderer = new Gorgon2D(_graphics);

                LabelPleaseWait.Visible = false;

                GorgonExample.LoadResources(_graphics);

                // Draw the image.
                DrawAPrettyPicture();
            }
            catch (Exception ex)
            {
                GorgonExample.HandleException(ex);
                GorgonApplication.Quit();
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
Exemple #2
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), "Fonts");

            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
                });

                // 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);

                // Load our logo.
                GorgonExample.LoadResources(_graphics);

                // We need to create a font factory so we can create/load (and cache) fonts.
                _fontFactory = new GorgonFontFactory(_graphics);

                // Create our fonts.
                GenerateGorgonFonts(LoadTrueTypeFonts(window), window);

                // Build our text sprite.
                _text = new GorgonTextSprite(_fontFactory.DefaultFont, Resources.Lorem_Ipsum)
                {
                    LineSpace = 0
                };

                return(window);
            }
            finally
            {
                GorgonExample.EndInit();
            }
        }
Exemple #3
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), "Polygonal Sprites");

            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
                });

                // 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);

                _texture = GorgonTexture2DView.FromFile(_graphics,
                                                        GetResourcePath(@"Textures\PolySprites\Ship.png"),
                                                        new GorgonCodecPng(),
                                                        new GorgonTexture2DLoadOptions
                {
                    Binding = TextureBinding.ShaderResource,
                    Name    = "Ship Texture",
                    Usage   = ResourceUsage.Immutable
                });

                GorgonExample.LoadResources(_graphics);

                CreateSprites();

                return(window);
            }
            finally
            {
                GorgonExample.EndInit();
            }
        }
Exemple #4
0
        /// <summary>
        /// Function to initialize the example.
        /// </summary>
        private void Initialize()
        {
            GorgonExample.ResourceBaseDirectory = new DirectoryInfo(Settings.Default.ResourceLocation);

            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]);

            _leftPanel = new GorgonSwapChain(_graphics,
                                             GroupControl1,
                                             new GorgonSwapChainInfo("Left Panel SwapChain")
            {
                Width  = GroupControl1.ClientSize.Width,
                Height = GroupControl1.ClientSize.Height,
                Format = BufferFormat.R8G8B8A8_UNorm
            });

            _rightPanel = new GorgonSwapChain(_graphics,
                                              GroupControl2,
                                              new GorgonSwapChainInfo(_leftPanel, "Right Panel SwapChain")
            {
                Width  = GroupControl2.ClientSize.Width,
                Height = GroupControl2.ClientSize.Height
            });

            _renderer = new Gorgon2D(_graphics);

            _fontFactory = new GorgonFontFactory(_graphics);
            _appFont     = _fontFactory.GetFont(new GorgonFontInfo(Font.FontFamily.Name, Font.Size * 1.33333f, FontHeightMode.Points, "Form Font")
            {
                Characters    = "SpdtoxDrag me!\u2190:1234567890.",
                TextureWidth  = 128,
                TextureHeight = 128,
                OutlineSize   = 2,
                FontStyle     = FontStyle.Bold,
                OutlineColor1 = GorgonColor.Black,
                OutlineColor2 = GorgonColor.Black
            });

            _torusTexture = GorgonTexture2DView.FromFile(_graphics,
                                                         Path.Combine(GorgonExample.GetResourcePath(@"Textures\GiveMeSomeControl\").FullName, "Torus.png"),
                                                         new GorgonCodecPng(),
                                                         new GorgonTexture2DLoadOptions
            {
                Binding = TextureBinding.ShaderResource,
                Name    = "Torus Animation Sheet",
                Usage   = ResourceUsage.Immutable
            });

            _torusLeft = new GorgonSprite
            {
                Anchor         = new DX.Vector2(0.5f, 0.5f), Size = new DX.Size2F(64, 64),
                TextureSampler = GorgonSamplerState.PointFiltering
            };
            _torusRight = new GorgonSprite
            {
                Anchor         = new DX.Vector2(0.5f, 0.5f), Size = new DX.Size2F(64, 64),
                TextureSampler = GorgonSamplerState.PointFiltering
            };

            BuildAnimation();

            GorgonExample.LoadResources(_graphics);
        }
Exemple #5
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;
        }
Exemple #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), "Post Processing");

            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
                });

                // 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);

                GorgonExample.LoadResources(_graphics);

                // Load the Gorgon logo to show in the lower right corner.
                var ddsCodec = new GorgonCodecDds();

                // Import the images we'll use in our post process chain.
                if (!LoadImageFiles(ddsCodec))
                {
                    return(window);
                }

                // Initialize the effects that we'll use for compositing, and the compositor itself.
                InitializeEffects();

                // Set up our quick and dirty GUI.
                _buttons = new Button[_compositor.Passes.Count];
                LayoutGUI();

                // Select a random image to start
                _currentImage = GorgonRandom.RandomInt32(0, _images.Length - 1);

                window.KeyUp     += Window_KeyUp;
                window.MouseUp   += Window_MouseUp;
                window.MouseMove += Window_MouseMove;
                window.MouseDown += Window_MouseDown;
                window.IsLoaded   = true;

                return(window);
            }
            finally
            {
                GorgonExample.EndInit();
            }
        }
Exemple #7
0
        /// <summary>
        /// Function to initialize the application.
        /// </summary>
        /// <returns>The main window.</returns>
        private static FormMain Initialize()
        {
            // Create our form and center on the primary monitor.
            FormMain window = GorgonExample.Initialize(new DX.Size2(1280, 800), "Gorgon MiniTri");

            try
            {
                // First we create and enumerate the list of video devices installed in the computer.
                // We must do this in order to tell Gorgon which video device we intend to use. Note that this method may be quite slow (particularly when running DEBUG versions of
                // Direct 3D). To counter this, this object and its Enumerate method are thread safe so this can be run in the background while keeping the main UI responsive.
                // Find out which devices we have installed in the system.

                // If no suitable device was found (no Direct 3D 12.0 support) in the computer, this method will throw an exception. However, if it succeeds, then the devices object
                // will be populated with the IGorgonVideoDeviceInfo for each video device in the system.
                //
                // Using this method, we could also enumerate the software rasterizer. These devices are typically used to determine if there's a driver error, and can be terribly slow to render
                // It is recommended that these only be used in diagnostic scenarios only.
                IReadOnlyList <IGorgonVideoAdapterInfo> deviceList = GorgonGraphics.EnumerateAdapters();

                if (deviceList.Count == 0)
                {
                    throw new
                          NotSupportedException("There are no suitable video adapters available in the system. This example is unable to continue and will now exit.");
                }

                // Now we create the main graphics interface with the first applicable video device.
                _graphics = new GorgonGraphics(deviceList[0]);

                // Check to ensure that we can support the format required for our swap chain.
                // If a video device can't support this format, then the odds are good it won't render anything. Since we're asking for a very common display format, this will
                // succeed nearly 100% of the time (unless you've somehow gotten an ancient video device to work with Direct 3D 11.1). Regardless, it's good form to the check for a
                // working display format prior to setting up the swap chain.
                //
                // This method is also used to determine if a format can be used for other objects (e.g. a texture, render target, etc...) Like the swap chain format, this is also a
                // best practice to check if the object you're creating supports the desired format.
                if ((_graphics.FormatSupport[BufferFormat.R8G8B8A8_UNorm].FormatSupport & BufferFormatSupport.Display) != BufferFormatSupport.Display)
                {
                    // We should never see this unless you've performed some form of black magic.
                    GorgonDialogs.ErrorBox(window, "We should not see this error.");
                    return(window);
                }

                // Finally, create a swap chain to display our output.
                // In this case we're setting up our swap chain to bind with our main window, and we use its client size to determine the width/height of the swap chain back buffers.
                // This width/height does not need to be the same size as the window, but, except for some scenarios, that would produce undesirable image quality.
                _swap = new GorgonSwapChain(_graphics,
                                            window,
                                            new GorgonSwapChainInfo("Main Swap Chain")
                {
                    Format = BufferFormat.R8G8B8A8_UNorm,
                    Width  = window.ClientSize.Width,
                    Height = window.ClientSize.Height
                })
                {
                    DoNotAutoResizeBackBuffer = true
                };

                // Create the shaders used to render the triangle.
                // These shaders provide transformation and coloring for the output pixel data.
                CreateShaders();

                // Set up our input layout.
                //
                // We'll be using this to describe to Direct 3D how the elements of a vertex is laid out in memory.
                // In order to provide synchronization between the layout on the CPU side and the GPU side, we have to pass the vertex shader because it will contain the vertex
                // layout to match with our C# input layout.
                _inputLayout = GorgonInputLayout.CreateUsingType <MiniTriVertex>(_graphics, _vertexShader);

                // Set up the triangle vertices.
                CreateVertexBuffer();

                // Set up the constant buffer.
                //
                // This is used (but could be used for more) to transform the vertex data from 3D space into 2D space.
                CreateConstantBuffer(window);

                // This defines where to send the pixel data when rendering. For now, this goes to our swap chain.
                _graphics.SetRenderTarget(_swap.RenderTargetView);

                // Create our draw call.
                //
                // This will pass all the necessary information to the GPU to render the triangle
                //
                // Since draw calls are immutable objects, we use builders to create them (and any pipeline state). Once a draw
                // call is built, it cannot be changed (except for the vertex, and if applicable, index, and instance ranges).
                //
                // Builders work on a fluent interface.  Much like LINQ and can be used to create multiple draw calls from the same
                // builder.
                var drawCallBuilder      = new GorgonDrawCallBuilder();
                var pipelineStateBuilder = new GorgonPipelineStateBuilder(_graphics);

                _drawCall = drawCallBuilder.VertexBuffer(_inputLayout, _vertexBuffer)
                            .VertexRange(0, 3)
                            .ConstantBuffer(ShaderType.Vertex, _constantBuffer)
                            .PipelineState(pipelineStateBuilder
                                           .PixelShader(_pixelShader)
                                           .VertexShader(_vertexShader)
                                           .RasterState(GorgonRasterState.NoCulling))
                            .Build();

                GorgonExample.LoadResources(_graphics);

                return(window);
            }
            finally
            {
                GorgonExample.EndInit();
            }
        }
Exemple #8
0
        /// <summary>
        /// Function to initialize the application.
        /// </summary>
        private static async Task InitializeAsync(FormMain window)
        {
            try
            {
                GorgonExample.ResourceBaseDirectory   = new DirectoryInfo(Settings.Default.ResourceLocation);
                GorgonExample.PlugInLocationDirectory = new DirectoryInfo(Settings.Default.PlugInLocation);

                // Load our packed file system plug in.
                window.UpdateStatus("Loading plugins...");

                IGorgonPlugInService plugIns = await Task.Run(() =>
                {
                    _assemblyCache = new GorgonMefPlugInCache(GorgonApplication.Log);
                    _assemblyCache.LoadPlugInAssemblies(GorgonExample.GetPlugInPath().FullName, "Gorgon.FileSystem.GorPack.dll");
                    return(new GorgonMefPlugInService(_assemblyCache));
                });

                window.UpdateStatus("Initializing graphics...");

                // Retrieve the list of video adapters. We can do this on a background thread because there's no interaction between other threads and the
                // underlying D3D backend yet.
                IReadOnlyList <IGorgonVideoAdapterInfo> videoDevices = await Task.Run(() => 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 Space Scene Example")
                {
                    Width  = Settings.Default.Resolution.Width,
                    Height = Settings.Default.Resolution.Height,
                    Format = BufferFormat.R8G8B8A8_UNorm
                });

                // Create a secondary render target for our scene. We use 16 bit floating point for the effect fidelity.
                // We'll lock our resolution to 1920x1080 (pretty common resolution for most people).
                _mainRtv = GorgonRenderTarget2DView.CreateRenderTarget(_graphics, new GorgonTexture2DInfo("Main RTV")
                {
                    Width   = (int)_baseResolution.X,
                    Height  = (int)_baseResolution.Y,
                    Format  = BufferFormat.R16G16B16A16_Float,
                    Binding = TextureBinding.ShaderResource
                });
                _mainSrv       = _mainRtv.GetShaderResourceView();
                _mainRtvAspect = _mainRtv.Width < _mainRtv.Height ? new DX.Vector2(1, (float)_mainRtv.Height / _mainRtv.Width) : new DX.Vector2((float)_mainRtv.Width / _mainRtv.Height, 1);

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

                // Set up our raw input.
                _input           = new GorgonRawInput(window, GorgonApplication.Log);
                _keyboard        = new GorgonRawKeyboard();
                _keyboard.KeyUp += Keyboard_KeyUp;
                _input.RegisterDevice(_keyboard);

                GorgonExample.LoadResources(_graphics);

                // Now for the fun stuff, load our asset resources. We can load this data by mounting a directory (which I did while developing), or use a packed file.
                //
                // The resource manager will hold all the data we need for the scene. Including 3D meshes, post processing effects, etc...
                _resources = new ResourceManagement(_renderer, plugIns);
                _resources.Load(Path.Combine(GorgonExample.GetResourcePath(@"FileSystems").FullName, "SpaceScene.gorPack"));

                window.UpdateStatus("Loading resources...");
                await _resources.LoadResourcesAsync();

                SetupScene();

                // Build up a font to use for rendering any GUI text.
                _helpFont = GorgonExample.Fonts.GetFont(new GorgonFontInfo("Segoe UI", 10.0f, FontHeightMode.Points, "Segoe UI 10pt")
                {
                    OutlineSize      = 2,
                    Characters       = (Resources.Instructions + "S:1234567890x").Distinct().ToArray(),
                    FontStyle        = FontStyle.Bold,
                    AntiAliasingMode = FontAntiAliasMode.AntiAlias,
                    OutlineColor1    = GorgonColor.Black,
                    OutlineColor2    = GorgonColor.Black
                });

                _textSprite = new GorgonTextSprite(_helpFont)
                {
                    Position = new DX.Vector2(0, 64),
                    DrawMode = TextDrawMode.OutlinedGlyphs,
                    Color    = GorgonColor.YellowPure
                };

                GorgonExample.ShowStatistics = true;

                // Set the idle here. We don't want to try and render until we're done loading.
                GorgonApplication.IdleMethod = Idle;
            }
            finally
            {
                GorgonExample.EndInit();
            }
        }
Exemple #9
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), "Animation");

            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 Animation Example Swap Chain")
                {
                    Width  = Settings.Default.Resolution.Width,
                    Height = Settings.Default.Resolution.Height,
                    Format = BufferFormat.R8G8B8A8_UNorm
                });

                _target = GorgonRenderTarget2DView.CreateRenderTarget(_graphics, new GorgonTexture2DInfo(_screen.RenderTargetView, "Video Target")
                {
                    Binding = TextureBinding.ShaderResource
                });
                _targetView = _target.GetShaderResourceView();
                _target.Clear(GorgonColor.CornFlowerBlue);

                // Load our textures.
                var gif = new GorgonCodecGif(decodingOptions: new GorgonGifDecodingOptions
                {
                    ReadAllFrames = true
                });

                // Find out how long to display each frame for.
                // We'll also convert it to milliseconds since GIF stores the delays as 1/100th of a second.
                _frameDelays = gif.GetFrameDelays(Path.Combine(GorgonExample.GetResourcePath(@"\Textures\Animation\").FullName, "metal.gif"))
                               .Select(item => item / 100.0f).ToArray();

                _metal = GorgonTexture2DView.FromFile(_graphics,
                                                      Path.Combine(GorgonExample.GetResourcePath(@"\Textures\Animation\").FullName, "metal.gif"),
                                                      gif,
                                                      new GorgonTexture2DLoadOptions
                {
                    Name    = @"Metal \m/",
                    Usage   = ResourceUsage.Immutable,
                    Binding = TextureBinding.ShaderResource
                });
                _trooper = GorgonTexture2DView.FromFile(_graphics,
                                                        Path.Combine(GorgonExample.GetResourcePath(@"\Textures\Animation\").FullName, "trooper.png"),
                                                        new GorgonCodecPng(),
                                                        new GorgonTexture2DLoadOptions
                {
                    Name    = "Trooper",
                    Usage   = ResourceUsage.Immutable,
                    Binding = TextureBinding.ShaderResource
                });

                GorgonExample.LoadResources(_graphics);

                _renderer       = new Gorgon2D(_graphics);
                _animatedSprite = new GorgonSprite
                {
                    Position = new DX.Vector2(_screen.Width / 2, _screen.Height / 2),
                    Size     = new DX.Size2F(_metal.Width, _metal.Height),
                    Anchor   = new DX.Vector2(0.5f, 0.5f)
                };

                MakeAn80sMusicVideo();

                // We need to set up a blend state so that the alpha in the render target doesn't get overwritten.
                var builder      = new Gorgon2DBatchStateBuilder();
                var blendBuilder = new GorgonBlendStateBuilder();
                _targetBatchState = builder.BlendState(blendBuilder
                                                       .ResetTo(GorgonBlendState.Default)
                                                       .DestinationBlend(alpha: Blend.DestinationAlpha)
                                                       .Build())
                                    .Build();

                return(window);
            }
            finally
            {
                GorgonExample.EndInit();
            }
        }
Exemple #10
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), "Lights");

            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);

                // Load in our texture for our logo background.
                _backgroundLogoTexture = GorgonTexture2DView.FromFile(_graphics,
                                                                      Path.Combine(GorgonExample.GetResourcePath(@"Textures\Lights\").FullName, "lights.dds"),
                                                                      new GorgonCodecDds(),
                                                                      new GorgonTexture2DLoadOptions
                {
                    Usage   = ResourceUsage.Immutable,
                    Binding = TextureBinding.ShaderResource,
                    Name    = "Logo"
                });

                _torchTexture = GorgonTexture2DView.FromFile(_graphics,
                                                             Path.Combine(GorgonExample.GetResourcePath(@"Textures\Lights\").FullName, "Torch.png"),
                                                             new GorgonCodecPng(),
                                                             new GorgonTexture2DLoadOptions
                {
                    Usage   = ResourceUsage.Immutable,
                    Binding = TextureBinding.ShaderResource,
                    Name    = "Torch"
                });

                UpdateRenderTarget();

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

                _logoSprite = new GorgonSprite
                {
                    Texture       = _backgroundLogoTexture,
                    Bounds        = new DX.RectangleF(0, 0, _backgroundLogoTexture.Width, _backgroundLogoTexture.Height),
                    TextureRegion = new DX.RectangleF(0, 0, 1, 1),
                    Anchor        = new DX.Vector2(0.5f, 0.5f)
                };

                _torchSprite = new GorgonSprite
                {
                    Texture       = _torchTexture,
                    Bounds        = new DX.RectangleF(0, 0, 55, _torchTexture.Height),
                    TextureRegion = _torchTexture.Texture.ToTexel(new DX.Rectangle(0, 0, 55, _torchTexture.Height)),
                };

                // Create the effect that will light up our sprite(s).
                _lightEffect = new Gorgon2DDeferredLightingEffect(_renderer)
                {
                    FlipYNormal = true // Need this to be true because CrazyBump exported the normal map with Y inverted.
                };

                _lightEffect.Lights.Add(new Gorgon2DLight
                {
                    Color           = new GorgonColor(0.25f, 0.25f, 0.25f),
                    Attenuation     = 75,
                    LightType       = LightType.Point,
                    SpecularEnabled = true,
                    SpecularPower   = 6.0f,
                    Position        = new DX.Vector3((_screen.Width / 2.0f) - 150.0f, (_screen.Height / 2.0f) - 150.0f, -50)
                });
                _lightEffect.Lights.Add(new Gorgon2DLight
                {
                    Color           = GorgonColor.White,
                    Intensity       = 0.075f,
                    LightType       = LightType.Directional,
                    SpecularEnabled = false,
                    Position        = new DX.Vector3(0, 0, -200),
                    LightDirection  = new DX.Vector3(0, 0, 1)
                });

                GorgonExample.LoadResources(_graphics);

                window.MouseMove += Window_MouseMove;
                window.KeyDown   += Window_KeyDown;

                _torchFrameTime = new GorgonTimerQpc();

                return(window);
            }
            finally
            {
                GorgonExample.EndInit();
            }
        }
Exemple #11
0
        /// <summary>
        /// Function to initialize the application.
        /// </summary>
        /// <returns>The main form for the application.</returns>
        private static FormMain Initialize()
        {
            // First, create our form.
            FormMain result = GorgonExample.Initialize(new DX.Size2(640, 480), "Initialization");

            try
            {
                result.KeyUp += MainForm_KeyUp;

                // Now we create and enumerate the list of video devices installed in the computer.
                // We must do this in order to tell Gorgon which video device we intend to use. Note that this method may be quite slow (particularly when running DEBUG versions of
                // Direct 3D). To counter this, this object and its Enumerate method are thread safe so this can be run in the background while keeping the main UI responsive.
                //
                // If no suitable device was found (no Direct 3D 11.4 support) in the computer, this method will return an empty list. However, if it succeeds, then the devices list
                // will be populated with an IGorgonVideoDeviceInfo for each suitable video device in the system.
                //
                // Using this method, we could also enumerate the WARP software rasterizer, and/of the D3D Reference device (only if the DEBUG functionality provided by the Windows
                // SDK is installed). These devices are typically used to determine if there's a driver error, and can be terribly slow to render (reference moreso than WARP). It is
                // recommended that these only be used in diagnostic scenarios only.
                IReadOnlyList <IGorgonVideoAdapterInfo> devices = GorgonGraphics.EnumerateAdapters(log: GorgonApplication.Log);

                if (devices.Count == 0)
                {
                    GorgonDialogs.ErrorBox(result, "This example requires a video adapter that supports Direct3D 11.4 or better.");
                    return(result);
                }

                // Now we create the main graphics interface with the first applicable video device.
                _graphics = new GorgonGraphics(devices[0], log: GorgonApplication.Log);

                // Check to ensure that we can support the format required for our swap chain.
                // If a video device can't support this format, then the odds are good it won't render anything. Since we're asking for a very common display format, this will
                // succeed nearly 100% of the time. Regardless, it's good form to the check for a working display format prior to setting up the swap chain.
                //
                // This is also used to determine if a format can be used for other objects (e.g. a texture, render target, etc...) And like the swap chain format, it is also best
                // practice to check if the object you're creating supports the desired format.
                if (!_graphics.FormatSupport[BufferFormat.R8G8B8A8_UNorm].IsDisplayFormat)
                {
                    // We should never see this unless you've got some very esoteric hardware.
                    GorgonDialogs.ErrorBox(result, "We should not see this error.");
                    return(result);
                }

                // Finally, create a swap chain to display our output.
                // In this case we're setting up our swap chain to bind with our main window, and we use its client size to determine the width/height of the swap chain back buffers.
                // This width/height does not need to be the same size as the window, but, except for some scenarios, that would produce undesirable image quality.
                _swap = new GorgonSwapChain(_graphics,
                                            result,
                                            new GorgonSwapChainInfo("Main Swap Chain")
                {
                    Format = BufferFormat.R8G8B8A8_UNorm, Width = result.ClientSize.Width, Height = result.ClientSize.Height
                });

                // Assign the swap chain as our default rendering surface.
                _graphics.SetRenderTarget(_swap.RenderTargetView);

                GorgonExample.LoadResources(_graphics);
            }
            finally
            {
                GorgonExample.EndInit();
            }

            return(result);
        }
Exemple #12
0
        /// <summary>
        /// Function to initialize the application.
        /// </summary>
        private static void Initialize()
        {
            GorgonExample.ShowStatistics = false;
            _window = GorgonExample.Initialize(new DX.Size2(Settings.Default.Resolution.Width, Settings.Default.Resolution.Height), "Primitives");

            try
            {
                // Find out which devices we have installed in the system.
                IReadOnlyList <IGorgonVideoAdapterInfo> deviceList = GorgonGraphics.EnumerateAdapters();

                if (deviceList.Count == 0)
                {
                    throw new
                          NotSupportedException("There are no suitable video adapters available in the system. This example is unable to continue and will now exit.");
                }

                _graphics = new GorgonGraphics(deviceList[0]);
                _renderer = new SimpleRenderer(_graphics);

                _swapChain = new GorgonSwapChain(_graphics,
                                                 _window,
                                                 new GorgonSwapChainInfo("Swap")
                {
                    Width  = _window.ClientSize.Width,
                    Height = _window.ClientSize.Height,
                    Format = BufferFormat.R8G8B8A8_UNorm
                });

                BuildDepthBuffer(_swapChain.Width, _swapChain.Height);

                _graphics.SetRenderTarget(_swapChain.RenderTargetView, _depthBuffer);

                LoadShaders();

                LoadTextures();

                BuildLights();

                BuildMeshes();

                _renderer.Camera = _camera = new Camera
                {
                    Fov        = 75.0f,
                    ViewWidth  = _swapChain.Width,
                    ViewHeight = _swapChain.Height
                };

                _input    = new GI.GorgonRawInput(_window);
                _keyboard = new GI.GorgonRawKeyboard();

                _input.RegisterDevice(_keyboard);

                _keyboard.KeyDown  += Keyboard_KeyDown;
                _window.MouseDown  += Mouse_Down;
                _window.MouseWheel += Mouse_Wheel;

                _swapChain.BeforeSwapChainResized += (sender, args) =>
                {
                    _graphics.SetDepthStencil(null);
                };

                // When we resize, update the projection and viewport to match our client size.
                _swapChain.AfterSwapChainResized += (sender, args) =>
                {
                    _camera.ViewWidth  = args.Size.Width;
                    _camera.ViewHeight = args.Size.Height;

                    BuildDepthBuffer(args.Size.Width, args.Size.Height);

                    _graphics.SetDepthStencil(_depthBuffer);
                };

                _2DRenderer = new Gorgon2D(_graphics);

                GorgonExample.LoadResources(_graphics);

                // Create a font so we can render some text.
                _font = GorgonExample.Fonts.GetFont(new GorgonFontInfo("Segoe UI", 14.0f, FontHeightMode.Points, "Segoe UI 14pt")
                {
                    OutlineSize   = 2,
                    OutlineColor1 = GorgonColor.Black,
                    OutlineColor2 = GorgonColor.Black
                });

                _textSprite = new GorgonTextSprite(_font)
                {
                    DrawMode = TextDrawMode.OutlinedGlyphs
                };
            }
            finally
            {
                GorgonExample.EndInit();
            }
        }
Exemple #13
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();
            }
        }
Exemple #14
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);
            GorgonExample.PlugInLocationDirectory = new DirectoryInfo(Settings.Default.PlugInLocation);

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

            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 Depth Buffer Example")
                {
                    Width  = Settings.Default.Resolution.Width,
                    Height = Settings.Default.Resolution.Height,
                    Format = BufferFormat.R8G8B8A8_UNorm
                });

                _depthBuffer = GorgonDepthStencil2DView.CreateDepthStencil(_graphics, new GorgonTexture2DInfo(_screen.RenderTargetView)
                {
                    Binding = TextureBinding.DepthStencil,
                    Format  = BufferFormat.D24_UNorm_S8_UInt
                });

                // Tell the graphics API that we want to render to the "screen" swap chain.
                _graphics.SetRenderTarget(_screen.RenderTargetView, _depthBuffer);

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

                GorgonExample.LoadResources(_graphics);

                // Load our packed file system plug in.
                _assemblyCache = new GorgonMefPlugInCache(GorgonApplication.Log);
                _assemblyCache.LoadPlugInAssemblies(GorgonExample.GetPlugInPath().FullName, "Gorgon.FileSystem.GorPack.dll");
                IGorgonPlugInService plugIns = new GorgonMefPlugInService(_assemblyCache);

                // Load the file system containing our application data (sprites, images, etc...)
                IGorgonFileSystemProviderFactory providerFactory = new GorgonFileSystemProviderFactory(plugIns, GorgonApplication.Log);
                IGorgonFileSystemProvider        provider        = providerFactory.CreateProvider("Gorgon.IO.GorPack.GorPackProvider");
                IGorgonFileSystem fileSystem = new GorgonFileSystem(provider, GorgonApplication.Log);

                // We can load the editor file system directly.
                // This is handy for switching a production environment where your data may be stored
                // as a compressed file, and a development environment where your data consists of loose
                // files.
                // fileSystem.Mount(@"D:\unpak\scratch\DeepAsAPuddle.gorPack\fs\");

                // For now though, we'll load the packed file.
                fileSystem.Mount(Path.Combine(GorgonExample.GetResourcePath(@"FileSystems").FullName, "Depth.gorPack"));

                // Get our sprites.  These make up the frames of animation for our Guy.
                // If and when there's an animation editor, we'll only need to create a single sprite and load the animation.
                IGorgonVirtualFile[] spriteFiles = fileSystem.FindFiles("/Sprites/", "*", true).ToArray();

                // Load our sprite data (any associated textures will be loaded as well).
                Dictionary <string, GorgonSprite> sprites = new Dictionary <string, GorgonSprite>(StringComparer.OrdinalIgnoreCase);

                for (int i = 0; i < spriteFiles.Length; i++)
                {
                    IGorgonVirtualFile file = spriteFiles[i];
                    (GorgonSprite sprite, GorgonTexture2D texture) = fileSystem.LoadSprite(_renderer, file.FullPath);

                    // The LoadSprite extension method will automatically find and load your associated texture if you're using
                    // a Gorgon editor file system. So it's important that you leep track of your textures, disposing of just
                    // the associated GorgonTexture2DView won't cut it here, so you'll need to dispose the actual texture resource
                    // when you're done with it.
                    if (!_textures.Contains(texture))
                    {
                        _textures.Add(texture);
                    }

                    // At super duper resolution, the example graphics would be really hard to see, so we'll scale them up.
                    sprite.Scale       = new DX.Vector2((_screen.Width / (_screen.Height / 2)) * 2.0f);
                    sprites[file.Name] = sprite;
                }

                _snowTile       = sprites["Snow"];
                _snowTile.Depth = 0.5f;

                _icicle       = sprites["Icicle"];
                _icicle.Depth = 0.2f;

                _guySprite       = sprites["Guy_Up_0"];
                _guySprite.Depth = 0.1f;
                _guyPosition     = new DX.Vector2(_screen.Width / 2 + _guySprite.ScaledSize.Width * 1.25f, _screen.Height / 2 + _guySprite.ScaledSize.Height);

                BuildAnimations(sprites);
            }
            finally
            {
                GorgonExample.EndInit();
            }

            return(window);
        }
Exemple #15
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();
            }
        }
Exemple #16
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();
            }
        }