protected static void FromD3DLock(PixelBox rval, DX.DataBox lbox)
        {
            var bpp  = PixelUtil.GetNumElemBytes(rval.Format);
            var size = 0;

            if (bpp != 0)
            {
                rval.RowPitch   = lbox.RowPitch / bpp;
                rval.SlicePitch = lbox.SlicePitch / bpp;
                Debug.Assert((lbox.RowPitch % bpp) == 0);
                Debug.Assert((lbox.SlicePitch % bpp) == 0);
                size = lbox.RowPitch * rval.Height;
            }
            else if (PixelUtil.IsCompressed(rval.Format))
            {
                rval.RowPitch   = rval.Width;
                rval.SlicePitch = rval.Width * rval.Height;
                size            = rval.Width * rval.Height;
            }
            else
            {
                throw new AxiomException("Invalid pixel format");
            }

            rval.Data = BufferBase.Wrap(lbox.DataPointer, size);
        }
Exemple #2
0
        /// <summary>
        /// Function to create a list of buffers to use.
        /// </summary>
        /// <param name="data">Data to copy/reference.</param>
        internal unsafe void CreateBuffers(byte *data)
        {
            int bufferIndex = 0;
            var formatInfo  = GorgonBufferFormatInfo.GetInfo(_image.Settings.Format);                   // Format information.

            // Allocate enough room for the array and mip levels.
            _buffers = new GorgonImageBuffer[GorgonImageData.GetDepthSliceCount(_image.Settings.Depth, _image.Settings.MipCount) * _image.Settings.ArrayCount];

            MipOffsetSize = new Tuple <int, int> [_image.Settings.MipCount * _image.Settings.ArrayCount];               // Offsets for the mip maps.
            DataBoxes     = new DX.DataBox[_image.Settings.ArrayCount * _image.Settings.MipCount];                      // Create the data boxes for textures.

            // Enumerate array indices. (For 1D and 2D only, 3D will always be 1)
            for (int array = 0; array < _image.Settings.ArrayCount; array++)
            {
                int mipWidth  = _image.Settings.Width;
                int mipHeight = _image.Settings.Height;
                int mipDepth  = _image.Settings.Depth;

                // Enumerate mip map levels.
                for (int mip = 0; mip < _image.Settings.MipCount; mip++)
                {
                    int arrayIndex       = mip + (array * _image.Settings.MipCount);
                    var pitchInformation = formatInfo.GetPitch(mipWidth, mipHeight, PitchFlags.None);

                    // Get data box for texture upload.
                    DataBoxes[arrayIndex] = new DX.DataBox(new IntPtr(data), pitchInformation.RowPitch, pitchInformation.SlicePitch);

                    // Calculate buffer offset by mip.
                    MipOffsetSize[arrayIndex] = new Tuple <int, int>(bufferIndex, mipDepth);

                    // Enumerate depth slices.
                    for (int depth = 0; depth < mipDepth; depth++)
                    {
                        // Get mip information.
                        _buffers[bufferIndex] = new GorgonImageBuffer(data, pitchInformation, mip, array, depth, mipWidth, mipHeight,
                                                                      mipDepth, _image.Settings.Format);

                        data += pitchInformation.SlicePitch;
                        bufferIndex++;
                    }

                    if (mipWidth > 1)
                    {
                        mipWidth >>= 1;
                    }
                    if (mipHeight > 1)
                    {
                        mipHeight >>= 1;
                    }
                    if (mipDepth > 1)
                    {
                        mipDepth >>= 1;
                    }
                }
            }
        }
Exemple #3
0
        public void LoadFromLoadInfo(IO.Files.Texture.TextureLoadInfo loadInfo)
        {
            var texDesc = new Texture2DDescription
            {
                ArraySize = 1,
                BindFlags = BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = loadInfo.Format,
                Height = loadInfo.Height,
                Width = loadInfo.Width,
                MipLevels = loadInfo.Layers.Count,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default
            };

            if (mTexture != gDefaultTexture)
            {
                if (mTexture != null)
                    mTexture.Dispose();
                if (NativeView != null)
                    NativeView.Dispose();
            }

            var boxes = new DataBox[texDesc.MipLevels];
            var streams = new DataStream[texDesc.MipLevels];
            try
            {
                for(var i = 0; i < texDesc.MipLevels; ++i)
                {
                    streams[i] = new DataStream(loadInfo.Layers[i].Length, true, true);
                    streams[i].WriteRange(loadInfo.Layers[i]);
                    streams[i].Position = 0;
                    boxes[i] = new DataBox(streams[i].DataPointer, loadInfo.RowPitchs[i], 0);
                }

                mTexture = new Texture2D(mContext.Device, texDesc, boxes);
                var srvd = new ShaderResourceViewDescription
                {
                    Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D,
                    Format = loadInfo.Format,
                    Texture2D = new ShaderResourceViewDescription.Texture2DResource { MipLevels = boxes.Length, MostDetailedMip = 0 }
                };

                NativeView = new ShaderResourceView(mContext.Device, mTexture, srvd);
            }
            finally
            {
                foreach (var stream in streams)
                {
                    if (stream != null)
                        stream.Dispose();
                }
            }
        }
Exemple #4
0
        /// <summary>
        /// Sets 2D texture data, specifying a mipmap level, source rectangle, start index, and number of elements.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="level"></param>
        /// <param name="data"></param>
        /// <param name="startIndex"></param>
        /// <param name="elementCount"></param>
        public void SetData <T>(int level, Rectangle?rect, T[] data, int startIndex, int elementCount) where T : struct
        {
            var elementSizeInByte = Marshal.SizeOf(typeof(T));
            var dataHandle        = GCHandle.Alloc(data, GCHandleType.Pinned);

            // Use try..finally to make sure dataHandle is freed in case of an error
            try {
                var startBytes = startIndex * elementSizeInByte;
                var dataPtr    = (IntPtr)(dataHandle.AddrOfPinnedObject().ToInt64() + startBytes);

                int x, y, w, h;
                if (rect.HasValue)
                {
                    x = rect.Value.X;
                    y = rect.Value.Y;
                    w = rect.Value.Width;
                    h = rect.Value.Height;
                }
                else
                {
                    x = 0;
                    y = 0;
                    w = Math.Max(Width >> level, 1);
                    h = Math.Max(Height >> level, 1);

                    // For DXT textures the width and height of each level is a multiple of 4.
                    if (format == ColorFormat.Dxt1 ||
                        format == ColorFormat.Dxt3 ||
                        format == ColorFormat.Dxt5)
                    {
                        w = (w + 3) & ~3;
                        h = (h + 3) & ~3;
                    }
                }

                var box = new SharpDX.DataBox(dataPtr, w * Converter.SizeOf(format), 0);

                var region = new SharpDX.Direct3D11.ResourceRegion();
                region.Top    = y;
                region.Front  = 0;
                region.Back   = 1;
                region.Bottom = y + h;
                region.Left   = x;
                region.Right  = x + w;

                lock (device.DeviceContext) {
                    device.DeviceContext.UpdateSubresource(box, tex2D, level, region);
                }
            } finally {
                dataHandle.Free();
            }
        }
