Ejemplo n.º 1
0
        /// <summary>
        /// Function to load the images for use with the example.
        /// </summary>
        /// <param name="codec">The codec for the images.</param>
        /// <returns><b>true</b> if files were loaded successfully, <b>false</b> if not.</returns>
        private static bool LoadImageFiles(IGorgonImageCodec codec)
        {
            DirectoryInfo dirInfo = GorgonExample.GetResourcePath(@"\Textures\PostProcess");

            FileInfo[] files = dirInfo.GetFiles("*.dds", SearchOption.TopDirectoryOnly);

            if (files.Length == 0)
            {
                GorgonDialogs.ErrorBox(null, $"No DDS images found in {dirInfo.FullName}.");
                GorgonApplication.Quit();
                return(false);
            }

            _images = new GorgonTexture2DView[files.Length];

            // Load all the DDS files from the resource area.
            for (int i = 0; i < files.Length; ++i)
            {
                _images[i] = GorgonTexture2DView.FromFile(_graphics,
                                                          files[i].FullName,
                                                          codec,
                                                          new GorgonTexture2DLoadOptions
                {
                    Binding = TextureBinding.ShaderResource,
                    Usage   = ResourceUsage.Immutable,
                    Name    = Path.GetFileNameWithoutExtension(files[i].Name)
                });
            }

            return(true);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Function to load true type fonts to generate from.
        /// </summary>
        /// <param name="window">The window containing the loading message.</param>
        /// <returns>The font families to use when building the bitmap fonts.</returns>
        private static IReadOnlyList <Drawing.FontFamily> LoadTrueTypeFonts(FormMain window)
        {
            // Load in a bunch of true type fonts.
            DirectoryInfo dirInfo = GorgonExample.GetResourcePath("Fonts");

            FileInfo[] files = dirInfo.GetFiles("*.ttf", SearchOption.TopDirectoryOnly);

            var fontFamilies = new List <Drawing.FontFamily>();

            // Load all external true type fonts for this example.
            // This takes a while...
            foreach (FileInfo file in files)
            {
                window.UpdateStatus($"Loading Font: {file.FullName}".Ellipses(50));
                Drawing.FontFamily externFont = _fontFactory.LoadTrueTypeFontFamily(file.FullName);
                _fontFamilies.Insert(0, externFont.Name);
                fontFamilies.Add(externFont);
            }

            window.UpdateStatus(null);

            fontFamilies.AddRange(Drawing.FontFamily.Families);

            return(fontFamilies);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Raises the <see cref="E:System.Windows.Forms.Form.Load" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            try
            {
                GorgonExample.PlugInLocationDirectory = new DirectoryInfo(Settings.Default.PlugInLocation);
                GorgonExample.ResourceBaseDirectory   = new DirectoryInfo(Settings.Default.ResourceLocation);

                // Create our virtual file system.
                _fileSystem = new GorgonFileSystem(Program.Log);
                _writer     = new GorgonFileSystemWriter(_fileSystem, Program.WriteDirectory.FullName);

                LoadText();

                labelFileSystem.Text    = $"{GorgonExample.GetResourcePath(@"FolderSystem\").FullName.Ellipses(100, true)} mounted as '/'.";
                labelWriteLocation.Text = $"{Program.WriteDirectory.FullName.Ellipses(100, true)} mounted as '/'";
            }
            catch (Exception ex)
            {
                GorgonExample.HandleException(ex);
                GorgonApplication.Quit();
            }
            finally
            {
                CommandEnable(!string.Equals(_originalText, _changedText, StringComparison.CurrentCulture));
                UpdateInfo();
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Function to load the text into the file system.
        /// </summary>
        private void LoadText()
        {
            DirectoryInfo physicalPath = GorgonExample.GetResourcePath(@"FolderSystem\");

            // Unload the mounted files.
            _writer.Unmount();
            _fileSystem.Unmount(physicalPath.FullName);

            _fileSystem.Mount(physicalPath.FullName);

            // Load the original before we mount the write directory.
            IGorgonVirtualFile file = _fileSystem.GetFile("/SomeText.txt");

            using (Stream stream = file.OpenStream())
            {
                byte[] textData = new byte[stream.Length];

                stream.Read(textData, 0, textData.Length);
                _originalText = Encoding.UTF8.GetString(textData);
            }

            // Set the write location to the users app data folder.
            _writer.Mount();

            // Load the modified version (if it exists, if it doesn't, the original will be loaded instead).
            file = _fileSystem.GetFile("/SomeText.txt");

            using (Stream stream = file.OpenStream())
            {
                byte[] textData = new byte[stream.Length];

                stream.Read(textData, 0, textData.Length);
                _changedText = Encoding.UTF8.GetString(textData);

                textDisplay.Text = string.Equals(_changedText, _originalText, StringComparison.CurrentCulture) ? _originalText : _changedText;
            }
        }
Ejemplo n.º 5
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);
        }
Ejemplo n.º 6
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;
        }
Ejemplo n.º 7
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();
            }
        }
