Beispiel #1
1
        /// <summary>
        ///   Initializes a new instance of the <see cref = "T:SharpDX.Direct3D10.Texture2D" /> class.
        /// </summary>
        /// <param name = "device">The device with which to associate the texture.</param>
        /// <param name = "description">The description of the texture.</param>
        /// <param name = "data">An array of initial texture data for each subresource.</param>
        public Texture2D(Device device, Texture2DDescription description, DataRectangle[] data)
            : base(IntPtr.Zero)
        {
            DataBox[] subResourceDatas = null;

            if (data != null)
            {
                subResourceDatas = new DataBox[data.Length];
                for (int i = 0; i < subResourceDatas.Length; i++)
                {
                    subResourceDatas[i].DataPointer = data[i].DataPointer;
                    subResourceDatas[i].RowPitch = data[i].Pitch;
                }
            }
            device.CreateTexture2D(ref description, subResourceDatas, this);
        }
Beispiel #2
0
        public ShaderResourceView ToTexture3D(Device graphicsDevice, Format format)
        {
            int sizeInBytes = sizeof(float) * width * height * depth;

            DataStream stream = new DataStream(sizeInBytes, true, true);
            for (int x = 0; x < width; x++)
                for (int y = 0; y < height; y++)
                    for (int z = 0; z < depth; z++)
                        stream.Write(values[x, y, z]);
            stream.Position = 0;

            DataBox dataBox = new DataBox(sizeof(float) * width, sizeof(float) * width * height, stream);
            Texture3DDescription description = new Texture3DDescription()
            {
                BindFlags = BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                Depth = depth,
                Format = format,
                Height = height,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                Usage = ResourceUsage.Default,
                Width = width
            };
            Texture3D texture = new Texture3D(graphicsDevice, description, dataBox);

            stream.Dispose();

            return new ShaderResourceView(graphicsDevice, texture);
        }
        protected internal Texture3D(GraphicsDevice device, TextureDescription description3D, DataBox[] dataBoxes = null) : base(device, description3D, ViewType.Full, 0, 0)
        {
#if SILICONSTUDIO_XENKO_GRAPHICS_API_OPENGLES
            throw new NotImplementedException();
#else
            Target = TextureTarget.Texture3D;
#endif
        }
Beispiel #4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MappedResource"/> struct.
 /// </summary>
 /// <param name="resource">The resource.</param>
 /// <param name="subResourceIndex">Index of the sub resource.</param>
 /// <param name="dataBox">The data box.</param>
 /// <param name="offsetInBytes">Offset since the beginning of the buffer.</param>
 /// <param name="sizeInBytes">Size of the mapped resource.</param>
 internal MappedResource(GraphicsResource resource, int subResourceIndex, DataBox dataBox, int offsetInBytes, int sizeInBytes)
 {
     Resource = resource;
     SubResourceIndex = subResourceIndex;
     DataBox = dataBox;
     OffsetInBytes = offsetInBytes;
     SizeInBytes = sizeInBytes;
 }
Beispiel #5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MappedResource"/> struct.
 /// </summary>
 /// <param name="resource">The resource.</param>
 /// <param name="subResourceIndex">Index of the sub resource.</param>
 /// <param name="dataBox">The data box.</param>
 internal MappedResource(GraphicsResource resource, int subResourceIndex, DataBox dataBox)
 {
     Resource = resource;
     SubResourceIndex = subResourceIndex;
     DataBox = dataBox;
     OffsetInBytes = 0;
     SizeInBytes = -1;
 }
Beispiel #6
0
        /// <summary>
        ///   Initializes a new instance of the <see cref = "T:SharpDX.Direct3D10.Texture1D" /> class.
        /// </summary>
        /// <param name = "device">The device with which to associate the texture.</param>
        /// <param name = "description">The description of the texture.</param>
        /// <param name = "data">An array of initial texture data for each subresource.</param>
        public Texture1D(Device device, Texture1DDescription description, DataStream[] data)
            : base(IntPtr.Zero)
        {
            var subResourceDatas = new DataBox[data.Length];
            for (int i = 0; i < subResourceDatas.Length; i++)
                subResourceDatas[i].DataPointer = data[i].DataPointer;

            device.CreateTexture1D(ref description, subResourceDatas, this);
        }
Beispiel #7
0
        /// <summary>
        ///   Initializes a new instance of the <see cref = "T:SharpDX.Direct3D10.Texture1D" /> class.
        /// </summary>
        /// <param name = "device">The device with which to associate the texture.</param>
        /// <param name = "description">The description of the texture.</param>
        /// <param name = "data">An array of initial texture data for each subresource.</param>
        public Texture1D(Device device, Texture1DDescription description, DataStream[] data)
            : base(IntPtr.Zero)
        {
            System.Diagnostics.Debug.Assert(data != null);

            var subResourceDatas = new DataBox[data.Length];
            for (int i = 0; i < subResourceDatas.Length; i++)
                subResourceDatas[i].DataPointer = data[i].DataPointer;

            device.CreateTexture1D(ref description, subResourceDatas, this);
        }
Beispiel #8
0
        /// <summary>
        ///   Initializes a new instance of the <see cref = "T:SharpDX.Direct3D11.Texture1D" /> class.
        /// </summary>
        /// <param name = "device">The device with which to associate the texture.</param>
        /// <param name = "description">The description of the texture.</param>
        /// <param name = "data">An array of initial texture data for each subresource.</param>
        /// <msdn-id>ff476520</msdn-id>	
        /// <unmanaged>HRESULT ID3D11Device::CreateTexture1D([In] const D3D11_TEXTURE1D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture1D** ppTexture1D)</unmanaged>	
        /// <unmanaged-short>ID3D11Device::CreateTexture1D</unmanaged-short>	
        public Texture1D(Device device, Texture1DDescription description, params IntPtr[] data)
            : base(IntPtr.Zero)
        {
            DataBox[] subResourceDatas = null;
            if (data != null && data.Length > 0)
            {
                subResourceDatas = new DataBox[data.Length];
                for (int i = 0; i < subResourceDatas.Length; i++)
                    subResourceDatas[i].DataPointer = data[i];

            }
            device.CreateTexture1D(ref description, subResourceDatas, this);
        }
Beispiel #9
0
        public void DataBoxGetTagsByNameMulti()
        {
            //Arrange
            var data = new DataBox("test.dat");
            var tag  = data.NewTag("tag");
            var tag2 = data.NewTag("tag", "subTag");

            //Act
            Tag[] tags = data.GetTagsByName("tag");

            //Assert
            Assert.IsTrue(tags.Any(x => x == tag));
            Assert.IsTrue(tags.Any(x => x == tag2));
        }
Beispiel #10
0
        /// <summary>
        ///   Initializes a new instance of the <see cref = "T:SharpDX.Direct3D10.Texture1D" /> class.
        /// </summary>
        /// <param name = "device">The device with which to associate the texture.</param>
        /// <param name = "description">The description of the texture.</param>
        /// <param name = "data">An array of initial texture data for each subresource.</param>
        public Texture1D(Device device, Texture1DDescription description, DataStream[] data)
            : base(IntPtr.Zero)
        {
            System.Diagnostics.Debug.Assert(data != null);

            var subResourceDatas = new DataBox[data.Length];

            for (int i = 0; i < subResourceDatas.Length; i++)
            {
                subResourceDatas[i].DataPointer = data[i].DataPointer;
            }

            device.CreateTexture1D(ref description, subResourceDatas, this);
        }
Beispiel #11
0
 /// <summary>
 ///   Initializes a new instance of the <see cref = "T:SharpDX.Direct3D11.Texture1D" /> class.
 /// </summary>
 /// <param name = "device">The device with which to associate the texture.</param>
 /// <param name = "description">The description of the texture.</param>
 /// <param name = "data">An array of initial texture data for each subresource.</param>
 /// <msdn-id>ff476520</msdn-id>
 /// <unmanaged>HRESULT ID3D11Device::CreateTexture1D([In] const D3D11_TEXTURE1D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture1D** ppTexture1D)</unmanaged>
 /// <unmanaged-short>ID3D11Device::CreateTexture1D</unmanaged-short>
 public Texture1D(Device device, Texture1DDescription description, params IntPtr[] data)
     : base(IntPtr.Zero)
 {
     DataBox[] subResourceDatas = null;
     if (data != null && data.Length > 0)
     {
         subResourceDatas = new DataBox[data.Length];
         for (int i = 0; i < subResourceDatas.Length; i++)
         {
             subResourceDatas[i].DataPointer = data[i];
         }
     }
     device.CreateTexture1D(ref description, subResourceDatas, this);
 }
