Exemplo n.º 1
0
        /// <summary>
        /// Function to build the layer that contains the sun.
        /// </summary>
        /// <param name="renderer">The 2D renderer for the application.</param>
        /// <param name="resources">The resources for the application.</param>
        /// <returns>The sprite layer that will contain the sun sprite.</returns>
        public static SpritesLayer GetSunLayer(Gorgon2D renderer, ResourceManagement resources)
        {
            GorgonSprite sunSprite = resources.Sprites["Star"];
            var          sunLayer  = new SpritesLayer(renderer)
            {
                ParallaxLevel = 2980.0f,                        // The sun is pretty far away the last I checked.
                Sprites       =
                {
                    new SpriteEntity("Sun")
                    {
                        Sprite        = sunSprite,
                        LocalPosition = new DX.Vector2(1200, -650)
                    }
                },
                PostProcessGroup = "Final Pass",
                Lights           =
                {
                    new Light
                    {
                        Attenuation        = float.MaxValue.Sqrt(),
                        Color              = GorgonColor.White,
                        SpecularPower      = 6.0f,
                        LocalLightPosition = new DX.Vector3(1200, -650, -1.0f),
                        Intensity          = 13.07f
                    }
                }
            };

            sunLayer.LoadResources();

            return(sunLayer);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Function to set up the renderer.
        /// </summary>
        /// <param name="renderer">Renderer to use.</param>
        public void SetupRenderer(Gorgon2D renderer)
        {
            if (DesignMode)
            {
                return;
            }

            try
            {
                Gorgon.ApplicationIdleLoopMethod = null;

                if (_renderer != renderer)
                {
                    CleanUpRenderer();
                }

                if (renderer == null)
                {
                    return;
                }

                _renderer = renderer;
                _graphics = renderer.Graphics;

                if (_swapChain == null)
                {
                    _swapChain = _graphics.Output.CreateSwapChain("ImageDisplay",
                                                                  new GorgonSwapChainSettings
                    {
                        Window = panelTextureDisplay,
                        Format = BufferFormat.R8G8B8A8_UIntNormal
                    });
                }

                if (_lastState == null)
                {
                    _lastState = renderer.Begin2D();
                }

                if (_defaultTexture == null)
                {
                    _defaultTexture = _graphics.Textures.CreateTexture <GorgonTexture2D>("DefaultPattern", Resources.Pattern);
                }

                if (_clipper == null)
                {
                    InitializeClipper(null, RectangleF.Empty);
                }

                _region = new RectangleF(0, 0, 1, 1);

                _renderer.Target = _swapChain;

                Gorgon.ApplicationIdleLoopMethod = Idle;
            }
            finally
            {
                ValidateCommands();
            }
        }
Exemplo n.º 3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ShadowBuilder"/> class.
 /// </summary>
 /// <param name="renderer">The renderer.</param>
 /// <param name="effect">The gaussian blur effect to use in order to soften the shadows.</param>
 /// <param name="sprite1">The first sprite to draw.</param>
 /// <param name="sprite2">The second sprite to draw.</param>
 public ShadowBuilder(Gorgon2D renderer, Gorgon2DGaussBlurEffect effect, GorgonSprite sprite1, GorgonSprite sprite2)
 {
     _renderer  = renderer;
     _gaussBlur = effect;
     _sprite1   = sprite1;
     _sprite2   = sprite2;
 }
Exemplo n.º 4
0
        /// <summary>
        /// Function to create the resources for the preview window.
        /// </summary>
        private void CreateResources()
        {
            _swapChain = GraphicsContext.LeaseSwapPresenter(PanelDisplay);
            _renderer  = GraphicsContext.Renderer2D;
            _titleFont = GraphicsContext.FontFactory.GetFont(new GorgonFontInfo(Font.FontFamily.Name, 10.0f, FontHeightMode.Points, $"PreviewTitleFont")
            {
                OutlineSize   = 2,
                OutlineColor1 = GorgonColor.Black,
                OutlineColor2 = GorgonColor.Black,
                FontStyle     = Graphics.Fonts.FontStyle.Bold
            });

            _titleText = new GorgonTextSprite(_titleFont)
            {
                DrawMode   = TextDrawMode.OutlinedGlyphs,
                Alignment  = Gorgon.UI.Alignment.Center,
                LayoutArea = new DX.Size2F(_swapChain.Width, _swapChain.Height)
            };

            using (var stream = new MemoryStream(Resources.no_thumbnail_256x256))
            {
                _defaultTexture = GorgonTexture2DView.FromStream(GraphicsContext.Graphics, stream, new GorgonCodecDds(), options: new GorgonTexture2DLoadOptions
                {
                    Name    = "DefaultPreviewTexture",
                    Binding = TextureBinding.ShaderResource,
                    Usage   = ResourceUsage.Immutable
                });
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Function to create a new image codec object.
        /// </summary>
        /// <param name="codec">The name of the codec to look up within the plug in.</param>
        /// <param name="renderer">The renderer used to retrieve sprite textures.</param>
        /// <returns>A new instance of a <see cref="IGorgonSpriteCodec"/>.</returns>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="codec"/>, or the <paramref name="renderer"/> parameter is <b>null</b>.</exception>
        /// <exception cref="ArgumentEmptyException">Thrown when the <paramref name="codec"/> parameter is empty.</exception>
        /// <exception cref="KeyNotFoundException">Thrown when the <paramref name="codec"/> was not found in this plug in.</exception>
        /// <remarks>
        /// <para>
        /// If the <paramref name="codec"/> is not found within the plug in, then an exception will be thrown. To determine whether the plug in has the desired <paramref name="codec"/>, check the
        /// <see cref="Codecs"/> property on the plug in to locate the plug in name.
        /// </para>
        /// </remarks>
        public IGorgonSpriteCodec CreateCodec(string codec, Gorgon2D renderer)
        {
            if (codec == null)
            {
                throw new ArgumentNullException(nameof(codec));
            }

            if (string.IsNullOrWhiteSpace(codec))
            {
                throw new ArgumentEmptyException(nameof(codec));
            }

            if (renderer == null)
            {
                throw new ArgumentNullException(nameof(renderer));
            }

            if (!Codecs.Any(item => string.Equals(codec, item.Name, StringComparison.OrdinalIgnoreCase)))
            {
                throw new KeyNotFoundException(string.Format(Resources.GOR2DIO_ERR_CODEC_NOT_IN_PLUGIN, codec));
            }

            IGorgonSpriteCodec result = OnCreateCodec(codec, renderer);

            if (result == null)
            {
                throw new KeyNotFoundException(string.Format(Resources.GOR2DIO_ERR_CODEC_NOT_IN_PLUGIN, codec));
            }

            return(result);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Function to perform initialization on the content.
        /// </summary>
        /// <returns>A control to embed into the container interface.</returns>
        protected override ContentPanel OnInitialize()
        {
            _delta = Program.Settings.AnimateStartPageLogo ? Program.Settings.StartPageAnimationPulseRate.Abs() : 0;

            _container = new ContentPanel(this)
            {
                CaptionVisible = false
            };

            _2D = Graphics.Output.Create2DRenderer(_container.PanelDisplay);

            // Create the logo for display.
            _logo = Graphics.Textures.FromMemory <GorgonTexture2D>("Logo", Resources.Gorgon_2_x_Logo_Blurry, new GorgonCodecDDS());

            var textureCoordinates = new RectangleF(Vector2.Zero, _logo.ToTexel(new Vector2(_logo.Settings.Width, _logo.Settings.Height / 3)));

            // Set up coordinates for our blurred images.
            _blurStates = new[]
            {
                textureCoordinates,                                                                    // No blur.
                new RectangleF(new Vector2(0, textureCoordinates.Height), textureCoordinates.Size),    // Medium blur.
                new RectangleF(new Vector2(0, textureCoordinates.Height * 2), textureCoordinates.Size) // Max blur.
            };

            _sourceState = _blurStates[2];
            _destState   = _blurStates[1];

            return(_container);
        }
Exemplo n.º 7
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            Visible    = true;
            ClientSize = new Size(1280, 720);

            _graphics = new GorgonGraphics();
            _swap     = _graphics.Output.CreateSwapChain("Swap", new GorgonSwapChainSettings
            {
                BufferCount = 2,
                IsWindowed  = true,
                Format      = BufferFormat.R8G8B8A8_UIntNormal,
                Width       = 1280,
                Height      = 720,
                Window      = this
            });

            _font = _graphics.Fonts.CreateFont("FontTest", new GorgonFontSettings
            {
                FontFamilyName = "Segoe UI",
                FontHeightMode = FontHeightMode.Pixels,
                Size           = 12.0f
            });

            _2d = _graphics.Output.Create2DRenderer(_swap);
            _2d.Begin2D();


            Gorgon.ApplicationIdleLoopMethod = Idle;
        }
Exemplo n.º 8
0
        /// <summary>
        /// Function called when the content is being initialized.
        /// </summary>
        /// <returns>
        /// A control to place in the primary interface window.
        /// </returns>
        protected override ContentPanel OnInitialize()
        {
            _panel = new PanelSpriteEditor(this);

            _swap = Graphics.Output.CreateSwapChain("SpriteEditorSwap",
                                                    new GorgonSwapChainSettings
            {
                Window = _panel.panelSprite,
                Format = BufferFormat.R8G8B8A8_UIntNormal
            });

            Renderer = Graphics.Output.Create2DRenderer(_swap);

            BackgroundTexture = Graphics.Textures.CreateTexture <GorgonTexture2D>("BackgroundTexture", Resources.Pattern);

            if ((_settings == null) || (!_settings.CreateContent))
            {
                return(_panel);
            }

            Sprite = Renderer.Renderables.CreateSprite(Name, _settings.Settings);
            var dependency = new Dependency(_settings.TextureDependency.EditorFile, TextureDependencyType);

            // Build the texture dependency.
            Dependencies.Add(dependency);
            Dependencies.CacheDependencyObject(dependency.EditorFile, dependency.Type, Sprite.Texture);

            InitSprite();

            return(_panel);
        }
Exemplo n.º 9
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);

            Cursor.Current = Cursors.WaitCursor;

            try
            {
                // Set up the graphics interface.
                _graphics = new GorgonGraphics();

                // Create our 2D renderer to display the image.
                _2D = _graphics.Output.Create2DRenderer(this, 1280, 800);

                // Center the window on the screen.
                Screen currentMonitor = Screen.FromControl(this);
                Location = new Point(currentMonitor.WorkingArea.Left + (currentMonitor.WorkingArea.Width / 2 - Width / 2),
                                     currentMonitor.WorkingArea.Top + (currentMonitor.WorkingArea.Height / 2 - Height / 2));

                // Load our base texture.
                _image = _graphics.Textures.FromMemory <GorgonTexture2D>("SourceTexture",
                                                                         Resources.SourceTexture,
                                                                         new GorgonCodecDDS());


                // Load the custom codec.
                if (!LoadCodec())
                {
                    GorgonDialogs.ErrorBox(this, "Unable to load the useless image codec plug-in.");
                    Gorgon.Quit();
                    return;
                }

                // Convert the image to our custom codec.
                ConvertImage();

                // Set up our idle time processing.
                Gorgon.ApplicationIdleLoopMethod = () =>
                {
                    _2D.Clear(Color.White);

                    // Draw to the window.
                    Draw();

                    // Render with a vsync interval of 2 (typically 30 FPS).
                    // We're not making an action game here.
                    _2D.Render(2);
                    return(true);
                };
            }
            catch (Exception ex)
            {
                GorgonDialogs.ErrorBox(this, ex);
                Gorgon.Quit();
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
Exemplo n.º 10
0
        /// <summary>Function to draw the texture.</summary>
        /// <param name="renderer">The renderer used to draw the texture.</param>
        /// <param name="image">The image being rendered.</param>
        /// <param name="batchState">The currently active batch render state.</param>
        protected override void OnDrawTexture(Gorgon2D renderer, IImageContent image, Gorgon2DBatchState batchState)
        {
            // We can use this for 3D textures because the texture is in slot 1, and slot 0, where the 2D texture is usually located is vacant and not used by the pixel shader.
            renderer.DrawFilledRectangle(TextureBounds,
                                         new GorgonColor(GorgonColor.White, Alpha),
                                         null,
                                         new DX.RectangleF(0, 0, 1, 1),
                                         0,
                                         textureSampler: GorgonSamplerState.PointFiltering);

            renderer.End();

            // Draw a frame around the volume rendering area.
            DX.RectangleF volRegion = _volRenderer.VolumeRegion;
            renderer.Begin();

            DX.Size2F textArea = renderer.DefaultFont.MeasureLine(Resources.GORIMG_TEXT_3DVIEW, false);
            renderer.DrawFilledRectangle(volRegion, new GorgonColor(GorgonColor.Black, 0.5f));
            renderer.DrawFilledRectangle(new DX.RectangleF(volRegion.Left - 1, volRegion.Bottom, volRegion.Width + 2, textArea.Height + 6), GorgonColor.White);
            renderer.DrawRectangle(new DX.RectangleF(volRegion.X - 1, volRegion.Y - 1, volRegion.Width + 2, volRegion.Height + 2), GorgonColor.White);
            renderer.DrawString("3D View", new DX.Vector2((volRegion.Right + volRegion.Left) / 2.0f - (textArea.Width / 2.0f), volRegion.Bottom + 3), color: GorgonColor.Black);

            renderer.End();

            _volRenderer.Render();

            return;
        }
Exemplo n.º 11
0
        /// <summary>
        /// Releases unmanaged and - optionally - managed resources.
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected override void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    if (_logo != null)
                    {
                        _logo.Dispose();
                    }

                    if (_2D != null)
                    {
                        _2D.Dispose();
                    }
                }
            }

            _container = null;
            _2D        = null;
            _logo      = null;
            _disposed  = true;

            base.Dispose(disposing);
        }
