<commit_before>﻿// Copyright (c) 2010-2011 SharpDX - <NAME>
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Globalization;
using System.Runtime.InteropServices;

namespace SharpDX.Direct3D11
{
    public partial class DeviceContext
    {
        /// <summary>
        ///   Constructs a new deferred context <see cref = "T:SharpDX.Direct3D11.DeviceContext" />.
        /// </summary>
        /// <param name = "device">The device with which to associate the state object.</param>
        /// <returns>The newly created object.</returns>
        public DeviceContext(Device device)
            : base(IntPtr.Zero)
        {
            device.CreateDeferredContext(0, this);
        }

        /// <summary>
        ///   Create a command list and record graphics commands into it.
        /// </summary>
        /// <param name = "restoreState">A flag indicating whether the immediate context state is saved (prior) and restored (after) the execution of a command list.</param>
        /// <returns>The created command list containing the queued rendering commands.</returns>
        public CommandList FinishCommandList(bool restoreState)
        {
            CommandList temp;
            FinishCommandListInternal(restoreState, out temp);
            return temp;
        }

        /// <summary>
        ///   Gets data from the GPU asynchronously.
        /// </summary>
        /// <param name = "data">The asynchronous data provider.</param>
        /// <returns>The data retrieved from the GPU.</returns>
        public DataStream GetData(Asynchronous data)
        {
            return GetData(data, AsynchronousFlags.None);
        }

        /// <summary>
        ///   Gets data from the GPU asynchronously.
        /// </summary>
        /// <param name = "data">The asynchronous data provider.</param>
        /// <returns>The data retrieved from the GPU.</returns>
        public T GetData<T>(Asynchronous data) where T : struct
        {
            return GetData<T>(data, AsynchronousFlags.None);
        }

        /// <summary>
        ///   Gets data from the GPU asynchronously.
        /// </summary>
        /// <param name = "data">The asynchronous data provider.</param>
        /// <param name = "flags">Flags specifying how the command should operate.</param>
        /// <returns>The data retrieved from the GPU.</returns>
        public DataStream GetData(Asynchronous data, AsynchronousFlags flags)
        {
            DataStream result = new DataStream(data.DataSize, true, true);
            GetDataInternal(data, result.DataPointer, (int) result.Length, flags);
            return result;
        }

        /// <summary>
        ///   Gets data from the GPU asynchronously.
        /// </summary>
        /// <param name = "data">The asynchronous data provider.</param>
        /// <param name = "flags">Flags specifying how the command should operate.</param>
        /// <returns>The data retrieved from the GPU.</returns>
        public T GetData<T>(Asynchronous data, AsynchronousFlags flags) where T : struct
        {
            unsafe
            {
                int size = Marshal.SizeOf(typeof (T));
                // TODO, verify if stackalloc is a good place to store async data
                byte* pBuffer = stackalloc byte[size];
                var stream = new DataStream((IntPtr)pBuffer, size, true, true);

                GetDataInternal(data, stream.DataPointer, size, flags);

                return stream.Read<T>();
            }
        }

        /// <summary>	
        /// Copy the entire contents of the source resource to the destination resource using the GPU. 	
        /// </summary>	
        /// <remarks>	
        /// This method is unusual in that it causes the GPU to perform the copy operation (similar to a memcpy by the CPU). As a result, it has a few restrictions designed for improving performance. For instance, the source and destination resources:  Must be different resources. Must be the same type. Must have identical dimensions (including width, height, depth, and size as appropriate). Will only be copied. CopyResource does not support any stretch, color key, blend, or format conversions. Must have compatible DXGI formats, which means the formats must be identical or at least from the same type group. For example, a DXGI_FORMAT_R32G32B32_FLOAT texture can be copied to an DXGI_FORMAT_R32G32B32_UINT texture since both of these formats are in the DXGI_FORMAT_R32G32B32_TYPELESS group. Might not be currently mapped.  You cannot use an {{Immutable}} resource as a destination. You can use a   {{depth-stencil}} resource as either a source or a destination.  Resources created with multisampling capability (see <see cref="SharpDX.DXGI.SampleDescription"/>) can be used as source and destination only if both source and destination have identical multisampled count and quality. If source and destination differ in multisampled count and quality or if one is multisampled and the other is not multisampled the call to ID3D11DeviceContext::CopyResource fails. The method is an asynchronous call which may be added to the command-buffer queue. This attempts to remove pipeline stalls that may occur when copying data.  An application that only needs to copy a portion of the data in a resource should use <see cref="SharpDX.Direct3D11.DeviceContext.CopySubresourceRegion_"/> instead. 	
        /// </remarks>	
        /// <param name="source">A reference to the source resource (see <see cref="SharpDX.Direct3D11.Resource"/>). </param>
        /// <param name="destination">A reference to the destination resource (see <see cref="SharpDX.Direct3D11.Resource"/>). </param>
        /// <unmanaged>void ID3D11DeviceContext::CopyResource([In] ID3D11Resource* pDstResource,[In] ID3D11Resource* pSrcResource)</unmanaged>
        public void CopyResource(Resource source, Resource destination)
        {
            CopyResource_(destination, source);
        }