Beispiel #12
0
        public void DataBoxGetTagsByCategoryMulti()
        {
            //Arrange
            var data = new DataBox("test.dat");
            var tag  = data.NewTag("tag 1", "category");
            var tag2 = data.NewTag("tag 2", "category");

            //Act
            Tag[] tags = data.GetTagsByCategory("category");

            //Assert
            Assert.IsTrue(tags.Any(x => x == tag));
            Assert.IsTrue(tags.Any(x => x == tag2));
        }
Beispiel #13
0
        internal void SetData(DataBox data, int mipLevel)
        {
            var format = EnumConverter.Convert(Format);

            if (graphicsDevice.OpenGLCapabilities.DirectStateAccess == DirectStateAccess.None)
            {
                graphicsDevice.BindManager.SetTexture(this, 0);

                if (!TextureFormatHelper.IsCompressed(Format))
                {
                    GL.TexSubImage3D(TextureTarget.Texture3D, mipLevel, 0, 0, 0, Width, Height, Length, format.Item2, format.Item3, data.Pointer);
                }
                else
                {
                    if (isInitialized)
                    {
                        GL.CompressedTexSubImage3D(TextureTarget.Texture3D, mipLevel, 0, 0, 0, Width, Height, Length, format.Item2, data.Size, data.Pointer);
                    }
                    else
                    {
                        GL.CompressedTexImage3D(TextureTarget.Texture3D, mipLevel, format.Item1, Width, Height, Length, 0, data.Size, data.Pointer);
                    }
                }
            }
            else if (graphicsDevice.OpenGLCapabilities.DirectStateAccess == DirectStateAccess.Extension)
            {
                if (!TextureFormatHelper.IsCompressed(Format))
                {
                    Ext.TextureSubImage3D(TextureID, OpenTK.Graphics.OpenGL.TextureTarget.Texture3D, mipLevel, 0, 0, 0, Width, Height, Length, (OpenTK.Graphics.OpenGL.PixelFormat)format.Item2, (OpenTK.Graphics.OpenGL.PixelType)format.Item3, data.Pointer);
                }
                else
                {
                    if (isInitialized)
                    {
                        Ext.CompressedTextureSubImage3D(TextureID, OpenTK.Graphics.OpenGL.TextureTarget.Texture3D, mipLevel, 0, 0, 0, Width, Height, Length, (OpenTK.Graphics.OpenGL.PixelFormat)format.Item2, Marshal.SizeOf(data), data.Pointer);
                    }
                    else
                    {
                        Ext.CompressedTextureImage3D(TextureID, OpenTK.Graphics.OpenGL.TextureTarget.Texture3D, mipLevel, (OpenTK.Graphics.OpenGL.ExtDirectStateAccess)format.Item1, Width, Height, Length, 0, Marshal.SizeOf(data), data.Pointer);
                    }
                }
            }
            else if (graphicsDevice.OpenGLCapabilities.DirectStateAccess == DirectStateAccess.Core)
            {
                //OpenGL 4.5
            }

            graphicsDevice.CheckGLError("Texture3D GenerateMipMaps");
        }
Beispiel #14
0
        public void Update()
        {
            var c = RenderFrame.Instance.deviceContext;

            BoundingBox = new RectangleF(X, Config.Height - Y, SizeX, -SizeY);

            float   texAvailable = texView != null ? 2 : 0;
            DataBox databox      = c.MapSubresource(Cbuffer, 0, MapMode.WriteDiscard, 0);

            databox.Data.Position = 0;
            databox.Data.Write(new Vector4(X / width * 2 - 1, Y / height * 2 - 1, SizeX / width, SizeY / height));
            databox.Data.Write(new Vector4(texAvailable, texAvailable, texAvailable, texAvailable));
            databox.Data.Write(Color.ToVector4());
            c.UnmapSubresource(Cbuffer, 0);
        }
Beispiel #15
0
        //////////////////////////////////////////////////////////////////////////////////////////
        // METHODS


        /// <summary>
        /// Retrieves the dynamic web texture.
        /// </summary>
        /// <returns>A SlimDX DirectX11 Texture of some website.</returns>
        public Texture2D GetTexture2D()
        {
            if (UpdateIfSurfaceIsNotDirty || _surface.IsDirty)
            {
                // copy the image into a texture 2D
                DataBox dataBox = Context.MapSubresource(_texture, 0, 0, MapMode.WriteDiscard, SlimDX.Direct3D11.MapFlags.None);
                dataBox.Data.WriteRange(_surface.Buffer, _view.Width * 4 * _view.Height);

                Context.UnmapSubresource(_texture, 0);

                _surface.IsDirty = false;
            }

            return(_texture);
        }
Beispiel #16
0
        public void Lock(out IntPtr data, out int width, out int height, out int pitchInBytes)
        {
            _dxDeviceContext.Device.ImmediateContext.CopyResource(_renderTexture, _lockableTexture);

            DataBox dBox
                = _dxDeviceContext.Device.ImmediateContext.MapSubresource(_lockableTexture,
                                                                          0, 0,
                                                                          MapMode.Read,
                                                                          SlimDX.Direct3D11.MapFlags.None);

            data         = dBox.Data.DataPointer;
            width        = _width;
            height       = _height;
            pitchInBytes = dBox.RowPitch;
        }
Beispiel #17
0
        public void DataBoxAddItemWithLink()
        {
            //Arrange
            var data = new DataBox("test.xml");

            //Act
            LinkEntry entry = data.NewLinkEntry("name", "description");
            LinkItem  link  = entry.AddLink("link", "http://testlink.ca");

            //Assert
            Assert.AreEqual(1, data.Entries.Count);
            Assert.AreEqual("link", ((LinkEntry)data.Entries[0]).Links[0].Name);
            Assert.AreEqual("http://testlink.ca", ((LinkEntry)data.Entries[0]).Links[0].Link);
            Assert.AreEqual(link, ((LinkEntry)data.Entries[0]).Links[0]);
        }
Beispiel #18
0
        private static List <DataBox> FillInitData(IntPtr pointer, int width, int height, int depth, int mipCount, int arraySize, Format format, int maxsize, int bitSize, int offset)
        {
            pointer += offset;

            List <DataBox> boxes = new List <DataBox>();

            int NumBytes = 0;
            int RowBytes = 0;
            int NumRows  = 0;

            int index = 0;

            for (int j = 0; j < arraySize; j++)
            {
                int w = width;
                int h = height;
                int d = depth;
                for (int i = 0; i < mipCount; i++)
                {
                    GetSurfaceInfo(w, h, format, out NumBytes, out RowBytes, out NumRows);

                    DataBox box = new DataBox(pointer, RowBytes, NumBytes);

                    boxes.Add(box);
                    index++;

                    pointer += NumBytes * d;

                    w = w >> 1;
                    h = h >> 1;
                    d = d >> 1;
                    if (w == 0)
                    {
                        w = 1;
                    }
                    if (h == 0)
                    {
                        h = 1;
                    }
                    if (d == 0)
                    {
                        d = 1;
                    }
                }
            }

            return(boxes);
        }
            private unsafe void Render(DataBox databox, BitmapData bitmap)
            {
                var sourcePtr = IntPtr.Add(databox.DataPointer, (this.sourceXOffset * SourcePixelSize) + (this.sourceYOffset * databox.RowPitch));
                var destPtr   = IntPtr.Add(bitmap.Scan0, (this.destXOffset * DestPixelSize) + (this.destYOffset * bitmap.Stride));

                for (var y = 0; y < this.height; y++)
                {
                    /*
                     * Accord.Video.FFMPEG.VideoFileWriter.WriteVideoFrame internally uses bimtaps/Format24bppRgb and converts other formats
                     *   => it's faster to do this while copying the data
                     * https://github.com/accord-net/framework/blob/development/Sources/Extras/Accord.Video.FFMPEG.GPL/VideoFileWriter.cpp#L600-L621
                     *
                     *
                     * fast B8G8R8A8_UNorm -> Format24bppRgb
                     * - 24bppRGB is actually BGR
                     * - alpha is always 0 => we can just copy raw data
                     *
                     * destPixelSize = 3:
                     *
                     * for body:
                     *
                     * |B|G|R|A|
                     *       |B|G|R|A|
                     *
                     *             |B|G|R|         last pixel in a row / if (width > 0)
                     */
                    var destinationBytePointer = (byte *)destPtr.ToPointer();
                    var sourceInt32Pointer     = (int *)sourcePtr.ToPointer();
                    var sourceWideEndPointer   = sourceInt32Pointer + this.width - 1;
                    while (sourceInt32Pointer < sourceWideEndPointer)
                    {
                        *(int *)destinationBytePointer = *sourceInt32Pointer++;
                        destinationBytePointer        += DestPixelSize;
                    }

                    if (this.width > 0)
                    {
                        var sourceBytePointer = (byte *)sourceInt32Pointer;
                        for (var i = 0; i < DestPixelSize; i++)
                        {
                            *destinationBytePointer++ = *sourceBytePointer++;
                        }
                    }

                    sourcePtr = IntPtr.Add(sourcePtr, databox.RowPitch);
                    destPtr   = IntPtr.Add(destPtr, bitmap.Stride);
                }
            }