Exemplo n.º 12
0
 /// <summary>Initializes a new instance of the <see cref="ExtractorService"/> class.</summary>
 /// <param name="renderer">The application 2D renderer.</param>
 /// <param name="fileManager">The file manager for the project files.</param>
 /// <param name="defaultCodec">The default sprite codec.</param>
 public ExtractorService(Gorgon2D renderer, IContentFileManager fileManager, IGorgonSpriteCodec defaultCodec)
 {
     _renderer     = renderer;
     _graphics     = renderer.Graphics;
     _fileManager  = fileManager;
     _defaultCodec = defaultCodec;
 }
Exemplo n.º 13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Clipper"/> class.
        /// </summary>
        /// <param name="renderer">The renderer to display the clipper UI.</param>
        /// <param name="renderControl">The control that will be rendered into.</param>
        /// <exception cref="System.ArgumentNullException">Thrown when the <paramref name="renderer"/> or the <paramref name="renderControl"/> parameter is NULL (Nothing in VB.Net).</exception>
        public Clipper(Gorgon2D renderer, Control renderControl)
        {
            if (renderer == null)
            {
                throw new ArgumentNullException("renderer");
            }

            if (renderControl == null)
            {
                throw new ArgumentNullException("renderControl");
            }

            _scale               = new Vector2(1);
            _dragAreas           = new RectangleF[8];
            SelectorAnimateSpeed = 0.5f;
            DragNodeSize         = new Size(8, 8);
            DragNodeColor        = new GorgonColor(0, 1, 1, 0.5f);
            DragNodeHoverColor   = new GorgonColor(1, 0, 0, 0.5f);

            _renderControl = renderControl;
            _renderer      = renderer;

            _textureSize = new Size(1, 1);

            SelectionSprite = renderer.Renderables.CreateSprite("SelectionSprite",
                                                                new GorgonSpriteSettings
            {
                Color = new GorgonColor(0, 0, 0.8f, 0.5f),
                Size  = new Vector2(1)
            });

            SelectionSprite.TextureSampler.HorizontalWrapping = TextureAddressing.Wrap;
            SelectionSprite.TextureSampler.VerticalWrapping   = TextureAddressing.Wrap;
        }