        /// <summary>	
        /// Copy a region from a source resource to a destination resource.	
        /// </summary>	
        /// <remarks>	
        /// The source box must be within the size of the source resource. The destination offsets, (x, y, and z) allow the source box to be offset when writing into the destination resource; however, the dimensions of the source box and the offsets must be within the size of the resource. If the resources are buffers, all coordinates are in bytes; if the resources are textures, all coordinates are in texels. {{D3D11CalcSubresource}} is a helper function for calculating subresource indexes. CopySubresourceRegion performs the copy on the GPU (similar to a memcpy by the CPU). As a consequence, the source and destination resources:  Must be different subresources (although they can be from the same resource). Must be the same type. Must have compatible DXGI formats (identical or from the same type group). For example, a DXGI_FORMAT_R32G32B32_FLOAT texture can be copied to an DXGI_FORMAT_R32G32B32_UINT texture since both of these formats are in the DXGI_FORMAT_R32G32B32_TYPELESS group. May not be currently mapped.  CopySubresourceRegion only supports copy; it does not support any stretch, color key, blend, or format conversions. An application that needs to copy an entire resource should use <see cref="SharpDX.Direct3D11.DeviceContext.CopyResource_"/> instead. CopySubresourceRegion is an asynchronous call which may be added to the command-buffer queue, this attempts to remove pipeline stalls that may occur when copying data. See performance considerations for more details. Note??If you use CopySubresourceRegion with a depth-stencil buffer or a multisampled resource, you must copy the whole subresource. In this situation, you must pass 0 to the DstX, DstY, and DstZ parameters and NULL to the pSrcBox parameter. In addition, source and destination resources, which are represented by the pSrcResource and pDstResource parameters, should have identical sample count values. Example The following code snippet copies a box (located at (120,100),(200,220)) from a source texture into a reqion (10,20),(90,140) in a destination texture. 	
        /// <code> D3D11_BOX sourceRegion;	<commit_msg>[Direct3D11] Add IsAvailableData for Begin/End Query statistics. Add new GetData method.<commit_after>﻿// Copyright (c) 2010-2011 SharpDX - <NAME>
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Globalization;
using System.Runtime.InteropServices;

namespace SharpDX.Direct3D11
{
    public partial class DeviceContext
    {
        /// <summary>
        ///   Constructs a new deferred context <see cref = "T:SharpDX.Direct3D11.DeviceContext" />.
        /// </summary>
        /// <param name = "device">The device with which to associate the state object.</param>
        /// <returns>The newly created object.</returns>
        public DeviceContext(Device device)
            : base(IntPtr.Zero)
        {
            device.CreateDeferredContext(0, this);
        }

        /// <summary>
        ///   Create a command list and record graphics commands into it.
        /// </summary>
        /// <param name = "restoreState">A flag indicating whether the immediate context state is saved (prior) and restored (after) the execution of a command list.</param>
        /// <returns>The created command list containing the queued rendering commands.</returns>
        public CommandList FinishCommandList(bool restoreState)
        {
            CommandList temp;
            FinishCommandListInternal(restoreState, out temp);
            return temp;
        }

