Ejemplo n.º 1
0
        /// <summary>
        /// Function to return the appropriate draw call based on the states provided.
        /// </summary>
        /// <param name="texture">The texture to display.</param>
        /// <param name="blendState">The blending state for the texture.</param>
        /// <param name="samplerState">The sampler state for the texture.</param>
        /// <param name="shader">The pixel shader to use.</param>
        /// <param name="constantBuffers">Constant buffers for the pixel shader, if required.</param>
        private void GetDrawCall(GorgonTexture2DView texture, GorgonBlendState blendState, GorgonSamplerState samplerState, GorgonPixelShader shader, GorgonConstantBuffers constantBuffers)
        {
            if ((_drawCall != null) &&
                (shader == _pixelShader) &&
                (_drawCall.PixelShader.Samplers[0] == samplerState) &&
                (_pipelineState.BlendStates[0] == blendState) &&
                (_drawCall.PixelShader.ShaderResources[0] == texture) &&
                (_drawCall.PixelShader.ConstantBuffers.DirtyEquals(constantBuffers)))
            {
                // This draw call hasn't changed, so return the previous one.
                return;
            }

            if (_pipelineState.BlendStates[0] != blendState)
            {
                _pipelineState = _pipeStateBuilder
                                 .BlendState(blendState)
                                 .Build();

                _drawCallBuilder.PipelineState(_pipelineState);
            }

            _drawCall = _drawCallBuilder.ConstantBuffers(ShaderType.Pixel, constantBuffers)
                        .SamplerState(ShaderType.Pixel, samplerState)
                        .ShaderResource(ShaderType.Pixel, texture)
                        .Build(_drawAllocator);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Function to load the images for use with the example.
        /// </summary>
        /// <param name="codec">The codec for the images.</param>
        /// <returns><b>true</b> if files were loaded successfully, <b>false</b> if not.</returns>
        private static bool LoadImageFiles(IGorgonImageCodec codec)
        {
            DirectoryInfo dirInfo = GorgonExample.GetResourcePath(@"\Textures\PostProcess");

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

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

            _images = new GorgonTexture2DView[files.Length];

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

            return(true);
        }
Ejemplo n.º 3
0
        /// <summary>Function to provide initialization for the plugin.</summary>
        /// <remarks>This method is only called when the plugin is loaded at startup.</remarks>
        protected override void OnInitialize()
        {
            ViewFactory.Register <ISpriteContent>(() => new SpriteEditorView());

            // Get built-in codec list.
            _defaultCodec = new GorgonV3SpriteBinaryCodec(GraphicsContext.Renderer2D);

            SpriteEditorSettings settings = ContentPlugInService.ReadContentSettings <SpriteEditorSettings>(typeof(SpriteEditorPlugIn).FullName, new JsonSharpDxRectConverter());

            if (settings != null)
            {
                _settings = settings;
            }

            _ddsCodec = new GorgonCodecDds();

            using (var noImageStream = new MemoryStream(Resources.NoImage_256x256))
            {
                _noImage = _ddsCodec.LoadFromStream(noImageStream);
            }

            _bgPattern = GorgonTexture2DView.CreateTexture(GraphicsContext.Graphics, new GorgonTexture2DInfo($"Sprite_Editor_Bg_Preview_{Guid.NewGuid():N}")
            {
                Width  = EditorCommonResources.CheckerBoardPatternImage.Width,
                Height = EditorCommonResources.CheckerBoardPatternImage.Height
            }, EditorCommonResources.CheckerBoardPatternImage);

            _rtv = GorgonRenderTarget2DView.CreateRenderTarget(GraphicsContext.Graphics, new GorgonTexture2DInfo($"SpriteEditor_Rtv_Preview_{Guid.NewGuid():N}")
            {
                Width   = 256,
                Height  = 256,
                Format  = BufferFormat.R8G8B8A8_UNorm,
                Binding = TextureBinding.ShaderResource
            });
        }
 /// <summary>
 /// Function called when a texture needs to be updated on the object.
 /// </summary>
 /// <param name="animObject">The object being animated.</param>
 /// <param name="texture">The texture to switch to.</param>
 /// <param name="textureCoordinates">The new texture coordinates to apply.</param>
 /// <param name="textureArrayIndex">The texture array index.</param>
 protected override void OnTexture2DUpdate(GorgonPolySprite animObject, GorgonTexture2DView texture, DX.RectangleF textureCoordinates, int textureArrayIndex)
 {
     animObject.Texture           = texture;
     animObject.TextureArrayIndex = textureArrayIndex;
     animObject.TextureOffset     = textureCoordinates.TopLeft;
     animObject.TextureScale      = new DX.Vector2(textureCoordinates.Width, textureCoordinates.Height);
 }
Ejemplo n.º 5
0
        /// <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
                });
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Function to render the thumbnail into the image passed in.
        /// </summary>
        /// <param name="image">The image to render the thumbnail into.</param>
        /// <param name="scale">The scale of the image.</param>
        private void RenderThumbnail(ref IGorgonImage image, float scale)
        {
            lock (_syncLock)
            {
                using (GorgonTexture2D texture = image.ToTexture2D(GraphicsContext.Graphics, new GorgonTexture2DLoadOptions
                {
                    Usage = ResourceUsage.Immutable,
                    IsTextureCube = false
                }))
                    using (var rtv = GorgonRenderTarget2DView.CreateRenderTarget(GraphicsContext.Graphics, new GorgonTexture2DInfo
                    {
                        ArrayCount = 1,
                        Binding = TextureBinding.ShaderResource,
                        Format = BufferFormat.R8G8B8A8_UNorm,
                        MipLevels = 1,
                        Height = (int)(image.Height * scale),
                        Width = (int)(image.Width * scale),
                        Usage = ResourceUsage.Default
                    }))
                    {
                        GorgonTexture2DView view = texture.GetShaderResourceView(mipCount: 1, arrayCount: 1);
                        rtv.Clear(GorgonColor.BlackTransparent);
                        GraphicsContext.Graphics.SetRenderTarget(rtv);
                        GraphicsContext.Graphics.DrawTexture(view, new DX.Rectangle(0, 0, rtv.Width, rtv.Height), blendState: GorgonBlendState.Default, samplerState: GorgonSamplerState.Default);
                        GraphicsContext.Graphics.SetRenderTarget(null);

                        image?.Dispose();
                        image = rtv.Texture.ToImage();
                    }
            }
        }