Exemplo n.º 14
0
 /// <summary>Initializes a new instance of the <see cref="T:Gorgon.Editor.SpriteEditor.Services.GorgonSpriteImporter"/> class.</summary>
 /// <param name="sourceFile">The file being imported.</param>
 /// <param name="codec">The original codec for the file.</param>
 /// <param name="renderer">The renderer used to locate the image linked to the sprite.</param>
 /// <param name="fileSystem">The file system containing the file being imported.</param>
 /// <param name="log">The log used for logging debug messages.</param>
 public GorgonSpriteImporter(FileInfo sourceFile, IGorgonSpriteCodec codec, Gorgon2D renderer, IGorgonFileSystem fileSystem, IGorgonLog log)
 {
     _log        = log ?? GorgonLog.NullLog;
     SourceFile  = sourceFile;
     _codec      = codec;
     _renderer   = renderer;
     _fileSystem = fileSystem;
 }
Exemplo n.º 15
0
 /// <summary>Function to draw the texture.</summary>
 /// <param name="renderer">The renderer used to draw the texture.</param>
 /// <param name="image">The image being rendered.</param>
 /// <param name="batchState">The currently active batch render state.</param>
 protected override void OnDrawTexture(Gorgon2D renderer, IImageContent image, Gorgon2DBatchState batchState) =>
 // We can use this for 3D textures because the texture is in slot 1, and slot 0, where the 2D texture is usually located is vacant and not used by the pixel shader.
 renderer.DrawFilledRectangle(TextureBounds,
                              new GorgonColor(GorgonColor.White, Alpha),
                              _textureView,
                              new DX.RectangleF(0, 0, 1, 1),
                              image.CurrentArrayIndex,
                              textureSampler: GorgonSamplerState.PointFiltering);