Exemple #5
0
        private void CaptureDX(Bitmap outputBMP)
        {
            // Try to get duplicated frame within given time is ms
            try
            {
                duplicatedOutput.AcquireNextFrame(5, out duplicateFrameInformation, out screenResource);
                // copy resource into memory that can be accessed by the CPU
                using (Texture2D screenTexture2D = screenResource.QueryInterface <Texture2D>())
                {
                    device.ImmediateContext.CopyResource(screenTexture2D, screenTexture);
                }
                // Get the desktop capture texture
                SharpDX.DataBox mapSource = device.ImmediateContext.MapSubresource(screenTexture, 0, MapMode.Read, SharpDX.Direct3D11.MapFlags.None);

                BitmapData mapDest = outputBMP.LockBits(screenBounds, ImageLockMode.WriteOnly, outputBMP.PixelFormat);

                IntPtr sourcePtr = mapSource.DataPointer;
                IntPtr destPtr   = mapDest.Scan0;

                for (int y = 0; y < screenBounds.Height; y++)
                {
                    // Copy a single line
                    Utilities.CopyMemory(destPtr, sourcePtr, screenBounds.Width * 4);

                    // Advance pointers
                    sourcePtr = IntPtr.Add(sourcePtr, mapSource.RowPitch);
                    destPtr   = IntPtr.Add(destPtr, mapDest.Stride);
                }

                outputBMP.UnlockBits(mapDest);
                device.ImmediateContext.UnmapSubresource(screenTexture, 0);

                duplicatedOutput.ReleaseFrame();
            }
            catch (SharpDXException e)
            {
                if (e.ResultCode.Code != SharpDX.DXGI.ResultCode.WaitTimeout.Result.Code)
                {
                    Trace.TraceError(e.Message);
                    Trace.TraceError(e.StackTrace);
                }
            }
        }
        internal unsafe void UpdateGeneric(List<MyInstanceData> instanceData, int capacity)
        {
            var instancesNum = instanceData.Count;
            if (m_capacity < instancesNum && VertexBuffer != VertexBufferId.NULL)
            {
                MyHwBuffers.Destroy(VertexBuffer);
                VertexBuffer = VertexBufferId.NULL;
            }
            if (m_capacity < instancesNum)
            {
                m_capacity = Math.Max(instancesNum, capacity);
                VertexBuffer = MyHwBuffers.CreateVertexBuffer(m_capacity, sizeof(MyVertexFormatGenericInstance), null, m_debugName + " instances buffer");
            }

            fixed (MyInstanceData* dataPtr = instanceData.ToArray())
            {
                DataBox srcBox = new DataBox(new IntPtr(dataPtr));
                ResourceRegion dstRegion = new ResourceRegion(0, 0, 0, sizeof(MyVertexFormatGenericInstance) * instancesNum, 1, 1);

                MyRender11.ImmediateContext.UpdateSubresource(srcBox, VertexBuffer.Buffer, 0, dstRegion);
            }
        }
Exemple #7
0
        /// <summary>
        /// Function to lock a sub resource.
        /// </summary>
        /// <param name="lockFlags">Flags used to lock the data.</param>
        /// <param name="mipLevel">Mip map level to lock.</param>
        /// <param name="arrayIndex">Array index to lock (1D/2D textures only).</param>
        /// <param name="context">Graphics context to use for the lock.</param>
        /// <returns>The locking data.</returns>
        public GorgonTextureLockData Lock(BufferLockFlags lockFlags, int mipLevel, int arrayIndex, GorgonGraphics context)
        {
            lock (_syncLock)
            {
                var key = new LockCacheKey(context, mipLevel, arrayIndex);
                GorgonTextureLockData result;

                if (_locks.TryGetValue(key, out result))
                {
                    return(result);
                }

                switch (_texture.ResourceType)
                {
                case ResourceType.Texture1D:
                case ResourceType.Texture2D:
                case ResourceType.Texture3D:
                    DX.DataStream lockStream;

                    DX.DataBox box = context.Context.MapSubresource(_texture.D3DResource,
                                                                    D3D.Resource.CalculateSubResourceIndex(mipLevel, arrayIndex, _texture.Settings.MipCount),
                                                                    GetMapMode(lockFlags),
                                                                    D3D.MapFlags.None,
                                                                    out lockStream);

                    result = new GorgonTextureLockData(context, _texture, this, box, mipLevel, arrayIndex);

                    _locks.Add(key, result);
                    break;

                default:
                    throw new GorgonException(GorgonResult.CannotCreate,
                                              string.Format(Resources.GORGFX_RESOURCE_INVALID, _texture.ResourceType));
                }

                return(result);
            }
        }
Exemple #8
0
        /// <summary>
        /// Получить изображение рабочего стола из DataBox
        /// </summary>
        private Image GetBitmap(DataBox mapSource)
        {
            Bitmap bitmap = new Bitmap(this._width, this._height, PixelFormat.Format32bppArgb);
            Rectangle boundsRect = new Rectangle(0, 0, this._width, this._height);

            BitmapData mapDest = bitmap.LockBits(boundsRect, ImageLockMode.WriteOnly, bitmap.PixelFormat);
            IntPtr sourcePtr = mapSource.DataPointer;
            IntPtr destPtr = mapDest.Scan0;
            for (int y = 0; y < this._height; y++)
            {
                Utilities.CopyMemory(destPtr, sourcePtr, this._width * 4);
                sourcePtr = IntPtr.Add(sourcePtr, mapSource.RowPitch);
                destPtr = IntPtr.Add(destPtr, mapDest.Stride);
            }
            bitmap.UnlockBits(mapDest);

            return bitmap;
        }
Exemple #9
0
        public void UpdateMemory(int width, int height, Format format, uint[] data, int pitch)
        {
            using (var stream = new DataStream(data.Length * 4, true, true))
            {
                stream.WriteRange(data);
                stream.Position = 0;
                var box = new DataBox(stream.DataPointer, pitch, 0);

                if (IsDirty(width, height, format, 1))
                    CreateNew(width, height, format, new[] { box });
                else
                {
                    var region = new ResourceRegion
                    {
                        Back = 1,
                        Bottom = height,
                        Front = 0,
                        Left = 0,
                        Right = width,
                        Top = 0
                    };
                    mContext.Context.UpdateSubresource(mTexture, 0, region, box.DataPointer, width * 4, 0);
                }
            }
        }