        /// <summary>
        /// Determines whether asynhronous query data is available.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <returns>
        ///   <c>true</c> if asynhronous query data is available; otherwise, <c>false</c>.
        /// </returns>
        /// <unmanaged>HRESULT ID3D11DeviceContext::GetData([In] ID3D11Asynchronous* pAsync,[Out, Buffer, Optional] void* pData,[In] unsigned int DataSize,[In] D3D11_ASYNC_GETDATA_FLAG GetDataFlags)</unmanaged>
        public bool IsDataAvailable(Asynchronous data)
        {
            return IsDataAvailable( data, AsynchronousFlags.None );
        }

        /// <summary>
        /// Determines whether asynhronous query data is available.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <returns>
        ///   <c>true</c> if asynhronous query data is available; otherwise, <c>false</c>.
        /// </returns>
        /// <unmanaged>HRESULT ID3D11DeviceContext::GetData([In] ID3D11Asynchronous* pAsync,[Out, Buffer, Optional] void* pData,[In] unsigned int DataSize,[In] D3D11_ASYNC_GETDATA_FLAG GetDataFlags)</unmanaged>
        public bool IsDataAvailable(Asynchronous data, AsynchronousFlags flags)
        {
            return GetDataInternal(data, IntPtr.Zero, 0, flags) == Result.Ok;
        }

        /// <summary>
        ///   Gets data from the GPU asynchronously.
        /// </summary>
        /// <param name = "data">The asynchronous data provider.</param>
        /// <returns>The data retrieved from the GPU.</returns>
        public DataStream GetData(Asynchronous data)
        {
            return GetData(data, AsynchronousFlags.None);
        }

        /// <summary>
        ///   Gets data from the GPU asynchronously.
        /// </summary>
        /// <param name = "data">The asynchronous data provider.</param>
        /// <returns>The data retrieved from the GPU.</returns>
        public T GetData<T>(Asynchronous data) where T : struct
        {
            return GetData<T>(data, AsynchronousFlags.None);
        }

        /// <summary>
        /// Gets data from the GPU asynchronously.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data">The asynchronous data provider.</param>
        /// <param name="result">The data retrieved from the GPU.</param>
        /// <returns>
        /// True if result contains valid data, false otherwise.
        /// </returns>
        public bool GetData<T>(Asynchronous data, out T result) where T : struct
        {
            return GetData(data, AsynchronousFlags.None, out result);
        }

        /// <summary>
        ///   Gets data from the GPU asynchronously.
        /// </summary>
        /// <param name = "data">The asynchronous data provider.</param>
        /// <param name = "flags">Flags specifying how the command should operate.</param>
        /// <returns>The data retrieved from the GPU.</returns>
        public DataStream GetData(Asynchronous data, AsynchronousFlags flags)
        {
            var result = new DataStream(data.DataSize, true, true);
            GetDataInternal(data, result.DataPointer, (int) result.Length, flags);
            return result;
        }

        /// <summary>
        ///   Gets data from the GPU asynchronously.
        /// </summary>
        /// <param name = "data">The asynchronous data provider.</param>
        /// <param name = "flags">Flags specifying how the command should operate.</param>
        /// <returns>The data retrieved from the GPU.</returns>
        public T GetData<T>(Asynchronous data, AsynchronousFlags flags) where T : struct
        {
            T result;
            GetData<T>(data, flags, out result);
            return result;
        }

        /// <summary>
        /// Gets data from the GPU asynchronously.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data">The asynchronous data provider.</param>
        /// <param name="flags">Flags specifying how the command should operate.</param>
        /// <param name="result">The data retrieved from the GPU.</param>
        /// <returns>
        /// True if result contains valid data, false otherwise.
        /// </returns>
        public bool GetData<T>(Asynchronous data, AsynchronousFlags flags, out T result) where T : struct
        {
            unsafe
            {
                result = default(T);
                return GetDataInternal(data, (IntPtr)Interop.Fixed(ref result), Utilities.SizeOf<T>(), flags) == Result.Ok;
            }
        }


