コード例 #1
0
ファイル: GorgonFonts.cs プロジェクト: tmp7701/Gorgon
        /// <summary>
        /// Function to create a new font texture object.
        /// </summary>
        /// <param name="fontName">Name of the font texture object.</param>
        /// <param name="settings">Settings for the font.</param>
        /// <returns>The new font texture object.</returns>
        /// <remarks>This method creates an object that contains a group of textures with font glyphs.  These textures can be used by another application to
        /// display text (or symbols) on the screen.  Kerning information (the proper spacing for a glyph) is included in the glyphs and font.
        /// <para>Please note that the <paramref name="fontName"/> parameter is user defined and does not have to be the same as the <see cref="P:GorgonLibrary.Graphics.GorgonFontSettings.FontFamilyName">FontFamilyName</see> in the <paramref name="settings"/> parameter.</para>
        /// <para>Fonts may only be created on the immediate context.</para>
        /// </remarks>
        /// <exception cref="System.ArgumentNullException">Thrown when the fontName or settings parameters are NULL (Nothing in VB.Net).</exception>
        /// <exception cref="System.ArgumentException">Thrown when the fontName parameter is an empty string.
        /// <para>-or-</para>
        /// <para>Thrown when the <see cref="P:GorgonLibrary.Graphics.GorgonFontSettings.TextureSize">settings.TextureSize</see> width or height is larger than can be handled by the current feature level.</para>
        /// <para>-or-</para>
        /// <para>Thrown when the <see cref="P:GorgonLibrary.Graphics.GorgonFontSettings.DefaultCharacter">settings.DefaultCharacter</see> cannot be located in the <see cref="P:GorgonLibrary.Graphics.GorgonFontSettings.Characters">settings.Characters</see> list.</para>
        /// </exception>
        /// <exception cref="GorgonLibrary.GorgonException">Thrown if the graphics context is deferred.</exception>
        public GorgonFont CreateFont(string fontName, GorgonFontSettings settings)
        {
            if (_graphics.IsDeferred)
            {
                throw new GorgonException(GorgonResult.CannotCreate, Resources.GORGFX_CANNOT_USE_DEFERRED_CONTEXT);
            }

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

            if (string.IsNullOrWhiteSpace("fontName"))
            {
                throw new ArgumentException(Resources.GORGFX_PARAMETER_MUST_NOT_BE_EMPTY, "fontName");
            }

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

            if (string.IsNullOrWhiteSpace(settings.FontFamilyName))
            {
                throw new ArgumentException(Resources.GORGFX_FONT_FAMILY_NAME_MUST_NOT_BE_EMPTY, "settings");
            }

            var result = new GorgonFont(_graphics, fontName, settings);

            result.GenerateFont(settings);

            _graphics.AddTrackedObject(result);

            return(result);
        }
コード例 #2
0
ファイル: GorgonFonts.cs プロジェクト: tmp7701/Gorgon
        /// <summary>
        /// Function to read a font from a stream.
        /// </summary>
        /// <param name="name">Name of the font object.</param>
        /// <param name="stream">Stream to read from.</param>
        /// <param name="missingTextureFunction">[Optional] A function that is called if a required user defined texture has not been loaded for the font.</param>
        /// <returns>The font in the stream.</returns>
        /// <remarks>
        /// The fonts will not store user defined glyph textures, in order to facilitate the loading of the textures the users must either load the texture
        /// before loading the font or specify a callback method in the <paramref name="missingTextureFunction"/> parameter.  This function will pass a name
        /// for the texture and will expect a texture to be returned.  If NULL is returned, then an exception will be raised.
        /// <para>Fonts may only be created on the immediate context.</para></remarks>
        /// <exception cref="System.ArgumentNullException">Thrown when the <paramref name="stream"/> or the <paramref name="name"/> parameters are NULL.</exception>
        /// <exception cref="System.ArgumentException">Thrown if the name parameter is an empty string.
        /// <para>-or-</para>
        /// <para>Thrown if the font uses external textures, but the stream is not a file stream.</para></exception>
        /// <exception cref="GorgonLibrary.GorgonException">Thrown if the font cannot be read.
        /// <para>-or-</para>
        /// <para>Thrown if the graphics context is deferred.</para>
        /// </exception>
        public GorgonFont FromStream(string name, Stream stream, Func <string, Size, GorgonTexture2D> missingTextureFunction = null)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentException(Resources.GORGFX_PARAMETER_MUST_NOT_BE_EMPTY, "name");
            }

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

            if (stream.Length == 0)
            {
                throw new ArgumentException(Resources.GORGFX_PARAMETER_MUST_NOT_BE_EMPTY, "stream");
            }

            var font = new GorgonFont(_graphics, name, new GorgonFontSettings());

            using (var chunk = new GorgonChunkReader(stream))
            {
                chunk.Begin(GorgonFont.FileHeader);
                font.ReadFont(chunk, missingTextureFunction);
            }

            _graphics.AddTrackedObject(font);

            return(font);
        }
コード例 #3
0
ファイル: GorgonExample.cs プロジェクト: ishkang/Gorgon
        /// <summary>
        /// Function to load the logo for display in the application.
        /// </summary>
        /// <param name="graphics">The graphics interface to use.</param>
        public static void LoadResources(GorgonGraphics graphics)
        {
            if (graphics == null)
            {
                throw new ArgumentNullException(nameof(graphics));
            }

            _factory   = new GorgonFontFactory(graphics);
            _statsFont = _factory.GetFont(new GorgonFontInfo("Segoe UI", 9, FontHeightMode.Points, "Segoe UI 9pt Bold Outlined")
            {
                AntiAliasingMode = FontAntiAliasMode.AntiAlias,
                FontStyle        = FontStyle.Bold,
                OutlineColor1    = GorgonColor.Black,
                OutlineColor2    = GorgonColor.Black,
                OutlineSize      = 2,
                TextureWidth     = 512,
                TextureHeight    = 256
            });

            using (var stream = new MemoryStream(Resources.Gorgon_Logo_Small))
            {
                var ddsCodec = new GorgonCodecDds();
                _logo = GorgonTexture2DView.FromStream(graphics, stream, ddsCodec, options: new GorgonTexture2DLoadOptions
                {
                    Name    = "Gorgon Logo Texture",
                    Binding = TextureBinding.ShaderResource,
                    Usage   = ResourceUsage.Immutable
                });
            }
        }
コード例 #4
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;
        }
コード例 #5
0
        /// <summary>
        /// Function to persist a <see cref="GorgonFont"/> to a file on the physical file system.
        /// </summary>
        /// <param name="fontData">A <see cref="GorgonFont"/> to persist to the stream.</param>
        /// <param name="filePath">The path to the file that will hold the font data.</param>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="filePath"/>, or the <paramref name="fontData"/> parameter is <b>null</b>.</exception>
        /// <exception cref="ArgumentEmptyException">Thrown when the <paramref name="filePath"/> is empty..</exception>
        /// <exception cref="GorgonException">Thrown when the font data in the stream has a pixel format that is unsupported.</exception>
        public void SaveToFile(GorgonFont fontData, string filePath)
        {
            FileStream stream = null;

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

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

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

            try
            {
                stream = File.Open(filePath, FileMode.Create, FileAccess.Write, FileShare.None);
                SaveToStream(fontData, stream);
            }
            finally
            {
                stream?.Dispose();
            }
        }
