示例#1
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
                });
            }
        }
示例#2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="WorldViewProjection"/> class.
        /// </summary>
        /// <param name="graphics">The graphics interface to use.</param>
        public Light(GorgonGraphics graphics)
        {
            _lightData[0].Attenuation   = 6.0f;
            _lightData[0].LightColor    = GorgonColor.White;
            _lightData[0].LightPosition = Vector3.Zero;
            _lightData[0].SpecularColor = GorgonColor.White;
            _lightData[0].SpecularPower = 512.0f;

            _buffer = graphics.Buffers.CreateConstantBuffer("LightBuffer",
                                                            new GorgonConstantBufferSettings
            {
                SizeInBytes = LightData.Size * _lightData.Length,
                Usage       = BufferUsage.Default
            });

            _lightStore = new GorgonDataStream(_buffer.SizeInBytes);
            unsafe
            {
                DirectAccess.ZeroMemory(_lightStore.UnsafePointer, _buffer.SizeInBytes);
                var data = (LightData *)_lightStore.UnsafePointer;
                *   data = _lightData[0];
            }

            _buffer.Update(_lightStore);

            graphics.Shaders.PixelShader.ConstantBuffers[1] = _buffer;
        }
示例#3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GorgonBuffer" /> class.
        /// </summary>
        /// <param name="graphics">The <see cref="GorgonGraphics"/> object used to create and manipulate the buffer.</param>
        /// <param name="info">Information used to create the buffer.</param>
        /// <param name="initialData">[Optional] The initial data used to populate the buffer.</param>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="info"/> parameter is <b>null</b>.</exception>
        /// <exception cref="ArgumentException">Thrown if the size of the buffer is less than 1 byte.</exception>
        /// <exception cref="GorgonException">Thrown if the buffer is created with a usage of <see cref="ResourceUsage.Immutable"/>, but the <paramref name="initialData"/> parameter is <b>null</b>.
        /// <para>-or-</para>
        /// <para>A value on the <paramref name="info"/> parameter is incorrect.</para>
        /// </exception>
        public GorgonBuffer(GorgonGraphics graphics, IGorgonBufferInfo info, GorgonNativeBuffer <byte> initialData = null)
            : base(graphics)
        {
            _info = new GorgonBufferInfo(info ?? throw new ArgumentNullException(nameof(info)));

            Initialize(initialData);
        }
        /// <summary>
        /// Function to create a <see cref="GorgonTexture2D"/> from a GDI+ bitmap.
        /// </summary>
        /// <param name="gdiBitmap">The GDI+ bitmap used to create the texture.</param>
        /// <param name="graphics">The graphics interface used to create the texture.</param>
        /// <param name="options">[Optional] Options used to further define the texture.</param>
        /// <returns>A new <see cref="GorgonTexture2D"/> containing the data from the <paramref name="gdiBitmap"/>.</returns>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="gdiBitmap"/>, or the <paramref name="graphics"/> parameter is <b>null</b>.</exception>
        /// <remarks>
        /// <para>
        /// A GDI+ bitmap is useful to holding image data in memory, but it cannot be sent to the GPU for use as a texture. This method allows an application to convert the GDI+ bitmap into a
        /// <see cref="GorgonTexture2D"/>.
        /// </para>
        /// <para>
        /// The resulting <see cref="GorgonTexture2D"/> will only contain a single mip level, and single array level. The only image type available will be 2D (i.e. image with a width and height). The GDI+
        /// bitmap should have a 32bpp rgba format, or a 24bpp rgb format or else an exception will be thrown.
        /// </para>
        /// <para>
        /// The optional <paramref name="options"/>parameter will define how Gorgon and shaders should handle the texture.  The <see cref="GorgonTextureLoadOptions"/> type contains the following:
        /// <list type="bullet">
        ///		<item>
        ///			<term>Binding</term>
        ///			<description>When defined, will indicate the <see cref="TextureBinding"/> that defines how the texture will be bound to the graphics pipeline. If it is omitted, then the binding will be
        ///         <see cref="TextureBinding.ShaderResource"/>.</description>
        ///		</item>
        ///		<item>
        ///			<term>Usage</term>
        ///			<description>When defined, will indicate the preferred usage for the texture. If it is omitted, then the usage will be set to <see cref="ResourceUsage.Default"/>.</description>
        ///		</item>
        ///		<item>
        ///			<term>Multisample info</term>
        ///			<description>When defined (i.e. not <b>null</b>), defines the multisampling to apply to the texture. If omitted, then the default is <see cref="GorgonMultisampleInfo.NoMultiSampling"/>.</description>
        ///		</item>
        ///		<item>
        ///		    <term>ConvertToPremultipliedAlpha</term>
        ///		    <description>Converts the image to premultiplied alpha before uploading the image data to the texture.</description>
        ///		</item>
        /// </list>
        /// </para>
        /// </remarks>
        public static GorgonTexture2D ToTexture2D(this Bitmap gdiBitmap,
                                                  GorgonGraphics graphics,
                                                  GorgonTexture2DLoadOptions options = null)
        {
            if (gdiBitmap == null)
            {
                throw new ArgumentNullException(nameof(gdiBitmap));
            }

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

            if (options == null)
            {
                options = _defaultLoadOptions;
            }

            if (string.IsNullOrEmpty(options.Name))
            {
                options.Name = GorgonGraphicsResource.GenerateName(GorgonTexture2D.NamePrefix);
            }

            using (IGorgonImage image = gdiBitmap.ToGorgonImage())
            {
                if (options.ConvertToPremultipliedAlpha)
                {
                    image.ConvertToPremultipliedAlpha();
                }

                return(new GorgonTexture2D(graphics, image, options));
            }
        }