Exemplo n.º 16
0
        /// <summary>Initializes a new instance of the <see cref="ResourceManagement"/> class.</summary>
        /// <param name="renderer">The renderer for the application.</param>
        /// <param name="plugIns>The plugin service used to load file system providers.</param>
        public ResourceManagement(Gorgon2D renderer, IGorgonPlugInService plugIns)
        {
            _renderer = renderer;
            _graphics = renderer.Graphics;
            _plugIns  = plugIns;

            _spriteCodec = new GorgonV3SpriteBinaryCodec(renderer);
        }
Exemplo n.º 17
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;
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Function to parse the polygon hull string data.
        /// </summary>
        /// <param name="renderer">The renderer used to generate the polygonal sprite.</param>
        /// <param name="polygonHull">The string containing the polygon hull data.</param>
        /// <returns>The polygon sprite from the polygon hull data.</returns>
        public static GorgonPolySprite ParsePolygonHullString(Gorgon2D renderer, string polygonHull)
        {
            var builder = new GorgonPolySpriteBuilder(renderer);

            ParseString(polygonHull, builder);

            return(builder.Anchor(new DX.Vector2(0.5f, 0.5f))
                   .Build());
        }
Exemplo n.º 19
0
        /// <summary>
        /// Function to convert a JSON string into a sprite object.
        /// </summary>
        /// <param name="renderer">The renderer for the sprite.</param>
        /// <param name="overrideTexture">The texture to assign to the sprite instead of the texture associated with the name stored in the file.</param>
        /// <param name="json">The JSON string containing the sprite data.</param>
        /// <returns>A new <see cref="GorgonPolySprite"/>.</returns>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="renderer"/>, or the <paramref name="json"/> parameter is <b>null</b>.</exception>
        /// <exception cref="ArgumentEmptyException">Thrown when the <paramref name="json"/> parameter is empty.</exception>
        /// <exception cref="GorgonException">Thrown if the JSON string does not contain sprite data, or there is a version mismatch.</exception>
        public static GorgonPolySprite FromJson(Gorgon2D renderer, GorgonTexture2DView overrideTexture, string json)
        {
            if (renderer == null)
            {
                throw new ArgumentNullException(nameof(renderer));
            }

            if (json == null)
            {
                throw new ArgumentNullException(nameof(json));
            }

            if (string.IsNullOrWhiteSpace(json))
            {
                throw new ArgumentEmptyException(nameof(json));
            }

            // Set up serialization so we can convert our more complicated structures.
            var serializer = new JsonSerializer
            {
                CheckAdditionalContent = false
            };

            serializer.Converters.Add(new JsonVector2Converter());
            serializer.Converters.Add(new JsonVector3Converter());
            serializer.Converters.Add(new JsonSize2FConverter());
            serializer.Converters.Add(new JsonGorgonColorConverter());
            serializer.Converters.Add(new JsonRectangleFConverter());
            serializer.Converters.Add(new JsonSamplerConverter(renderer.Graphics));
            serializer.Converters.Add(new JsonTexture2DConverter(renderer.Graphics, overrideTexture));
            serializer.Converters.Add(new VersionConverter());

            // Parse the string so we can extract our header/version for comparison.
            var     jobj        = JObject.Parse(json);
            ulong   jsonID      = jobj[GorgonSpriteExtensions.JsonHeaderProp].Value <ulong>();
            Version jsonVersion = jobj[GorgonSpriteExtensions.JsonVersionProp].ToObject <Version>(serializer);

            if (jsonID != CurrentFileHeader)
            {
                throw new GorgonException(GorgonResult.CannotRead, Resources.GOR2DIO_ERR_JSON_NOT_SPRITE);
            }

            if (!jsonVersion.Equals(CurrentVersion))
            {
                throw new GorgonException(GorgonResult.CannotRead, string.Format(Resources.GOR2DIO_ERR_SPRITE_VERSION_MISMATCH, CurrentVersion, jsonVersion));
            }

            GorgonPolySprite workingSpriteData = jobj.ToObject <GorgonPolySprite>(serializer);

            // We have to rebuild the sprite because it's only data at this point and we need to build up its vertex/index buffers before we can render it.
            var builder = new GorgonPolySpriteBuilder(renderer);

            builder.ResetTo(workingSpriteData);

            return(builder.Build());
        }