コード例 #6
0
ファイル: GorgonRenderables.cs プロジェクト: tmp7701/Gorgon
        /// <summary>
        /// Function to create a new text object.
        /// </summary>
        /// <param name="name">Name of the text object.</param>
        /// <param name="font">Font to use for the text.</param>
        /// <param name="text">Initial text to display.</param>
        /// <param name="color">Color of the text.</param>
        /// <param name="shadowed">TRUE to place a shadow behind the text, FALSE to display normally.</param>
        /// <param name="shadowOffset">Offset of the shadow.</param>
        /// <param name="shadowOpacity">Opacity for the shadow.</param>
        /// <returns>A new text object.</returns>
        /// <exception cref="System.ArgumentNullException">Thrown when the <paramref name="name"/> parameter is NULL (Nothing in VB.Net).</exception>
        /// <exception cref="System.ArgumentException">Thrown when the name parameter is an empty string.</exception>
        public GorgonText CreateText(string name, GorgonFont font, string text, GorgonColor color, bool shadowed, Vector2 shadowOffset, float shadowOpacity)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }

            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentException(Resources.GOR2D_PARAMETER_MUST_NOT_BE_EMPTY, "name");
            }

            var result = new GorgonText(_gorgon2D, _cache, name, font)
            {
                ShadowEnabled   = shadowed,
                ShadowOffset    = shadowOffset,
                ShadowOpacity   = shadowOpacity,
                Color           = color,
                Text            = text,
                CullingMode     = CullingMode.Back,
                AlphaTestValues = GorgonRangeF.Empty,
                BlendingMode    = BlendingMode.Modulate
            };

            return(result);
        }
コード例 #7
0
ファイル: PanelSpriteEditor.cs プロジェクト: tmp7701/Gorgon
        /// <summary>
        /// Function to create a zoom window.
        /// </summary>
        private void CreateZoomWindow()
        {
            if (_content.Texture == null)
            {
                return;
            }

            _zoomWindow = new ZoomWindow(_content.Renderer, _content.Texture)
            {
                Clipper           = _clipper,
                BackgroundTexture = _content.BackgroundTexture,
                Position          = _content.Texture.ToPixel(_content.Sprite.TextureOffset),
                ZoomAmount        = GorgonSpriteEditorPlugIn.Settings.ZoomWindowScaleFactor,
                ZoomWindowSize    = new Vector2(GorgonSpriteEditorPlugIn.Settings.ZoomWindowSize)
            };

            if (_zoomFont == null)
            {
                _zoomFont = ContentObject.Graphics.Fonts.CreateFont("MagnifierCaptionFont",
                                                                    new GorgonFontSettings
                {
                    AntiAliasingMode = FontAntiAliasMode.AntiAlias,
                    Characters       = _zoomWindow.ZoomWindowText + ":.01234567890x ",
                    FontFamilyName   = "Segoe UI",
                    FontHeightMode   = FontHeightMode.Points,
                    Size             = 10.0f,
                    TextureSize      = new Size(64, 64)
                });
            }

            _zoomWindow.ZoomWindowFont = _zoomFont;
        }
コード例 #8
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
                });
            }
        }
コード例 #9
0
ファイル: GorgonFonts.cs プロジェクト: tmp7701/Gorgon
        /// <summary>
        /// Function to clean up any resources.
        /// </summary>
        internal void CleanUp()
        {
            if (_default != null)
            {
                _default.Dispose();
            }

            _default = null;
        }
コード例 #10
0
ファイル: GorgonExample.cs プロジェクト: ishkang/Gorgon
        /// <summary>
        /// Function to force the resources for the application to unload.
        /// </summary>
        public static void UnloadResources()
        {
            GorgonTexture2DView logo    = Interlocked.Exchange(ref _logo, null);
            GorgonFont          font    = Interlocked.Exchange(ref _statsFont, null);
            GorgonFontFactory   factory = Interlocked.Exchange(ref _factory, null);

            logo?.Dispose();
            font?.Dispose();
            factory?.Dispose();
        }
コード例 #11
0
        /// <summary>
        /// Function to write the font data to the stream.
        /// </summary>
        /// <param name="fontData">The font data to write.</param>
        /// <param name="stream">The stream to write into.</param>
        /// <remarks>
        /// <para>
        /// Implementors must override this method to write out the font data in the expected format.
        /// </para>
        /// </remarks>
        protected override void OnWriteFontData(GorgonFont fontData, Stream stream)
        {
            var             fontFile = new GorgonChunkFileWriter(stream, FileHeader.ChunkID());
            IGorgonFontInfo fontInfo = fontData.Info;

            try
            {
                fontFile.Open();

                GorgonBinaryWriter writer = fontFile.OpenChunk(FontInfoChunk);

                writer.Write(fontInfo.FontFamilyName);
                writer.Write(fontInfo.Size);
                writer.WriteValue(fontInfo.FontHeightMode);
                writer.WriteValue(fontInfo.FontStyle);
                writer.Write(fontInfo.DefaultCharacter);
                writer.Write(string.Join(string.Empty, fontInfo.Characters));
                writer.WriteValue(fontInfo.AntiAliasingMode);
                writer.Write(fontInfo.OutlineColor1.ToARGB());
                writer.Write(fontInfo.OutlineColor2.ToARGB());
                writer.Write(fontInfo.OutlineSize);
                writer.Write(fontInfo.PackingSpacing);
                writer.Write(fontInfo.TextureWidth);
                writer.Write(fontInfo.TextureHeight);
                writer.Write(fontInfo.UsePremultipliedTextures);
                writer.Write(fontInfo.UseKerningPairs);
                fontFile.CloseChunk();

                writer = fontFile.OpenChunk(FontHeightChunk);
                writer.Write(fontData.FontHeight);
                writer.Write(fontData.LineHeight);
                writer.Write(fontData.Ascent);
                writer.Write(fontData.Descent);
                fontFile.CloseChunk();

                if (fontInfo.Brush != null)
                {
                    writer = fontFile.OpenChunk(BrushChunk);
                    writer.Write((int)fontInfo.Brush.BrushType);
                    fontInfo.Brush.WriteBrushData(writer);
                    fontFile.CloseChunk();
                }

                if (fontInfo.UseKerningPairs)
                {
                    WriteKerningValues(fontData, fontFile);
                }
            }
            finally
            {
                fontFile.Close();
            }
        }
コード例 #12
0
        /// <summary>Function called during resource creation.</summary>
        /// <param name="context">The current application graphics context.</param>
        /// <param name="swapChain">The swap chain for presenting the rendered data.</param>
        protected override void OnCreateResources(IGraphicsContext context, GorgonSwapChain swapChain)
        {
            _axisFont = context.FontFactory.GetFont(new GorgonFontInfo("Segoe UI", 12, FontHeightMode.Points, "Segoe UI Bold 12pt - Axis Font")
            {
                OutlineColor1 = GorgonColor.Black,
                OutlineColor2 = GorgonColor.Black,
                OutlineSize   = 3,
                FontStyle     = FontStyle.Bold
            });

            _selectionRect = new MarchingAnts(context.Renderer2D);
        }