示例#5
0
        /// <summary>
        /// Raises the <see cref="E:System.Windows.Forms.Form.Load" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            Cursor.Current = Cursors.WaitCursor;

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

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

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

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


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

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

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

                    // Draw to the window.
                    Draw();

                    // Render with a vsync interval of 2 (typically 30 FPS).
                    // We're not making an action game here.
                    _2D.Render(2);
                    return(true);
                };
            }
            catch (Exception ex)
            {
                GorgonDialogs.ErrorBox(this, ex);
                Gorgon.Quit();
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
示例#6
0
文件: Program.cs 项目: tmp7701/Gorgon
        /// <summary>
        /// Function to initialize the application.
        /// </summary>
        private static void Initialize()
        {
            // Create our form and center on the primary monitor.
            _mainForm = new formMain
            {
                ClientSize = new Size(640, 480),
            };

            _mainForm.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width / 2 - _mainForm.Width / 2,
                                           Screen.PrimaryScreen.WorkingArea.Height / 2 - _mainForm.Height / 2);


            // Create the main graphics interface for SM 4.0.
            // This is basically a Direct 3D 10 capable video device.  This is here to illustrate how to
            // force a feature level.
            Graphics = new GorgonGraphics(DeviceFeatureLevel.SM4);

            // Check to ensure that we can support the format required for our swap chain.
            // If a video device can't support this format, then the odds are good it won't render anything, and thus
            // this is here for illustration on how to determine if a format is OK for display purposes.
            if (!Graphics.VideoDevice.SupportsDisplayFormat(BufferFormat.R8G8B8A8_UIntNormal))
            {
                GorgonDialogs.ErrorBox(_mainForm, "We should not see this error.");
                return;
            }

            // Create a swap chain as our graphics output to the window.
            _swap = Graphics.Output.CreateSwapChain("Main", new GorgonSwapChainSettings
            {
                Window = _mainForm,                                                                                             // Assign to our form.
            });
        }
示例#7
0
 /// <summary>
 /// Function to retrieve the list of disposables for a given graphics instance.
 /// </summary>
 /// <param name="graphics">The graphics instance that owns the disposable resources.</param>
 /// <returns>An enumerable containing the list of resources for the graphics instance.</returns>
 public static IEnumerable <WeakReference <IDisposable> > GetDisposables(this GorgonGraphics graphics)
 {
     lock (_syncLock)
     {
         return(_disposables[graphics]);
     }
 }