Exemplo n.º 20
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();
            }
        }
Exemplo n.º 21
0
        /// <summary>Initializes a new instance of the <see cref="SelectionRectangle"/> class.</summary>
        /// <param name="graphics">The graphics context to use.</param>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="graphics"/> parameter is <b>null</b>.</exception>
        public SelectionRectangle(IGraphicsContext graphics)
        {
            if (graphics == null)
            {
                throw new ArgumentNullException(nameof(graphics));
            }

            _renderer         = graphics.Renderer2D;
            _selectionTexture = new Lazy <GorgonTexture2DView>(CreateSelectionTexture, LazyThreadSafetyMode.ExecutionAndPublication);
        }
Exemplo n.º 22
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();
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// Function to locate the associated texture codec and file for a sprite.
        /// </summary>
        /// <param name="fileSystem">The file system to evaluate.</param>
        /// <param name="localDir">The local directory for the sprite file.</param>
        /// <param name="renderer">The renderer used for resource look up.</param>
        /// <param name="textureName">The name of the texture.</param>
        /// <param name="codecs">The list of available image codecs to use when determining texture type.</param>
        /// <returns>A tuple containing the codec, the texture file, and a flag to indicate that the texture was previously loaded into memory.</returns>
        private static (IGorgonImageCodec codec, IGorgonVirtualFile file, bool alreadyLoaded) LocateTextureCodecAndFile(
            IGorgonFileSystem fileSystem,
            IGorgonVirtualDirectory localDir,
            Gorgon2D renderer,
            string textureName,
            IEnumerable <IGorgonImageCodec> codecs)
        {
            // First, attempt to locate the resource by its name.  If it's already loaded, we should not load it again.
            GorgonTexture2D texture = renderer.Graphics
                                      .LocateResourcesByName <GorgonTexture2D>(textureName)
                                      .FirstOrDefault();

            if (texture != null)
            {
                return(null, null, true);
            }

            IGorgonImageCodec codec;

            // We couldn't find the texture in our loaded resources, so try to locate it on the file system.

            // First, check the local directory.
            IEnumerable <IGorgonVirtualFile> files = fileSystem.FindFiles(localDir.FullPath, $"{textureName}.*", false);

            foreach (IGorgonVirtualFile file in files)
            {
                codec = FindTextureCodec(file, codecs);

                if (codec != null)
                {
                    return(codec, file, false);
                }
            }

            // Check to see if the name has path information for the texture in the name.
            // The GorgonEditor from v2 does this.
            if (!textureName.Contains("/"))
            {
                // It is not.  We cannot load the texture.
                return(null, null, false);
            }

            IGorgonVirtualFile textureFile = fileSystem.GetFile(textureName);

            if (textureFile == null)
            {
                return(null, null, false);
            }

            // Try to find a codec for the image file.
            codec = FindTextureCodec(textureFile, codecs);

            return(codec == null ? (null, null, false) : (codec, textureFile, false));
        }