        /// <summary>	
        /// Copy the entire contents of the source resource to the destination resource using the GPU. 	
        /// </summary>	
        /// <remarks>	
        /// This method is unusual in that it causes the GPU to perform the copy operation (similar to a memcpy by the CPU). As a result, it has a few restrictions designed for improving performance. For instance, the source and destination resources:  Must be different resources. Must be the same type. Must have identical dimensions (including width, height, depth, and size as appropriate). Will only be copied. CopyResource does not support any stretch, color key, blend, or format conversions. Must have compatible DXGI formats, which means the formats must be identical or at least from the same type group. For example, a DXGI_FORMAT_R32G32B32_FLOAT texture can be copied to an DXGI_FORMAT_R32G32B32_UINT texture since both of these formats are in the DXGI_FORMAT_R32G32B32_TYPELESS group. Might not be currently mapped.  You cannot use an {{Immutable}} resource as a destination. You can use a   {{depth-stencil}} resource as either a source or a destination.  Resources created with multisampling capability (see <see cref="SharpDX.DXGI.SampleDescription"/>) can be used as source and destination only if both source and destination have identical multisampled count and quality. If source and destination differ in multisampled count and quality or if one is multisampled and the other is not multisampled the call to ID3D11DeviceContext::CopyResource fails. The method is an asynchronous call which may be added to the command-buffer queue. This attempts to remove pipeline stalls that may occur when copying data.  An application that only needs to copy a portion of the data in a resource should use <see cref="SharpDX.Direct3D11.DeviceContext.CopySubresourceRegion_"/> instead. 	
        /// </remarks>	
        /// <param name="source">A reference to the source resource (see <see cref="SharpDX.Direct3D11.Resource"/>). </param>
        /// <param name="destination">A reference to the destination resource (see <see cref="SharpDX.Direct3D11.Resource"/>). </param>
        /// <unmanaged>void ID3D11DeviceContext::CopyResource([In] ID3D11Resource* pDstResource,[In] ID3D11Resource* pSrcResource)</unmanaged>
        public void CopyResource(Resource source, Resource destination)
        {
            CopyResource_(destination, source);
        }

        /// <summary>	
        /// Copy a region from a source resource to a destination resource.	
        /// </summary>	
        /// <remarks>	
        /// The source box must be within the size of the source resource. The destination offsets, (x, y, and z) allow the source box to be offset when writing into the destination resource; however, the dimensions of the source box and the offsets must be within the size of the resource. If the resources are buffers, all coordinates are in bytes; if the resources are textures, all coordinates are in texels. {{D3D11CalcSubresource}} is a helper function for calculating subresource indexes. CopySubresourceRegion performs the copy on the GPU (similar to a memcpy by the CPU). As a consequence, the source and destination resources:  Must be different subresources (although they can be from the same resource). Must be the same type. Must have compatible DXGI formats (identical or from the same type group). For example, a DXGI_FORMAT_R32G32B32_FLOAT texture can be copied to an DXGI_FORMAT_R32G32B32_UINT texture since both of these formats are in the DXGI_FORMAT_R32G32B32_TYPELESS group. May not be currently mapped.  CopySubresourceRegion only supports copy; it does not support any stretch, color key, blend, or format conversions. An application that needs to copy an entire resource should use <see cref="SharpDX.Direct3D11.DeviceContext.CopyResource_"/> instead. CopySubresourceRegion is an asynchronous call which may be added to the command-buffer queue, this attempts to remove pipeline stalls that may occur when copying data. See performance considerations for more details. Note??If you use CopySubresourceRegion with a depth-stencil buffer or a multisampled resource, you must copy the whole subresource. In this situation, you must pass 0 to the DstX, DstY, and DstZ parameters and NULL to the pSrcBox parameter. In addition, source and destination resources, which are represented by the pSrcResource and pDstResource parameters, should have identical sample count values. Example The following code snippet copies a box (located at (120,100),(200,220)) from a source texture into a reqion (10,20),(90,140) in a destination texture. 	
        /// <code> D3D11_BOX sourceRegion;	
{'fraction_non_alphanumeric': 0.08675559790376369, 'fraction_numerical': 0.010862315388280133, 'mean_word_length': 2.8586397058823527, 'pattern_counts': {'":': 0, '<': 182, '<?xml version=': 0, '>': 182, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4811910', 'n_tokens_mistral': 5415, 'n_tokens_neox': 5099, 'n_words': 2307}