コード例 #13
0
        /// <summary>
        /// Function to build the font from the data provided.
        /// </summary>
        /// <param name="info">The font information used to generate the font.</param>
        /// <param name="fontHeight">The height of the font, in pixels.</param>
        /// <param name="lineHeight">The height of a line, in pixels.</param>
        /// <param name="ascent">The ascent for the font, in pixels.</param>
        /// <param name="descent">The descent for the font, in pixels.</param>
        /// <param name="textures">The textures associated with the font.</param>
        /// <param name="glyphs">The glyphs associated with the font.</param>
        /// <param name="kerningValues">The kerning values, if any, associated with the font.</param>
        /// <returns>A new <seealso cref="GorgonFont"/>.</returns>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="info"/>, <paramref name="textures"/>, or the <paramref name="glyphs"/> parameter is <b>null</b>.</exception>
        /// <exception cref="ArgumentEmptyException">Thrown when the <paramref name="textures"/>, or the <paramref name="glyphs"/> parameter is empty.</exception>
        /// <remarks>
        /// <para>
        /// Codec implementors should call this method once all information has been gathered for the font. This will load the font data into the <seealso cref="GorgonFont"/>, and store that font in the
        /// <seealso cref="Factory"/> cache for reuse.
        /// </para>
        /// <para>
        /// This method must be called because an application will not be able to create a <seealso cref="GorgonFont"/> directly.
        /// </para>
        /// </remarks>
        protected GorgonFont BuildFont(IGorgonFontInfo info,
                                       float fontHeight,
                                       float lineHeight,
                                       float ascent,
                                       float descent,
                                       IReadOnlyList <GorgonTexture2D> textures,
                                       IReadOnlyList <GorgonGlyph> glyphs,
                                       IReadOnlyDictionary <GorgonKerningPair, int> kerningValues)
        {
            if (info == null)
            {
                throw new ArgumentNullException(nameof(info));
            }

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

            if (textures.Count == 0)
            {
                throw new ArgumentException(Resources.GORGFX_ERR_PARAMETER_MUST_NOT_BE_EMPTY, nameof(textures));
            }

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

            if (glyphs.Count == 0)
            {
                throw new ArgumentException(Resources.GORGFX_ERR_PARAMETER_MUST_NOT_BE_EMPTY, nameof(glyphs));
            }

            GorgonFont result = null;

            try
            {
                result = new GorgonFont(info.Name, Factory, info, fontHeight, lineHeight, ascent, descent, glyphs, textures, kerningValues);

                // Register with the factory font cache.
                Factory.RegisterFont(result);

                return(result);
            }
            catch
            {
                result?.Dispose();
                throw;
            }
        }
コード例 #14
0
        /// <summary>
        /// Function to write out the kerning pair information for the font.
        /// </summary>
        /// <param name="fontData">The font data to write.</param>
        /// <param name="fontFile">The font file that is being persisted.</param>
        private static void WriteKerningValues(GorgonFont fontData, GorgonChunkFileWriter fontFile)
        {
            GorgonBinaryWriter writer = fontFile.OpenChunk(KernDataChunk);

            writer.Write(fontData.KerningPairs.Count);

            foreach (KeyValuePair <GorgonKerningPair, int> kerningInfo in fontData.KerningPairs)
            {
                writer.Write(kerningInfo.Key.LeftCharacter);
                writer.Write(kerningInfo.Key.RightCharacter);
                writer.Write(kerningInfo.Value);
            }

            fontFile.CloseChunk();
        }
コード例 #15
0
ファイル: GorgonDrawing.cs プロジェクト: tmp7701/Gorgon
        /// <summary>
        /// Function to measure a string.
        /// </summary>
        /// <param name="font">Font to use when measuring.</param>
        /// <param name="text">Text to measure.</param>
        /// <param name="wordWrap">TRUE if word wrapping should be used.</param>
        /// <param name="bounds">Boundaries for the size of the string.</param>
        /// <returns>The size of the string.</returns>
        public Vector2 MeasureString(GorgonFont font, string text, bool wordWrap, SizeF bounds)
        {
            _string.Font = font;
            Vector2 size = _string.MeasureText(text, wordWrap, bounds.Width);

            if (size.X > bounds.Width)
            {
                size.X = bounds.Width;
            }
            if (size.Y > bounds.Height)
            {
                size.Y = bounds.Height;
            }

            return(size);
        }
コード例 #16
0
ファイル: GorgonDrawing.cs プロジェクト: tmp7701/Gorgon
        /// <summary>
        /// Function to draw a string.
        /// </summary>
        /// <param name="font">Font to use.</param>
        /// <param name="text">Text to draw.</param>
        /// <param name="position">Position of the text.</param>
        /// <param name="color">Color of the text.</param>
        /// <param name="useShadow">TRUE to use a shadow, FALSE to display normally.</param>
        /// <param name="shadowOffset">Offset of the shadow, in pixels.</param>
        /// <param name="shadowOpacity">Opacity of the shadow.</param>
        /// <exception cref="System.ArgumentNullException">Thrown when the <paramref name="font"/> parameter is NULL (Nothing in VB.Net).</exception>
        public void DrawString(GorgonFont font, string text, Vector2 position, GorgonColor color, bool useShadow, Vector2 shadowOffset, float shadowOpacity)
        {
            GorgonDebug.AssertNull(font, "font");

            if (string.IsNullOrEmpty(text))
            {
                return;
            }

            SetStates(_string);

            _string.Position      = position;
            _string.Font          = font;
            _string.Text          = text;
            _string.Color         = color;
            _string.ShadowEnabled = useShadow;
            _string.ShadowOffset  = shadowOffset;
            _string.ShadowOpacity = shadowOpacity;
            _string.Draw();
        }
コード例 #17
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();
        }
コード例 #18
0
        /// <summary>
        /// Function to persist a <see cref="GorgonFont"/> to a stream.
        /// </summary>
        /// <param name="fontData">A <see cref="GorgonFont"/> to persist to the stream.</param>
        /// <param name="stream">The stream that will receive the font data.</param>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="stream"/>, or the <paramref name="fontData"/> parameter is <b>null</b>.</exception>
        /// <exception cref="ArgumentEmptyException">Thrown when the <paramref name="stream"/> is read only.</exception>
        /// <exception cref="GorgonException">Thrown when the font data in the stream has a pixel format that is unsupported.</exception>
        public void SaveToStream(GorgonFont fontData, Stream stream)
        {
            if (fontData == null)
            {
                throw new ArgumentNullException(nameof(fontData));
            }

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

            if (!stream.CanWrite)
            {
                throw new IOException(Resources.GORGFX_ERR_STREAM_READ_ONLY);
            }

            if (!stream.CanSeek)
            {
                throw new IOException(Resources.GORGFX_ERR_STREAM_NO_SEEK);
            }

            OnWriteFontData(fontData, stream);
        }