Ejemplo n.º 8
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();
            }
        }
Ejemplo n.º 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), "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();
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Function to generate the Gorgon bitmap fonts.
        /// </summary>
        /// <param name="fontFamilies">The list of TrueType font families to use.</param>
        /// <param name="window">The window that contains the loading message.</param>
        private static void GenerateGorgonFonts(IReadOnlyList <Drawing.FontFamily> fontFamilies, FormMain window)
        {
            // Pick a font to use with outlines.
            int fontWithOutlineIndex = GorgonRandom.RandomInt32(1, 5);

            _glowIndex = GorgonRandom.RandomInt32(fontWithOutlineIndex + 1, fontWithOutlineIndex + 5);
            int fontWithGradient = GorgonRandom.RandomInt32(_glowIndex + 1, _glowIndex + 5);
            int fontWithTexture  = GorgonRandom.RandomInt32(fontWithGradient + 1, fontWithGradient + 5).Min(_fontFamilies.Count - 1);

            var pngCodec = new GorgonCodecPng();

            using (IGorgonImage texture = pngCodec.LoadFromFile(Path.Combine(GorgonExample.GetResourcePath(@"Textures\Fonts\").FullName, "Gradient.png")))
            {
                for (int i = 0; i < _fontFamilies.Count; ++i)
                {
                    string fontFamily = _fontFamilies[i];

                    // Use this to determine if the font is avaiable.
                    if (fontFamilies.All(item => !string.Equals(item.Name, fontFamily, StringComparison.InvariantCultureIgnoreCase)))
                    {
                        // Can't locate this one, move on...
                        continue;
                    }

                    bool isExternal =
                        Drawing.FontFamily.Families.All(item => !string.Equals(item.Name, fontFamily, StringComparison.InvariantCultureIgnoreCase));
                    string           fontName;
                    int              outlineSize   = 0;
                    GorgonColor      outlineColor1 = GorgonColor.BlackTransparent;
                    GorgonColor      outlineColor2 = GorgonColor.BlackTransparent;
                    GorgonGlyphBrush brush         = null;

                    if (i == fontWithOutlineIndex)
                    {
                        fontName      = $"{fontFamily} 32px Outlined{(isExternal ? " External TTF" : string.Empty)}";
                        outlineColor1 = GorgonColor.Black;
                        outlineColor2 = GorgonColor.Black;
                        outlineSize   = 3;
                    }
                    else if (i == _glowIndex)
                    {
                        fontName      = $"{fontFamily} 32px Outline as Glow{(isExternal ? " External TTF" : string.Empty)}";
                        outlineColor1 = new GorgonColor(GorgonColor.YellowPure, 1.0f);
                        outlineColor2 = new GorgonColor(GorgonColor.DarkRed, 0.0f);
                        outlineSize   = 16;
                    }
                    else if (i == fontWithGradient)
                    {
                        fontName = $"{fontFamily} 32px Gradient{(isExternal ? " External TTF" : string.Empty)}";
                        brush    = new GorgonGlyphLinearGradientBrush
                        {
                            StartColor = GorgonColor.White,
                            EndColor   = GorgonColor.Black,
                            Angle      = 45.0f
                        };
                    }
                    else if (i == fontWithTexture)
                    {
                        fontName = $"{fontFamily} 32px Textured{(isExternal ? " External TTF" : string.Empty)}";
                        brush    = new GorgonGlyphTextureBrush(texture);
                    }
                    else
                    {
                        fontName = $"{fontFamily} 32px{(isExternal ? " External TTF" : string.Empty)}";
                    }

                    window.UpdateStatus($"Generating Font: {fontFamily}".Ellipses(50));

                    var fontInfo = new GorgonFontInfo(fontFamily,
                                                      30.25f,
                                                      name:
                                                      fontName)
                    {
                        AntiAliasingMode         = FontAntiAliasMode.AntiAlias,
                        OutlineSize              = outlineSize,
                        OutlineColor1            = outlineColor1,
                        OutlineColor2            = outlineColor2,
                        UsePremultipliedTextures = false,
                        Brush = brush
                    };

                    _font.Add(_fontFactory.GetFont(fontInfo));

                    // Texture brushes have to be disposed when we're done with them.
                    var disposableBrush = brush as IDisposable;
                    disposableBrush?.Dispose();
                }
            }
        }
Ejemplo n.º 11
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();
            }
        }
Ejemplo n.º 12
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);
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Function to update the information label.
 /// </summary>
 private void UpdateInfo() => labelInfo.Text = string.Equals(_originalText, textDisplay.Text, StringComparison.CurrentCulture)
                          ? $"Using original text from {GorgonExample.GetResourcePath(@"FolderSystem\").FullName.Ellipses(100, true)}"
                          : $"Using modified text from {Program.WriteDirectory.FullName.Ellipses(100, true)}";
Ejemplo n.º 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);
            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();
            }
        }