Exemple #10
0
 private ShaderResourceView GenerateProvinceTexture(IContext context, IList<LandProvince> provinces, Func<LandProvince, CustomColor> colorGenerator)
 {
     int maxId = provinces.Max(p => p.NumericId);
     Texture1D provinceTexture = new Texture1D(context.DirectX.Device, new Texture1DDescription
     {
         Width = maxId + 1,
         Format = Format.R32G32B32A32_Float,
         BindFlags = BindFlags.ShaderResource,
         ArraySize = 1,
         MipLevels = 1
     });
     int rowPitch = 16 * provinceTexture.Description.Width;
     var byteArray = new byte[rowPitch];
     foreach (LandProvince province in provinces)
     {
         CustomColor color = colorGenerator(province);
         Array.Copy(BitConverter.GetBytes(color.Red), 0, byteArray, province.NumericId * 16, 4);
         Array.Copy(BitConverter.GetBytes(color.Green), 0, byteArray, province.NumericId * 16 + 4, 4);
         Array.Copy(BitConverter.GetBytes(color.Blue), 0, byteArray, province.NumericId * 16 + 8, 4);
         Array.Copy(BitConverter.GetBytes(1.0f), 0, byteArray, province.NumericId * 16 + 12, 4);
     }
     DataStream dataStream = new DataStream(rowPitch,true, true);
     dataStream.Write(byteArray,0,rowPitch);
     DataBox data = new DataBox(dataStream.DataPointer, rowPitch, rowPitch);
     //ResourceRegion region = new ResourceRegion();
     context.DirectX.DeviceContext.UpdateSubresource(data, provinceTexture);
     return new ShaderResourceView(context.DirectX.Device, provinceTexture);
 }
        // Simple DDS loader ported from http://msdn.microsoft.com/en-us/library/windows/apps/jj651550.aspx
        static void CreateTextureFromDDS(
            SharpDX.Direct3D11.Device d3dDevice,
            ImageDescription imageDesc,
            //SharpDX.Toolkit.Graphics.DDS.Header header,
            //DDS_HEADER* header,
            IntPtr bitData,
            //_In_reads_bytes_(bitSize) const byte* bitData,
            int bitSize,
            out SharpDX.Direct3D11.Resource texture,
            //_Out_opt_ ID3D11Resource** texture,
            out ShaderResourceView textureView
            //_Out_opt_ ID3D11ShaderResourceView** textureView,
            )
        {
            int width = imageDesc.Width;
            int height = imageDesc.Height;
            int depth = imageDesc.Depth;

            int arraySize = imageDesc.ArraySize;
            Format format = imageDesc.Format;
            bool isCubeMap = imageDesc.Dimension == TextureDimension.TextureCube;

            int mipCount = imageDesc.MipLevels;// MipMapCount;
            if (0 == mipCount)
            {
                mipCount = 1;
            }

            // Create the texture
            DataBox[] initData = new DataBox[mipCount * arraySize];
            //std::unique_ptr<D3D11_SUBRESOURCE_DATA> initData(new D3D11_SUBRESOURCE_DATA[mipCount * arraySize]);

            int maxsize = 1;
            if (isCubeMap)
            {
                maxsize = SharpDX.Direct3D11.Resource.MaximumTextureCubeSize;
            }
            else
            {
                maxsize = (imageDesc.Dimension == TextureDimension.Texture3D)
                    ? SharpDX.Direct3D11.Resource.MaximumTexture3DSize
                    : SharpDX.Direct3D11.Resource.MaximumTexture2DSize;
            }

            int skipMip = 0;
            int twidth = 0;
            int theight = 0;
            int tdepth = 0;
            FillInitData(width, height, depth, mipCount, arraySize, format, maxsize, bitSize, bitData, out twidth, out theight, out tdepth, out skipMip, initData);

            CreateD3DResources(d3dDevice, imageDesc.Dimension, twidth, theight, tdepth, mipCount - skipMip, arraySize, format, isCubeMap, initData, out texture, out textureView);
        }
        static unsafe void CreateCommonTextures()
        {
            { 
                var desc = new Texture2DDescription();
                desc.ArraySize = 1;
                desc.BindFlags = BindFlags.ShaderResource;
                desc.Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm;
                desc.Height = 1;
                desc.Width = 1;
                desc.Usage = ResourceUsage.Immutable;
                desc.MipLevels = 1;
                desc.SampleDescription.Count = 1;
                desc.SampleDescription.Quality = 0;

                DataBox[] databox = new DataBox[1];
                uint data = 0;
                void* ptr = &data;

                databox[0].DataPointer = new IntPtr(ptr);
                databox[0].RowPitch = 4;

                ZeroTexId = RegisterTexture("EMPTY", null, MyTextureEnum.SYSTEM, new Texture2D(MyRender11.Device, desc, databox), new Vector2(1, 1));

                data = (255 << 16) | (127 << 8) | 127;
                MissingNormalGlossTexId = RegisterTexture("MISSING_NORMAL_GLOSS", null, MyTextureEnum.SYSTEM, new Texture2D(MyRender11.Device, desc, databox), new Vector2(1, 1));

                data = 255;
                MissingExtensionTexId = RegisterTexture("MISSING_EXTENSIONS", null, MyTextureEnum.SYSTEM, new Texture2D(MyRender11.Device, desc, databox), new Vector2(1, 1));

                data = (127 << 16) | (0 << 8) | 255;
                DebugPinkTexId = RegisterTexture("Pink", null, MyTextureEnum.SYSTEM, new Texture2D(MyRender11.Device, desc, databox), new Vector2(1, 1));
            }
            {
                var desc = new Texture2DDescription();
                desc.ArraySize = 6;
                desc.BindFlags = BindFlags.ShaderResource;
                desc.Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm;
                desc.Height = 1;
                desc.Width = 1;
                desc.Usage = ResourceUsage.Immutable;
                desc.MipLevels = 1;
                desc.SampleDescription.Count = 1;
                desc.SampleDescription.Quality = 0;
                desc.OptionFlags = ResourceOptionFlags.TextureCube;

                DataBox[] databox = new DataBox[6];
                uint data = 0;
                void* ptr = &data;

                for (int i = 0; i < 6; i++)
                {
                    databox[i].DataPointer = new IntPtr(ptr);
                    databox[i].RowPitch = 4;
                }

                MissingCubeTexId = RegisterTexture("MISSING_CUBEMAP", null, MyTextureEnum.SYSTEM, new Texture2D(MyRender11.Device, desc, databox), new Vector2(1, 1));
            }
            {
                byte[] ditherData = new byte[] {
                    0, 32, 8, 40, 2, 34, 10, 42,
                    48, 16, 56, 24, 50, 18, 58, 26,
                    12, 44, 4, 36, 14, 46, 6, 38, 
                    60, 28, 52, 20, 62, 30, 54, 22,
                    3, 35, 11, 43, 1, 33, 9, 41,
                    51, 19, 59, 27, 49, 17, 57, 25,
                    15, 47, 7, 39, 13, 45, 5, 37,
                    63, 31, 55, 23, 61, 29, 53, 21 };
                for (int i = 0; i < 64; i++)
                {
                    ditherData[i] *= 4;
                }
                var desc = new Texture2DDescription();
                desc.ArraySize = 1;
                desc.BindFlags = BindFlags.ShaderResource;
                desc.Format = SharpDX.DXGI.Format.R8_UNorm;
                desc.Height = 8;
                desc.Width = 8;
                desc.Usage = ResourceUsage.Immutable;
                desc.MipLevels = 1;
                desc.SampleDescription.Count = 1;
                desc.SampleDescription.Quality = 0;

                DataBox[] databox = new DataBox[1];
                fixed (byte* dptr = ditherData)
                {
                    databox[0].DataPointer = new IntPtr(dptr);
                    databox[0].RowPitch = 8;
                    Dithering8x8TexId = RegisterTexture("DITHER_8x8", null, MyTextureEnum.SYSTEM, new Texture2D(MyRender11.Device, desc, databox), new Vector2(8, 8));
                }

                byte bdata = 255;
                void *ptr = &bdata;
                databox[0].DataPointer = new IntPtr(ptr);
                databox[0].RowPitch = 1;
                desc.Height = 1;
                desc.Width = 1;

                MissingAlphamaskTexId = RegisterTexture("MISSING_ALPHAMASK", null, MyTextureEnum.SYSTEM, new Texture2D(MyRender11.Device, desc, databox), new Vector2(1, 1));
            }
        }
        internal unsafe void UpdateCube(List<MyCubeInstanceData> instanceData, int capacity)
        {
            Debug.Assert(m_type == MyRenderInstanceBufferType.Cube);

            var instancesNum = instanceData.Count;
            if (m_capacity < instancesNum && VB != VertexBufferId.NULL)
            {
                MyHwBuffers.Destroy(VB);
                VB = VertexBufferId.NULL;
            }
            if (m_capacity < instancesNum)
            {
                m_capacity = Math.Max(instancesNum, capacity);
                VB = MyHwBuffers.CreateVertexBuffer(m_capacity, sizeof(MyVertexFormatCubeInstance), null, m_debugName + " instances buffer");
            }

            var rawBuffer = new MyVertexFormatCubeInstance[m_capacity];
            for (int i = 0; i < instancesNum; i++)
            {
                fixed (byte* pSource = instanceData[i].RawBones(), pTarget = rawBuffer[i].bones)
                {
                    for (int j = 0; j < MyRender11Constants.CUBE_INSTANCE_BONES_NUM * 4; j++)
                        pTarget[j] = pSource[j];
                }
                rawBuffer[i].translationRotation = new HalfVector4(instanceData[i].m_translationAndRot);
                rawBuffer[i].colorMaskHSV = new HalfVector4(instanceData[i].ColorMaskHSV);
            }

            fixed (MyVertexFormatCubeInstance* dataPtr = rawBuffer)
            {
                DataBox srcBox = new DataBox(new IntPtr(dataPtr));
                ResourceRegion dstRegion = new ResourceRegion(0, 0, 0, sizeof(MyVertexFormatCubeInstance) * instancesNum, 1, 1);

                MyRender11.ImmediateContext.UpdateSubresource(srcBox, VB.Buffer, 0, dstRegion);
            }

            BumpRenderable();
        }
        public override int MakeVertexBuffer(int size)
        {
            var bufferDesc = new BufferDescription(
                    size,
                    SharpDX.Direct3D11.ResourceUsage.Dynamic,
                    SharpDX.Direct3D11.BindFlags.VertexBuffer,
                    SharpDX.Direct3D11.CpuAccessFlags.Write,
                    0,
                    3
            );
            var buffer = new Buffer(device, bufferDesc);
            var bufferBinding = new VertexBufferBinding(buffer, 0, 0);
            var databox = new DataBox();

            // TODO there are no bounds checking here; we can only actually add 16 or 32
            lastVertexBuffer++;

            vertexBuffers[lastVertexBuffer] = buffer;
            vertexBufferDataBoxes[lastVertexBuffer] = databox;
            context.InputAssembler.SetVertexBuffers(lastVertexBuffer, bufferBinding);

            return lastVertexBuffer;
        }