Ejemplo n.º 7
0
        /// <summary>Imports the data.</summary>
        /// <param name="temporaryDirectory">The temporary directory for writing any transitory data.</param>
        /// <param name="cancelToken">The cancel token.</param>
        /// <remarks>
        /// <para>
        /// The <paramref name="temporaryDirectory"/> should be used to write any working/temporary data used by the import.  Note that all data written into this directory will be deleted when the
        /// project is unloaded from memory.
        /// </para>
        /// </remarks>
        public FileInfo ImportData(DirectoryInfo temporaryDirectory, CancellationToken cancelToken)
        {
            var spriteCodec = new GorgonV3SpriteBinaryCodec(_renderer);

            _log.Print("Importing associated texture for sprite...", LoggingLevel.Simple);
            GorgonTexture2DView texture = GetTexture();

            try
            {
                _log.Print($"Importing file '{SourceFile.FullName}' (Codec: {_codec.Name})...", LoggingLevel.Verbose);
                GorgonSprite sprite = _codec.FromFile(SourceFile.FullName);

                if (sprite.Texture == null)
                {
                    sprite.Texture = texture;
                }

                var tempFile = new FileInfo(Path.Combine(temporaryDirectory.FullName, Path.GetFileNameWithoutExtension(SourceFile.Name)));

                _log.Print($"Converting '{SourceFile.FullName}' to Gorgon v3 Sprite file format.", LoggingLevel.Verbose);
                spriteCodec.Save(sprite, tempFile.FullName);

                return(tempFile);
            }
            finally
            {
                texture?.Dispose();
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Function to render the image into the preview area.
        /// </summary>
        private void RenderImage()
        {
            if ((IsDesignTime) || (_swapChain == null))
            {
                return;
            }

            GorgonTexture2DView image = _previewTexture ?? _defaultTexture;

            _swapChain.RenderTargetView.Clear(BackColor);

            GraphicsContext.Graphics.SetRenderTarget(_swapChain.RenderTargetView);

            _renderer.Begin();

            var   halfClient = new DX.Vector2(ClientSize.Width / 2.0f, ClientSize.Height / 2.0f);
            float scale      = ((float)ClientSize.Width / image.Width).Min((float)ClientSize.Height / image.Height);
            float width      = image.Width * scale;
            float height     = image.Height * scale;
            float x          = halfClient.X - (width / 2.0f);
            float y          = halfClient.Y - (height / 2.0f);

            _renderer.DrawFilledRectangle(new DX.RectangleF(x, y, width, height), GorgonColor.White, image, new DX.RectangleF(0, 0, 1, 1));

            _titleText.LayoutArea = new DX.Size2F(_swapChain.Width, _titleText.Size.Height * 1.5f);
            _titleText.Position   = new DX.Vector2(0, _swapChain.Height - (_titleText.Size.Height * 1.5f).Min(_swapChain.Height * 0.25f));// _swapChain.Height - _titleText.Size.Height);

            _renderer.DrawFilledRectangle(new DX.RectangleF(0, _titleText.Position.Y, _swapChain.Width, _titleText.LayoutArea.Value.Height), new GorgonColor(0, 0, 0, 0.5f));

            _renderer.DrawTextSprite(_titleText);
            _renderer.End();

            _swapChain.Present(1);
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Function to blit the specified texture into the current output target.
 /// </summary>
 /// <param name="texture">The texture to blit.</param>
 /// <param name="textureCoordinates">[Optional] The texture coordinates to use on the source texture.</param>
 /// <param name="samplerState">[Optional] The sampler state to apply.</param>
 protected void Blit(GorgonTexture2DView texture, DX.RectangleF?textureCoordinates = null, GorgonSamplerState samplerState = null) =>
 Renderer.DrawFilledRectangle(new DX.RectangleF(0, 0, OutputSize.Width, OutputSize.Height),
                              GorgonColor.White,
                              texture,
                              textureCoordinates ?? new DX.RectangleF(0, 0, 1, 1),
                              textureSampler: samplerState ?? GorgonSamplerState.Default,
                              depth: 0.1f);
Ejemplo n.º 10
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
                });
            }
        }