Beispiel #20
0
        public static Texture2D LoadTextureFromFile(SharpDX.Direct3D11.Device aDevice, string aFullPath)
        {
            Texture2D      result = null;
            ImagingFactory fac    = new ImagingFactory();

            BitmapDecoder     bc  = new SharpDX.WIC.BitmapDecoder(fac, aFullPath, DecodeOptions.CacheOnLoad);
            BitmapFrameDecode bfc = bc.GetFrame(0);
            FormatConverter   fc  = new FormatConverter(fac);

            System.Guid desiredFormat = PixelFormat.Format32bppBGRA;
            fc.Initialize(bfc, desiredFormat);

            float[] buffer = new float[fc.Size.Width * fc.Size.Height];

            bool canConvert = fc.CanConvert(bfc.PixelFormat, desiredFormat);

            fc.CopyPixels <float>(buffer);
            GCHandle handle      = GCHandle.Alloc(buffer, GCHandleType.Pinned);
            float    sizeOfPixel = PixelFormat.GetBitsPerPixel(desiredFormat) / 8;

            if (sizeOfPixel != 4.0f)
            {
                throw new System.Exception("Unknown error");
            }

            DataBox db = new DataBox(handle.AddrOfPinnedObject(), fc.Size.Width * (int)sizeOfPixel, fc.Size.Width * fc.Size.Height * (int)sizeOfPixel);

            int width  = fc.Size.Width;
            int height = fc.Size.Height;

            Texture2DDescription fTextureDesc = new Texture2DDescription();

            fTextureDesc.CpuAccessFlags    = CpuAccessFlags.None;
            fTextureDesc.Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm;
            fTextureDesc.Width             = width;
            fTextureDesc.Height            = height;
            fTextureDesc.Usage             = ResourceUsage.Default;
            fTextureDesc.MipLevels         = 1;
            fTextureDesc.ArraySize         = 1;
            fTextureDesc.OptionFlags       = ResourceOptionFlags.None;
            fTextureDesc.BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource;
            fTextureDesc.SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0);

            result = new Texture2D(aDevice, fTextureDesc, new DataBox[] { db });
            handle.Free();

            return(result);
        }
Beispiel #21
0
        /// <summary>
        /// Copies a range of data to an array
        /// </summary>
        /// <param name="index">Index from which to start copying</param>
        /// <param name="count">Number of elements to copy</param>
        /// <param name="array">Destination array to copy to</param>
        /// <param name="arrayIndex">Destination array index to copy to</param>
        public void CopyRangeTo(int index, int count, T[] array, int arrayIndex)
        {
            if (count == 0)
            {
                return;
            }

            if (count < 0)
            {
                throw new IndexOutOfRangeException();
            }
            if (index < 0 || index >= Count)
            {
                throw new IndexOutOfRangeException();
            }
            if (index + count < 0 || index + count > Count)
            {
                throw new IndexOutOfRangeException();
            }

            if (array == null)
            {
                throw new ArgumentNullException();
            }
            if (arrayIndex < 0 || arrayIndex >= array.Length)
            {
                throw new IndexOutOfRangeException();
            }
            if (arrayIndex + array.Length < 0 || arrayIndex + count > array.Length)
            {
                throw new IndexOutOfRangeException();
            }

            int    dataSize      = Marshal.SizeOf(typeof(T));
            Buffer stagingBuffer = new Buffer(context.Device, dataSize * count, ResourceUsage.Staging,
                                              BindFlags.None, CpuAccessFlags.Read, ResourceOptionFlags.None, 0);

            context.CopySubresourceRegion(buffer, 0,
                                          new ResourceRegion(dataSize * index, 0, 0, dataSize * (index + count), 1, 1),
                                          stagingBuffer, 0, 0, 0, 0);

            DataBox box = context.MapSubresource(stagingBuffer, MapMode.Read, MapFlags.None);

            box.Data.ReadRange <T>(array, arrayIndex, count);
            context.UnmapSubresource(stagingBuffer, 0);

            stagingBuffer.Dispose();
        }
        public Texture2D TryGetNextFrameAsTexture2D(Device device)
        {
            if (_hWnd == IntPtr.Zero)
            {
                return(null);
            }

            var hdcSrc  = NativeMethods.GetDCEx(_hWnd, IntPtr.Zero, DeviceContextValues.Window | DeviceContextValues.Cache | DeviceContextValues.LockWindowUpdate);
            var hdcDest = NativeMethods.CreateCompatibleDC(hdcSrc);

            NativeMethods.GetWindowRect(_hWnd, out var rect);
            var(width, height) = (rect.Right - rect.Left, rect.Bottom - rect.Top);
            var hBitmap = NativeMethods.CreateCompatibleBitmap(hdcSrc, width, height);
            var hOld    = NativeMethods.SelectObject(hdcDest, hBitmap);

            NativeMethods.BitBlt(hdcDest, 0, 0, width, height, hdcSrc, 0, 0, TernaryRasterOperations.SRCCOPY);
            NativeMethods.SelectObject(hdcDest, hOld);
            NativeMethods.DeleteDC(hdcDest);
            NativeMethods.ReleaseDC(_hWnd, hdcSrc);

            using var img = Image.FromHbitmap(hBitmap);
            NativeMethods.DeleteObject(hBitmap);

            using var bitmap = img.Clone(Rectangle.FromLTRB(0, 0, width, height), PixelFormat.Format32bppArgb);
            var bits = bitmap.LockBits(Rectangle.FromLTRB(0, 0, width, height), ImageLockMode.ReadOnly, img.PixelFormat);

            var data = new DataBox {
                DataPointer = bits.Scan0, RowPitch = bits.Width * 4, SlicePitch = bits.Height
            };

            var texture2dDescription = new Texture2DDescription
            {
                ArraySize         = 1,
                BindFlags         = BindFlags.ShaderResource | BindFlags.RenderTarget,
                CpuAccessFlags    = CpuAccessFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Height            = height,
                MipLevels         = 1,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                Width             = width
            };
            var texture2d = new Texture2D(device, texture2dDescription, new[] { data });

            bitmap.UnlockBits(bits);

            return(texture2d);
        }
Beispiel #23
0
        public void DataBoxAddMultiItems()
        {
            //Arrange
            var data = new DataBox("test.xml");

            //Act
            LinkEntry entry1 = data.NewLinkEntry("name 1", "description");
            LinkEntry entry2 = data.NewLinkEntry("name 2", "description");
            LinkEntry entry3 = data.NewLinkEntry("name 3", "description");

            //Assert
            Assert.AreEqual(3, data.Entries.Count);
            Assert.AreEqual(entry1, data.Entries[0]);
            Assert.AreEqual(entry2, data.Entries[1]);
            Assert.AreEqual(entry3, data.Entries[2]);
        }
Beispiel #24
0
        public void Update(ITexture3D texture, int mipLevel, DataBox data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            Texture3D internalTexture = graphicsDevice.Cast <Texture3D>(texture, "textureArray");

            if (internalTexture.Usage == ResourceUsage.Immutable)
            {
                throw new ArgumentException("Can't update immutable resource.", "texture");
            }

            internalTexture.SetData(data, mipLevel);
        }
Beispiel #25
0
    public T[] FillArrayFromStagingBuffer(DeviceContext context)
    {
        T[] array = arrays[nextArrayIdx];
        nextArrayIdx = (nextArrayIdx + 1) % arrays.Length;

        DataBox dataBox = context.MapSubresource(buffer, 0, MapMode.Read, MapFlags.None, out DataStream dataStream);

        try {
            dataStream.ReadRange(array, 0, array.Length);
        } finally {
            context.UnmapSubresource(buffer, 0);
            dataStream.Dispose();
        }

        return(array);
    }
Beispiel #26
0
 public bool Read(BinaryReader br)
 {
     fileNumber.Read(br);
     sequentialChoiceNumber = br.ReadInt16();
     unknown1      = br.ReadInt16();
     offset        = br.ReadInt16();
     offset        = HandleOffsetOnRead(offset); // since the offset is counted from the end of the header not the start of the file we make our own adjustment to it to turn into a real offset from the start of the file. since we will be dealing with full file streams this makes it easier to reason about and recalcuate the offets.
     unknown2      = br.ReadInt16();
     unknown3      = br.ReadInt16();
     lookupCode    = br.ReadInt16();
     unknown4      = br.ReadInt16();
     unknown5      = br.ReadInt16();
     trailingBlock = new DataBox(0x82);
     trailingBlock.Read(br);
     return(true);
 }