Exemplo n.º 24
0
        /// <summary>
        /// Function to build the background layer representing distant stars.
        /// </summary>
        /// <param name="renderer">The 2D renderer for the application.</param>
        /// <param name="resources">The resources for the application.</param>
        /// <returns>The background layer.</returns>
        public static BgStarLayer GetBackgroundLayer(Gorgon2D renderer, ResourceManagement resources)
        {
            var backgroundLayer = new BgStarLayer(renderer)
            {
                PostProcessGroup = "Final Pass",                                        // These post process groups allow us to assign which sprite layers end up in post processing, and which are blitted immediately.
                StarsTexture     = resources.Textures["StarsNoAlpha"]
            };

            backgroundLayer.LoadResources();
            return(backgroundLayer);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Function to create a new 2D renderer interface.
        /// </summary>
        /// <param name="target">Default target for the renderer.</param>
        /// <param name="systemCreatedSwap">TRUE if the system generated the swap chain, FALSE if not.</param>
        /// <param name="vertexCacheSize">The number of vertices that can be placed in the vertex cache.</param>
        /// <returns>A new 2D graphics interface.</returns>
        /// <exception cref="System.ArgumentNullException">Thrown when the <paramref name="target"/> parameter is NULL (Nothing in VB.Net).</exception>
        private static Gorgon2D Create2DRenderer(GorgonRenderTargetView target, bool systemCreatedSwap, int vertexCacheSize)
        {
            if (target == null)
            {
                throw new ArgumentNullException("target");
            }

            var result = new Gorgon2D(target, vertexCacheSize, systemCreatedSwap);

            result.Graphics.ImmediateContext.AddTrackedObject(result);

            return(result);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Gorgon2DEffect"/> class.
        /// </summary>
        /// <param name="renderer">The 2D renderer used to render the effect.</param>
        /// <param name="effectName">Name of the effect.</param>
        /// <param name="effectDescription">The effect description.</param>
        /// <param name="passCount">The number of passes required to render the effect.</param>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="renderer"/>, or the <paramref name="effectName"/> parameter is <b>null</b>.</exception>
        /// <exception cref="ArgumentEmptyException">Thrown when the <paramref name="effectName"/> parameter is empty.</exception>
        protected Gorgon2DEffect(Gorgon2D renderer, string effectName, string effectDescription, int passCount)
            : base(effectName)
        {
            Renderer = renderer ?? throw new ArgumentNullException(nameof(renderer));

            _targets   = new GorgonRenderTargetView[1];
            _viewports = new DX.ViewportF[1];

            // Ensure no less than 1 pass.
            PassCount   = passCount.Max(1);
            Description = effectDescription ?? string.Empty;

            _targetEnumerator   = Graphics.RenderTargets.TakeWhile(item => item != null);
            _viewportEnumerator = Graphics.Viewports.TakeWhile(item => (!item.Width.EqualsEpsilon(0)) && (!item.Height.EqualsEpsilon(0)));
        }
Exemplo n.º 27
0
        /// <summary>
        /// Raises the <see cref="E:System.Windows.Forms.Form.FormClosing"></see> event.
        /// </summary>
        /// <param name="e">A <see cref="T:System.Windows.Forms.FormClosingEventArgs"></see> that contains the event data.</param>
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);

            GorgonExample.UnloadResources();

            // Perform clean up.
            Gorgon2D        renderer = Interlocked.Exchange(ref _renderer, null);
            GorgonSwapChain screen   = Interlocked.Exchange(ref _screen, null);
            GorgonGraphics  graphics = Interlocked.Exchange(ref _graphics, null);

            renderer?.Dispose();
            screen?.Dispose();
            graphics?.Dispose();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="GorgonPolySpriteCodecCommon"/> class.
        /// </summary>
        /// <param name="renderer">The renderer used for resource handling.</param>
        /// <param name="name">The codec name.</param>
        /// <param name="description">The friendly description for the codec.</param>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="renderer"/>, or the <paramref name="name"/> parameter is <b>null</b>.</exception>
        /// <exception cref="ArgumentEmptyException">Thrown when the <paramref name="name"/> parameter is empty.</exception>
        protected GorgonPolySpriteCodecCommon(Gorgon2D renderer, string name, string description)
        {
            Renderer = renderer ?? throw new ArgumentNullException(nameof(renderer));

            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentEmptyException(nameof(name));
            }

            FileExtensions = new[]
            {
                new GorgonFileExtension(".gorPSprite", Resources.GOR2DIO_POLYSPRITE_FILE_EXTENSION_DESC)
            };
            Codec            = name;
            CodecDescription = string.IsNullOrWhiteSpace(description) ? name : description;
        }