示例#8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Cube"/> class.
        /// </summary>
        /// <param name="graphics">The graphics object used to create the buffers needed by this object.</param>
        /// <param name="inputLayout">The input layout describing how a vertex is laid out.</param>
        public Cube(GorgonGraphics graphics, GorgonInputLayout inputLayout)
        {
            CubeVertex[] vertices =
            {
                new CubeVertex(new DX.Vector3(-0.5f,  0.5f, -0.5f), new DX.Vector3(0,       0, 0)),
                new CubeVertex(new DX.Vector3(0.5f,   0.5f, -0.5f), new DX.Vector3(1.0f, 1.0f, 0)),
                new CubeVertex(new DX.Vector3(0.5f,  -0.5f, -0.5f), new DX.Vector3(0.0f, 1.0f, 0)),
                new CubeVertex(new DX.Vector3(-0.5f, -0.5f, -0.5f), new DX.Vector3(1.0f, 0.0f, 0)),

                new CubeVertex(new DX.Vector3(-0.5f,  0.5f,  0.5f), new DX.Vector3(0,       0, 0)),
                new CubeVertex(new DX.Vector3(0.5f,   0.5f,  0.5f), new DX.Vector3(1.0f, 1.0f, 0)),
                new CubeVertex(new DX.Vector3(0.5f,  -0.5f,  0.5f), new DX.Vector3(0.0f, 1.0f, 0)),
                new CubeVertex(new DX.Vector3(-0.5f, -0.5f,  0.5f), new DX.Vector3(1.0f, 0.0f, 0)),
            };

            ushort[] indices =
            {
                // Front face.
                0, 1, 2,
                2, 3, 0,
                // Back face.
                5, 4, 6,
                4, 7, 6,
                // Left face.
                4, 0, 3,
                3, 7, 4,
                // Right face.
                1, 5, 6,
                6, 2, 1,
                // Top face
                4, 5, 1,
                1, 0, 4,
                // Bottom face
                2, 6, 7,
                7, 3, 2
            };

            // Create our index buffer and vertex buffer and populate with our cube data.
            using (var indexPtr = GorgonNativeBuffer <ushort> .Pin(indices))
                using (var vertexPtr = GorgonNativeBuffer <CubeVertex> .Pin(vertices))
                {
                    IndexBuffer = new GorgonIndexBuffer(graphics,
                                                        new GorgonIndexBufferInfo("Volume Index Buffer")
                    {
                        Usage           = ResourceUsage.Immutable,
                        IndexCount      = indices.Length,
                        Use16BitIndices = true
                    },
                                                        indexPtr);

                    VertexBuffer = new GorgonVertexBufferBindings(inputLayout)
                    {
                        [0] = GorgonVertexBufferBinding.CreateVertexBuffer(graphics,
                                                                           vertices.Length,
                                                                           ResourceUsage.Immutable,
                                                                           initialData: vertexPtr,
                                                                           bufferName: "Volume Vertex Buffer")
                    };
                }
        }
示例#9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Triangle"/> class.
        /// </summary>
        /// <param name="graphics">The graphics interface.</param>
        /// <param name="point1">The 1st point in the triangle.</param>
        /// <param name="point2">The 2nd point in the triangle.</param>
        /// <param name="point3">The 3rd point in the triangle.</param>
        public Triangle(GorgonGraphics graphics, Vertex3D point1, Vertex3D point2, Vertex3D point3)
        {
            PrimitiveType = PrimitiveType.TriangleList;
            VertexCount   = 3;
            IndexCount    = 3;
            TriangleCount = 1;

            point1.Tangent = new Vector4(1.0f, 0, 0, 1.0f);
            point2.Tangent = new Vector4(1.0f, 0, 0, 1.0f);
            point3.Tangent = new Vector4(1.0f, 0, 0, 1.0f);

            VertexBuffer = graphics.Buffers.CreateVertexBuffer("TriVB",
                                                               new[]
            {
                point1,
                point2,
                point3
            }, BufferUsage.Immutable);

            IndexBuffer = graphics.Buffers.CreateIndexBuffer("TriIB",
                                                             new[]
            {
                0,
                1,
                2
            }, BufferUsage.Immutable);
        }
示例#10
0
        /// <summary>
        /// Function to dispose all IDisposable objects registered to the graphics interface.
        /// </summary>
        /// <param name="graphics">The graphics interface that holds all the IDisposable objects.</param>
        public static void DisposeAll(this GorgonGraphics graphics)
        {
            lock (_syncLock)
            {
                if ((!_disposables.TryGetValue(graphics, out List <WeakReference <IDisposable> > disposables)) ||
                    (disposables == null))
                {
                    return;
                }

                if (disposables.Count == 0)
                {
                    _disposables.Remove(graphics);
                    return;
                }

                while (disposables.Count > 0)
                {
                    if (!disposables[0].TryGetTarget(out IDisposable disposeRef))
                    {
                        disposables.RemoveAt(0);
                        continue;
                    }

                    disposeRef.Dispose();
                }

                disposables.Clear();
                _disposables.Remove(graphics);
            }
        }