Beispiel #27
0
        /// <summary>
        ///   Initializes a new instance of the <see cref = "T:SharpDX.Direct3D10.Texture2D" /> class.
        /// </summary>
        /// <param name = "device">The device with which to associate the texture.</param>
        /// <param name = "description">The description of the texture.</param>
        /// <param name = "data">An array of initial texture data for each subresource.</param>
        public Texture2D(Device device, Texture2DDescription description, DataRectangle[] data)
            : base(IntPtr.Zero)
        {
            DataBox[] subResourceDatas = null;

            if (data != null)
            {
                subResourceDatas = new DataBox[data.Length];
                for (int i = 0; i < subResourceDatas.Length; i++)
                {
                    subResourceDatas[i].DataPointer = data[i].DataPointer;
                    subResourceDatas[i].RowPitch    = data[i].Pitch;
                }
            }
            device.CreateTexture2D(ref description, subResourceDatas, this);
        }
Beispiel #28
0
        public unsafe Font(Device device, DeviceContext context, FontContent font)
        {
            Content = font;
            Sources = new StructuredBuffer <GlyphSource>(device, font.Characters.Count, font.Name + " Glyph Sources");
            Atlas   = new Texture2D(device, new Texture2DDescription
            {
                ArraySize         = 1,
                BindFlags         = BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.None,
                Format            = SharpDX.DXGI.Format.R8_SNorm,
                Height            = font.Atlas.Height,
                Width             = font.Atlas.Width,
                MipLevels         = font.Atlas.MipLevels,
                OptionFlags       = ResourceOptionFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                Usage             = ResourceUsage.Default
            });
            Atlas.DebugName    = font.Name + " Atlas";
            AtlasSRV           = new ShaderResourceView(device, Atlas);
            AtlasSRV.DebugName = font.Name + " Atlas SRV";

            var data = font.Atlas.Pin();

            for (int mipLevel = 0; mipLevel < font.Atlas.MipLevels; ++mipLevel)
            {
                var databox = new DataBox(new IntPtr(data + font.Atlas.GetMipStartIndex(mipLevel)), font.Atlas.GetRowPitch(mipLevel), 0);
                context.UpdateSubresource(databox, Atlas, mipLevel);
            }
            font.Atlas.Unpin();

            sourceIds = new Dictionary <char, int>();
            int nextSourceId = 0;
            var sourcesData  = new GlyphSource[font.Characters.Count];

            foreach (var character in font.Characters)
            {
                sourceIds.Add(character.Key, nextSourceId);
                sourcesData[nextSourceId] = new GlyphSource
                {
                    Minimum       = new Vector2(character.Value.SourceMinimum.X, character.Value.SourceMinimum.Y),
                    PackedSpan    = character.Value.SourceSpan.X | (character.Value.SourceSpan.Y << 16),
                    DistanceScale = character.Value.DistanceScale
                };
                ++nextSourceId;
            }
            Sources.Update(context, sourcesData);
        }
Beispiel #29
0
        public override void Initialize()
        {
            Texture2D minimapTexture = new Texture2D(Context.DirectX.Device, new Texture2DDescription
            {
                Width             = Size.X,
                Height            = Size.Y,
                Format            = Format.R8G8B8A8_UNorm_SRgb,
                BindFlags         = BindFlags.ShaderResource,
                ArraySize         = 1,
                MipLevels         = 1,
                SampleDescription = new SampleDescription(1, 0)
            });

            int rowPitch  = 4 * minimapTexture.Description.Width;
            int byteCount = rowPitch * minimapTexture.Description.Height;
            var byteArray = new byte[byteCount];

            for (int i = 0; i < minimapTexture.Description.Width; i++)
            {
                for (int j = 0; j < minimapTexture.Description.Height; j++)
                {
                    if (ProvincePicker.ClosestProvince(new Vector3D((
                                                                        (float)i * Context.World.Size.X) / Size.X, 0, ((float)(Size.Y - j) * Context.World.Size.Y) / Size.Y)) is LandProvince)
                    {
                        byteArray[4 * (j * minimapTexture.Description.Width + i)]     = 106;
                        byteArray[4 * (j * minimapTexture.Description.Width + i) + 1] = 98;
                        byteArray[4 * (j * minimapTexture.Description.Width + i) + 2] = 85;
                        byteArray[4 * (j * minimapTexture.Description.Width + i) + 3] = 255;
                    }
                    else
                    {
                        byteArray[4 * (j * minimapTexture.Description.Width + i)]     = 197;
                        byteArray[4 * (j * minimapTexture.Description.Width + i) + 1] = 183;
                        byteArray[4 * (j * minimapTexture.Description.Width + i) + 2] = 164;
                        byteArray[4 * (j * minimapTexture.Description.Width + i) + 3] = 255;
                    }
                }
            }
            DataStream dataStream = new DataStream(byteCount, true, true);

            dataStream.Write(byteArray, 0, byteCount);
            DataBox data = new DataBox(dataStream.DataPointer, rowPitch, byteCount);

            Context.DirectX.DeviceContext.UpdateSubresource(data, minimapTexture);
            _minimapTexture = new ShaderResourceView(Context.DirectX.Device, minimapTexture);
            _mapTexture     = new TexturedRectangle(Context, _minimapTexture, Size);
        }
Beispiel #30
0
        /// <summary>
        /// Takes a file and breaks it down into IElements then returns it in a structured format
        /// </summary>
        /// <param name="br">The file to process</param>
        /// <param name="fileName">The name of the file to be processed (used only for displaying error messages)</param>
        /// <returns>A class containing the processed file data</returns>
        public KCFile ParseFile(BinaryReader br, string fileName)
        {
            KCFile workingFile = new KCFile();
            List <IInstruction> instructions = new List <IInstruction>();

            DataBox footer = ReadFooter(br);

            workingFile.footer = footer;
            workingFile.header = ReadHeader(br);

            long streamEnd = br.BaseStream.Length - footer.GetContentsSize();

            while (br.BaseStream.Position != streamEnd) // will need to check this for accuracy as it has been unreliable in some cases in the past
            {
                Opcode opcode = FileIOHelper.ReadOpcode(br);
                br.BaseStream.Position -= OpcodeInfo.OPCODE_SIZE; // set the position back by 2, the size of the opcodes, as the instruction parsers will expect to given a position starting with an opcode

                if (opcode == Opcode.INVALID)
                {
                    string errorMessage = string.Format("There was an unexpected opcode when reading file {0} at position {1} after reading {2} instructions", fileName, br.BaseStream.Position.ToString("X"), instructions.Count.ToString());
                    MessageBox.Show(errorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Environment.Exit(1);
                }

                IInstruction newInstruction;
                Type         instructionParserType = OpcodeInfo.GetInstructionParserType(opcode);

                if (instructionParserType == typeof(InstructionBox))
                {
                    newInstruction = MakeInstructionBox(opcode);
                    newInstruction.Read(br);
                }
                else
                {
                    newInstruction = (IInstruction)Activator.CreateInstance(instructionParserType);
                    newInstruction.Read(br);
                }

                instructions.Add(newInstruction);
            }

            //string finishMessage = string.Format("Parsed file {0} with {1} instructions", fileName, instructions.Count.ToString());
            //MessageBox.Show(finishMessage);

            workingFile.instructions = instructions;
            return(workingFile);
        }
Beispiel #31
0
        internal BoxProperties ToBox(DataBox dtBox)
        {
            BoxProperties boxProperties = new BoxProperties(null
                                                            , dtBox.Dimensions[0], dtBox.Dimensions[1], dtBox.Dimensions[2]);

            boxProperties.ID.SetNameDesc(dtBox.Name, dtBox.Description);
            Color[] colors = new Color[6];
            for (int i = 0; i < 6; ++i)
            {
                colors[i] = Color.Turquoise;
            }
            boxProperties.SetAllColors(colors);
            boxProperties.ShowTape = false;
            boxProperties.SetWeight(dtBox.Weight);
            boxProperties.SetNetWeight(new OptDouble(dtBox.NetWeight > 0, dtBox.NetWeight));
            return(boxProperties);
        }
Beispiel #32
0
        static IHtmlControl GetAdminPanel(LightObject user)
        {
            bool isModerator = user.Get(BasketballUserType.IsModerator);

            return(new HPanel(
                       Decor.Button(isModerator ? "Лишить прав модератора" : "Сделать модератором")
                       .Event("moderator_rights", "", delegate
            {
                LightObject editUser = DataBox.LoadObject(context.UserConnection, UserType.User, user.Id);
                editUser.Set(BasketballUserType.IsModerator, !isModerator);
                editUser.Box.Update();

                context.UserStorage.Update();
            }
                              )
                       ));
        }
Beispiel #33
0
        private async void GetData_Click(object sender, EventArgs e)
        {
            try
            {
                var Data = await _GetCovid.GetData((string)CountryList.SelectedValue);

                BinData.Add(Data);

                DataBox.DataSource = BinData;
                DataBox.Update();
                DataBox.Refresh();
            }//end try
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }//end catch
        }