コード例 #19
0
ファイル: MainForm.cs プロジェクト: hammerforgegames/Gorgon
        /// <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);

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

                // Load the assembly.
                _assemblyCache = new GorgonMefPlugInCache(GorgonApplication.Log);

                // Create the plugin service.
                IGorgonPlugInService plugInService = new GorgonMefPlugInService(_assemblyCache);

                // Create the factory to retrieve gaming device drivers.
                var factory = new GorgonGamingDeviceDriverFactory(plugInService);

                // Create the raw input interface.
                _input = new GorgonRawInput(this, GorgonApplication.Log);

                // Get available gaming device driver plug ins.
                _assemblyCache.LoadPlugInAssemblies(GorgonExample.GetPlugInPath().FullName, "Gorgon.Input.DirectInput.dll");
                _assemblyCache.LoadPlugInAssemblies(GorgonExample.GetPlugInPath().FullName, "Gorgon.Input.XInput.dll");

                _drivers = factory.LoadAllDrivers();

                _joystickList = new List <IGorgonGamingDevice>();

                // Get all gaming devices from the drivers.
                foreach (IGorgonGamingDeviceDriver driver in _drivers)
                {
                    IReadOnlyList <IGorgonGamingDeviceInfo> infoList = driver.EnumerateGamingDevices(true);

                    foreach (IGorgonGamingDeviceInfo info in infoList)
                    {
                        IGorgonGamingDevice device = driver.CreateGamingDevice(info);

                        // Turn off dead zones for this example.
                        foreach (GorgonGamingDeviceAxis axis in device.Axis)
                        {
                            axis.DeadZone = GorgonRange.Empty;
                        }

                        _joystickList.Add(device);
                    }
                }

                // Create mouse.
                _mouse = new GorgonRawMouse();

                // Create the graphics interface.
                ClientSize = Settings.Default.Resolution;

                IReadOnlyList <IGorgonVideoAdapterInfo> adapters = GorgonGraphics.EnumerateAdapters();
                _graphics = new GorgonGraphics(adapters[0], log: GorgonApplication.Log);
                _screen   = new GorgonSwapChain(_graphics, this, new GorgonSwapChainInfo("INeedYourInput Swapchain")
                {
                    Width  = Settings.Default.Resolution.Width,
                    Height = Settings.Default.Resolution.Height,
                    Format = BufferFormat.R8G8B8A8_UNorm
                });
                _graphics.SetRenderTarget(_screen.RenderTargetView);

                if (!Settings.Default.IsWindowed)
                {
                    _screen.EnterFullScreen();
                }

                // For the backup image. Used to make it as large as the monitor that we're on.
                var currentScreen = Screen.FromHandle(Handle);

                // Relocate the window to the center of the screen.
                Location = new Point(currentScreen.Bounds.Left + (currentScreen.WorkingArea.Width / 2) - (ClientSize.Width / 2),
                                     currentScreen.Bounds.Top + (currentScreen.WorkingArea.Height / 2) - (ClientSize.Height / 2));


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

                // Create the text font.
                var fontFactory = new GorgonFontFactory(_graphics);
                _font = fontFactory.GetFont(new GorgonFontInfo("Arial", 9.0f, FontHeightMode.Points, "Arial 9pt")
                {
                    FontStyle        = FontStyle.Bold,
                    AntiAliasingMode = FontAntiAliasMode.AntiAlias
                });

                // Create text sprite.
                _messageSprite = new GorgonTextSprite(_font, "Using mouse and keyboard (Windows Forms).")
                {
                    Color = Color.Black
                };

                // Create a back buffer.
                _backBuffer = GorgonRenderTarget2DView.CreateRenderTarget(_graphics, new GorgonTexture2DInfo("Backbuffer storage")
                {
                    Width  = _screen.Width,
                    Height = _screen.Height,
                    Format = _screen.Format
                });
                _backBuffer.Clear(Color.White);
                _backBufferView = _backBuffer.GetShaderResourceView();

                // Clear our backup image to white to match our primary screen.
                using (IGorgonImage image = new GorgonImage(new GorgonImageInfo(ImageType.Image2D, _screen.Format)
                {
                    Width = _screen.Width,
                    Height = _screen.Height,
                    Format = _screen.Format
                }))
                {
                    image.Buffers[0].Fill(0xff);
                    _backupImage = image.ToTexture2D(_graphics,
                                                     new GorgonTexture2DLoadOptions
                    {
                        Binding = TextureBinding.None,
                        Usage   = ResourceUsage.Staging
                    });
                }

                // Set gorgon events.
                _screen.BeforeSwapChainResized += BeforeSwapChainResized;
                _screen.AfterSwapChainResized  += AfterSwapChainResized;

                // Enable the mouse.
                Cursor = Cursors.Cross;
                _mouse.MouseButtonDown += MouseInput;
                _mouse.MouseMove       += MouseInput;
                _mouse.MouseWheelMove  += (sender, args) =>
                {
                    _radius += args.WheelDelta.Sign();

                    if (_radius < 2.0f)
                    {
                        _radius = 2.0f;
                    }
                    if (_radius > 10.0f)
                    {
                        _radius = 10.0f;
                    }
                };

                // Set the mouse position.
                _mouse.Position = new Point(ClientSize.Width / 2, ClientSize.Height / 2);

                _noBlending = _blendBuilder.BlendState(GorgonBlendState.NoBlending)
                              .Build();
                _inverted = _blendBuilder.BlendState(GorgonBlendState.Inverted)
                            .Build();

                // Set up blending states for our pen.
                var blendStateBuilder = new GorgonBlendStateBuilder();
                _currentBlend = _drawModulatedBlend = _blendBuilder.BlendState(blendStateBuilder
                                                                               .ResetTo(GorgonBlendState.Default)
                                                                               .DestinationBlend(alpha: Blend.One)
                                                                               .Build())
                                                      .Build();

                _drawAdditiveBlend = _blendBuilder.BlendState(blendStateBuilder
                                                              .ResetTo(GorgonBlendState.Additive)
                                                              .DestinationBlend(alpha: Blend.One)
                                                              .Build())
                                     .Build();

                _drawNoBlend = _blendBuilder.BlendState(blendStateBuilder
                                                        .ResetTo(GorgonBlendState.NoBlending)
                                                        .DestinationBlend(alpha: Blend.One)
                                                        .Build())
                               .Build();

                GorgonApplication.IdleMethod = Gorgon_Idle;
            }
            catch (ReflectionTypeLoadException refEx)
            {
                string refErr = string.Join("\n", refEx.LoaderExceptions.Select(item => item.Message));
                GorgonDialogs.ErrorBox(this, refErr);
            }
            catch (Exception ex)
            {
                GorgonExample.HandleException(ex);
                GorgonApplication.Quit();
            }
        }