示例#11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="WorldViewProjection"/> class.
        /// </summary>
        /// <param name="graphics">The graphics interface to use.</param>
        public WorldViewProjection(GorgonGraphics graphics)
        {
            Matrix dummy = Matrix.Identity;

            _projViewBuffer = graphics.Buffers.CreateConstantBuffer("WVPBuffer",
                                                                    new GorgonConstantBufferSettings
            {
                SizeInBytes = DirectAccess.SizeOf <ViewProjectionData>(),
                Usage       = BufferUsage.Default
            });

            _viewProj = new ViewProjectionData
            {
                Projection     = Matrix.Identity,
                View           = Matrix.Identity,
                ViewProjection = Matrix.Identity
            };

            _projViewBuffer.Update(ref _viewProj);

            _worldBuffer = graphics.Buffers.CreateConstantBuffer("WorldBuffer", ref dummy, BufferUsage.Default);

            _camData.CameraLookAt = new Vector3(0, 0, -1.0f);
            _camData.CameraUp     = new Vector3(0, 1, 0);
            _cameraBuffer         = graphics.Buffers.CreateConstantBuffer("CameraBuffer", ref _camData, BufferUsage.Default);

            graphics.Shaders.VertexShader.ConstantBuffers[0] = _projViewBuffer;
            graphics.Shaders.VertexShader.ConstantBuffers[1] = _worldBuffer;
            graphics.Shaders.PixelShader.ConstantBuffers[0]  = _cameraBuffer;
        }
        /// <summary>
        /// Function to create a <see cref="GorgonTexture1D"/> from a <see cref="GorgonImage"/>.
        /// </summary>
        /// <param name="image">The image used to create the texture.</param>
        /// <param name="graphics">The graphics interface used to create the texture.</param>
        /// <param name="options">[Optional] Options used to further define the texture.</param>
        /// <returns>A new <see cref="GorgonTexture1D"/> containing the data from the <paramref name="image"/>.</returns>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="image"/>, or the <paramref name="graphics"/> parameter is <b>null</b>.</exception>
        /// <remarks>
        /// <para>
        /// A <see cref="GorgonImage"/> is useful to holding image data in memory, but it cannot be sent to the GPU for use as a texture. This method allows an application to convert the
        /// <see cref="GorgonImage"/> into a <see cref="GorgonTexture1D"/>.
        /// </para>
        /// <para>
        /// If specified, the <paramref name="options"/>parameter will define how Gorgon and shaders should handle the texture.  The <see cref="GorgonTextureLoadOptions"/> type contains the following:
        /// <list type="bullet">
        ///		<item>
        ///			<term>Binding</term>
        ///			<description>When defined, will indicate the <see cref="TextureBinding"/> that defines how the texture will be bound to the graphics pipeline. If it is omitted, then the binding will be
        ///         <see cref="TextureBinding.ShaderResource"/>.</description>
        ///		</item>
        ///		<item>
        ///			<term>Usage</term>
        ///			<description>When defined, will indicate the preferred usage for the texture. If it is omitted, then the usage will be set to <see cref="ResourceUsage.Default"/>.</description>
        ///		</item>
        ///		<item>
        ///			<term>Multisample info</term>
        ///			<description>This is not available on 1D textures, and is ignored.</description>
        ///		</item>
        /// </list>
        /// </para>
        /// </remarks>
        public static GorgonTexture1D ToTexture1D(this IGorgonImage image,
                                                  GorgonGraphics graphics,
                                                  GorgonTextureLoadOptions options = null)
        {
            if (image == null)
            {
                throw new ArgumentNullException(nameof(image));
            }

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

            if (options == null)
            {
                options = _defaultLoadOptions;
            }

            if (string.IsNullOrEmpty(options.Name))
            {
                options.Name = GorgonGraphicsResource.GenerateName(GorgonTexture1D.NamePrefix);
            }

            return(new GorgonTexture1D(graphics, image, options));
        }
示例#13
0
        /// <summary>
        /// Function to initialize the example and prepare the required components.
        /// </summary>
        private static void Initialize()
        {
            // We will need to access the graphics device in order to use compute functionality, so we'll use the first usable device in the system.
            // Find out which devices we have installed in the system.
            IReadOnlyList <IGorgonVideoAdapterInfo> deviceList = GorgonGraphics.EnumerateAdapters();

            Console.WriteLine("Enumerating video devices...");

            IGorgonVideoAdapterInfo firstDevice = deviceList.FirstOrDefault(item => item.FeatureSet >= FeatureSet.Level_12_0);

            // If a device with a feature set of at least 12.0 not found, then we cannot run this example. The compute engine requires a minimum
            // of feature level 12.0 to run.
            if (firstDevice == null)
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("No Level 12.0 or better adapters found in the system. This example requires a FeatureLevel 12.0 or better adapter.");
                Console.ResetColor();
                return;
            }

            Console.WriteLine($"Using the '{firstDevice.Name}' video device.\n");

            // We have to create a graphics interface to allow the compute engine to communicate with the GPU.
            _graphics = new GorgonGraphics(firstDevice);

            // We will also need to compile a compute shader so we can actually perform the work.
            Console.WriteLine("Compiling the compute shader (SimpleCompute)...");
            _computeShader = GorgonShaderFactory.Compile <GorgonComputeShader>(_graphics, Resources.ComputeShader, "SimpleCompute");

            // Finally, the star of the show, the compute engine.
            Console.WriteLine("Creating compute engine...");
            _engine = new GorgonComputeEngine(_graphics);
        }