Beispiel #34
0
        public void WriteArray(float[][] values, int row0, int row1, Buffer buffer)
        {
            if (buffer.Description.Usage != ResourceUsage.Dynamic)
            {
                throw new System.Exception("Not supported operation: WriteArray()!");
            }

            DataBox db = ctx.MapSubresource(buffer, 0, SharpDX.Direct3D11.MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None);
            int     N  = values[0].Length;

            for (int row = row0; row < row1; row++)
            {
                System.IntPtr ptr = new System.IntPtr(db.DataPointer.ToInt64() + (row - row0) * N * 4);
                Marshal.Copy(values[row], 0, ptr, N);
            }
            ctx.UnmapSubresource(buffer, 0);
        }
        DataBox[] GetHDRTextureData(string sourcePath, out int InputWidth, out int InputHeight)
        {
            float[] imageFloats = TextureLoader.LoadHDRTexture(sourcePath, out InputWidth, out InputHeight, out int pixelSize);
            if (InputWidth == 0)
            {
                Console.WriteLine("Texture not loaded!");
                return(null);
            }

            IntPtr pSrcBits = System.Runtime.InteropServices.Marshal.UnsafeAddrOfPinnedArrayElement(imageFloats, 0);

            DataBox[] initData = new DataBox[1];
            initData[0].DataPointer = pSrcBits;
            initData[0].RowPitch    = InputWidth * pixelSize;
            initData[0].SlicePitch  = InputWidth * InputHeight * pixelSize;
            return(initData);
        }
Beispiel #36
0
        public JsonSearcher()
            : base()
        {
            this.inputBox               = new JsonTextBox();
            this.searchResults          = new DataBox();
            this.startSearchEvent       = new JsonScriptObjectEventSource();
            this.MinimumCharacterCount  = 3;
            this.attacher               = new JsonFunction();
            this.attacher.ExecutionType = JavascriptExecutionTypes.OnWindowLoad;
            this.AddJsonFunction(this.attacher);
            this.AutoRegisterScript = true;
            this.Controls.Add(inputBox);
            this.Controls.Add(searchResults);
            this.Controls.Add(startSearchEvent);

            this.AddRequiredScript(typeof(JsonSearcher));//"naizari.javascript.jsoncontrols.jsonsearcher.js");
        }
Beispiel #37
0
        public unsafe void Map <T>(DeviceContext4 context4,
                                   int offset,
                                   T[]            data,
                                   int dataOffset,
                                   int dataLength,
                                   MapMode mapMode   = MapMode.WriteDiscard,
                                   MapFlags mapFlags = MapFlags.None)
            where T : unmanaged
        {
            DataBox box     = context4.MapSubresource(_buffer, 0, mapMode, mapFlags);
            T *     vpctPtr = (T *)box.DataPointer;

            for (int i = 0; i < dataLength; i++)
            {
                *(vpctPtr + offset + i) = data[i + dataOffset];
            }
            context4.UnmapSubresource(_buffer, 0);
        }
Beispiel #38
0
        public static void CopyWriteTexture(SlimDX.Direct3D10.Texture3D texture, DataBox data, int TSize)
        {
            var copy = new SlimDX.Direct3D10.Texture3D(texture.Device, new SlimDX.Direct3D10.Texture3DDescription
            {
                BindFlags      = SlimDX.Direct3D10.BindFlags.None,
                CpuAccessFlags = SlimDX.Direct3D10.CpuAccessFlags.None,
                Format         = texture.Description.Format,
                Width          = texture.Description.Width,
                Height         = texture.Description.Height,
                MipLevels      = texture.Description.MipLevels,
                Usage          = SlimDX.Direct3D10.ResourceUsage.Default,
                OptionFlags    = SlimDX.Direct3D10.ResourceOptionFlags.None,
                Depth          = texture.Description.Depth
            }, data);

            texture.Device.CopyResource(copy, texture);
            copy.Dispose();
        }
Beispiel #39
0
        private void InitializeFromImpl(DataBox[] dataBoxes = null)
        {
            if (ParentTexture != null)
            {
                NativeDeviceChild = ParentTexture.NativeDeviceChild;
            }

            if (NativeDeviceChild == null)
            {
                switch (Dimension)
                {
                    case TextureDimension.Texture1D:
                        NativeDeviceChild = new Texture1D(GraphicsDevice.NativeDevice, ConvertToNativeDescription1D(), ConvertDataBoxes(dataBoxes));
                        break;
                    case TextureDimension.Texture2D:
                    case TextureDimension.TextureCube:
                        NativeDeviceChild = new Texture2D(GraphicsDevice.NativeDevice, ConvertToNativeDescription2D(), ConvertDataBoxes(dataBoxes));
                        break;
                    case TextureDimension.Texture3D:
                        NativeDeviceChild = new Texture3D(GraphicsDevice.NativeDevice, ConvertToNativeDescription3D(), ConvertDataBoxes(dataBoxes));
                        break;
                }
            }

            NativeShaderResourceView = GetShaderResourceView(ViewType, ArraySlice, MipLevel);
            NativeUnorderedAccessView = GetUnorderedAccessView(ViewType, ArraySlice, MipLevel);
            NativeRenderTargetView = GetRenderTargetView(ViewType, ArraySlice, MipLevel);
            NativeDepthStencilView = GetDepthStencilView(out HasStencil);
        }
Beispiel #40
0
        internal unsafe static SharpDX.DataBox[] ConvertDataBoxes(DataBox[] dataBoxes)
        {
            if (dataBoxes == null || dataBoxes.Length == 0)
                return null;

            var sharpDXDataBoxes = new SharpDX.DataBox[dataBoxes.Length];
            fixed (void* pDataBoxes = sharpDXDataBoxes)
                Utilities.Write((IntPtr)pDataBoxes, dataBoxes, 0, dataBoxes.Length);

            return sharpDXDataBoxes;
        }
Beispiel #41
0
 /// <summary>
 ///   Initializes a new instance of the <see cref = "T:SharpDX.Direct3D10.Texture3D" /> class.
 /// </summary>
 /// <param name = "device">The device with which to associate the texture.</param>
 /// <param name = "description">The description of the texture.</param>
 /// <param name = "data">The initial texture data.</param>
 public Texture3D(Device device, Texture3DDescription description, DataBox data)
     : this(device, description, new[] {data})
 {
 }
 internal DataBoxEntityChangeProcessor(EntityType et)
     : base(et)
 {
     this.DataBox = new DataBox(et);
 }
        private unsafe Texture CreateDebugTexture(GraphicsDevice device, byte[] data, int width, int height, int mipmaps, int arraySize, PixelFormat format, TextureFlags flags, GraphicsResourceUsage usage)
        {
            fixed (byte* pData = data)
            {
                var sizeInBytes = format.SizeInBytes();

                var offset = 0;
                var dataBoxes = new DataBox[arraySize * mipmaps];
                for (int array = 0; array < arraySize; array++)
                {
                    for (int mip = 0; mip < mipmaps; mip++)
                    {
                        var w = width >> mip;
                        var h = height >> mip;
                        var rowStride = w * sizeInBytes;
                        var sliceStride = rowStride * h;

                        dataBoxes[array * mipmaps + mip] = new DataBox((IntPtr)pData + offset, rowStride, sliceStride);

                        offset += sliceStride;
                    }
                }

                return Texture.New2D(device, width, height, mipmaps, format, dataBoxes, flags, arraySize, usage);
            }
        }
Beispiel #44
0
 protected internal Texture2D(GraphicsDevice device, TextureDescription description2D, DataBox[] dataBoxes = null, bool initialize = true) : base(device, description2D, TextureTarget.Texture2D, dataBoxes, initialize)
 {
 }