Exemplo n.º 29
0
        /// <summary>
        /// Function to draw the statistics and the logo for the example.
        /// </summary>
        /// <param name="renderer">The 2D renderer that we are using.</param>
        public static void DrawStatsAndLogo(Gorgon2D renderer)
        {
            renderer.ValidateObject(nameof(renderer));

            GorgonRenderTargetView currentRtv = renderer.Graphics.RenderTargets[0];

            if ((currentRtv == null) || (_logo == null) || (_statsFont == null))
            {
                return;
            }

            // We won't include these in the draw call count.
            _statsText.Length = 0;
            _statsText.AppendFormat("Average FPS: {0:0.0}\nFrame Delta: {1:0.00#} seconds\nDraw Call Count: {2}", GorgonTiming.AverageFPS, GorgonTiming.Delta, renderer.Graphics.DrawCallCount);

            DX.Size2F measure     = _statsFont.MeasureText(_statsText.ToString(), true);
            var       statsRegion = new DX.RectangleF(0, 0, currentRtv.Width, measure.Height + 4);
            var       logoRegion  = new DX.RectangleF(currentRtv.Width - _logo.Width - 5, currentRtv.Height - _logo.Height - 2, _logo.Width, _logo.Height);

            renderer.Begin();

            if (ShowStatistics)
            {
                // Draw translucent window.
                renderer.DrawFilledRectangle(statsRegion, new GorgonColor(0, 0, 0, 0.5f));
                // Draw lines for separators.
                renderer.DrawLine(0, measure.Height + 3, currentRtv.Width, measure.Height + 3, GorgonColor.White);
                renderer.DrawLine(0, measure.Height + 4, currentRtv.Width, measure.Height + 4, GorgonColor.Black);

                // Draw FPS text.
                renderer.DrawString(_statsText.ToString(), DX.Vector2.One, _statsFont, GorgonColor.White);
            }

            // Draw logo.
            renderer.DrawFilledRectangle(logoRegion, GorgonColor.White, _logo, new DX.RectangleF(0, 0, 1, 1));

            renderer.End();

            renderer.Graphics.ResetDrawCallStatistics();
        }