示例#14
0
        /// <summary>
        /// Function to set up the renderer.
        /// </summary>
        /// <param name="renderer">Renderer to use.</param>
        public void SetupRenderer(Gorgon2D renderer)
        {
            if (DesignMode)
            {
                return;
            }

            try
            {
                Gorgon.ApplicationIdleLoopMethod = null;

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

                if (renderer == null)
                {
                    return;
                }

                _renderer = renderer;
                _graphics = renderer.Graphics;

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

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

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

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

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

                _renderer.Target = _swapChain;

                Gorgon.ApplicationIdleLoopMethod = Idle;
            }
            finally
            {
                ValidateCommands();
            }
        }
示例#15
0
        /// <summary>
        /// Function to unregister a disposable object from a graphics interface.
        /// </summary>
        /// <param name="disposable">The disposable object to unregister.</param>
        /// <param name="graphics">The graphics object that the IDisposable belonged to.</param>
        public static void UnregisterDisposable(this IDisposable disposable, GorgonGraphics graphics)
        {
            if ((disposable == null) ||
                (graphics == null))
            {
                return;
            }

            lock (_syncLock)
            {
                if (!_disposables.TryGetValue(graphics, out List <WeakReference <IDisposable> > disposables))
                {
                    return;
                }

                if ((disposables == null) ||
                    (disposables.Count == 0))
                {
                    _disposables.Remove(graphics);
                    return;
                }

                disposables.RemoveAll(weakRef =>
                {
                    // Remove any dead references.
                    return(!weakRef.TryGetTarget(out IDisposable disposeRef) ? true : disposeRef == disposable);
                });
            }
        }
示例#16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Gorgon2DStateRecall"/> class.
        /// </summary>
        /// <param name="renderer">The renderer that is creating this object.</param>
        internal Gorgon2DStateRecall(Gorgon2D renderer)
        {
            Gorgon2D  = renderer;
            _graphics = renderer.Graphics;

            Save();
        }
示例#17
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BatchRenderer"/> class.
 /// </summary>
 /// <param name="graphics">The graphics interface that uses this renderer.</param>
 public BatchRenderer(GorgonGraphics graphics)
 {
     Graphics              = graphics;
     SpriteTransformer     = new SpriteTransformer();
     TextSpriteTransformer = new TextSpriteTransformer();
     CreateBuffers();
 }
示例#18
0
        /// <summary>
        /// Function to load a texture from a file.
        /// </summary>
        /// <param name="graphics">The graphics interface that will own the texture.</param>
        /// <param name="filePath">The path to the file.</param>
        /// <param name="codec">The codec that is used to decode the the data in the stream.</param>
        /// <param name="options">[Optional] Options used to further define the texture.</param>
        /// <returns>A new <see cref="GorgonTexture3DView"/></returns>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="graphics"/>, <paramref name="filePath"/>, or the <paramref name="codec"/> parameter is <b>null</b>.</exception>
        /// <exception cref="ArgumentEmptyException">Thrown when the <paramref name="filePath"/> parameter is empty.</exception>
        /// <remarks>
        /// <para>
        /// This will load an <see cref="IGorgonImage"/> from a file on disk and put it into a <see cref="GorgonTexture3D"/> object and return a <see cref="GorgonTexture3DView"/>.
        /// </para>
        /// <para>
        /// If specified, the <paramref name="options"/>parameter will define how Gorgon and shaders should handle the texture.  The <see cref="GorgonTextureLoadOptions"/> type contains the following:
        /// <list type="bullet">
        ///		<item>
        ///			<term>Binding</term>
        ///			<description>When defined, will indicate the <see cref="TextureBinding"/> that defines how the texture will be bound to the graphics pipeline. If it is omitted, then the binding will be
        ///         <see cref="TextureBinding.ShaderResource"/>.</description>
        ///		</item>
        ///		<item>
        ///			<term>Usage</term>
        ///			<description>When defined, will indicate the preferred usage for the texture. If it is omitted, then the usage will be set to <see cref="ResourceUsage.Default"/>.</description>
        ///		</item>
        ///		<item>
        ///			<term>Multisample info</term>
        ///			<description>When defined (i.e. not <b>null</b>), defines the multisampling to apply to the texture. If omitted, then the default is <see cref="GorgonMultisampleInfo.NoMultiSampling"/>.</description>
        ///		</item>
        /// </list>
        /// </para>
        /// <para>
        /// Since the <see cref="GorgonTexture3D"/> created by this method is linked to the <see cref="GorgonTexture3DView"/> returned, disposal of either one will dispose of the other on your behalf. If
        /// the user created a <see cref="GorgonTexture3DView"/> from the <see cref="GorgonTexture3D.GetShaderResourceView"/> method on the <see cref="GorgonTexture3D"/>, then it's assumed the user knows
        /// what they are doing and will handle the disposal of the texture and view on their own.
        /// </para>
        /// </remarks>
        public static GorgonTexture3DView FromFile(GorgonGraphics graphics, string filePath, IGorgonImageCodec codec, GorgonTextureLoadOptions options = null)
        {
            if (graphics == null)
            {
                throw new ArgumentNullException(nameof(graphics));
            }

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

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

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

            using (IGorgonImage image = codec.LoadFromFile(filePath))
            {
                GorgonTexture3D     texture = image.ToTexture3D(graphics, options);
                GorgonTexture3DView view    = texture.GetShaderResourceView();
                view.OwnsResource = true;
                return(view);
            }
        }