Beispiel #45
0
        private void InitializeFromImpl(DataBox[] dataBoxes = null)
        {
            if (ParentTexture != null)
            {
                resourceId = ParentTexture.ResourceId;

                // copy parameters
                InternalFormat = ParentTexture.InternalFormat;
                FormatGl = ParentTexture.FormatGl;
                Type = ParentTexture.Type;
                Target = ParentTexture.Target;
                DepthPitch = ParentTexture.DepthPitch;
                RowPitch = ParentTexture.RowPitch;
                IsDepthBuffer = ParentTexture.IsDepthBuffer;
                HasStencil = ParentTexture.HasStencil;
                IsRenderbuffer = ParentTexture.IsRenderbuffer;

                resourceIdStencil = ParentTexture.ResourceIdStencil;
                pixelBufferObjectId = ParentTexture.PixelBufferObjectId;
            }

            if (resourceId == 0)
            {
                switch (Dimension)
                {
                    case TextureDimension.Texture1D:
#if !SILICONSTUDIO_PLATFORM_MONO_MOBILE
                        Target = TextureTarget.Texture1D;
                        break;
#endif
                    case TextureDimension.Texture2D:
                        Target = TextureTarget.Texture2D;
                        break;
                    case TextureDimension.Texture3D:
                        Target = TextureTarget.Texture3D;
                        break;
                    case TextureDimension.TextureCube:
                        Target = TextureTarget.TextureCubeMap;
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }

                PixelInternalFormat internalFormat;
                PixelFormatGl format;
                PixelType type;
                int pixelSize;
                bool compressed;
                OpenGLConvertExtensions.ConvertPixelFormat(GraphicsDevice, ref textureDescription.Format, out internalFormat, out format, out type, out pixelSize, out compressed);

                InternalFormat = internalFormat;
                FormatGl = format;
                Type = type;
                DepthPitch = Description.Width * Description.Height * pixelSize;
                RowPitch = Description.Width * pixelSize;

                if ((Description.Flags & TextureFlags.DepthStencil) != 0)
                {
                    IsDepthBuffer = true;
                    HasStencil = InternalHasStencil(Format);
                }
                else
                {
                    IsDepthBuffer = false;
                    HasStencil = false;
                }

                if ((Description.Flags & TextureFlagsCustomResourceId) != 0)
                    return;

                using (GraphicsDevice.UseOpenGLCreationContext())
                {
                    // Depth texture are render buffer for now
                    // TODO: enable switch
                    if ((Description.Flags & TextureFlags.DepthStencil) != 0 && (Description.Flags & TextureFlags.ShaderResource) == 0)
                    {
                        RenderbufferStorage depth, stencil;
                        ConvertDepthFormat(GraphicsDevice, Description.Format, out depth, out stencil);

                        GL.GenRenderbuffers(1, out resourceId);
                        GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, resourceId);
                        GL.RenderbufferStorage(RenderbufferTarget.Renderbuffer, depth, Width, Height);

                        if (stencil != 0)
                        {
                            // separate stencil
                            GL.GenRenderbuffers(1, out resourceIdStencil);
                            GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, resourceIdStencil);
                            GL.RenderbufferStorage(RenderbufferTarget.Renderbuffer, stencil, Width, Height);
                        }
                        else if (HasStencil)
                        {
                            // depth+stencil in a single texture
                            resourceIdStencil = resourceId;
                        }

                        GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, 0);

                        IsRenderbuffer = true;
                        return;
                    }
                    else
                    {
                        GL.GenTextures(1, out resourceId);
                        GL.BindTexture(Target, resourceId);

                        IsRenderbuffer = false;
                    }

                    // No filtering on depth buffer
                    if ((Description.Flags & (TextureFlags.RenderTarget | TextureFlags.DepthStencil)) != TextureFlags.None)
                    {
                        GL.TexParameter(Target, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest);
                        GL.TexParameter(Target, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest);
                        GL.TexParameter(Target, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge);
                        GL.TexParameter(Target, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge);
                        BoundSamplerState = GraphicsDevice.SamplerStates.PointClamp;
                    }
#if SILICONSTUDIO_XENKO_GRAPHICS_API_OPENGLES
                    else if (Description.MipLevels <= 1)
                    {
                        GL.TexParameter(Target, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest);
                        GL.TexParameter(Target, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
                    }
#endif

#if SILICONSTUDIO_XENKO_GRAPHICS_API_OPENGLES
                    if (!GraphicsDevice.IsOpenGLES2)
#endif
                    {
                        GL.TexParameter(Target, TextureParameterName.TextureBaseLevel, 0);
                        GL.TexParameter(Target, TextureParameterName.TextureMaxLevel, Description.MipLevels - 1);
                    }

                    if (Description.MipLevels == 0)
                        throw new NotImplementedException();

                    var setSize = TextureSetSize(Target);

                    for (var arrayIndex = 0; arrayIndex < Description.ArraySize; ++arrayIndex)
                    {
                        var offsetArray = arrayIndex*Description.MipLevels;
                        for (int i = 0; i < Description.MipLevels; ++i)
                        {
                            IntPtr data = IntPtr.Zero;
                            var width = CalculateMipSize(Description.Width, i);
                            var height = CalculateMipSize(Description.Height, i);
                            if (dataBoxes != null && i < dataBoxes.Length)
                            {
                                if (setSize > 1 && !compressed && dataBoxes[i].RowPitch != width*pixelSize)
                                    throw new NotSupportedException("Can't upload texture with pitch in glTexImage2D.");
                                // Might be possible, need to check API better.
                                data = dataBoxes[offsetArray + i].DataPointer;
                            }

                            if (setSize == 2)
                            {
                                var dataSetTarget = GetTextureTargetForDataSet2D(Target, arrayIndex);
                                if (compressed)
                                {
                                    GL.CompressedTexImage2D(dataSetTarget, i, (CompressedInternalFormat2D)internalFormat,
                                        width, height, 0, dataBoxes[offsetArray + i].SlicePitch, data);
                                }
                                else
                                {
                                    GL.TexImage2D(dataSetTarget, i, internalFormat, width, height, 0, format, type, data);
                                }
                            }
                            else if (setSize == 3)
                            {
                                var dataSetTarget = GetTextureTargetForDataSet3D(Target);
                                var depth = Target == TextureTarget.Texture2DArray ? Description.Depth : CalculateMipSize(Description.Depth, i); // no depth mipmaps in Texture2DArray
                                if (compressed)
                                {
                                    GL.CompressedTexImage3D(dataSetTarget, i, (CompressedInternalFormat3D)internalFormat,
                                        width, height, depth, 0, dataBoxes[offsetArray + i].SlicePitch, data);
                                }
                                else
                                {
                                    GL.TexImage3D(dataSetTarget, i, (TextureComponentCount3D)internalFormat,
                                        width, height, depth, 0, format, type, data);
                                }
                            }
#if !SILICONSTUDIO_XENKO_GRAPHICS_API_OPENGLES
                            else if (setSize == 1)
                            {
                                if (compressed)
                                {
                                    GL.CompressedTexImage1D(TextureTarget.Texture1D, i, internalFormat,
                                        width, 0, dataBoxes[offsetArray + i].SlicePitch, data);
                                }
                                else
                                {
                                    GL.TexImage1D(TextureTarget.Texture1D, i, internalFormat,
                                        width, 0, format, type, data);
                                }
                            }
#endif
                        }
                    }
                    GL.BindTexture(Target, 0);

                    InitializePixelBufferObject();
                }

                GraphicsDevice.TextureMemory += (Depth * DepthStride) / (float)0x100000;
            }
        }