コード例 #20
0
ファイル: Program.cs プロジェクト: tmp7701/Gorgon
        /// <summary>
        /// Function to initialize the application.
        /// </summary>
        private static void Initialize()
        {
            _form = new MainForm();
            _form.Show();

            // Create the graphics interface.
            _graphics = new GorgonGraphics();

            // Create the primary swap chain.
            _mainScreen = _graphics.Output.CreateSwapChain("MainScreen", new GorgonSwapChainSettings
            {
                Width      = Settings.Default.ScreenWidth,
                Height     = Settings.Default.ScreenHeight,
                Format     = BufferFormat.R8G8B8A8_UIntNormal,
                Window     = _form,
                IsWindowed = Settings.Default.Windowed
            });

            // Center the display.
            if (_mainScreen.Settings.IsWindowed)
            {
                _form.Location =
                    new Point(
                        _mainScreen.VideoOutput.OutputBounds.Width / 2 - _form.Width / 2 + _mainScreen.VideoOutput.OutputBounds.Left,
                        _mainScreen.VideoOutput.OutputBounds.Height / 2 - _form.Height / 2 + _mainScreen.VideoOutput.OutputBounds.Top);
            }

            // Load the ball texture.
            _ballTexture = _graphics.Textures.FromFile <GorgonTexture2D>("BallTexture", GetResourcePath(@"Textures\Balls\BallsTexture.dds"), new GorgonCodecDDS());

            // Create the 2D interface.
            _2D = _graphics.Output.Create2DRenderer(_mainScreen);
            _2D.IsLogoVisible = true;

            // Set our drawing code to use modulated blending.
            _2D.Drawing.BlendingMode = BlendingMode.Modulate;
            _2D.Drawing.Blending.DestinationAlphaBlend = BlendType.InverseSourceAlpha;

            // Create the wall sprite.
            _wall = _2D.Renderables.CreateSprite("Wall", new Vector2(63, 63), _ballTexture);
            _wall.BlendingMode = BlendingMode.None;

            // Create the ball sprite.
            _ball = _2D.Renderables.CreateSprite("Ball", new Vector2(64, 64), _ballTexture, new Vector2(0.5f, 0.5f));
            _ball.SmoothingMode = SmoothingMode.Smooth;
            _ball.Anchor        = new Vector2(32, 32);
            _ball.Blending.DestinationAlphaBlend = BlendType.InverseSourceAlpha;

            // Create the ball render target.
            _ballTarget = _graphics.Output.CreateRenderTarget("BallTarget", new GorgonRenderTarget2DSettings
            {
                DepthStencilFormat = BufferFormat.Unknown,
                Width         = Settings.Default.ScreenWidth,
                Height        = Settings.Default.ScreenHeight,
                Format        = BufferFormat.R8G8B8A8_UIntNormal,
                Multisampling = GorgonMultisampling.NoMultiSampling
            });
            _2D.Effects.GaussianBlur.BlurRenderTargetsSize = new Size(512, 512);
            _2D.Effects.GaussianBlur.BlurAmount            = 10.0f;

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

                _ballTarget.Dispose();

                _ballTarget = _graphics.Output.CreateRenderTarget("BallTarget", new GorgonRenderTarget2DSettings
                {
                    DepthStencilFormat = BufferFormat.Unknown,
                    Width         = args.Width,
                    Height        = args.Height,
                    Format        = BufferFormat.R8G8B8A8_UIntNormal,
                    Multisampling = GorgonMultisampling.NoMultiSampling
                });

                Vector2 newTargetSize;
                newTargetSize.X = (512.0f * (args.Width / (float)Settings.Default.ScreenWidth)).Min(512);
                newTargetSize.Y = (512.0f * (args.Height / (float)Settings.Default.ScreenHeight)).Min(512);

                _2D.Effects.GaussianBlur.BlurRenderTargetsSize = (Size)newTargetSize;
                _2D.Effects.Displacement.BackgroundImage       = _ballTarget;
            };

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

            // Assign event handlers.
            _form.KeyDown += _form_KeyDown;

            // Create statistics render target.
            _statsTarget = _graphics.Output.CreateRenderTarget("Statistics", new GorgonRenderTarget2DSettings
            {
                Width  = 160,
                Height = 66,
                Format = BufferFormat.R8G8B8A8_UIntNormal
            });

            // Draw our stats window frame.
            _2D.Target = _statsTarget;
            _2D.Clear(new GorgonColor(0, 0, 0, 0.5f));
            _2D.Drawing.DrawRectangle(new RectangleF(0, 0, _statsTarget.Settings.Width - 1, _statsTarget.Settings.Height - 1),
                                      new GorgonColor(0.86667f, 0.84314f, 0.7451f, 1.0f));
            _2D.Target = null;

            // Create our font.
            _ballFont = _graphics.Fonts.CreateFont("Arial 9pt Bold", new GorgonFontSettings
            {
                AntiAliasingMode = FontAntiAliasMode.AntiAlias,
                FontStyle        = FontStyle.Bold,
                FontFamilyName   = "Arial",
                FontHeightMode   = FontHeightMode.Points,
                Characters       = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890()_.-+:\u2191\u2193",
                Size             = 9.0f,
                OutlineColor1    = GorgonColor.Black,
                OutlineSize      = 1
            });

            // Statistics text buffer.
            _fpsText  = new StringBuilder(64);
            _helpText = new StringBuilder();
            _helpText.AppendFormat(Resources.HelpText,
                                   _graphics.VideoDevice.Name,
                                   _graphics.VideoDevice.SupportedFeatureLevel,
                                   _graphics.VideoDevice.DedicatedVideoMemory.FormatMemory());

            // Create a static text block.  This will perform MUCH better than drawing the text
            // every frame with DrawString.
            _helpTextSprite          = _2D.Renderables.CreateText("Help Text", _ballFont, _helpText.ToString(), Color.Yellow);
            _helpTextSprite.Position = new Vector2(3, 72);
            _helpTextSprite.Blending.DestinationAlphaBlend = BlendType.InverseSourceAlpha;
        }
コード例 #21
0
        /// <summary>
        /// Function called during idle time the application.
        /// </summary>
        /// <returns><b>true</b> to continue executing, <b>false</b> to stop.</returns>
        private static bool Idle()
        {
            GorgonFont currentFont = _font[_fontIndex];

            if (_startTime < 0)
            {
                _startTime = GorgonTiming.SecondsSinceStart;
            }

            _screen.RenderTargetView.Clear(_glowIndex != _fontIndex ? GorgonColor.CornFlowerBlue : new GorgonColor(0, 0, 0.2f));

            DX.Size2F textSize = currentFont.MeasureText(Resources.Lorem_Ipsum, false);
            var       position = new DX.Vector2((int)((_screen.Width / 2.0f) - (textSize.Width / 2.0f)).Max(4.0f), (int)((_screen.Height / 2.0f) - (textSize.Height / 2.0f)).Max(100));

            _text.Font     = currentFont;
            _text.Position = position;

            // If we have glow on, then draw the glow outline in a separate pass.
            if (_glowIndex == _fontIndex)
            {
                _text.OutlineTint = new GorgonColor(1, 1, 1, _glowAlpha);
                _text.DrawMode    = TextDrawMode.OutlineOnly;
                _renderer.Begin(Gorgon2DBatchState.AdditiveBlend);
                _renderer.DrawTextSprite(_text);
                _renderer.End();
            }

            _text.OutlineTint = GorgonColor.White;
            _text.Color       = _glowIndex != _fontIndex ? GorgonColor.White : GorgonColor.Black;
            _text.DrawMode    = ((_glowIndex == _fontIndex) || (!currentFont.HasOutline)) ? TextDrawMode.GlyphsOnly : TextDrawMode.OutlinedGlyphs;

            // Draw the font identification.
            _renderer.Begin();
            _renderer.DrawString($"Now displaying [c #FFFFE03F]'{currentFont.Name}'[/c]...", new DX.Vector2(4.0f, 64.0f));
            _renderer.DrawTextSprite(_text);
            _renderer.End();

            GorgonExample.DrawStatsAndLogo(_renderer);

            // Animate our glow alpha.
            _glowAlpha += _glowVelocity * GorgonTiming.Delta;

            if (_glowAlpha > 1.0f)
            {
                _glowAlpha    = 1.0f;
                _glowVelocity = -0.5f;
            }
            else if (_glowAlpha < 0.25f)
            {
                _glowAlpha    = 0.25f;
                _glowVelocity = 0.5f;
            }

            // Animate the line height so we can drop the lines and make them bounce... just because we can.
            float normalSin = (_bounceAngle.ToRadians().Sin() + 1.0f) / 2.0f;
            float scaledSin = normalSin * (1.0f - _max);

            _text.LineSpace = scaledSin + _max;

            _bounceAngle += _angleSpeed * GorgonTiming.Delta;

            if (_bounceAngle > 90.0f)
            {
                _bounceAngle = 90.0f;
                if (_max.EqualsEpsilon(0))
                {
                    _max = 0.5f;
                }
                else
                {
                    _max += 0.125f;
                }

                if (_max >= 1.0f)
                {
                    _max = 1.0f;
                }
                _angleSpeed = -_angleSpeed * (_max + 1.0f);
            }

            if (_bounceAngle < -90.0f)
            {
                _angleSpeed  = -_angleSpeed;
                _bounceAngle = -90.0f;
            }

            int timeDiff = (int)(GorgonTiming.SecondsSinceStart - _startTime).FastCeiling();

            // Switch to a new font every 4 seconds.
            if (timeDiff > 4)
            {
                _startTime = GorgonTiming.SecondsSinceStart;
                ++_fontIndex;
                _text.LineSpace = -0.015f;

                // Reset glow animation.
                if (_fontIndex == _glowIndex)
                {
                    _glowAlpha    = 1.0f;
                    _glowVelocity = -0.5f;
                }

                // Reset bounce.
                _bounceAngle = -90.0f;
                _max         = 0.0f;
                _angleSpeed  = 360.0f;
            }


            if (_fontIndex >= _font.Count)
            {
                _fontIndex = 0;
            }

            _screen.Present(1);

            return(true);
        }