Exemple #15
0
        public void UpdateMemory(int width, int height, Format format, byte[] data, int pitch)
        {
            using (var stream = new DataStream(data.Length, true, true))
            {
                stream.WriteRange(data);
                stream.Position = 0;
                var box = new DataBox(stream.DataPointer, pitch, 0);

                if (width != mTexture.Description.Width || height != mTexture.Description.Height ||
                    format != mTexture.Description.Format || mTexture.Description.MipLevels != 1 ||
                    mTexture == gDefaultTexture)
                {
                    CreateNew(width, height, format, new[] { box });
                }
                else
                {
                    var region = new ResourceRegion
                    {
                        Back = 1,
                        Bottom = height,
                        Front = 0,
                        Left = 0,
                        Right = width,
                        Top = 0
                    };
                    mContext.Context.UpdateSubresource(mTexture, 0, region, box.DataPointer, width * 4, 0);
                }
            }
        }
Exemple #16
0
        public void UpdateTexture(int width, int height, Format format, List<byte[]> layers, List<int> rowSizes)
        {
            var boxes = new DataBox[layers.Count];
            var streams = new DataStream[layers.Count];
            try
            {
                for (var i = 0; i < layers.Count; ++i)
                {
                    streams[i] = new DataStream(layers[i].Length, true, true);
                    streams[i].WriteRange(layers[i]);
                    streams[i].Position = 0;
                    boxes[i] = new DataBox(streams[i].DataPointer, rowSizes[i], 0);
                }

                if (IsDirty(width, height, format, layers.Count))
                    CreateNew(width, height, format, boxes);
                else
                {
                    for (var i = 0; i < layers.Count; ++i)
                    {
                        mContext.Context.UpdateSubresource(boxes[i], mTexture, i);
                    }
                }
            }
            finally
            {
                foreach (var strm in streams)
                {
                    if (strm != null)
                        strm.Dispose();
                }
            }
        }