Beispiel #46
0
        public void UpdateBufferData(string bufferName, DataStream data)
        {
            var buffer = GetBuffer(bufferName);

            DataBox src = new DataBox((int)data.Length, 0, data);
            Engine.Global.Device3d.GetImmediateContext().UpdateSubresource(src, buffer, 0);
        }
        private void InitializeFromImpl(DataBox[] dataBoxes = null)
        {
            NativeFormat = VulkanConvertExtensions.ConvertPixelFormat(ViewFormat);
            HasStencil = IsStencilFormat(ViewFormat);
            
            NativeImageAspect = IsDepthStencil ? ImageAspectFlags.Depth : ImageAspectFlags.Color;
            if (HasStencil)
                NativeImageAspect |= ImageAspectFlags.Stencil;

            // For depth-stencil formats, automatically fall back to a supported one
            if (IsDepthStencil && HasStencil)
            {
                NativeFormat = GetFallbackDepthStencilFormat(GraphicsDevice, NativeFormat);
            }

            if (Usage == GraphicsResourceUsage.Staging)
            {
                if (NativeImage != SharpVulkan.Image.Null)
                    throw new InvalidOperationException();

                if (isNotOwningResources)
                    throw new InvalidOperationException();

                if (ParentTexture != null)
                {
                    // Create only a view
                    NativeBuffer = ParentTexture.NativeBuffer;
                    NativeMemory = ParentTexture.NativeMemory;
                }
                else
                {
                    CreateBuffer();

                    if (dataBoxes != null)
                        throw new InvalidOperationException();
                }
            }
            else
            {
                if (NativeImage != SharpVulkan.Image.Null)
                    throw new InvalidOperationException();

                NativeLayout =
                    IsRenderTarget ? ImageLayout.ColorAttachmentOptimal :
                    IsDepthStencil ? ImageLayout.DepthStencilAttachmentOptimal :
                    IsShaderResource ? ImageLayout.ShaderReadOnlyOptimal :
                    ImageLayout.General;

                if (NativeLayout == ImageLayout.TransferDestinationOptimal)
                    NativeAccessMask = AccessFlags.TransferRead;

                if (NativeLayout == ImageLayout.ColorAttachmentOptimal)
                    NativeAccessMask = AccessFlags.ColorAttachmentWrite;

                if (NativeLayout == ImageLayout.DepthStencilAttachmentOptimal)
                    NativeAccessMask = AccessFlags.DepthStencilAttachmentWrite;

                if (NativeLayout == ImageLayout.ShaderReadOnlyOptimal)
                    NativeAccessMask = AccessFlags.ShaderRead | AccessFlags.InputAttachmentRead;

                NativePipelineStageMask =
                    IsRenderTarget ? PipelineStageFlags.ColorAttachmentOutput :
                    IsDepthStencil ? PipelineStageFlags.ColorAttachmentOutput | PipelineStageFlags.EarlyFragmentTests | PipelineStageFlags.LateFragmentTests :
                    IsShaderResource ? PipelineStageFlags.VertexInput | PipelineStageFlags.FragmentShader :
                    PipelineStageFlags.None;

                if (ParentTexture != null)
                {
                    // Create only a view
                    NativeImage = ParentTexture.NativeImage;
                    NativeMemory = ParentTexture.NativeMemory;
                }
                else
                {
                    if (!isNotOwningResources)
                    {
                        CreateImage();

                        InitializeImage(dataBoxes);
                    }
                }

                if (!isNotOwningResources)
                {
                    NativeImageView = GetImageView(ViewType, ArraySlice, MipLevel);
                    NativeColorAttachmentView = GetColorAttachmentView(ViewType, ArraySlice, MipLevel);
                    NativeDepthStencilView = GetDepthStencilView();
                }
            }
        }
        private unsafe void InitializeImage(DataBox[] dataBoxes)
        {
            var commandBuffer = GraphicsDevice.NativeCopyCommandBuffer;
            var beginInfo = new CommandBufferBeginInfo { StructureType = StructureType.CommandBufferBeginInfo };
            commandBuffer.Begin(ref beginInfo);

            if (dataBoxes != null && dataBoxes.Length > 0)
            {
                // Buffer-to-image copies need to be aligned to the pixel size and 4 (always a power of 2)
                var blockSize = Format.IsCompressed() ? NativeFormat.BlockSizeInBytes() : TexturePixelSize;
                var alignmentMask = (blockSize < 4 ? 4 : blockSize) - 1;

                int totalSize = dataBoxes.Length * alignmentMask;
                for (int i = 0; i < dataBoxes.Length; i++)
                {
                    totalSize += dataBoxes[i].SlicePitch;
                }

                SharpVulkan.Buffer uploadResource;
                int uploadOffset;
                var uploadMemory = GraphicsDevice.AllocateUploadBuffer(totalSize, out uploadResource, out uploadOffset);

                // Upload buffer barrier
                var bufferMemoryBarrier = new BufferMemoryBarrier(uploadResource, AccessFlags.HostWrite, AccessFlags.TransferRead, (ulong)uploadOffset, (ulong)totalSize);

                // Image barrier
                var initialBarrier = new ImageMemoryBarrier(NativeImage, ImageLayout.Undefined, ImageLayout.TransferDestinationOptimal, AccessFlags.None, AccessFlags.TransferWrite, new ImageSubresourceRange(NativeImageAspect));
                commandBuffer.PipelineBarrier(PipelineStageFlags.TopOfPipe, PipelineStageFlags.Transfer, DependencyFlags.None, 0, null, 1, &bufferMemoryBarrier, 1, &initialBarrier);

                // Copy data boxes to upload buffer
                var copies = new BufferImageCopy[dataBoxes.Length];
                for (int i = 0; i < copies.Length; i++)
                {
                    var slicePitch = dataBoxes[i].SlicePitch;

                    int arraySlice = i / MipLevels;
                    int mipSlice = i % MipLevels;
                    var mipMapDescription = GetMipMapDescription(mipSlice);

                    SubresourceLayout layout;
                    GraphicsDevice.NativeDevice.GetImageSubresourceLayout(NativeImage, new ImageSubresource(NativeImageAspect, (uint)arraySlice, (uint)mipSlice), out layout);

                    var alignment = ((uploadOffset + alignmentMask) & ~alignmentMask) - uploadOffset;
                    uploadMemory += alignment;
                    uploadOffset += alignment;

                    Utilities.CopyMemory(uploadMemory, dataBoxes[i].DataPointer, slicePitch);

                    // TODO VULKAN: Check if pitches are valid
                    copies[i] = new BufferImageCopy
                    {
                        BufferOffset = (ulong)uploadOffset,
                        ImageSubresource = new ImageSubresourceLayers(ImageAspectFlags.Color, (uint)arraySlice, 1, (uint)mipSlice),
                        BufferRowLength = 0, //(uint)(dataBoxes[i].RowPitch / pixelSize),
                        BufferImageHeight = 0, //(uint)(dataBoxes[i].SlicePitch / dataBoxes[i].RowPitch),
                        ImageOffset = new Offset3D(0, 0, arraySlice),
                        ImageExtent = new Extent3D((uint)mipMapDescription.Width, (uint)mipMapDescription.Height, 1)
                    };

                    uploadMemory += slicePitch;
                    uploadOffset += slicePitch;
                }

                // Copy from upload buffer to image
                fixed (BufferImageCopy* copiesPointer = &copies[0])
                {
                    commandBuffer.CopyBufferToImage(uploadResource, NativeImage, ImageLayout.TransferDestinationOptimal, (uint)copies.Length, copiesPointer);
                }

                IsInitialized = true;
            }

            // Transition to default layout
            var imageMemoryBarrier = new ImageMemoryBarrier(NativeImage,
                dataBoxes == null || dataBoxes.Length == 0 ? ImageLayout.Undefined : ImageLayout.TransferDestinationOptimal, NativeLayout,
                dataBoxes == null || dataBoxes.Length == 0 ? AccessFlags.None : AccessFlags.TransferWrite, NativeAccessMask, new ImageSubresourceRange(NativeImageAspect));
            commandBuffer.PipelineBarrier(PipelineStageFlags.Transfer, PipelineStageFlags.AllCommands, DependencyFlags.None, 0, null, 0, null, 1, &imageMemoryBarrier);

            // Close and submit
            commandBuffer.End();

            var submitInfo = new SubmitInfo
            {
                StructureType = StructureType.SubmitInfo,
                CommandBufferCount = 1,
                CommandBuffers = new IntPtr(&commandBuffer),
            };

            lock (GraphicsDevice.QueueLock)
            {
                GraphicsDevice.NativeCommandQueue.Submit(1, &submitInfo, Fence.Null);
                GraphicsDevice.NativeCommandQueue.WaitIdle();
                commandBuffer.Reset(CommandBufferResetFlags.None);
            }
        }
Beispiel #49
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Texture1DBase" /> class.
 /// </summary>
 /// <param name="device">The <see cref="GraphicsDevice"/>.</param>
 /// <param name="description1D">The description.</param>
 /// <param name="dataBox">A variable-length parameters list containing data rectangles.</param>
 /// <msdn-id>ff476520</msdn-id>	
 /// <unmanaged>HRESULT ID3D11Device::CreateTexture1D([In] const D3D11_TEXTURE1D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture1D** ppTexture1D)</unmanaged>	
 /// <unmanaged-short>ID3D11Device::CreateTexture1D</unmanaged-short>	
 protected internal Texture1DBase(GraphicsDevice device, Texture1DDescription description1D, DataBox[] dataBox)
     : base(device, description1D)
 {
     Resource = new Direct3D11.Texture1D(device, description1D, dataBox);
     Initialize(Resource);
 }
Beispiel #50
0
 /// <summary>
 ///   Initializes a new instance of the <see cref = "T:SharpDX.Direct3D11.Texture3D" /> class.
 /// </summary>
 /// <param name = "device">The device with which to associate the texture.</param>
 /// <param name = "description">The description of the texture.</param>
 /// <param name = "data">An array of initial texture data for each subresource.</param>
 public Texture3D(Device device, Texture3DDescription description, DataBox[] data) : base(IntPtr.Zero)
 {
     device.CreateTexture3D(ref description, data, this);
 }
Beispiel #51
0
 public void Recreate(DataBox[] dataBoxes = null)
 {
     InitializeFromImpl(dataBoxes);
 }
Beispiel #52
0
 protected internal Texture1D(GraphicsDevice device, TextureDescription description1D, DataBox[] dataBox = null)
     : base(device, description1D)
 {
 }