示例#19
0
        /// <summary>
        /// Function to clean up the renderer objects.
        /// </summary>
        private void CleanUpRenderer()
        {
            if (_renderer == null)
            {
                return;
            }

            if (_lastState != null)
            {
                _renderer.End2D(_lastState);
                _lastState = null;
            }

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

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

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

            _clipper  = null;
            _graphics = null;
        }
示例#20
0
        /// <summary>
        /// Function to create a vertex buffer and its binding.
        /// </summary>
        /// <typeparam name="T">The type of data representing a vertex, must be an unmanaged value type.</typeparam>
        /// <param name="graphics">The graphics interface that will create the buffer.</param>
        /// <param name="vertexCount">The total number vertices that the buffer can hold.</param>
        /// <param name="usage">[Optional] The intended usage for the buffer.</param>
        /// <param name="binding">[Optional] The binding options for the buffer.</param>
        /// <param name="initialData">[Optional] An initial set of vertex data to send to the buffer.</param>
        /// <param name="bindingIndex">[Optional] The index, in vertices, inside the buffer where binding is to begin.</param>
        /// <param name="bufferName">[Optional] A name for the buffer.</param>
        /// <returns>A new <see cref="GorgonVertexBufferBinding"/>.</returns>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="graphics"/> parameter is <b>null</b>.</exception>
        /// <remarks>
        /// <para>
        /// Use this to quickly create a vertex buffer and its binding based on a known vertex data type.
        /// </para>
        /// <para>
        /// Be aware that the <see cref="VertexBuffer"/> created by this method must be disposed manually after it is no longer of any use.
        /// </para>
        /// </remarks>
        /// <seealso cref="GorgonVertexBuffer"/>
        public static GorgonVertexBufferBinding CreateVertexBuffer <T>(GorgonGraphics graphics,
                                                                       int vertexCount,
                                                                       ResourceUsage usage = ResourceUsage.Default,
                                                                       VertexIndexBufferBinding binding   = VertexIndexBufferBinding.None,
                                                                       GorgonNativeBuffer <T> initialData = null,
                                                                       int bindingIndex  = 0,
                                                                       string bufferName = null)
            where T : unmanaged
        {
            if (graphics == null)
            {
                throw new ArgumentNullException(nameof(graphics));
            }

            int vertexSize = Unsafe.SizeOf <T>();
            var buffer     = new GorgonVertexBuffer(graphics,
                                                    new GorgonVertexBufferInfo(bufferName)
            {
                SizeInBytes = vertexCount * vertexSize,
                Binding     = binding,
                Usage       = usage
            },
                                                    initialData?.Cast <byte>());


            return(new GorgonVertexBufferBinding(buffer, vertexSize, bindingIndex * vertexSize));
        }
示例#21
0
        /// <summary>Initializes a new instance of the <see cref="T:Gorgon.Editor.SpriteEditor.SpriteVertexOffsetRenderer"/> class.</summary>
        /// <param name="sprite">The sprite view model.</param>
        /// <param name="graphics">The graphics interface for the application.</param>
        /// <param name="swapChain">The swap chain for the render area.</param>
        /// <param name="renderer">The 2D renderer for the application.</param>
        /// <param name="vertexEditor">The editor used to modify the sprite vertices.</param>
        /// <param name="initialZoom">The initial zoom scale value.</param>
        public SpriteVertexOffsetRenderer(ISpriteContent sprite, GorgonGraphics graphics, GorgonSwapChain swapChain, Gorgon2D renderer, ISpriteVertexEditService vertexEditor, float initialZoom)
            : base(sprite, graphics, swapChain, renderer, initialZoom)
        {
            InitialTextureAlpha           = 0;
            _vertexEditor                 = vertexEditor;
            _vertexEditor.RectToClient    = r => ToClient(r).Truncate();
            _vertexEditor.PointToClient   = p => ToClient(p).Truncate();
            _vertexEditor.PointFromClient = p => FromClient(p).Truncate();

            _workingSprite = new GorgonSprite
            {
                Texture           = sprite.Texture,
                TextureRegion     = sprite.TextureCoordinates,
                TextureArrayIndex = TextureArrayIndex,
                Size   = sprite.Size,
                Scale  = DX.Vector2.One,
                Anchor = DX.Vector2.Zero,
                Color  = GorgonColor.White,
                Depth  = 0.1f
            };

            UpdateWorkingSprite();

            _vertexEditor.VerticesChanged     += VertexEditor_VerticesChanged;
            _vertexEditor.KeyboardIconClicked += VertexEditor_KeyboardIconClicked;
            _vertexEditor.VertexSelected      += VertexEditor_VertexSelected;

            _camera = new Gorgon2DPerspectiveCamera(renderer, new DX.Size2F(swapChain.Width, swapChain.Height));
        }