コード例 #22
0
 /// <summary>
 /// Function to write the font data to the stream.
 /// </summary>
 /// <param name="fontData">The font data to write.</param>
 /// <param name="stream">The stream to write into.</param>
 /// <exception cref="NotSupportedException">This operation is not supported by this codec.</exception>
 protected override void OnWriteFontData(GorgonFont fontData, Stream stream) => throw new NotSupportedException();
コード例 #23
0
ファイル: Program.cs プロジェクト: tmp7701/Gorgon
        /// <summary>
        /// Function to initialize the example application.
        /// </summary>
        private static void Initialize()
        {
            var pathBrush = new GorgonGlyphPathGradientBrush
            {
                SurroundColors =
                {
                    Color.Red,
                    Color.Green,
                    Color.Blue,
                    Color.Yellow
                },
                CenterColor = Color.White,
                Points      =
                {
                    new Vector2(0,   8),
                    new Vector2(8,   0),
                    new Vector2(16,  8),
                    new Vector2(8,  16),
                },
                CenterPoint   = new Vector2(8, 8),
                Interpolation =
                {
                    new GorgonGlyphBrushInterpolator(0,    Color.Purple),
                    new GorgonGlyphBrushInterpolator(0.5f, Color.Cyan),
                    new GorgonGlyphBrushInterpolator(1.0f, Color.Firebrick)
                },
                WrapMode = WrapMode.TileFlipXY
            };

            var linBrush = new GorgonGlyphLinearGradientBrush
            {
                Angle      = 45.0f,
                StartColor = Color.Purple,
                EndColor   = Color.Yellow
            };

            var hatchBrush = new GorgonGlyphHatchBrush
            {
                HatchStyle      = HatchStyle.Percent50,
                ForegroundColor = Color.Purple,
                BackgroundColor = Color.Yellow
            };

            _formMain = new formMain();

            // Create our graphics object(s).
            _graphics = new GorgonGraphics();

            var textBrush = new GorgonGlyphTextureBrush(_graphics.Textures.FromFile <GorgonTexture2D>("Stars",
                                                                                                      GetResourcePath(@"Images\Stars-12.jpg"),
                                                                                                      new GorgonCodecJPEG()))
            {
                TextureRegion = new RectangleF(0.0f, 0.0f, 0.5f, 0.5f),
                WrapMode      = WrapMode.Tile
            };


            _renderer = _graphics.Output.Create2DRenderer(_formMain,
                                                          Settings.Default.ScreenResolution.Width,
                                                          Settings.Default.ScreenResolution.Height,
                                                          BufferFormat.Unknown,
                                                          !Settings.Default.FullScreen);

            Screen activeMonitor = Screen.FromControl(_formMain);

            // Center the window on the screen.
            _formMain.Location = new Point(activeMonitor.WorkingArea.Width / 2 - _formMain.Width / 2, activeMonitor.WorkingArea.Height / 2 - _formMain.Height / 2);

            _specialGlyphTexture = _graphics.Textures.FromFile <GorgonTexture2D>("StyledT", GetResourcePath(@"Fonts\StylizedT.png"),
                                                                                 new GorgonCodecPNG());

            _font = _graphics.Fonts.CreateFont("TestFont",
                                               new GorgonFontSettings
            {
                AntiAliasingMode = FontAntiAliasMode.AntiAlias,
                FontFamilyName   = "Times New Roman",
                FontStyle        = FontStyle.Bold,
                Size             = 24.0f,
                Brush            = textBrush,
                Glyphs           =
                {
                    new GorgonGlyph('T', _specialGlyphTexture, new Rectangle(11, 14, 111, 97), new Point(-3, -8), 97)
                }
            });

            // TODO: This is for testing font capabilities.
            _renderer.Drawing.BlendingMode = BlendingMode.Modulate;

            _font.Save(@"d:\unpak\fontTest.gorFont");

            _font.Dispose();

            textBrush.Texture.Dispose();

            _font = _graphics.Fonts.FromFile("TestFont", @"d:\unpak\fontTest.gorFont");
        }
コード例 #24
0
ファイル: Program.cs プロジェクト: ishkang/Gorgon
        /// <summary>
        /// Function to initialize the application.
        /// </summary>
        private static void Initialize()
        {
            GorgonExample.ShowStatistics = false;
            _window = GorgonExample.Initialize(new DX.Size2(Settings.Default.Resolution.Width, Settings.Default.Resolution.Height), "Primitives");

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

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

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

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

                BuildDepthBuffer(_swapChain.Width, _swapChain.Height);

                _graphics.SetRenderTarget(_swapChain.RenderTargetView, _depthBuffer);

                LoadShaders();

                LoadTextures();

                BuildLights();

                BuildMeshes();

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

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

                _input.RegisterDevice(_keyboard);

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

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

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

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

                    _graphics.SetDepthStencil(_depthBuffer);
                };

                _2DRenderer = new Gorgon2D(_graphics);

                GorgonExample.LoadResources(_graphics);

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

                _textSprite = new GorgonTextSprite(_font)
                {
                    DrawMode = TextDrawMode.OutlinedGlyphs
                };
            }
            finally
            {
                GorgonExample.EndInit();
            }
        }
コード例 #25
0
ファイル: Form.cs プロジェクト: ishkang/Gorgon
        /// <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;
        }