Exemplo n.º 30
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ZoomWindow"/> class.
        /// </summary>
        /// <param name="renderer">The renderer to use for magnification.</param>
        /// <param name="texture">The texture to zoom.</param>
        /// <exception cref="System.ArgumentNullException">Thrown when the <paramref name="renderer"/> or the <paramref name="texture"/> parameter is NULL (Nothing in VB.Net).</exception>
        public ZoomWindow(Gorgon2D renderer, GorgonTexture2D texture)
        {
            if (renderer == null)
            {
                throw new ArgumentNullException("renderer");
            }

            if (texture == null)
            {
                throw new ArgumentNullException("texture");
            }

            _windowSize = new Vector2(128, 128);
            Position    = Vector2.Zero;
            _zoom       = 2.0f;
            _renderer   = renderer;
            _texture    = texture;

            _sprite = _renderer.Renderables.CreateSprite("Zoomer",
                                                         new GorgonSpriteSettings
            {
                Texture         = _texture,
                Size            = _windowSize,
                InitialPosition = ZoomWindowLocation,
                TextureRegion   = new RectangleF(0, 0, 1, 1)
            });

            _sprite.TextureSampler.HorizontalWrapping = TextureAddressing.Border;
            _sprite.TextureSampler.VerticalWrapping   = TextureAddressing.Border;
            _sprite.TextureSampler.BorderColor        = GorgonColor.Transparent;
            _sprite.TextureSampler.TextureFilter      = TextureFilter.Point;

            _zoomWindowText = APIResources.GOREDIT_TEXT_ZOOM;
            _zoomFont       = renderer.Graphics.Fonts.DefaultFont;

            UpdateTextureCoordinates();
        }