Ejemplo n.º 11
0
        /// <summary>Function to perform the rendering.</summary>
        public void Render()
        {
            if (DataContext == null)
            {
                return;
            }

            _graphics.SetRenderTarget(_swapChain.RenderTargetView);

            if (DataContext.Atlas == null)
            {
                DrawMessage();
                return;
            }

            GorgonTexture2DView texture = _textureSprite.Texture = DataContext.Atlas.Textures[DataContext.PreviewTextureIndex]; // Change to use index.

            float scale = CalcZoomToSize(new DX.Size2F(texture.Width + 8, texture.Height + 8), new DX.Size2F(_swapChain.Width, _swapChain.Height));

            _textureSprite.Size     = new DX.Size2F(scale * texture.Width, scale * texture.Height).Truncate();
            _textureSprite.Position = new DX.Vector2(-_textureSprite.Size.Width * 0.5f, -_textureSprite.Size.Height * 0.5f).Truncate();

            _renderer.Begin(camera: _camera);
            _renderer.DrawFilledRectangle(new DX.RectangleF(-_swapChain.Width * 0.5f, -_swapChain.Height * 0.5f, _swapChain.Width, _swapChain.Height),
                                          GorgonColor.White,
                                          _bgTexture,
                                          new DX.RectangleF(0, 0, (float)_swapChain.Width / _bgTexture.Width, (float)_swapChain.Height / _bgTexture.Height));

            _textureSprite.TextureArrayIndex = DataContext.PreviewArrayIndex; // Change to use index.
            _renderer.DrawSprite(_textureSprite);

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

            GorgonVertexShader       vertexShader   = Interlocked.Exchange(ref _vertexDeferShader, null);
            GorgonPixelShader        deferredShader = Interlocked.Exchange(ref _pixelDeferShader, null);
            GorgonPixelShader        lightShader    = Interlocked.Exchange(ref _pixelLitShader, null);
            GorgonConstantBufferView lightData      = Interlocked.Exchange(ref _lightData, null);
            GorgonConstantBufferView globalData     = Interlocked.Exchange(ref _globalData, null);

            GorgonRenderTargetView[] targets     = Interlocked.Exchange(ref _gbufferTargets, null);
            GorgonTexture2DView      textureView = Interlocked.Exchange(ref _gbufferTexture, null);

            textureView?.Dispose();

            for (int i = 0; i < targets.Length; ++i)
            {
                targets[i]?.Dispose();
            }

            globalData?.Dispose();
            lightData?.Dispose();
            lightShader?.Dispose();
            deferredShader?.Dispose();
            vertexShader?.Dispose();
        }