Exemple #17
0
        public static void InitDefaultTexture(GxContext context)
        {
            var desc = new Texture2DDescription
            {
                ArraySize = 1,
                BindFlags = BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = Format.R8G8B8A8_UNorm,
                Height = 2,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Immutable,
                Width = 2
            };

            using (var strm = new DataStream(16, true, true))
            {
                strm.WriteRange(new[] {0xFFFF0000, 0xFF00FF00, 0xFF0000FF, 0xFFFFFFFF});
                var layerData = new DataBox(strm.DataPointer) {RowPitch = 8};
                gDefaultTexture = new Texture2D(context.Device, desc, new[] { layerData });
            }

            var srvd = new ShaderResourceViewDescription
            {
                Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D,
                Format = Format.R8G8B8A8_UNorm,
                Texture2D = new ShaderResourceViewDescription.Texture2DResource
                {
                    MipLevels = 1,
                    MostDetailedMip = 0
                }
            };

            gDefaultView = new ShaderResourceView(context.Device, gDefaultTexture, srvd);
        }
Exemple #18
0
        private void CreateNew(int width, int height, Format format, DataBox[] boxes)
        {
            if (mTexture != gDefaultTexture)
            {
                mTexture.Dispose();
                NativeView.Dispose();
            }

            var desc = mTexture.Description;
            desc.Width = width;
            desc.Height = height;
            desc.Format = format;
            desc.Usage = ResourceUsage.Default;
            mTexture = new Texture2D(mContext.Device, desc, boxes);

            var srvd = new ShaderResourceViewDescription
            {
                Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D,
                Format = format,
                Texture2D = new ShaderResourceViewDescription.Texture2DResource { MipLevels = boxes.Length, MostDetailedMip = 0 }
            };

            NativeView = new ShaderResourceView(mContext.Device, mTexture, srvd);
        }
        internal unsafe static void UpdateVertexBuffer(InstancingId id)
        {
            var info = id.Info;
            if (info.Capacity == 0)
            { 
                return;
            }

            fixed (byte* ptr = info.Data)
            {
                if(Data[id.Index].VB == VertexBufferId.NULL)
                {
                    Data[id.Index].VB = MyHwBuffers.CreateVertexBuffer(info.Capacity, info.Stride, new IntPtr(ptr), info.DebugName);
                }
                else
                {
                    var vb = Data[id.Index].VB;
                    MyHwBuffers.ResizeVertexBuffer(vb, info.Capacity);

                    DataBox srcBox = new DataBox(new IntPtr(ptr));
                    ResourceRegion dstRegion = new ResourceRegion(0, 0, 0, info.Stride * info.Capacity, 1, 1);

                    MyRender11.ImmediateContext.UpdateSubresource(srcBox, vb.Buffer, 0, dstRegion);
                }
            }
        }
        public System.Drawing.Bitmap Capture()
        {
            isInCapture = true;
            
            try
            {

                // init
                bool captureDone = false;
                bitmap = new System.Drawing.Bitmap(captureRect.Width, captureRect.Height, PixelFormat.Format32bppArgb);

                // the capture needs some time
                for (int i = 0; !captureDone; i++)
                {
                    try
                    {


                        //capture
                        duplicatedOutput.AcquireNextFrame(-1, out duplicateFrameInformation, out screenResource);
                        // only for wait
                        if (i > 0)
                        {
                            using (var screenTexture2D = screenResource.QueryInterface<Texture2D>())
                                device.ImmediateContext.CopyResource(screenTexture2D, screenTexture);

                            mapSource = device.ImmediateContext.MapSubresource(screenTexture, 0, MapMode.Read, MapFlags.None);

                            mapDest = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, captureRect.Width, captureRect.Height),
                                                                  ImageLockMode.WriteOnly, bitmap.PixelFormat);

                            sourcePtr = mapSource.DataPointer;
                            destPtr = mapDest.Scan0;

                            // set x position offset to rect.x
                            int rowPitch = mapSource.RowPitch - offsetX;
                            // set pointer to y position
                            sourcePtr = IntPtr.Add(sourcePtr, mapSource.RowPitch * captureRect.Y);

                            for (int y = 0; y < captureRect.Height; y++) // needs to speed up!!
                            {
                                // set pointer to x position
                                sourcePtr = IntPtr.Add(sourcePtr, offsetX);

                                // copy pixel to bmp
                                Utilities.CopyMemory(destPtr, sourcePtr, pWidth);

                                // incement pointert to next line
                                sourcePtr = IntPtr.Add(sourcePtr, rowPitch);
                                destPtr = IntPtr.Add(destPtr, mapDest.Stride);
                            }



                            bitmap.UnlockBits(mapDest);
                            device.ImmediateContext.UnmapSubresource(screenTexture, 0);

                            captureDone = true;
                        }

                        screenResource.Dispose();
                        duplicatedOutput.ReleaseFrame();

                        //Thread STAThread = new Thread(() =>
                        //{
                            //EffectShader x = new EffectShader(captureRect.Width, captureRect.Height, 1, ShaderFilename);
                            //bitmap = x.ApplyShader(bitmap);
                            //x = null;
                        //});
                        //STAThread.SetApartmentState(ApartmentState.STA);
                        //STAThread.Start();
                        //STAThread.Join();

                        //STAThread = null;

                    }
                    catch//(Exception ex)  //                    catch (SharpDXException e)
                    {
                        //if (e.ResultCode.Code != SharpDX.DXGI.ResultCode.WaitTimeout.Result.Code)
                        //{
                        //   // throw e;
                        //}

                        return new Bitmap(captureRect.Width, captureRect.Height, PixelFormat.Format32bppArgb);
                    }
                }

            }
            catch 
            {
                return new Bitmap(captureRect.Width, captureRect.Height, PixelFormat.Format32bppArgb);
            }

            isInCapture = false;
            return bitmap;
        }
        static void LoadTexture(TexId texId)
        {
            var contentPath = Textures.Data[texId.Index].ContentPath;
            string path;
            
            if (string.IsNullOrEmpty(contentPath))
                path = Path.Combine(MyFileSystem.ContentPath, Textures.Data[texId.Index].Name);
            else
                path = Path.Combine(contentPath, Textures.Data[texId.Index].Name);

            Debug.Assert(Textures.Data[texId.Index].Resource == null);
            Debug.Assert(GetView(texId) == null, "Texture " + Textures.Data[texId.Index].Name + " in invalid state");

            Image img = null;

            if (MyFileSystem.FileExists(path))
            {
                try
                {
                    using (var s = MyFileSystem.OpenRead(path))
                    {
                        img = Image.Load(s);
                    }
                }
                catch(Exception e)
                {
                    MyRender11.Log.WriteLine("Could not load texture: " + path + ", exception: " + e);
                }
            }

            if(img != null)
            {
                
                int skipMipmaps = (Textures.Data[texId.Index].Type != MyTextureEnum.GUI && img.Description.MipLevels > 1) ? MyRender11.RenderSettings.TextureQuality.MipmapsToSkip(img.Description.Width, img.Description.Height) : 0;

                int targetMipmaps = img.Description.MipLevels - skipMipmaps;
                var mipmapsData = new DataBox[(img.Description.MipLevels - skipMipmaps) * img.Description.ArraySize];
                for(int z = 0; z<img.Description.ArraySize; z++)
                {
                    for (int i = 0; i < targetMipmaps; i++)
                    {
                        var pixels = img.GetPixelBuffer(z, i + skipMipmaps);
                        mipmapsData[Resource.CalculateSubResourceIndex(i, z, targetMipmaps)] = 
                            new DataBox { DataPointer = pixels.DataPointer, RowPitch = pixels.RowStride };
                    }
                }

                var targetWidth = img.Description.Width >> skipMipmaps;
                var targetHeight = img.Description.Height >> skipMipmaps;

                var desc = new Texture2DDescription
                {
                    MipLevels = targetMipmaps,
                    Format = img.Description.Format,
                    Height = targetHeight,
                    Width = targetWidth,
                    ArraySize = img.Description.ArraySize,
                    BindFlags = BindFlags.ShaderResource,
                    CpuAccessFlags = CpuAccessFlags.None,
                    Usage = ResourceUsage.Immutable,
                    SampleDescription = new SharpDX.DXGI.SampleDescription { Count = 1, Quality = 0 },
                    OptionFlags = img.Description.Dimension == TextureDimension.TextureCube ? ResourceOptionFlags.TextureCube : ResourceOptionFlags.None
                };

                var resource = new Texture2D(MyRender11.Device, desc, mipmapsData);
                Textures.Data[texId.Index].Resource = resource;
                Textures.Data[texId.Index].Size = new Vector2(targetWidth, targetHeight);
                Textures.Data[texId.Index].SkippedMipmaps = skipMipmaps;
                Textures.Data[texId.Index].FileExists = true;
                Views[texId.Index] = new ShaderResourceView(MyRender11.Device, resource);
                resource.DebugName = path;
                Views[texId.Index].DebugName = path;

                img.Dispose();
            }
            else
            {
                // set data to some crap
                TexId replacingId = ZeroTexId;

                switch(Textures.Data[texId.Index].Type)
                {
                    case MyTextureEnum.NORMALMAP_GLOSS:
                        replacingId = MissingNormalGlossTexId;
                        break;
                    case MyTextureEnum.EXTENSIONS:
                        replacingId = MissingExtensionTexId;
                        break;
                    case MyTextureEnum.ALPHAMASK:
                        replacingId = MissingAlphamaskTexId;
                        break;
                    case MyTextureEnum.CUBEMAP:
                        replacingId = MissingCubeTexId;
                        break;
                    case MyTextureEnum.COLOR_METAL:
                        replacingId = MyRender11.DebugMode ? DebugPinkTexId : ZeroTexId;
                        break;
                }

                Views[texId.Index] = Views[replacingId.Index];
                Textures.Data[texId.Index].Resource = Textures.Data[replacingId.Index].Resource;
                Textures.Data[texId.Index].Size = Textures.Data[replacingId.Index].Size;
                Textures.Data[texId.Index].OwnsData = false;
            }
        }