示例#22
0
        /// <summary>
        /// Function to locate a graphics resource by its name.
        /// </summary>
        /// <typeparam name="T">The type of graphics resource to look up. Must inherit from <see cref="GorgonGraphicsResource"/>.</typeparam>
        /// <param name="graphics">The graphics instance that was used to create the resource.</param>
        /// <param name="name">The name of the resource to find.</param>
        /// <param name="filterType">[Optional] The type of filter to apply.</param>
        /// <param name="comparisonType">[Optional] The type of string comparison to use for name comparison.</param>
        /// <returns>An enumerable containing the resources with names that match the filter type.</returns>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="graphics"/> parameter is <b>null</b>.</exception>
        /// <remarks>
        /// <para>
        /// Each instance of the <seealso cref="GorgonGraphics"/> keeps a weak registration of each objected inheriting from <see cref="GorgonGraphicsResource"/> that was created during the lifetime of the
        /// application. Using this registration an application can look up any previously created resource (assuming it's not been collected, or disposed) should it be necessary.
        /// </para>
        /// <para>
        /// <note type="important">
        /// Resource names are not required to be unique. Therefore, searching for the name may result in multiple items being returned in the enumerable.
        /// </note>
        /// </para>
        /// </remarks>
        /// <seealso cref="GorgonGraphicsResource"/>
        public static IEnumerable <T> LocateResourcesByName <T>(this GorgonGraphics graphics,
                                                                string name,
                                                                LocateFilterType filterType     = LocateFilterType.Equal,
                                                                StringComparison comparisonType = StringComparison.CurrentCultureIgnoreCase)
            where T : GorgonGraphicsResource
        {
            if (graphics == null)
            {
                throw new ArgumentNullException(nameof(graphics));
            }

            if (string.IsNullOrWhiteSpace(name))
            {
                return(Enumerable.Empty <T>());
            }

            return(graphics.GetDisposables()
                   .Select(item =>
            {
                // If the object has been collected/disposed, then do nothing.
                if ((!item.TryGetTarget(out IDisposable disposable)) ||
                    (!(disposable is T resource)) ||
                    (resource.IsDisposed))
                {
                    return null;
                }

                return !NameComparison(name, resource.Name, filterType, comparisonType) ? null : resource;
            })
                   .Where(item => item != null));
        }
示例#23
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;
        }
示例#24
0
        /// <summary>
        /// Function to create a constant buffer and an associated view, initialized with the specified set of values.
        /// </summary>
        /// <typeparam name="T">The type of data to store in the buffer. Must be an unmanaged value type.</typeparam>
        /// <param name="graphics">The graphics interface to use when creating the target.</param>
        /// <param name="value">The array of values to store in the buffer.</param>
        /// <param name="name">[Optional] The name of the buffer.</param>
        /// <param name="usage">[Optional] The intended usage of the buffer.</param>
        /// <param name="firstElement">[Optional] The index of the first constant within the buffer to view.</param>
        /// <param name="elementCount">[Optional] The number of constants in the buffer to view.</param>
        /// <returns>A new <see cref="GorgonConstantBufferView"/>.</returns>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="graphics"/> parameter is <b>null</b>.</exception>
        /// <remarks>
        /// <para>
        /// This is a convenience method that will create a <see cref="GorgonConstantBuffer"/> and a <see cref="GorgonConstantBufferView"/> as a single object that can be used to pass constant information
        /// to a shader. The buffer created will match the size of the type specified by <typeparamref name="T"/> (adjusted to the nearest 16 bytes), multiplied by the length of the array and it will also
        /// upload the <paramref name="value"/> array specified into the buffer.
        /// </para>
        /// <para>
        /// Since the <see cref="GorgonConstantBuffer"/> created by this method is linked to the <see cref="GorgonConstantBufferView"/> returned, disposal of either one will dispose of the other on your
        /// behalf. If the user created a <see cref="GorgonConstantBufferView"/> from the <see cref="GorgonConstantBuffer.GetView"/> method on the <see cref="GorgonConstantBuffer"/>, then it's assumed the
        /// user knows what they are doing and will handle the disposal of the buffer and view on their own.
        /// </para>
        /// <para>
        /// The <paramref name="firstElement"/> parameter must be between 0 and <seealso cref="TotalElementCount"/> - 1.  If it is not it will be constrained to those values to ensure there is no out of
        /// bounds access to the buffer.
        /// </para>
        /// <para>
        /// If the <paramref name="elementCount"/> parameter is omitted (or less than 1), then the remainder of the buffer is mapped to the view up to 256 elements (4096 constants, or 65536 bytes). If it
        /// is provided, then the number of elements will be mapped to the view, up to a maximum of 256 elements.  If the value exceeds 256, then it will be constrained to 256.
        /// </para>
        /// <para>
        /// The <paramref name="usage"/> parameter defines where the GPU should place the resource for best performance.
        /// </para>
        /// <para>
        /// A constant buffer constant is a single float4 value (4 floating point values).
        /// </para>
        /// </remarks>
        /// <seealso cref="GorgonConstantBuffer"/>
        public static GorgonConstantBufferView CreateConstantBuffer <T>(GorgonGraphics graphics, T[] value, string name = null, ResourceUsage usage = ResourceUsage.Default, int firstElement = 0, int elementCount = 0)
            where T : unmanaged
        {
            if (graphics == null)
            {
                throw new ArgumentNullException(nameof(graphics));
            }

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

            var buffer = new GorgonConstantBuffer(graphics, new GorgonConstantBufferInfo(name)
            {
                Usage       = usage,
                SizeInBytes = Unsafe.SizeOf <T>() * value.Length
            });

            buffer.SetData(value);
            GorgonConstantBufferView view = buffer.GetView(firstElement, elementCount);

            view._ownsBuffer = true;
            return(view);
        }