Ejemplo n.º 13
0
        /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
        public override void Dispose()
        {
            GorgonTexture2DView noImage = Interlocked.Exchange(ref _noImage, null);

            noImage?.Dispose();

            base.Dispose();
        }
Ejemplo n.º 14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GorgonKeyTexture2D" /> struct.
 /// </summary>
 /// <param name="time">The time for the key frame.</param>
 /// <param name="value">The value to apply to the key frame.</param>
 /// <param name="textureCoordinates">Region on the texture to update.</param>
 /// <param name="textureArrayIndex">The texture array index to use with a texture array.</param>
 public GorgonKeyTexture2D(float time, GorgonTexture2DView value, DX.RectangleF textureCoordinates, int textureArrayIndex)
 {
     Time                = time;
     Value               = value;
     TextureName         = value?.Texture.Name ?? string.Empty;
     _textureCoordinates = textureCoordinates;
     _textureArrayIndex  = textureArrayIndex;
 }
Ejemplo n.º 15
0
        /// <summary>
        /// Handles the Click event of the ButtonImagePath control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void ButtonImagePath_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;

            IGorgonImage image = null;
            var          png   = new GorgonCodecPng();

            try
            {
                if (DialogOpenPng.ShowDialog(this) != DialogResult.OK)
                {
                    return;
                }

                TextImagePath.Text = DialogOpenPng.FileName;
                _sourceTexture?.Texture?.Dispose();
                _outputTexture?.Dispose();
                _sourceTexture = null;
                _outputTexture = null;

                image          = png.LoadFromFile(DialogOpenPng.FileName);
                _sourceTexture = image.ConvertToFormat(BufferFormat.R8G8B8A8_UNorm)
                                 .ToTexture2D(_graphics,
                                              new GorgonTexture2DLoadOptions
                {
                    Name =
                        Path.GetFileNameWithoutExtension(DialogOpenPng.FileName)
                }).GetShaderResourceView();

                _outputTexture = new GorgonTexture2D(_graphics,
                                                     new GorgonTexture2DInfo(_sourceTexture, "Output")
                {
                    Format  = BufferFormat.R8G8B8A8_Typeless,
                    Binding = TextureBinding.ShaderResource | TextureBinding.ReadWriteView
                });

                // Get an SRV for the output texture so we can render it later.
                _outputView = _outputTexture.GetShaderResourceView(BufferFormat.R8G8B8A8_UNorm);

                // Get a UAV for the output.
                _outputUav = _outputTexture.GetReadWriteView(BufferFormat.R32_UInt);

                // Process the newly loaded texture.
                _sobel.Process(_sourceTexture, _outputUav, TrackThickness.Value, TrackThreshold.Value / 100.0f);

                TrackThreshold.Enabled = TrackThickness.Enabled = true;
            }
            catch (Exception ex)
            {
                GorgonDialogs.ErrorBox(this, ex);
                TrackThreshold.Enabled = TrackThickness.Enabled = false;
            }
            finally
            {
                image?.Dispose();
                Cursor.Current = Cursors.Default;
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Function to build up the render targets.
        /// </summary>
        /// <param name="width">The width of the render targets.</param>
        /// <param name="height">The height of the render targets.</param>
        /// <param name="format">The format of the buffer.</param>
        private void BuildRenderTargets(int width, int height, BufferFormat format)
        {
            // For the lighting effect, we use a deferred rendering technique where we have 3 render targets for diffuse, specularity, and normal mapping.
            // These targets are sub resources of the same texture resource (array indices).

            // Diffuse.
            _rtvInfo.Width      = width;
            _rtvInfo.Height     = height;
            _rtvInfo.Format     = format;
            _rtvInfo.ArrayCount = 2;

            _gbufferTargets[0] = Graphics.TemporaryTargets.Rent(_rtvInfo, "Gorgon 2D GBuffer - Diffuse/Specular", false);
            _gbufferTargets[0].Clear(GorgonColor.Black);
            // Specular.
            _gbufferTargets[1] = _gbufferTargets[0].Texture.GetRenderTargetView(arrayIndex: 1, arrayCount: 1);

            _rtvInfo.Format     = BufferFormat.R8G8B8A8_UNorm;
            _rtvInfo.ArrayCount = 1;

            // Normals.
            // We'll clear it before the pass, the default color is insufficient.
            _gbufferTargets[2] = Graphics.TemporaryTargets.Rent(_rtvInfo, "Gorgon 2D Buffer - Normals", false);
            GorgonTexture2DView normalSrv = _gbufferTargets[2].GetShaderResourceView();

            if ((_pixelLitShaderState.ShaderResources[1] != normalSrv) ||
                (_diffuseFilter != DiffuseFiltering) ||
                (_normalFilter != NormalFiltering) ||
                (_specularFilter != SpecularFiltering))
            {
                _diffuseFilter  = DiffuseFiltering ?? GorgonSamplerState.Default;
                _normalFilter   = NormalFiltering ?? GorgonSamplerState.PointFiltering;
                _specularFilter = SpecularFiltering ?? GorgonSamplerState.Default;

                _pixelDeferShaderState = PixelShaderBuilder.ResetTo(_pixelDeferShaderState)
                                         .SamplerState(_diffuseFilter, 0)
                                         .SamplerState(_normalFilter, 1)
                                         .SamplerState(_specularFilter, 2)
                                         .Build();

                _pixelLitShaderState = PixelShaderBuilder
                                       .ResetTo(_pixelLitShaderState)
                                       .ShaderResource(normalSrv, 1)
                                       .SamplerState(_diffuseFilter, 0)
                                       .SamplerState(_normalFilter, 1)
                                       .SamplerState(_specularFilter, 2)
                                       .Build();

                _lightingState = BatchStateBuilder
                                 .ResetTo(_lightingState)
                                 .PixelShaderState(_pixelLitShaderState)
                                 .Build();
            }


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

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

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

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

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

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

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

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

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

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

            builder.ResetTo(workingSpriteData);

            return(builder.Build());
        }
Ejemplo n.º 18
0
        /// <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();
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Function to update the render target and texture view.
 /// </summary>
 private static void UpdateRenderTarget()
 {
     // This will be our final output target for our effect.
     _finalTarget = GorgonRenderTarget2DView.CreateRenderTarget(_graphics, new GorgonTexture2DInfo(_screen.RenderTargetView, "Final Render Target")
     {
         Binding = TextureBinding.ShaderResource
     });
     // And this is the texture we will display at the end of the frame.
     _finalTexture = _finalTarget.GetShaderResourceView();
 }
Ejemplo n.º 20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DrawCallFactory"/> class.
 /// </summary>
 /// <param name="graphics">The graphics interface to use when creating states.</param>
 /// <param name="defaultTexture">The default texture to use as a fallback when no texture is passed by renderable.</param>
 /// <param name="inputLayout">The input layout defining a vertex type.</param>
 public DrawCallFactory(GorgonGraphics graphics, GorgonTexture2DView defaultTexture, GorgonInputLayout inputLayout)
 {
     _inputLayout        = inputLayout;
     _drawIndexAllocator = new GorgonDrawCallPoolAllocator <GorgonDrawIndexCall>(128);
     _drawAllocator      = new GorgonDrawCallPoolAllocator <GorgonDrawCall>(128);
     _drawIndexBuilder   = new GorgonDrawIndexCallBuilder();
     _drawBuilder        = new GorgonDrawCallBuilder();
     _stateBuilder       = new GorgonPipelineStateBuilder(graphics);
     _defaultTexture     = defaultTexture;
 }
Ejemplo n.º 21
0
        /// <summary>
        /// Function to initialize the application.
        /// </summary>
        /// <returns>The main window for the application.</returns>
        private static FormMain Initialize()
        {
            GorgonExample.ResourceBaseDirectory = new DirectoryInfo(Settings.Default.ResourceLocation);
            FormMain window =
                GorgonExample.Initialize(new DX.Size2(Settings.Default.Resolution.Width, Settings.Default.Resolution.Height), "Polygonal Sprites");

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

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

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

                _screen = new GorgonSwapChain(_graphics,
                                              window,
                                              new GorgonSwapChainInfo("Gorgon2D Effects Example Swap Chain")
                {
                    Width  = Settings.Default.Resolution.Width,
                    Height = Settings.Default.Resolution.Height,
                    Format = BufferFormat.R8G8B8A8_UNorm
                });

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

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

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

                GorgonExample.LoadResources(_graphics);

                CreateSprites();

                return(window);
            }
            finally
            {
                GorgonExample.EndInit();
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Function to load the resources for the layer.
        /// </summary>
        public override void LoadResources()
        {
            _drawCalls = new List <GorgonDrawIndexCall>();
            BuildConstantBuffers();

            for (int i = 0; i < Planets.Count; ++i)
            {
                Planet planet = Planets[i];

                for (int j = 0; j < planet.Layers.Count; ++j)
                {
                    PlanetaryLayer layer = planet.Layers[j];

                    GorgonVertexShader vertexShader = _resources.VertexShaders[layer.Mesh.Material.VertexShader];
                    GorgonPixelShader  pixelShader  = _resources.PixelShaders[layer.Mesh.Material.PixelShader];

                    // Create our vertex layout now.
                    if (_vertexLayout == null)
                    {
                        _vertexLayout = _vertexLayout = GorgonInputLayout.CreateUsingType <Vertex3D>(_graphics, vertexShader);
                    }

                    // Set up a pipeline state for the mesh.
                    GorgonPipelineState pipelineState = _stateBuilder.Clear()
                                                        .PixelShader(pixelShader)
                                                        .VertexShader(vertexShader)
                                                        .BlendState(layer.Mesh.Material.BlendState)
                                                        .PrimitiveType(PrimitiveType.TriangleList)
                                                        .Build();
                    _drawCallBuilder.Clear()
                    .PipelineState(pipelineState)
                    .IndexBuffer(layer.Mesh.IndexBuffer, 0, layer.Mesh.IndexCount)
                    .VertexBuffer(_vertexLayout, new GorgonVertexBufferBinding(layer.Mesh.VertexBuffer, Vertex3D.Size))
                    .ConstantBuffer(ShaderType.Vertex, _viewProjectionBuffer)
                    .ConstantBuffer(ShaderType.Vertex, _worldBuffer, 1)
                    .ConstantBuffer(ShaderType.Pixel, _cameraBuffer)
                    .ConstantBuffer(ShaderType.Pixel, _lightBuffer, 1)
                    .ConstantBuffer(ShaderType.Pixel, _materialBuffer, 2);

                    (int startTexture, int textureCount) = layer.Mesh.Material.Textures.GetDirtyItems();

                    for (int k = startTexture; k < startTexture + textureCount; ++k)
                    {
                        GorgonTexture2DView texture = _resources.Textures[layer.Mesh.Material.Textures[k]];
                        _drawCallBuilder.ShaderResource(ShaderType.Pixel, texture, k);
                        // We should have this in the material, but since we know what we've got here, this will be fine.
                        _drawCallBuilder.SamplerState(ShaderType.Pixel, GorgonSamplerState.Wrapping, k);
                    }

                    _drawCalls.Add(_drawCallBuilder.Build());
                }
            }

            UpdateLightTransforms();
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Function to render the image data into an 32 bit RGBA pixel format render target and then return it as the properly formatted image data.
        /// </summary>
        /// <param name="texture">The texture to render.</param>
        /// <returns>The converted image data for the texture.</returns>
        private IGorgonImage RenderImageData(GorgonTexture2DView texture)
        {
            GorgonRenderTargetView   oldRtv        = _graphics.RenderTargets[0];
            GorgonRenderTarget2DView convertTarget = null;
            GorgonTexture2DView      rtvTexture    = null;
            IGorgonImage             tempImage     = null;
            BufferFormat             targetFormat  = texture.FormatInformation.IsSRgb ? BufferFormat.R8G8B8A8_UNorm_SRgb : BufferFormat.R8G8B8A8_UNorm;

            try
            {
                IGorgonImage resultImage = new GorgonImage(new GorgonImageInfo(ImageType.Image2D, targetFormat)
                {
                    Width      = texture.Width,
                    Height     = texture.Height,
                    ArrayCount = texture.ArrayCount
                });

                convertTarget = GorgonRenderTarget2DView.CreateRenderTarget(_graphics, new GorgonTexture2DInfo(texture, "Convert_rtv")
                {
                    ArrayCount = 1,
                    MipLevels  = 1,
                    Format     = targetFormat,
                    Binding    = TextureBinding.ShaderResource
                });

                rtvTexture = convertTarget.GetShaderResourceView();

                for (int i = 0; i < texture.ArrayCount; ++i)
                {
                    convertTarget.Clear(GorgonColor.BlackTransparent);
                    _graphics.SetRenderTarget(convertTarget);
                    _renderer.Begin();
                    _renderer.DrawFilledRectangle(new DX.RectangleF(0, 0, texture.Width, texture.Height),
                                                  GorgonColor.White,
                                                  texture,
                                                  new DX.RectangleF(0, 0, 1, 1),
                                                  i);
                    _renderer.End();

                    tempImage?.Dispose();
                    tempImage = convertTarget.Texture.ToImage();
                    tempImage.Buffers[0].CopyTo(resultImage.Buffers[0, i]);
                }

                return(resultImage);
            }
            finally
            {
                tempImage?.Dispose();
                _graphics.SetRenderTarget(oldRtv);
                rtvTexture?.Dispose();
                convertTarget?.Dispose();
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Function to create the selection texture.
        /// </summary>
        private GorgonTexture2DView CreateSelectionTexture()
        {
            GorgonTexture2DView result;

            using (var stream = new MemoryStream(Resources.selection_16x16))
            {
                result = GorgonTexture2DView.FromStream(_renderer.Graphics, stream, new GorgonCodecDds());
            }

            return(result);
        }
Ejemplo n.º 25
0
        /// <summary>Function to create the texture for the view.</summary>
        /// <param name="graphics">The graphics interface used to create the texture.</param>
        /// <param name="imageData">The image data to create the texture from.</param>
        /// <param name="name">The name of the texture.</param>
        protected override void OnCreateTexture(GorgonGraphics graphics, IGorgonImage imageData, string name)
        {
            _texture = imageData.ToTexture2D(graphics, new GorgonTexture2DLoadOptions
            {
                Name          = name,
                Binding       = TextureBinding.ShaderResource,
                Usage         = ResourceUsage.Immutable,
                IsTextureCube = false
            });

            _textureView = _texture.GetShaderResourceView();
        }
Ejemplo n.º 26
0
 /// <summary>
 /// Function to build an instance of the marching ants texture.
 /// </summary>
 /// <returns>A new instance of the marching ants texture.</returns>
 private GorgonTexture2DView Build()
 {
     using (var image = new MemoryStream(Resources.march_ants_diag_32x32))
     {
         return(GorgonTexture2DView.FromStream(_renderer.Graphics, image, new GorgonCodecDds(),
                                               options: new GorgonTexture2DLoadOptions
         {
             Name = "MarchingAntsTexture",
             Usage = ResourceUsage.Immutable
         }));
     }
 }
Ejemplo n.º 27
0
        /// <summary>
        /// Function to load the texture information.
        /// </summary>
        /// <param name="reader">The reader containing the texture information.</param>
        /// <param name="overrideTexture">The texture to assign to the sprite instead of the texture associated with the name stored in the file.</param>
        /// <param name="textureOffset">The texture transform offset.</param>
        /// <param name="textureScale">The texture transform scale.</param>
        /// <param name="textureArrayIndex">The texture array index.</param>
        /// <returns>The texture attached to the sprite.</returns>
        private GorgonTexture2DView LoadTexture(GorgonBinaryReader reader, GorgonTexture2DView overrideTexture, out DX.Vector2 textureOffset, out DX.Vector2 textureScale, out int textureArrayIndex)
        {
            // Write out as much info about the texture as we can so we can look it up based on these values when loading.
            string textureName = reader.ReadString();

            textureOffset     = DX.Vector2.Zero;
            textureScale      = DX.Vector2.One;
            textureArrayIndex = 0;

            if (string.IsNullOrWhiteSpace(textureName))
            {
                return(null);
            }

            reader.ReadValue(out textureOffset);
            reader.ReadValue(out textureScale);
            reader.ReadValue(out textureArrayIndex);
            reader.ReadValue(out int textureWidth);
            reader.ReadValue(out int textureHeight);
            reader.ReadValue(out BufferFormat textureFormat);
            reader.ReadValue(out int textureArrayCount);
            reader.ReadValue(out int textureMipCount);

            GorgonTexture2D texture = null;

            // Locate the texture resource.
            if (overrideTexture == null)
            {
                texture = Renderer.Graphics.LocateResourcesByName <GorgonTexture2D>(textureName)
                          .FirstOrDefault(item => item.Width == textureWidth &&
                                          item.Height == textureHeight &&
                                          item.Format == textureFormat &&
                                          item.ArrayCount == textureArrayCount &&
                                          item.MipLevels == textureMipCount);

                if (texture == null)
                {
                    textureOffset     = DX.Vector2.Zero;
                    textureScale      = DX.Vector2.One;
                    textureArrayIndex = 0;
                    return(null);
                }
            }

            reader.ReadValue(out int viewArrayIndex);
            reader.ReadValue(out int viewArrayCount);
            reader.ReadValue(out int viewMipSlice);
            reader.ReadValue(out int viewMipCount);
            reader.ReadValue(out BufferFormat viewFormat);

            return(overrideTexture ?? texture.GetShaderResourceView(viewFormat, viewMipSlice, viewMipCount, viewArrayIndex, viewArrayCount));
        }
Ejemplo n.º 28
0
        /// <summary>Function called to shut down the view.</summary>
        protected override void OnShutdown()
        {
            DataContext?.OnUnload();

            // Reset the view.
            SetDataContext(null);

            foreach (ITextureViewerService service in _viewers.Values)
            {
                service.Dispose();
            }

            _background?.Dispose();
            _background = null;
        }
Ejemplo n.º 29
0
        /// <summary>Function to perform setup on the renderer.</summary>
        public void Setup()
        {
            _bgTexture = GorgonTexture2DView.CreateTexture(_graphics, new GorgonTexture2DInfo("Texture Atlas BG Texture")
            {
                Binding = TextureBinding.ShaderResource,
                Usage   = ResourceUsage.Immutable,
                Width   = EditorCommonResources.CheckerBoardPatternImage.Width,
                Height  = EditorCommonResources.CheckerBoardPatternImage.Height
            }, EditorCommonResources.CheckerBoardPatternImage);

            _camera = new Gorgon2DOrthoCamera(_renderer, new DX.Size2F(_swapChain.Width, _swapChain.Height))
            {
                Anchor = new DX.Vector2(0.5f, 0.5f)
            };
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Function called after a swap chain is resized.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="AfterSwapChainResizedEventArgs"/> instance containing the event data.</param>
        private void AfterSwapChainResized(object sender, AfterSwapChainResizedEventArgs e)
        {
            // Restore the render target buffer and restore the contents of it.
            _backBuffer = GorgonRenderTarget2DView.CreateRenderTarget(_graphics,
                                                                      new GorgonTexture2DInfo("Backbuffer")
            {
                Width  = ClientSize.Width,
                Height = ClientSize.Height,
                Format = BufferFormat.R8G8B8A8_UNorm
            });
            _backBuffer.Clear(Color.White);
            _backupImage.CopyTo(_backBuffer.Texture, new DX.Rectangle(0, 0, _backBuffer.Width, _backBuffer.Height));

            _backBufferView = _backBuffer.GetShaderResourceView();
        }