コード例 #26
0
ファイル: MainForm.cs プロジェクト: tmp7701/Gorgon
        /// <summary>
        /// Function called to initialize the application.
        /// </summary>
        private void Initialize()
        {
            // 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.
            _graphics = new GorgonGraphics();
            _2D       = _graphics.Output.Create2DRenderer(this, ClientSize.Width, ClientSize.Height, BufferFormat.R8G8B8A8_UIntNormal, Settings.Default.IsWindowed);

            // Show the logo because I'm insecure.
            _2D.IsLogoVisible = true;

            // Create fonts.
            _textFont = _graphics.Fonts.CreateFont("GiGi_24pt", new GorgonFontSettings
            {
                FontFamilyName   = "GiGi",
                AntiAliasingMode = FontAntiAliasMode.AntiAlias,
                Size             = 24.0f,
                FontHeightMode   = FontHeightMode.Points,
                TextureSize      = new Size(512, 256)
            });

            // Use the form font for this one.
            _helpFont = _graphics.Fonts.CreateFont("FormFont", new GorgonFontSettings
            {
                FontFamilyName   = Font.FontFamily.Name,
                FontStyle        = FontStyle.Bold,
                AntiAliasingMode = FontAntiAliasMode.AntiAlias,
                Size             = Font.Size,
                FontHeightMode   = FontHeightMode.Points
            });

            // Create our file system and mount the resources.
            _fileSystem = new GorgonFileSystem();
            _fileSystem.Mount(Program.GetResourcePath(@"FolderSystem\"));

            // Get the sprite image.
            _spriteImage = _graphics.Textures.FromMemory <GorgonTexture2D>("0_HardVacuum", _fileSystem.ReadFile("/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] = _2D.Renderables.FromMemory <GorgonSprite>("Base", _fileSystem.ReadFile("/Sprites/base.gorSprite"));
            _sprites[1] = _2D.Renderables.FromMemory <GorgonSprite>("Mother", _fileSystem.ReadFile("/Sprites/Mother.gorSprite"));
            _sprites[2] = _2D.Renderables.FromMemory <GorgonSprite>("Mother2c", _fileSystem.ReadFile("/Sprites/Mother2c.gorSprite"));

            // Get poetry.
            _textPosition    = new Vector2(0, ClientSize.Height + _textFont.LineHeight);
            _poetry          = _2D.Renderables.CreateText("Poetry", _textFont, Encoding.UTF8.GetString(_fileSystem.ReadFile("/SomeText.txt")), Color.Black);
            _poetry.Position = _textPosition;

            // Set up help text.
            _helpText          = _2D.Renderables.CreateText("Help", _helpFont, "F1 - Show/hide this help text.\nS - Show frame statistics.\nESC - Exit.", Color.Blue);
            _helpText.Position = new Vector2(3, 3);

            // Set the initial blur value.
            // We set a small render target for the blur, this will help
            // speed up the effect.
            _2D.Effects.GaussianBlur.BlurAmount            = 13.0f;
            _2D.Effects.GaussianBlur.BlurRenderTargetsSize = new Size(128, 128);
            _2D.Effects.GaussianBlur.RenderScene           = pass =>
            {
                // Draw the sprite at the upper left corner instead of
                // centered.  Otherwise it'll be centered in the blur
                // render target and will be clipped.
                _sprites[2].Anchor   = Vector2.Zero;
                _sprites[2].Position = Vector2.Zero;
                // Scale to the size of the blur target.
                _sprites[2].Scale = new Vector2(1.0f, _2D.Effects.GaussianBlur.BlurRenderTargetsSize.Height / _sprites[2].Size.Y);
                // Adjust the texture size to avoid bleed when blurring.
                // Bleed means that other portions of the texture get pulled
                // in to the texture because of bi-linear filtering (and the
                // blur operates in a similar manner, and therefore unwanted
                // pixels get pulled in as well).
                // See http://tape-worm.net/?page_id=277 for more info.
                _sprites[2].TextureSize = new Vector2(125.0f / _spriteImage.Settings.Width, _sprites[2].TextureSize.Y);

                _sprites[2].Draw();

                // Reset.
                _sprites[2].TextureSize = new Vector2(128.0f / _spriteImage.Settings.Width, _sprites[2].TextureSize.Y);
            };

            Gorgon.ApplicationIdleLoopMethod = Idle;
        }
コード例 #27
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();
            }
        }
コード例 #28
0
        /// <summary>
        /// Function to initialize the application.
        /// </summary>
        private static void Initialize()
        {
            _form = new FormMain();

            _graphics  = new GorgonGraphics();
            _swapChain = _graphics.Output.CreateSwapChain("Swap",
                                                          new GorgonSwapChainSettings
            {
                Window             = _form,
                IsWindowed         = true,
                DepthStencilFormat = BufferFormat.D24_UIntNormal_S8_UInt,
                Format             = BufferFormat.R8G8B8A8_UIntNormal
            });

            _renderer2D = _graphics.Output.Create2DRenderer(_swapChain);

            _font = _graphics.Fonts.CreateFont("AppFont",
                                               new GorgonFontSettings
            {
                FontFamilyName   = "Calibri",
                FontStyle        = FontStyle.Bold,
                FontHeightMode   = FontHeightMode.Pixels,
                AntiAliasingMode = FontAntiAliasMode.AntiAlias,
                OutlineSize      = 1,
                OutlineColor1    = Color.Black,
                Size             = 16.0f
            });

            _vertexShader       = _graphics.Shaders.CreateShader <GorgonVertexShader>("VertexShader", "PrimVS", Resources.Shaders);
            _pixelShader        = _graphics.Shaders.CreateShader <GorgonPixelShader>("PixelShader", "PrimPS", Resources.Shaders);
            _bumpShader         = _graphics.Shaders.CreateShader <GorgonPixelShader>("PixelShader", "PrimPSBump", Resources.Shaders);
            _waterShader        = _graphics.Shaders.CreateShader <GorgonPixelShader>("PixelShader", "PrimPSWaterBump", Resources.Shaders);
            _normalVertexShader = _graphics.Shaders.CreateShader <GorgonVertexShader>("NormalVertexShader", "NormalVS", Resources.Shaders);
            _normalPixelShader  = _graphics.Shaders.CreateShader <GorgonPixelShader>("NormalPixelShader", "NormalPS", Resources.Shaders);
            _vertexLayout       = _graphics.Input.CreateInputLayout("Vertex3D", typeof(Vertex3D), _vertexShader);
            _normalVertexLayout = _graphics.Input.CreateInputLayout("NormalVertex",
                                                                    new[]
            {
                new GorgonInputElement("SV_POSITION",
                                       BufferFormat.R32G32B32A32_Float,
                                       0,
                                       0,
                                       0,
                                       false,
                                       0),
            },
                                                                    _normalVertexShader);

            _graphics.Shaders.VertexShader.Current = _vertexShader;
            _graphics.Shaders.PixelShader.Current  = _pixelShader;
            _graphics.Input.Layout        = _vertexLayout;
            _graphics.Input.PrimitiveType = PrimitiveType.TriangleList;

            _texture       = _graphics.Textures.CreateTexture <GorgonTexture2D>("UVTexture", Resources.UV);
            _earf          = _graphics.Textures.CreateTexture <GorgonTexture2D>("Earf", Resources.earthmap1k);
            _normalMap     = _graphics.Textures.FromMemory <GorgonTexture2D>("RainNRM", Resources.Rain_Height_NRM, new GorgonCodecDDS());
            _normalEarfMap = _graphics.Textures.FromMemory <GorgonTexture2D>("EarfNRM", Resources.earthbump1k_NRM, new GorgonCodecDDS());
            _specMap       = _graphics.Textures.FromMemory <GorgonTexture2D>("RainSPC", Resources.Rain_Height_SPEC, new GorgonCodecDDS());
            _specEarfMap   = _graphics.Textures.CreateTexture <GorgonTexture2D>("EarfSPC", Resources.earthspec1k);
            _cloudMap      = _graphics.Textures.CreateTexture <GorgonTexture2D>("EarfClouds", Resources.earthcloudmap);
            _gorgNrm       = _graphics.Textures.CreateTexture <GorgonTexture2D>("EarfClouds", Resources.normalmap);

            var depth = new GorgonDepthStencilStates
            {
                DepthComparison     = ComparisonOperator.LessEqual,
                IsDepthEnabled      = true,
                IsDepthWriteEnabled = true
            };

            _graphics.Output.DepthStencilState.States = depth;
            _graphics.Output.SetRenderTarget(_swapChain, _swapChain.DepthStencilBuffer);
            _graphics.Rasterizer.States = GorgonRasterizerStates.CullBackFace;
            _graphics.Rasterizer.SetViewport(new GorgonViewport(0, 0, _form.ClientSize.Width, _form.ClientSize.Height, 0, 1.0f));
            _graphics.Shaders.PixelShader.TextureSamplers[0] = GorgonTextureSamplerStates.LinearFilter;

            _wvp = new WorldViewProjection(_graphics);
            _wvp.UpdateProjection(75.0f, _form.ClientSize.Width, _form.ClientSize.Height);

            // When we resize, update the projection and viewport to match our client size.
            _form.Resize += (sender, args) =>
            {
                _graphics.Rasterizer.SetViewport(new GorgonViewport(0, 0, _form.ClientSize.Width, _form.ClientSize.Height, 0, 1.0f));
                _wvp.UpdateProjection(75.0f, _form.ClientSize.Width, _form.ClientSize.Height);
            };

            var     fnU = new Vector3(0.5f, 1.0f, 0);
            var     fnV = new Vector3(1.0f, 1.0f, 0);
            Vector3 faceNormal;

            Vector3.Cross(ref fnU, ref fnV, out faceNormal);
            faceNormal.Normalize();

            _triangle = new Triangle(_graphics, new Vertex3D
            {
                Position = new Vector4(-12.5f, -1.5f, 12.5f, 1),
                Normal   = faceNormal,
                UV       = new Vector2(0, 1.0f)
            }, new Vertex3D
            {
                Position = new Vector4(0, 24.5f, 12.5f, 1),
                Normal   = faceNormal,
                UV       = new Vector2(0.5f, 0.0f)
            }, new Vertex3D
            {
                Position = new Vector4(12.5f, -1.5f, 12.5f, 1),
                Normal   = faceNormal,
                UV       = new Vector2(1.0f, 1.0f)
            })
            {
                Texture  = _texture,
                Position = new Vector3(0, 0, 1.0f)
            };

            _plane = new Plane(_graphics, new Vector2(25.0f, 25.0f), new RectangleF(0, 0, 1.0f, 1.0f), new Vector3(90, 0, 0), 32, 32)
            {
                Position = new Vector3(0, -1.5f, 1.0f),
                Texture  = _texture
            };

            _cube = new Cube(_graphics, new Vector3(1, 1, 1), new RectangleF(0, 0, 1.0f, 1.0f), new Vector3(45.0f, 0, 0), 1, 1)
            {
                Position = new Vector3(0, 0, 1.5f),
                Texture  = _texture
            };

            _sphere = new Sphere(_graphics, 1.0f, new RectangleF(0.0f, 0.0f, 1.0f, 1.0f), Vector3.Zero, 64, 64)
            {
                Position = new Vector3(-2.0f, 1.0f, 0.75f),
                Texture  = _earf
            };

            _clouds = new Sphere(_graphics, 5.175f, new RectangleF(0.0f, 0.0f, 1.0f, 1.0f), Vector3.Zero, 16, 16)
            {
                Position = new Vector3(10, 2, 9.5f),
                Texture  = _cloudMap
            };

            _icoSphere = new IcoSphere(_graphics, 5.0f, new RectangleF(0, 0, 1, 1), Vector3.Zero, 3)
            {
                Rotation = new Vector3(0, -45.0f, 0),
                Position = new Vector3(10, 2, 9.5f),
                Texture  = _earf
            };

            _graphics.Shaders.PixelShader.TextureSamplers[0] = new GorgonTextureSamplerStates
            {
                TextureFilter        = TextureFilter.Linear,
                HorizontalAddressing = TextureAddressing.Wrap,
                VerticalAddressing   = TextureAddressing.Wrap,
                DepthAddressing      = TextureAddressing.Wrap,
                ComparisonFunction   = ComparisonOperator.Always
            };
            _graphics.Shaders.PixelShader.TextureSamplers[2] = new GorgonTextureSamplerStates
            {
                TextureFilter        = TextureFilter.Linear,
                HorizontalAddressing = TextureAddressing.Wrap,
                VerticalAddressing   = TextureAddressing.Wrap,
                DepthAddressing      = TextureAddressing.Wrap,
                ComparisonFunction   = ComparisonOperator.Always
            };

            _graphics.Shaders.PixelShader.TextureSamplers[1] = new GorgonTextureSamplerStates
            {
                TextureFilter        = TextureFilter.Linear,
                HorizontalAddressing = TextureAddressing.Wrap,
                VerticalAddressing   = TextureAddressing.Wrap,
                DepthAddressing      = TextureAddressing.Wrap,
                ComparisonFunction   = ComparisonOperator.Always
            };

            _material = new Material
            {
                UVOffset      = Vector2.Zero,
                SpecularPower = 1.0f
            };

            _materialBuffer = _graphics.Buffers.CreateConstantBuffer("uvOffset", ref _material, BufferUsage.Default);

            _graphics.Shaders.PixelShader.ConstantBuffers[2] = _materialBuffer;

            _light = new Light(_graphics);
            var lightPosition = new Vector3(1.0f, 1.0f, -1.0f);

            _light.UpdateLightPosition(ref lightPosition, 0);
            GorgonColor color = GorgonColor.White;

            _light.UpdateSpecular(ref color, 256.0f, 0);

            lightPosition = new Vector3(-5.0f, 5.0f, 8.0f);
            _light.UpdateLightPosition(ref lightPosition, 1);
            color = Color.Yellow;
            _light.UpdateColor(ref color, 1);
            _light.UpdateSpecular(ref color, 2048.0f, 1);
            _light.UpdateAttenuation(10.0f, 1);

            lightPosition = new Vector3(5.0f, 3.0f, 10.0f);
            _light.UpdateLightPosition(ref lightPosition, 2);
            color = Color.Red;
            _light.UpdateColor(ref color, 2);
            _light.UpdateAttenuation(16.0f, 2);

            var eye    = Vector3.Zero;
            var lookAt = Vector3.UnitZ;
            var up     = Vector3.UnitY;

            _wvp.UpdateViewMatrix(ref eye, ref lookAt, ref up);

            _cameraRotation = Vector2.Zero;

            Gorgon.PlugIns.LoadPlugInAssembly(Application.StartupPath + @"\Gorgon.Input.Raw.dll");

            _input    = GorgonInputFactory.CreateInputFactory("GorgonLibrary.Input.GorgonRawPlugIn");
            _keyboard = _input.CreateKeyboard(_form);
            _mouse    = _input.CreatePointingDevice(_form);

            _keyboard.KeyDown += (sender, args) =>
            {
                if (args.Key == KeyboardKeys.L)
                {
                    _lock = !_lock;
                }
            };

            _mouse.PointingDeviceDown      += Mouse_Down;
            _mouse.PointingDeviceUp        += Mouse_Up;
            _mouse.PointingDeviceWheelMove += (sender, args) =>
            {
                if (args.WheelDelta < 0)
                {
                    _sensitivity -= 0.05f;

                    if (_sensitivity < 0.05f)
                    {
                        _sensitivity = 0.05f;
                    }
                }
                else if (args.WheelDelta > 0)
                {
                    _sensitivity += 0.05f;

                    if (_sensitivity > 2.0f)
                    {
                        _sensitivity = 2.0f;
                    }
                }
            };
            _mouse.PointingDeviceMove += (sender, args) =>
            {
                if (!_mouse.Exclusive)
                {
                    return;
                }

                var delta = args.RelativePosition;
                _cameraRotation.Y      += delta.Y * _sensitivity;                                        //((360.0f * 0.002f) * delta.Y.Sign());
                _cameraRotation.X      += delta.X * _sensitivity;                                        //((360.0f * 0.002f) * delta.X.Sign());
                _mouseStart             = _mouse.Position;
                _mouse.RelativePosition = PointF.Empty;
            };
        }
コード例 #29
0
ファイル: Form.cs プロジェクト: hammerforgegames/Gorgon
        /// <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);
        }
コード例 #30
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();
            }
        }