Exemple #22
0
        private ShaderResourceView GenerateTexture(IContext context, int sliceCount)
        {
            Texture1D provinceTexture = new Texture1D(context.DirectX.Device, new Texture1DDescription
            {
                Width = sliceCount,
                Format = Format.R32G32B32A32_Float,
                BindFlags = BindFlags.ShaderResource,
                ArraySize = 1,
                MipLevels = 1
            });

            int rowPitch = 16 * sliceCount;
            var byteArray = new byte[rowPitch];
            for (int i = 0; i < sliceCount; i++)
            {
                CustomColor color = ColorInSlice(i);
                Array.Copy(BitConverter.GetBytes(color.Red), 0, byteArray, i * 16, 4);
                Array.Copy(BitConverter.GetBytes(color.Green), 0, byteArray, i * 16 + 4, 4);
                Array.Copy(BitConverter.GetBytes(color.Blue), 0, byteArray, i * 16 + 8, 4);
                Array.Copy(BitConverter.GetBytes(1.0f), 0, byteArray, i * 16 + 12, 4);
            }
            DataStream dataStream = new DataStream(rowPitch, true, true);
            dataStream.Write(byteArray, 0, rowPitch);
            DataBox data = new DataBox(dataStream.DataPointer, rowPitch, rowPitch);
            context.DirectX.DeviceContext.UpdateSubresource(data, provinceTexture);

            return new ShaderResourceView(context.DirectX.Device, provinceTexture);
        }
Exemple #23
0
        /// <summary>
        /// Create a Texture2D array which contains mipmapped versions of all symbol drawings
        /// </summary>
        public static Texture2D CreateTextures11(Device device, ITileSet tileSet)
        {
            var numDistinctBitmaps = EnumHelpers.GetEnumMax<SymbolID>() + 1;

            int maxTileSize = 64;
            int mipLevels = 4; // 64, 32, 16, 8

            var atlasTexture = new Texture2D(device, new Texture2DDescription()
            {
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,

                Format = Format.B8G8R8A8_UNorm,
                Width = maxTileSize,
                Height = maxTileSize,
                SampleDescription = new SampleDescription(1, 0),

                ArraySize = numDistinctBitmaps,
                MipLevels = mipLevels,
            });

            for (int mipLevel = 0; mipLevel < mipLevels; ++mipLevel)
            {
                int tileSize = maxTileSize >> mipLevel;

                const int bytesPerPixel = 4;
                var pixelArray = new byte[tileSize * tileSize * bytesPerPixel];

                for (int i = 0; i < numDistinctBitmaps; ++i)
                {
                    tileSet.GetTileRawBitmap((SymbolID)i, tileSize, pixelArray);
            #if COLORMIPMAPS
                    byte r, g, b;
                    switch (mipLevel)
                    {
                        case 0: r = 255; g = 0; b = 0; break;
                        case 1: r = 0; g = 255; b = 0; break;
                        case 2: r = 0; g = 0; b = 255; break;
                        case 3: r = 255; g = 255; b = 0; break;
                        case 4: r = 255; g = 0; b = 255; break;
                        case 5: r = 0; g = 255; b = 255; break;

                        default: throw new Exception();
                    }

                    for (int y = 0; y < tileSize; ++y)
                    {
                        for (int x = 0; x < tileSize; ++x)
                        {
                            pixelArray[y * tileSize * 4 + x * 4 + 0] = b;
                            pixelArray[y * tileSize * 4 + x * 4 + 1] = g;
                            pixelArray[y * tileSize * 4 + x * 4 + 2] = r;
                            pixelArray[y * tileSize * 4 + x * 4 + 3] = 255;
                        }
                    }
            #endif

            #if TEST
                    for (int y = 0; y < tileSize; ++y)
                    {
                        for (int x = 0; x < tileSize; ++x)
                        {
                            if (x == y)
                            {
                                pixelArray[y * tileSize * 4 + x * 4 + 0] = 255;
                                pixelArray[y * tileSize * 4 + x * 4 + 1] = (byte)y;
                                pixelArray[y * tileSize * 4 + x * 4 + 2] = (byte)(x + y);
                                pixelArray[y * tileSize * 4 + x * 4 + 3] = 255;
                            }
                        }
                    }
            #endif

                    using (var dataStream = DataStream.Create(pixelArray, true, false))
                    {
                        var box = new DataBox(dataStream.DataPointer, tileSize * 4, 0);
                        device.ImmediateContext.UpdateSubresource(box, atlasTexture, Texture2D.CalculateSubResourceIndex(mipLevel, i, mipLevels));
                    }
                }
            }

            return atlasTexture;
        }