示例#25
0
文件: Text.cs 项目: tmp7701/Gorgon
 public void TestInitialize()
 {
     _form     = new TestForm();
     _graphics = new GorgonGraphics();
     _renderer = _graphics.Output.Create2DRenderer(_form.panelDisplay);
     _screen   = (GorgonSwapChain)_renderer.DefaultTarget;
 }
示例#26
0
 /// <summary>Initializes a new instance of the <see cref="ExtractorService"/> class.</summary>
 /// <param name="renderer">The application 2D renderer.</param>
 /// <param name="fileManager">The file manager for the project files.</param>
 /// <param name="defaultCodec">The default sprite codec.</param>
 public ExtractorService(Gorgon2D renderer, IContentFileManager fileManager, IGorgonSpriteCodec defaultCodec)
 {
     _renderer     = renderer;
     _graphics     = renderer.Graphics;
     _fileManager  = fileManager;
     _defaultCodec = defaultCodec;
 }
示例#27
0
        /// <summary>Initializes a new instance of the <see cref="PlanetLayer"/> class.</summary>
        /// <param name="graphics">The graphics interface for the application.</param>
        /// <param name="resources">The resources for the application.</param>
        public PlanetLayer(GorgonGraphics graphics, ResourceManagement resources)
        {
            _graphics  = graphics;
            _resources = resources;

            _stateBuilder    = new GorgonPipelineStateBuilder(graphics);
            _drawCallBuilder = new GorgonDrawIndexCallBuilder();
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="GorgonPipelineStateBuilder"/> class.
 /// </summary>
 /// <param name="graphics">The graphics object that will build the pipeline state.</param>
 public GorgonPipelineStateBuilder(GorgonGraphics graphics)
 {
     Graphics = graphics ?? throw new ArgumentNullException(nameof(graphics));
     _workState.RwBlendStates[0]  = GorgonBlendState.Default;
     _workState.RasterState       = GorgonRasterState.Default;
     _workState.DepthStencilState = GorgonDepthStencilState.Default;
     _workState.PrimitiveType     = Core.PrimitiveType.TriangleList;
 }
        /// <summary>Initializes a new instance of the <see cref="ResourceManagement"/> class.</summary>
        /// <param name="renderer">The renderer for the application.</param>
        /// <param name="plugIns>The plugin service used to load file system providers.</param>
        public ResourceManagement(Gorgon2D renderer, IGorgonPlugInService plugIns)
        {
            _renderer = renderer;
            _graphics = renderer.Graphics;
            _plugIns  = plugIns;

            _spriteCodec = new GorgonV3SpriteBinaryCodec(renderer);
        }
示例#30
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CameraController"/> class.
 /// </summary>
 /// <param name="graphics">The graphics interface used for the camera buffer data.</param>
 public CameraController(GorgonGraphics graphics)
 {
     Graphics      = graphics;
     _cameraBuffer = GorgonConstantBufferView.CreateConstantBuffer(graphics,
                                                                   ref _viewProjectionMatrix,
                                                                   "Gorgon 2D Camera Constant Buffer",
                                                                   ResourceUsage.Dynamic);
 }