Beispiel #53
0
        public void UpdateRectangles( IList< Image4ub > images, IList< Rect2i > targets )
        {
#if false
            var wrapper = D3D10Wrapper.Instance;

            var im = new Image4ub( this.Size, Color4ub.Red );
            fixed( void* ptr = im.Pixels )
            {
                var userBuffer = new IntPtr( ptr );
                var dataStream = new DataStream( userBuffer, 4 * im.NumPixels, true, true );
                var sourceBox = new DataBox( 4 * im.Width, 4 * im.Width * im.Height, dataStream );

                var targetRegion = new ResourceRegion
                {
                    Back = 1,
                    Front = 0,
                    Bottom = 4096,
                    Top = 0,
                    Left = 0,
                    Right = 4096
                };

                wrapper.Device.UpdateSubresource( sourceBox, Texture, 0, targetRegion );
                dataStream.Close();
            }

            return;
#endif
            if( images.Count != targets.Count )
            {
                throw new ArgumentException( "images and targets must be of the same length" );
            }

            var rect = Texture.Map( 0, MapMode.WriteDiscard, MapFlags.None );

            for( int i = 0; i < images.Count; ++i )
            {
                var im = images[ i ];
                var target = targets[ i ];

                for( int y = 0; y < im.Height; ++y )
                {
                    int sourceOffset = 4 * y * im.Width;
                    int sourceCount = 4 * im.Width;

                    rect.Data.Position = 4 * ( ( y + target.Origin.y ) * Width + target.Origin.x );
                    rect.Data.Write( im.Pixels, sourceOffset, sourceCount );
                }
            }

            rect.Data.Close();
            Texture.Unmap( 0 );
        }
 protected internal TextureCube(GraphicsDevice device, TextureDescription description2D, DataBox[] dataBoxes = null) : base(device, description2D, TextureTarget.TextureCubeMap)
 {
     throw new NotImplementedException();
 }
Beispiel #55
0
 internal unsafe void UpdateSubresource(GraphicsResource resource, int subResourceIndex, DataBox databox, ResourceRegion region)
 {
     if (resource == null) throw new ArgumentNullException("resource");
     NativeDeviceContext.UpdateSubresource(*(SharpDX.DataBox*)Interop.Cast(ref databox), resource.NativeResource, subResourceIndex, *(SharpDX.Direct3D11.ResourceRegion*)Interop.Cast(ref region));
 }
Beispiel #56
0
        /// <summary>
        /// Draws the specified topology.
        /// </summary>
        /// <param name="topology">The topology.</param>
        /// <param name="isIndexed">if set to <c>true</c> [is indexed].</param>
        /// <param name="indices">The indices.</param>
        /// <param name="indexCount">The index count.</param>
        /// <param name="vertexCount">The vertex count.</param>
        /// <returns>IntPtr.</returns>
        /// <exception cref="System.ArgumentNullException">Indices cannot be null</exception>
        /// <exception cref="System.ArgumentException">Too many indices;indexCount</exception>
        /// <exception cref="System.InvalidOperationException">Begin must be called before Draw</exception>
        protected unsafe IntPtr Draw(PrimitiveTopology topology, bool isIndexed, IntPtr indices, int indexCount, int vertexCount)
        {
            if (isIndexed && indices == IntPtr.Zero)
            {
                throw new ArgumentNullException("Indices cannot be null");
            }

            if (indexCount >= maxIndices)
            {
                throw new ArgumentException("Too many indices", "indexCount");
            }

            if (vertexCount >= maxVertices)
            {
                throw new ArgumentException("Too many vertices");
            }

            if (!inBeginEndPair)
            {
                throw new InvalidOperationException("Begin must be called before Draw");
            }

            // Can we merge this primitive in with an existing batch, or must we flush first?
            bool wrapIndexBuffer = currentIndex + indexCount > maxIndices;
            bool wrapVertexBuffer = currentVertex + vertexCount > maxVertices;

            if ((topology != currentTopology) ||
                (isIndexed != currentlyIndexed) ||
                !CanBatchPrimitives(topology) ||
                wrapIndexBuffer || wrapVertexBuffer)
            {
                FlushBatch();
            }

            if (wrapIndexBuffer)
            {
                currentIndex = 0;
            }

            if (wrapVertexBuffer)
            {
                currentVertex = 0;
            }

            // If we are not already in a batch, lock the buffers.
            if (currentTopology == PrimitiveType.Undefined)
            {
                if (isIndexed)
                {
                    mappedIndices = LockBuffer(indexBuffer, currentIndex);
                    baseIndex = currentIndex;
                }

                mappedVertices = LockBuffer(vertexBuffer, currentVertex);
                baseVertex = currentVertex;

                currentTopology = topology;
                currentlyIndexed = isIndexed;
            }

            // Copy over the index data.
            if (isIndexed)
            {
                short* outputIndices = (short*)mappedIndices.DataPointer + currentIndex;

                for (int i = 0; i < indexCount; i++)
                {
                    outputIndices[i] = (short)(((short*)indices)[i] + currentVertex - baseVertex);
                }

                currentIndex += indexCount;
            }

            // Return the output vertex data location.
            var result = (IntPtr)((byte*)mappedVertices.DataPointer + (currentVertex * VertexSize));
            currentVertex += vertexCount;
            return result;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="Texture2DBase" /> class.
 /// </summary>
 /// <param name="device">The <see cref="GraphicsDevice"/>.</param>
 /// <param name="description2D">The description.</param>
 /// <param name="dataBoxes">A variable-length parameters list containing data rectangles.</param>
 /// <msdn-id>ff476521</msdn-id>	
 /// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged>	
 /// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short>	
 protected internal Texture2DBase(GraphicsDevice device, Texture2DDescription description2D, DataBox[] dataBoxes)
     : base(device ,description2D)
 {
     Resource = new Direct3D11.Texture2D(device, description2D, dataBoxes);
 }
Beispiel #58
0
        /// <summary>
        /// Upload a character's bitmap into the current cache.
        /// </summary>
        /// <param name="character">The character specifications corresponding to the bitmap</param>
        public void UploadCharacterBitmap(CharacterSpecification character)
        {
            if(character.Bitmap == null)
                throw new ArgumentNullException("character");

            if(character.IsBitmapUploaded)
                throw new InvalidOperationException("The character '"+character.Character+"' upload has been requested while its current glyph is valid.");

            var targetSize = new Int2(character.Bitmap.Width, character.Bitmap.Rows);
            if (!packer.Insert(targetSize.X, targetSize.Y, ref character.Glyph.Subrect))
            {
                // not enough space to place the new character -> remove less used characters and try again
                RemoveLessUsedCharacters();
                if (!packer.Insert(targetSize.X, targetSize.Y, ref character.Glyph.Subrect))
                {
                    // memory is too fragmented in order to place the new character -> clear all the characters and restart.
                    ClearCache();
                    if (!packer.Insert(targetSize.X, targetSize.Y, ref character.Glyph.Subrect))
                        throw new InvalidOperationException("The rendered character is too big for the cache texture");
                }
            }
            // updload the bitmap on the texture (if the size in the bitmap is not null)
            if (character.Bitmap.Rows != 0 && character.Bitmap.Width != 0)
            {
                var dataBox = new DataBox(character.Bitmap.Buffer, character.Bitmap.Pitch, character.Bitmap.Pitch * character.Bitmap.Rows);
                var region = new ResourceRegion(character.Glyph.Subrect.Left, character.Glyph.Subrect.Top, 0, character.Glyph.Subrect.Right, character.Glyph.Subrect.Bottom, 1);
                system.GraphicsDevice.UpdateSubresource(cacheTextures[0], 0, dataBox, region);
            }

            // update the glyph data
            character.IsBitmapUploaded = true;
            character.Glyph.BitmapIndex = 0;
        }
Beispiel #59
0
 protected internal Texture1D(GraphicsDevice device, TextureDescription description1D, DataBox[] dataBox = null)
     : base(device, description1D, ViewType.Full, 0, 0)
 {
     Target = TextureTarget1D;
 }
Beispiel #60
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Texture3DBase" /> class.
 /// </summary>
 /// <param name="device">The <see cref="GraphicsDevice"/>.</param>
 /// <param name="description3D">The description.</param>
 /// <param name="dataRectangles">A variable-length parameters list containing data rectangles.</param>
 /// <msdn-id>ff476522</msdn-id>	
 /// <unmanaged>HRESULT ID3D11Device::CreateTexture3D([In] const D3D11_TEXTURE3D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture3D** ppTexture3D)</unmanaged>	
 /// <unmanaged-short>ID3D11Device::CreateTexture3D</unmanaged-short>	
 protected internal Texture3DBase(GraphicsDevice device, Texture3DDescription description3D, DataBox[] dataRectangles)
     : base(device, description3D)
 {
     Resource = new Direct3D11.Texture3D(device, description3D, dataRectangles);
     Initialize(Resource);
 }