Exemple #24
0
 private void UpdateTexture(IContext context, ShaderResourceView texture, int sliceCount)
 {
     int rowPitch = 16 * sliceCount;
     var byteArray = new byte[rowPitch];
     for(int i=0; i<sliceCount; i++)
     {
         CustomColor color = ColorInSlice(i);
         Array.Copy(BitConverter.GetBytes(color.Red), 0, byteArray, i * 16, 4);
         Array.Copy(BitConverter.GetBytes(color.Green), 0, byteArray, i * 16 + 4, 4);
         Array.Copy(BitConverter.GetBytes(color.Blue), 0, byteArray, i * 16 + 8, 4);
         Array.Copy(BitConverter.GetBytes(1.0f), 0, byteArray, i * 16 + 12, 4);
     }
     DataStream dataStream = new DataStream(rowPitch, true, true);
     dataStream.Write(byteArray, 0, rowPitch);
     DataBox data = new DataBox(dataStream.DataPointer, rowPitch, rowPitch);
     context.DirectX.DeviceContext.UpdateSubresource(data, texture.Resource);
 }
        // Simple DDS loader ported from http://msdn.microsoft.com/en-us/library/windows/apps/jj651550.aspx
        static void CreateD3DResources(
            SharpDX.Direct3D11.Device d3dDevice,
            TextureDimension resDim,
            int width,
            int height,
            int depth,
            int mipCount,
            int arraySize,
            Format format,
            bool isCubeMap,
            DataBox[] initData,
            //_In_reads_(mipCount*arraySize) D3D11_SUBRESOURCE_DATA* initData,
            out SharpDX.Direct3D11.Resource texture,
            out SharpDX.Direct3D11.ShaderResourceView textureView
            //_Out_opt_ ID3D11Resource** texture,
            //_Out_opt_ ID3D11ShaderResourceView** textureView
            )
        {
            texture = null;
            textureView = null;

            if (d3dDevice == null || initData == null)
            {
                return;
            }

            switch (resDim)
            {
                case TextureDimension.Texture1D:// D3D11_RESOURCE_DIMENSION_TEXTURE1D:
                    {
                        Texture1DDescription desc = new Texture1DDescription();
                        //D3D11_TEXTURE1D_DESC desc;
                        desc.Width = width;
                        desc.MipLevels = mipCount;
                        desc.ArraySize = arraySize;
                        desc.Format = format;
                        desc.Usage = ResourceUsage.Default;
                        desc.BindFlags = BindFlags.ShaderResource;// D3D11_BIND_SHADER_RESOURCE;
                        desc.CpuAccessFlags = CpuAccessFlags.None;
                        desc.OptionFlags = ResourceOptionFlags.None;

                        Texture1D tex = null;
                        //ID3D11Texture1D* tex = nullptr;
                        tex = new Texture1D(d3dDevice, desc, initData);
                        //hr = d3dDevice->CreateTexture1D(&desc, initData, &tex);

                        if (tex != null)
                        {
                            ShaderResourceViewDescription SRVDesc = new ShaderResourceViewDescription();
                            //D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
                            //memset(&SRVDesc, 0, sizeof(SRVDesc));
                            SRVDesc.Format = format;

                            if (arraySize > 1)
                            {
                                SRVDesc.Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture1DArray;// D3D_SRV_DIMENSION_TEXTURE1DARRAY;
                                SRVDesc.Texture1DArray.MipLevels = desc.MipLevels;
                                SRVDesc.Texture1DArray.ArraySize = arraySize;
                            }
                            else
                            {
                                SRVDesc.Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture1D;// D3D_SRV_DIMENSION_TEXTURE1D;
                                SRVDesc.Texture1D.MipLevels = desc.MipLevels;
                            }

                            textureView = new ShaderResourceView(d3dDevice, tex, SRVDesc);
                            //hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView);

                            if (textureView == null)
                            {
                                tex.Dispose();
                                return;
                            }

                            texture = tex;
                        }
                    }
                    break;

                case TextureDimension.TextureCube:
                case TextureDimension.Texture2D:// D3D11_RESOURCE_DIMENSION_TEXTURE2D:
                    {
                        Texture2DDescription desc = new Texture2DDescription();
                        desc.Width = width;
                        desc.Height = height;
                        desc.MipLevels = mipCount;
                        desc.ArraySize = arraySize;
                        desc.Format = format;
                        desc.SampleDescription.Count = 1;
                        desc.SampleDescription.Quality = 0;
                        desc.Usage = ResourceUsage.Default;
                        desc.BindFlags = BindFlags.ShaderResource;
                        desc.CpuAccessFlags = CpuAccessFlags.None;
                        desc.OptionFlags = (isCubeMap) ? ResourceOptionFlags.TextureCube : ResourceOptionFlags.None;

                        Texture2D tex = null;
                        tex = new Texture2D(d3dDevice, desc, initData);
                        tex.DebugName = "Test";
                        //hr = d3dDevice->CreateTexture2D(&desc, initData, &tex);

                        if (tex != null)
                        {
                            ShaderResourceViewDescription SRVDesc = new ShaderResourceViewDescription();
                            SRVDesc.Format = format;

                            if (isCubeMap)
                            {
                                if (arraySize > 6)
                                {
                                    SRVDesc.Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.TextureCubeArray;
                                    SRVDesc.TextureCubeArray.MipLevels = desc.MipLevels;

                                    // Earlier we set arraySize to (NumCubes * 6)
                                    SRVDesc.TextureCubeArray.CubeCount = arraySize / 6;
                                }
                                else
                                {
                                    SRVDesc.Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.TextureCube;
                                    SRVDesc.TextureCube.MipLevels = desc.MipLevels;
                                }
                            }
                            else if (arraySize > 1)
                            {
                                SRVDesc.Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2DArray;
                                SRVDesc.Texture2DArray.MipLevels = desc.MipLevels;
                                SRVDesc.Texture2DArray.ArraySize = arraySize;
                            }
                            else
                            {
                                SRVDesc.Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D;
                                SRVDesc.Texture2D.MipLevels = desc.MipLevels;
                            }

                            textureView = new ShaderResourceView(d3dDevice, tex, SRVDesc);
                            //hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView);

                            texture = tex;
                        }
                    }
                    break;

                case TextureDimension.Texture3D:
                    {
                        Texture3DDescription desc = new Texture3DDescription();
                        desc.Width = width;
                        desc.Height = height;
                        desc.Depth = depth;
                        desc.MipLevels = mipCount;
                        desc.Format = format;
                        desc.Usage = ResourceUsage.Default;
                        desc.BindFlags = BindFlags.ShaderResource;
                        desc.CpuAccessFlags = CpuAccessFlags.None;
                        desc.OptionFlags = ResourceOptionFlags.None;

                        Texture3D tex = null;
                        tex = new Texture3D(d3dDevice, desc, initData);
                        //hr = d3dDevice->CreateTexture3D(&desc, initData, &tex);

                        if (tex != null)
                        {
                            ShaderResourceViewDescription SRVDesc = new ShaderResourceViewDescription();
                            SRVDesc.Format = format;
                            SRVDesc.Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture3D;
                            SRVDesc.Texture3D.MipLevels = desc.MipLevels;

                            textureView = new ShaderResourceView(d3dDevice, tex, SRVDesc);
                            texture = tex;
                        }
                    }
                    break;
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="GorgonTextureLockData"/> class.
        /// </summary>
        /// <param name="graphics">The graphics context that owns this lock.</param>
        /// <param name="texture">The texture that owns this lock.</param>
        /// <param name="cache">Lock cache that will contain this lock.</param>
        /// <param name="data">The data returned from the lock.</param>
        /// <param name="mipLevel">The mip level of the sub resource.</param>
        /// <param name="arrayIndex">Array index of the sub resource.</param>
        internal GorgonTextureLockData(GorgonGraphics graphics, GorgonTexture texture, GorgonTextureLockCache cache, DX.DataBox data, int mipLevel, int arrayIndex)
            : base(mipLevel, arrayIndex, 0)
        {
            Graphics = graphics;
            Texture  = texture;
            _cache   = cache;

            Width  = Texture.Settings.Width;
            Height = Texture.Settings.Height;
            Depth  = Texture.Settings.Depth;

            // Calculate the current size at the given mip level.
            for (int mip = 0; mip < mipLevel; ++mip)
            {
                if (Width > 1)
                {
                    Width >>= 1;
                }
                if (Height > 1)
                {
                    Height >>= 1;
                }
                if (Depth > 1)
                {
                    Depth >>= 1;
                }
            }

            PitchInformation = new GorgonFormatPitch(data.RowPitch, data.SlicePitch);
            Data             = new GorgonDataStream(data.DataPointer.ToPointer(), data.SlicePitch);
        }
        // Simple DDS loader ported from http://msdn.microsoft.com/en-us/library/windows/apps/jj651550.aspx
        static void FillInitData(
            int width,
            int height,
            int depth,
            int mipCount,
            int arraySize,
            Format format,
            int maxsize,
            int bitSize,
            IntPtr bitData,
            out int twidth,
            out int theight,
            out int tdepth,
            out int skipMip,
            DataBox[] initData
            )
        {
            if (bitData == IntPtr.Zero)
            {
                throw new ArgumentNullException("bitData");
            }

            skipMip = 0;
            twidth = 0;
            theight = 0;
            tdepth = 0;

            int numBytes = 0;
            int rowBytes = 0;
            int numRows = 0;
            IntPtr pSrcBits = bitData;
            IntPtr pEndBits = IntPtr.Add(bitData, bitSize);

            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++)
                {
                    //FormatHelper.
                    if (FormatHelper.IsCompressed(format))
                    {
                        int numBlocksWide = 0;
                        if (width > 0)
                        {
                            numBlocksWide = Math.Max(1, (width + 3) / 4);
                        }
                        int numBlocksHigh = 0;
                        if (height > 0)
                        {
                            numBlocksHigh = Math.Max(1, (height + 3) / 4);
                        }
                        int bytesPerBlock = 0;

                        switch (format)
                        {
                            case Format.BC1_Typeless:
                            case Format.BC1_UNorm:
                            case Format.BC1_UNorm_SRgb:
                            case Format.BC4_Typeless:
                            case Format.BC4_UNorm:
                            case Format.BC4_SNorm:
                                bytesPerBlock = 8;
                                break;

                            case Format.BC2_Typeless:
                            case Format.BC2_UNorm:
                            case Format.BC2_UNorm_SRgb:
                            case Format.BC3_Typeless:
                            case Format.BC3_UNorm:
                            case Format.BC3_UNorm_SRgb:
                            case Format.BC5_Typeless:
                            case Format.BC5_UNorm:
                            case Format.BC5_SNorm:
                            case Format.BC6H_Typeless:
                            case Format.BC6H_Uf16:
                            case Format.BC6H_Sf16:
                            case Format.BC7_Typeless:
                            case Format.BC7_UNorm:
                            case Format.BC7_UNorm_SRgb:
                                bytesPerBlock = 16;
                                break;
                            default:
                                break;
                        }
                        rowBytes = numBlocksWide * bytesPerBlock;
                        numRows = numBlocksHigh;
                    }
                    else if (FormatHelper.IsPacked(format))
                    {
                        rowBytes = ((width + 1) >> 1) * 4;
                        numRows = height;
                    }
                    else
                    {
                        int bpp = FormatHelper.SizeOfInBits(format);// BitsPerPixel(fmt);
                        rowBytes = (width * bpp + 7) / 8; // round up to nearest byte
                        numRows = height;
                    }

                    numBytes = rowBytes * numRows;
                    //GetSurfaceInfo(w, h, format, NumBytes, RowBytes, NumRows);

                    if ((mipCount <= 1) || maxsize <= 0 || (w <= maxsize && h <= maxsize && d <= maxsize))
                    {
                        if (twidth <= 0)
                        {
                            twidth = w;
                            theight = h;
                            tdepth = d;
                        }

                        initData[index].DataPointer = pSrcBits;
                        initData[index].RowPitch = rowBytes;
                        initData[index].SlicePitch = numBytes;
                        ++index;
                    }
                    else
                    {
                        ++skipMip;
                    }

                    if (pSrcBits.ToInt64() + (numBytes * d) > pEndBits.ToInt64())
                    {
                        throw new IndexOutOfRangeException("Gone past end of DDS");
                    }

                    IntPtr.Add(pSrcBits, 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;
                    }
                }
            }

            if (index == 0)
            {
                throw new Exception("Failed to create DataBoxes");
            }
        }
Exemple #28
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);
        }