예제 #1
0
 internal virtual void Dispose()
 {
     if (m_resource != null)
     {
         m_resource.Dispose();
         m_resource = null;
     }
 }
예제 #2
0
 internal static MyMapping MapDiscard(DeviceContext context, Resource buffer)
 {
     MyMapping mapping;
     mapping.context = context;
     mapping.buffer = buffer;
     mapping.dataBox = context.MapSubresource(buffer, 0, MapMode.WriteDiscard, MapFlags.None, out mapping.stream);
     return mapping;
 }
예제 #3
0
        // 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);
        }
예제 #4
0
        /// <summary>
        /// gets color data, only works for the 4 supported formats.
        /// Mainly for debug purposes
        /// </summary>
        /// <returns></returns>
        public unsafe Color[] GetColorData(Resource res, Format format, int subresource, Size3 size)
        {
            Debug.Assert(IO.SupportedFormats.Contains(format) || format == Format.R8_UInt);

            if (format == Format.R32G32B32A32_Float)
            {
                var tmp    = GetData(res, subresource, size, 4 * 4);
                var result = new Color[size.Product];
                fixed(byte *pBuffer = tmp)
                {
                    for (int i = 0; i < result.Length; i++)
                    {
                        result[i] = ((Color *)pBuffer)[i];
                    }
                }

                return(result);
            }
            else if (format == Format.R8_UInt)
            {
                var tmp    = GetData(res, subresource, size, 1);
                var result = new Color[size.Product];
                fixed(byte *pBuffer = tmp)
                {
                    for (int dst = 0, src = 0; dst < result.Length; ++dst, src += 1)
                    {
                        result[dst] = new Color((float)(pBuffer[src]), 0.0f, 0.0f);
                    }
                }

                return(result);
            }


            else
            {
                var  tmp      = GetData(res, subresource, size, 4);
                var  result   = new Color[size.Product];
                bool isSigned = format == Format.R8G8B8A8_SNorm;
                bool isSrgb   = format == Format.R8G8B8A8_UNorm_SRgb;
                fixed(byte *pBuffer = tmp)
                {
                    for (int dst = 0, src = 0; dst < result.Length; ++dst, src += 4)
                    {
                        result[dst] = new Color(pBuffer[src], pBuffer[src + 1], pBuffer[src + 2], pBuffer[src + 3], isSigned);
                        if (isSrgb)
                        {
                            result[dst] = result[dst].FromSrgb();
                        }
                    }
                }

                return(result);
            }
        }
예제 #5
0
 public void Destroy()
 {
     TextureState = FileTextureState.Unloaded;
     if (m_ownsData)
     {
         m_srv.Dispose();
         m_resource.Dispose();
     }
     m_srv      = null;
     m_resource = null;
 }
예제 #6
0
        /// <summary>
        /// 原始思想:http://stackoverflow.com/questions/19364012/d3d11-creating-a-cube-map-from-6-images
        /// 上面的链接页面中,OptionFlags 的参数错误,后参考 http://www.gamedev.net/topic/647237-dx11-cube-texture-creation/ 做出修正。
        /// </summary>
        /// <param name="device"></param>
        /// <param name="texture2Ds"></param>
        /// <returns></returns>
        public static ShaderResourceView CreateCubeMapFrom6Textures(Device device, Texture2D[] texture2Ds)
        {
            Debug.Assert(texture2Ds.Length == 6);
            var texElemDesc  = texture2Ds[0].Description;
            var texArrayDesc = new Texture2DDescription()
            {
                Width             = texElemDesc.Width,
                Height            = texElemDesc.Height,
                MipLevels         = texElemDesc.MipLevels,
                ArraySize         = 6,
                Format            = texElemDesc.Format,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.TextureCube
            };
            var texArray     = new Texture2D(device, texArrayDesc);
            var context      = device.ImmediateContext;
            var sourceRegion = new ResourceRegion();

            for (var i = 0; i < 6; ++i)
            {
                for (var mipLevel = 0; mipLevel < texArrayDesc.MipLevels; ++mipLevel)
                {
                    sourceRegion.Left   = 0;
                    sourceRegion.Right  = texArrayDesc.Width >> mipLevel;
                    sourceRegion.Top    = 0;
                    sourceRegion.Bottom = texArrayDesc.Height >> mipLevel;
                    sourceRegion.Front  = 0;
                    sourceRegion.Back   = 1;
                    if (sourceRegion.Bottom <= 0 || sourceRegion.Right <= 0)
                    {
                        break;
                    }
                    var n = Resource.CalculateSubResourceIndex(mipLevel, i, texArrayDesc.MipLevels);
                    context.CopySubresourceRegion(texture2Ds[i], mipLevel, sourceRegion, texArray, n);
                }
            }

            var viewDesc = new ShaderResourceViewDescription()
            {
                Format      = texArrayDesc.Format,
                Dimension   = ShaderResourceViewDimension.TextureCube,
                TextureCube = new ShaderResourceViewDescription.TextureCubeResource()
                {
                    MostDetailedMip = 0,
                    MipLevels       = texArrayDesc.MipLevels
                }
            };

            return(new ShaderResourceView(device, texArray, viewDesc));
        }
예제 #7
0
            protected internal void Reset(DataBox[] dataBoxes)
            {
                Dispose();

                if (dataBoxes == null)
                    m_resource = new Texture2D(MyRender11.Device, m_desc);
                else
                    m_resource = new Texture2D(MyRender11.Device, m_desc, dataBoxes);
                m_resource.DebugName = m_name;
                m_srv = new ShaderResourceView(MyRender11.Device, m_resource);
                m_srv.DebugName = m_name;
            }
 public Texture2D CreateColoredTexture(Color color)
 {
     using (var bitmap = new Bitmap(1, 1, PixelFormat.Format32bppArgb)) {
         using (var g = Graphics.FromImage(bitmap)) {
             g.Clear(SDColor.FromArgb(color.A, color.R, color.G, color.B));
         }
         using (var ms = new MemoryStream()) {
             bitmap.Save(ms, ImageFormat.Png);
             ms.Position = 0;
             return(Resource.FromMemory <Texture2D>(device, ms.GetBuffer()));
         }
     }
 }
예제 #9
0
            public void OnDeviceEnd()
            {
                m_resource.Dispose();
                m_resource = null;

                m_dsv.Dispose();
                m_dsv_roDepth.Dispose();
                m_dsv_roStencil.Dispose();
                m_dsv_ro.Dispose();

                m_srvDepth.OnDeviceEnd();
                m_srvStencil.OnDeviceEnd();
            }
예제 #10
0
 public void OnDeviceEndInternal()
 {
     if (m_srv != null)
     {
         m_srv.Dispose();
         m_srv = null;
     }
     if (m_resource != null)
     {
         m_resource.Dispose();
         m_resource = null;
     }
 }
예제 #11
0
        public SwapChain(Form form, Renderer renderer, int fullScreenWidth, int fullScreenHeight)
        {
            if (fullScreenWidth == 0 || fullScreenHeight == 0)
            {
                fullScreenWidth  = SystemInformation.VirtualScreen.Width;
                fullScreenHeight = SystemInformation.VirtualScreen.Height;
            }
            this.fullScreenWidth  = fullScreenWidth;
            this.fullScreenHeight = fullScreenHeight;

            formWidth  = form.ClientSize.Width;
            formHeight = form.ClientSize.Height;

            var swapChainDescriptor = new SwapChainDescription()
            {
                BufferCount       = 1,
                Usage             = Usage.RenderTargetOutput,
                Flags             = SwapChainFlags.AllowModeSwitch,
                IsWindowed        = true,
                ModeDescription   = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(0, 1), Format.R8G8B8A8_UNorm),
                OutputHandle      = form.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard
            };

            using (var factory = new Factory1()) {
                swapChain = new DXSwapChain(factory, renderer.Device, swapChainDescriptor);
            }
            using (var resource = Resource.FromSwapChain <Texture2D>(swapChain, 0)) {
                RenderTarget = new RenderTargetGroup(resource);
            }

            using (var fac = swapChain.GetParent <Factory>()) {
                fac.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAltEnter);
            }

            form.ResizeBegin += (o, e) => {
                formHeight = ((Form)o).Height;
                formWidth  = ((Form)o).Width;
            };
            form.ResizeBegin += (o, e) => {
                isResizing = true;
            };
            form.ResizeEnd += (o, e) => {
                isResizing = false;
                HandleResize(o, e);
            };
            form.KeyDown += HandleKeyDown;

            form.SizeChanged += HandleResize;
        }
예제 #12
0
        private void BuildBuffer()
        {
            Utilities.Dispose(ref backBuffer);
            Utilities.Dispose(ref renderView);
            Utilities.Dispose(ref depthBuffer);
            Utilities.Dispose(ref depthView);

            Trace.TraceInformation("Building new buffer");
            swapChain.ResizeBuffers(swapChainDescription.BufferCount, (int)ScreenSize.X, (int)ScreenSize.Y, Format.Unknown, SwapChainFlags.None);
            backBuffer  = Resource.FromSwapChain <Texture2D>(swapChain, 0);
            renderView  = new RenderTargetView(graphicsDevice, backBuffer);
            depthBuffer = new Texture2D(graphicsDevice, new Texture2DDescription()
            {
                Format            = Format.D32_Float_S8X24_UInt,
                ArraySize         = 1,
                MipLevels         = 1,
                Width             = (int)ScreenSize.X,
                Height            = (int)ScreenSize.Y,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.DepthStencil,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None
            });
            depthView = new DepthStencilView(graphicsDevice, depthBuffer);

            rasterizerState = new RasterizerState(graphicsDevice, new RasterizerStateDescription()
            {
                CullMode = CullMode.Back,
                FillMode = FillMode.Solid
            });

            graphicsContext.Rasterizer.State = rasterizerState;
            graphicsContext.Rasterizer.SetViewport(0, 0, (int)ScreenSize.X, (int)ScreenSize.Y);

            BlendStateDescription blending = new BlendStateDescription();

            blending.RenderTarget[0].IsBlendEnabled        = true;
            blending.RenderTarget[0].BlendOperation        = BlendOperation.Add;
            blending.RenderTarget[0].AlphaBlendOperation   = BlendOperation.Add;
            blending.RenderTarget[0].SourceBlend           = BlendOption.SourceAlpha;
            blending.RenderTarget[0].DestinationBlend      = BlendOption.InverseSourceAlpha;
            blending.RenderTarget[0].SourceAlphaBlend      = BlendOption.Zero;
            blending.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero;
            blending.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;

            blendState = new BlendState(graphicsDevice, blending);

            graphicsContext.OutputMerger.SetBlendState(blendState);
            graphicsContext.OutputMerger.SetTargets(depthView, renderView);
        }
예제 #13
0
            protected internal void Dispose()
            {
                if (m_resource != null)
                {
                    m_resource.Dispose();
                    m_resource = null;
                }

                if (m_srv != null)
                {
                    m_srv.Dispose();
                    m_srv = null;
                }
            }
예제 #14
0
            protected internal void Dispose()
            {
                if (m_resource != null)
                {
                    m_resource.Dispose();
                    m_resource = null;
                }

                if (m_srv != null)
                {
                    m_srv.Dispose();
                    m_srv = null;
                }
            }
예제 #15
0
        private void ResetDeviceToNewViewportSize(Size newSizeInPixel)
        {
            backBuffer.Dispose();
            surface.Dispose();
            RenderTarget.Dispose();

            width  = (int)newSizeInPixel.Width;
            height = (int)newSizeInPixel.Height;
            swapChain.ResizeBuffers(BackBufferCount, width, height, BackBufferFormat, SwapChainFlags.None);
            backBuffer   = Resource.FromSwapChain <Texture2D>(swapChain, 0);
            surface      = backBuffer.QueryInterface <Surface>();
            RenderTarget = new RenderTarget(direct2DFactory, surface, defaultRenderTargetProperties);
            Screen       = new ScreenSpace(newSizeInPixel);
        }
예제 #16
0
            public void Clear()
            {
                if (m_resource != null)
                {
                    m_resource.Dispose();
                    m_resource = null;
                }

                if (m_srv != null)
                {
                    m_srv.Dispose();
                    m_srv = null;
                }
            }
            public void Clear()
            {
                if (m_resource != null)
                {
                    m_resource.Dispose();
                    m_resource = null;
                }

                if (m_srv != null)
                {
                    m_srv.Dispose();
                    m_srv = null;
                }
            }
예제 #18
0
        public static ShaderResourceView CreateShaderResourceView(Device device, Resource resource, Format format, ShaderResourceViewDimension viewDimension, int mipLevels, int mostDetailedMip, int arraySize, int firstArraySlice)
        {
            ShaderResourceViewDescription srvd = new ShaderResourceViewDescription();

            srvd.Format    = format;
            srvd.Dimension = viewDimension;
            switch (viewDimension)
            {
            case ShaderResourceViewDimension.Buffer:    //  D3D11_SRV_DIMENSION_BUFFER:
                srvd.Buffer.ElementOffset = mipLevels;
                srvd.Buffer.ElementWidth  = ElementSize(format);
                srvd.Buffer.ElementCount  = arraySize;
                srvd.Buffer.FirstElement  = firstArraySlice;
                break;

            case ShaderResourceViewDimension.Texture2D:    // D3D11_SRV_DIMENSION_TEXTURE2D:
                srvd.Texture2D.MipLevels       = mipLevels;
                srvd.Texture2D.MostDetailedMip = mostDetailedMip;
                break;

            case ShaderResourceViewDimension.Texture2DArray:    // D3D11_SRV_DIMENSION_TEXTURE2DARRAY:
                srvd.Texture2DArray.MipLevels       = mipLevels;
                srvd.Texture2DArray.MostDetailedMip = mostDetailedMip;
                srvd.Texture2DArray.ArraySize       = arraySize;
                srvd.Texture2DArray.FirstArraySlice = firstArraySlice;
                break;

            case ShaderResourceViewDimension.TextureCube:    // D3D11_SRV_DIMENSION_TEXTURECUBE:
                srvd.TextureCube.MipLevels       = mipLevels;
                srvd.TextureCube.MostDetailedMip = mostDetailedMip;
                break;

            case ShaderResourceViewDimension.Texture3D:    // D3D11_SRV_DIMENSION_TEXTURE3D:
                srvd.Texture3D.MipLevels       = mipLevels;
                srvd.Texture3D.MostDetailedMip = mostDetailedMip;
                break;

            case ShaderResourceViewDimension.Texture2DMultisampled:
            case ShaderResourceViewDimension.Texture2DMultisampledArray:
                //nothing to do here
                break;

            default:
                throw new Exception();     //not implemented....
            }
            ShaderResourceView srv = new ShaderResourceView(device, resource, srvd);

            return(srv);
        }
예제 #19
0
        public static UnorderedAccessView CreateUnorderedAccessView(Device device, Resource resource, Format format, UnorderedAccessViewDimension viewDimension, int firstElement, int numElements, UnorderedAccessViewBufferFlags flags, int mipSlice)
        {
            UnorderedAccessViewDescription uavd = new UnorderedAccessViewDescription();

            uavd.Format    = format;
            uavd.Dimension = viewDimension;

            switch (viewDimension)
            {
            case UnorderedAccessViewDimension.Texture1D:
                uavd.Texture1D.MipSlice = mipSlice;
                break;

            case UnorderedAccessViewDimension.Texture1DArray:
                uavd.Texture1DArray.MipSlice        = mipSlice;
                uavd.Texture1DArray.ArraySize       = numElements;
                uavd.Texture1DArray.FirstArraySlice = firstElement;
                break;

            case UnorderedAccessViewDimension.Texture2D:
                uavd.Texture2D.MipSlice = mipSlice;
                break;

            case UnorderedAccessViewDimension.Texture2DArray:
                uavd.Texture2DArray.MipSlice        = mipSlice;
                uavd.Texture2DArray.ArraySize       = numElements;
                uavd.Texture2DArray.FirstArraySlice = firstElement;
                break;

            case UnorderedAccessViewDimension.Texture3D:
                uavd.Texture3D.MipSlice    = mipSlice;
                uavd.Texture3D.WSize       = numElements;
                uavd.Texture3D.FirstWSlice = firstElement;
                break;

            case UnorderedAccessViewDimension.Buffer:
                uavd.Buffer.ElementCount = numElements;
                uavd.Buffer.FirstElement = firstElement;
                uavd.Buffer.Flags        = flags;
                break;

            case UnorderedAccessViewDimension.Unknown:
            default:
                return(null);
            }
            var uav = new UnorderedAccessView(device, resource, uavd);

            return(uav);
        }
예제 #20
0
        internal void Init()
        {
            var srcData = MyTextures.Textures.Data[m_mergeList[0].Index];
            var srcDesc = MyTextures.GetView(m_mergeList[0]).Description;

            Size     = MyTextures.GetSize(m_mergeList[0]);
            ArrayLen = m_mergeList.Length;

            Texture2DDescription desc = new Texture2DDescription();

            desc.ArraySize                 = ArrayLen;
            desc.BindFlags                 = BindFlags.ShaderResource;
            desc.CpuAccessFlags            = CpuAccessFlags.None;
            desc.Format                    = srcDesc.Format;
            desc.Height                    = (int)Size.Y;
            desc.Width                     = (int)Size.X;
            desc.MipLevels                 = srcDesc.Texture2D.MipLevels;
            desc.SampleDescription.Count   = 1;
            desc.SampleDescription.Quality = 0;
            desc.Usage                     = ResourceUsage.Default;
            m_resource                     = new Texture2D(MyRender11.Device, desc);
            m_resource.DebugName           = m_debugName;

            // foreach mip
            var mipmaps = srcDesc.Texture2D.MipLevels;

            for (int a = 0; a < ArrayLen; a++)
            {
                var data  = MyTextures.Textures.Data[m_mergeList[a].Index];
                var tex2D = data.Resource as Texture2D;
                MyRenderProxy.Assert(tex2D != null, "MyTextureArray supports only 2D textures. Inconsistent texture: " + data.Name);
                bool consistent = tex2D.Description.Format == desc.Format && tex2D.Description.MipLevels == desc.MipLevels &&
                                  tex2D.Description.Width == desc.Width && tex2D.Description.Height == desc.Height;
                if (!consistent)
                {
                    string errorMsg = "All MyTextureArray has to have the same pixel format, width / height and # of mipmaps. Inconsistent textures: " + data.Name + " / " + srcData.Name;
                    MyRenderProxy.Error(errorMsg);
                    MyRender11.Log.WriteLine(errorMsg);
                }

                for (int m = 0; m < mipmaps; m++)
                {
                    MyRender11.DeviceContext.CopySubresourceRegion(tex2D, Resource.CalculateSubResourceIndex(m, 0, mipmaps), null, Resource,
                                                                   Resource.CalculateSubResourceIndex(m, a, mipmaps));
                }
            }

            m_Srv = new ShaderResourceView(MyRender11.Device, Resource);
        }
예제 #21
0
        /// <summary>
        /// Registers the resource with the given flags in the scope of the Cuda runtime system.
        /// </summary>
        /// <param name="resource">The resource to register.</param>
        /// <param name="viewFlags">The view flags to use.</param>
        /// <param name="cudaGraphicsResource">The resulting graphics resource.</param>
        internal static void RegisterResource(
            Resource resource,
            DirectXViewFlags viewFlags,
            out IntPtr cudaGraphicsResource)
        {
            CudaException.ThrowIfFailed(
                CudaNativeMethods.cuGraphicsD3D11RegisterResource(
                    out cudaGraphicsResource,
                    resource.NativePointer,
                    CudaGraphicsRegisterFlags.None));

            CudaException.ThrowIfFailed(
                CudaNativeMethods.cuGraphicsResourceSetMapFlags(
                    cudaGraphicsResource,
                    (CudaGraphicsMapFlags)viewFlags));
        }
예제 #22
0
            protected internal void Reset(DataBox[] dataBoxes)
            {
                Dispose();

                if (dataBoxes == null)
                {
                    m_resource = new Texture2D(MyRender11.Device, m_desc);
                }
                else
                {
                    m_resource = new Texture2D(MyRender11.Device, m_desc, dataBoxes);
                }
                m_resource.DebugName = m_name;
                m_srv           = new ShaderResourceView(MyRender11.Device, m_resource);
                m_srv.DebugName = m_name;
            }
예제 #23
0
            protected void OnDeviceInitInternal()
            {
                m_resource           = new Texture2D(MyRender11.Device, m_resourceDesc);
                m_resource.DebugName = m_name;

                m_srv           = new ShaderResourceView(MyRender11.Device, m_resource, m_srvDesc);
                m_srv.DebugName = m_name;

                for (int nSlice = 0; nSlice < NumSlices; nSlice++)
                {
                    for (int nMipmap = 0; nMipmap < MipmapLevels; nMipmap++)
                    {
                        m_arraySubresourcesSrv[nSlice, nMipmap].OnDeviceInit();
                    }
                }
            }
예제 #24
0
            public void OnDeviceEnd()
            {
                ByteSize = 0;

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

                if (m_resource != null)
                {
                    m_resource.Dispose();
                    m_resource = null;
                }
            }
예제 #25
0
        internal MyTextureArray(TexId[] mergeList, string debugName)
        {
            var srcDesc = MyTextures.GetView(mergeList[0]).Description;

            Size     = MyTextures.GetSize(mergeList[0]);
            ArrayLen = mergeList.Length;

            Texture2DDescription desc = new Texture2DDescription();

            desc.ArraySize                 = ArrayLen;
            desc.BindFlags                 = BindFlags.ShaderResource;
            desc.CpuAccessFlags            = CpuAccessFlags.None;
            desc.Format                    = srcDesc.Format;
            desc.Height                    = (int)Size.Y;
            desc.Width                     = (int)Size.X;
            desc.MipLevels                 = srcDesc.Texture2D.MipLevels;
            desc.SampleDescription.Count   = 1;
            desc.SampleDescription.Quality = 0;
            desc.Usage                     = ResourceUsage.Default;
            m_resource                     = new Texture2D(MyRender11.Device, desc);
            m_resource.DebugName           = debugName;

            // foreach mip
            var mipmaps = desc.MipLevels;// (int)Math.Log(Size.X, 2) + 1;

            for (int a = 0; a < ArrayLen; a++)
            {
                var tex2D = MyTextures.Textures.Data[mergeList[a].Index].Resource as Texture2D;
                MyRenderProxy.Assert(tex2D != null, "MyTextureArray supports only 2D textures");
                MyRenderProxy.Assert(tex2D.Description.Format == desc.Format && tex2D.Description.MipLevels == desc.MipLevels &&
                                     tex2D.Description.Width == desc.Width && tex2D.Description.Height == desc.Height,
                                     "All MyTextureArray has to have the same pixel format, width / height and # of mipmaps.");

                for (int m = 0; m < mipmaps; m++)
                {
                    if (((Texture2D)MyTextures.Textures.Data[mergeList[a].Index].Resource).Description.Format != ((Texture2D)Resource).Description.Format)
                    {
                        MyRender11.Log.WriteLine(String.Format("Inconsistent format in textures array {0}", MyTextures.Textures.Data[mergeList[a].Index].Name));
                    }

                    MyRender11.DeviceContext.CopySubresourceRegion(MyTextures.Textures.Data[mergeList[a].Index].Resource, Resource.CalculateSubResourceIndex(m, 0, mipmaps), null, Resource,
                                                                   Resource.CalculateSubResourceIndex(m, a, mipmaps));
                }
            }

            ShaderView = new ShaderResourceView(MyRender11.Device, Resource);
        }
예제 #26
0
        /// <summary>
        /// Simple DDS loader ported from http://msdn.microsoft.com/en-us/library/windows/apps/jj651550.aspx
        /// </summary>
        /// <param name="d3dDevice"></param>
        /// <param name="ddsData"></param>
        /// <param name="ddsDataSize"></param>
        /// <param name="texture"></param>
        /// <param name="textureView"></param>
        // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
        // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
        // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
        // PARTICULAR PURPOSE.
        //
        // Copyright (c) Microsoft Corporation. All rights reserved.
        public static unsafe void CreateDDSTextureFromMemory(
            SharpDX.Direct3D11.Device d3dDevice,
            IntPtr ddsData,
            int ddsDataSize,
            out SharpDX.Direct3D11.Resource texture,
            out ShaderResourceView textureView
            )
        {
            if (d3dDevice == null || ddsData == IntPtr.Zero)
            {
                throw new ArgumentException();
            }

            // Validate DDS file in memory

            ImageDescription imageDesc;
            ConversionFlags  convFlags;

            if (!DecodeDDSHeader(ddsData, ddsDataSize, DDSFlags.None, out imageDesc, out convFlags))
            {
                throw new Exception("Invalid DDS header");
            }

            int offset = sizeof(uint) + Utilities.SizeOf <DDS.Header>();

            if ((convFlags & ConversionFlags.DX10) != 0)
            {
                offset += Utilities.SizeOf <DDS.HeaderDXT10>();
            }

            var pal8 = (int *)0;

            if ((convFlags & ConversionFlags.Pal8) != 0)
            {
                pal8    = (int *)((byte *)(ddsData) + offset);
                offset += (256 * sizeof(uint));
            }

            if (ddsDataSize < offset)
            {
                throw new InvalidOperationException();
            }

            //ptrdiff_t offset = sizeof(uint32) + sizeof(DDS_HEADER) + (bDXT10Header ? sizeof(DDS_HEADER_DXT10) : 0);

            CreateTextureFromDDS(d3dDevice, imageDesc, IntPtr.Add(ddsData, offset), ddsDataSize - offset, out texture, out textureView);
        }
예제 #27
0
        protected override void OnSurfaceInvalidated(object sender, EventArgs e)
        {
            var swapChain        = D3DApp11.I.SwapChain;
            var clientSize       = D3DApp11.I.ControlWindow.ClientSize;
            var device           = D3DApp11.I.D3DDevice;
            var immediateContext = D3DApp11.I.ImmediateContext;

            // Dispose all previous allocated resources
            Utilities.Dispose(ref _backBuffer);
            Utilities.Dispose(ref _renderView);
            Utilities.Dispose(ref _depthBuffer);
            Utilities.Dispose(ref _depthView);

            // Resize the backbuffer
            swapChain.ResizeBuffers(_swapChainDescription.BufferCount, clientSize.Width, clientSize.Height, Format.Unknown, SwapChainFlags.None);
            // Get the backbuffer from the swapchain
            _backBuffer = Resource.FromSwapChain <Texture2D>(swapChain, 0);

            // Renderview on the backbuffer
            _renderView = new RenderTargetView(device, _backBuffer);

            // Create the depth buffer
            _depthBuffer = new Texture2D(device, new Texture2DDescription()
            {
                Format            = Format.D32_Float_S8X24_UInt,
                ArraySize         = 1,
                MipLevels         = 1,
                Width             = clientSize.Width,
                Height            = clientSize.Height,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.DepthStencil,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None
            });

            // Create the depth buffer view
            _depthView = new DepthStencilView(device, _depthBuffer);

            // Setup targets and viewport for rendering
            _viewport = new Viewport(0, 0, clientSize.Width, clientSize.Height, 0.0f, 1.0f);
            immediateContext.Rasterizer.SetViewport(_viewport);
            immediateContext.OutputMerger.SetTargets(_depthView, _renderView);

            base.OnSurfaceInvalidated(sender, e);
        }
예제 #28
0
        public void Resize(Int2 resolution, bool fullScreen)
        {
            Helpers.Dispose(ref drawingSurfaceRTV);
            Helpers.Dispose(ref drawingSurfaceBuffer);
            swapChain.ResizeBuffers(2, resolution.X, resolution.Y, Format.Unknown, SwapChainFlags.None);
            swapChain.IsFullScreen = fullScreen;

            // Get the backbuffer from the swapchain.
            drawingSurfaceBuffer           = Resource.FromSwapChain <Texture2D>(swapChain, 0);
            drawingSurfaceBuffer.DebugName = "Window Backbuffer";
            drawingSurfaceRTV = new RenderTargetView(Device, drawingSurfaceBuffer)
            {
                DebugName = "Window Backbuffer RTV"
            };

            Resolution = resolution;
        }
예제 #29
0
        public SharpDXDevice(Window window)
        {
            this.window = window;
            width       = (int)window.ViewportSize.Width;
            height      = (int)window.ViewportSize.Height;
            DxDevice.CreateWithSwapChain(DriverType.Hardware,
#if DEBUG
                                         DeviceCreationFlags.Debug |
#endif
                                         DeviceCreationFlags.BgraSupport,
                                         CreateSwapChainDescription(), out device, out swapChain);
            direct2DFactory             = new D2dFactory();
            backBuffer                  = Resource.FromSwapChain <Texture2D>(swapChain, 0);
            surface                     = backBuffer.QueryInterface <Surface>();
            RenderTarget                = new RenderTarget(direct2DFactory, surface, defaultRenderTargetProperties);
            window.ViewportSizeChanged += ResetDeviceToNewViewportSize;
            Screen = new ScreenSpace(window.ViewportSize);
        }
            public void Init(string name, Texture2DDescription desc, DataBox[] dataBoxes, Vector2I size, int bytes,
                             bool enableDxInitialisation)
            {
                Clear();

                m_name  = name;
                m_size  = size;
                m_desc  = desc;
                m_bytes = bytes;

                if (enableDxInitialisation)
                {
                    m_resource           = new Texture2D(MyRender11.Device, m_desc, dataBoxes);
                    m_resource.DebugName = name;
                    m_srv           = new ShaderResourceView(MyRender11.Device, m_resource);
                    m_srv.DebugName = name;
                }
            }
예제 #31
0
            public void Init(string name, Texture2DDescription desc, DataBox[] dataBoxes, Vector2I size, int bytes,
                bool enableDxInitialisation)
            {
                Clear();

                m_name = name;
                m_size = size;
                m_desc = desc;
                m_bytes = bytes;

                if (enableDxInitialisation)
                {
                    m_resource = new Texture2D(MyRender11.Device, m_desc, dataBoxes);
                    m_resource.DebugName = name;
                    m_srv = new ShaderResourceView(MyRender11.Device, m_resource);
                    m_srv.DebugName = name;
                }
            }
예제 #32
0
        private void DoResize(int width, int height)
        {
            while (Renderer.Instance.RenderingInProgress)
            {
            }
            var rt = RenderTarget.RenderTargets[0];

            rt.Clear();
            swapChain.ResizeBuffers(1, width, height, Format.Unknown, SwapChainFlags.AllowModeSwitch);
            using (var tex = Resource.FromSwapChain <Texture2D>(swapChain, 0)) {
                rt.Update(null, new RenderTargetView(Renderer.Instance.Device, tex));
                rt.SendResizeEvent();
            }
            Viewport = new Viewport(0, 0, width, height);
            OnResize?.Invoke(this, new Event.SResizeEvent {
                Size = new System.Drawing.Size(width, height)
            });
        }
예제 #33
0
        public void Initialize()
        {
            if (!_deviceManager.IsInitialized)
            {
                throw new InvalidOperationException("Device manager is not initialized");
            }

            if (Initialized)
            {
                Uninitialize();
            }

            var swapChainDescription = new SwapChainDescription1
            {
                Width             = Width,
                Height            = Height,
                Format            = Format.B8G8R8A8_UNorm,
                Stereo            = false,
                SampleDescription = new SampleDescription(SampleCount, SampleQuality),
                Usage             = Usage.BackBuffer | Usage.RenderTargetOutput,
                BufferCount       = 1,
                Scaling           = Scaling.Stretch,
                SwapEffect        = SwapEffect.Discard,
                Flags             = SwapChainFlags.AllowModeSwitch
            };
            var fullScreenDescription = new SwapChainFullScreenDescription
            {
                RefreshRate = new Rational(60, 1),
                Scaling     = DisplayModeScaling.Centered,
                Windowed    = true
            };

            using (var dxgiDevice2 = _deviceManager.Device.QueryInterface <Device2>())
                using (var dxgiFactory2 = dxgiDevice2.Adapter.GetParent <Factory2>())
                {
                    SwapChain = new SwapChain1(dxgiFactory2, _deviceManager.Device, _windowHandle, ref swapChainDescription, fullScreenDescription);
                    dxgiFactory2.MakeWindowAssociation(_windowHandle, WindowAssociationFlags.IgnoreAll);
                }

            Texture          = Resource.FromSwapChain <Texture2D>(SwapChain, 0);
            RenderTargetView = new RenderTargetView(_deviceManager.Device, Texture);

            Initialized = true;
        }
예제 #34
0
        public static RenderTargetView CreateRenderTargetView(Device device, Resource renderTarget, Format format, RenderTargetViewDimension viewDimension, int mipSlice, int arraySize, int firstArraySlice)
        {
            RenderTargetView            rtv;
            RenderTargetViewDescription rtvd = new RenderTargetViewDescription();

            rtvd.Format    = format;
            rtvd.Dimension = viewDimension;
            switch (viewDimension)
            {
            case RenderTargetViewDimension.Buffer:                           // D3D11_RTV_DIMENSION_BUFFER:
                rtvd.Buffer.ElementOffset = mipSlice;
                rtvd.Buffer.ElementWidth  = arraySize * ElementSize(format); // arraySize; //assume square buffer... is this the width?
                rtvd.Buffer.FirstElement  = 0 * ElementSize(format);         //firstArraySlice;
                rtvd.Buffer.ElementCount  = arraySize;                       //*arraySize*ElementSize(format); //does this represent the height??
                break;

            case RenderTargetViewDimension.Texture2D:    // D3D11_RTV_DIMENSION_TEXTURE2D:
                rtvd.Texture2D.MipSlice = mipSlice;
                break;

            case RenderTargetViewDimension.Texture2DArray:    // D3D11_RTV_DIMENSION_TEXTURE2DARRAY:
                rtvd.Texture2DArray.MipSlice        = mipSlice;
                rtvd.Texture2DArray.ArraySize       = arraySize;
                rtvd.Texture2DArray.FirstArraySlice = firstArraySlice;
                break;

            case RenderTargetViewDimension.Texture2DMultisampled:    // D3D11_RTV_DIMENSION_TEXTURE2DMS:
                break;

            case RenderTargetViewDimension.Texture2DMultisampledArray:    // D3D11_RTV_DIMENSION_TEXTURE2DMSARRAY:
                rtvd.Texture2DMSArray.ArraySize       = arraySize;
                rtvd.Texture2DMSArray.FirstArraySlice = firstArraySlice;
                break;

            case RenderTargetViewDimension.Texture3D:    // D3D11_RTV_DIMENSION_TEXTURE3D:
                rtvd.Texture3D.MipSlice        = mipSlice;
                rtvd.Texture3D.DepthSliceCount = arraySize;
                rtvd.Texture3D.FirstDepthSlice = firstArraySlice;
                break;
            }
            rtv = new RenderTargetView(device, renderTarget, rtvd);
            return(rtv);
        }
예제 #35
0
        private ShaderResourceView GetShaderResourceView(Device device)
        {
            lock (_sharedViews)
            {
                IntPtr viewPointer;
                if (_sharedViews.TryGetValue(device.NativePointer, out viewPointer))
                {
                    return(new ShaderResourceView(viewPointer));
                }

                using (SharpDX.DXGI.Resource resource = Texture.QueryInterface <SharpDX.DXGI.Resource>())
                    using (Resource sharedResource = device.OpenSharedResource <Resource>(resource.SharedHandle))
                    {
                        ShaderResourceView shaderView = new ShaderResourceView(device, sharedResource);
                        _sharedViews.Add(device.NativePointer, shaderView.NativePointer);
                        return(shaderView);
                    }
            }
        }
예제 #36
0
            unsafe void InitDxObjects(string name, Vector2I size, Format format, byte[] bytePattern)
            {
                Texture2DDescription desc = new Texture2DDescription();

                desc.Format            = format;
                desc.ArraySize         = 1;
                desc.Height            = size.Y;
                desc.Width             = size.X;
                desc.MipLevels         = MyResourceUtils.GetMipmapsCount(Math.Max(size.X, size.Y));
                desc.BindFlags         = BindFlags.ShaderResource;
                desc.CpuAccessFlags    = CpuAccessFlags.None;
                desc.OptionFlags       = ResourceOptionFlags.None;
                desc.Usage             = ResourceUsage.Immutable;
                desc.SampleDescription = new SampleDescription(1, 0);

                Vector2I strides0;

                strides0.X = MyResourceUtils.GetMipmapStride(desc.Width, 0);
                strides0.Y = MyResourceUtils.GetMipmapStride(desc.Height, 0);
                byte[]    dataBoxData  = CreateTextureDataByPattern(strides0, bytePattern);
                DataBox[] dataBoxes    = new DataBox[desc.MipLevels];
                int       blocksOffset = 0;

                fixed(void *ptr = dataBoxData)
                {
                    for (int i = 0; i < dataBoxes.Length; i++)
                    {
                        dataBoxes[i].SlicePitch  = 0;
                        dataBoxes[i].RowPitch    = MyResourceUtils.GetMipmapStride(size.X, i) * bytePattern.Length / 16;
                        dataBoxes[i].DataPointer = new IntPtr(((byte *)ptr) + blocksOffset * bytePattern.Length);

                        Vector2I blocksInMipmap;
                        blocksInMipmap.X = MyResourceUtils.GetMipmapStride(size.X, i) / 4;
                        blocksInMipmap.Y = MyResourceUtils.GetMipmapStride(size.Y, i) / 4;
                        blocksOffset    += blocksInMipmap.X * blocksInMipmap.Y;
                    }
                    m_resource           = new Texture2D(MyRender11.Device, desc, dataBoxes);
                    m_resource.DebugName = name;
                }

                m_srv           = new ShaderResourceView(MyRender11.Device, m_resource);
                m_srv.DebugName = name;
            }
예제 #37
0
 internal static MyMapping MapDiscard(Resource buffer)
 {
     return MapDiscard(MyRender11.ImmediateContext, buffer);
 }
예제 #38
0
 private unsafe static byte[] GetScreenData(Resource res, byte[] screenData, ImageFileFormat fmt)
 {
     return MyTextureData.ToData(res, screenData, fmt);
 }
예제 #39
0
            public void OnDeviceInit()
            {
                ISrvBindable firstTex = MyManagers.FileTextures.GetTexture(m_listSubresourceFilenames[0], m_type, true);
                var srcDesc = firstTex.Srv.Description;
                Vector2I Size = firstTex.Size;

                Texture2DDescription desc = new Texture2DDescription();
                desc.ArraySize = m_listSubresourceFilenames.Count;
                desc.BindFlags = BindFlags.ShaderResource;
                desc.CpuAccessFlags = CpuAccessFlags.None;
                desc.Format = srcDesc.Format;
                desc.Height = (int) Size.Y;
                desc.Width = (int) Size.X;
                desc.MipLevels = srcDesc.Texture2D.MipLevels;
                desc.SampleDescription.Count = 1;
                desc.SampleDescription.Quality = 0;
                desc.Usage = ResourceUsage.Default;
                m_resource = new Texture2D(MyRender11.Device, desc);
                m_resource.DebugName = m_resourceName;
                TextureFormat = srcDesc.Format;

                // foreach mip
                var mipmaps = srcDesc.Texture2D.MipLevels;

                int i = 0;
                foreach (var path in m_listSubresourceFilenames)
                {
                    ISrvBindable tex = MyManagers.FileTextures.GetTexture(path, m_type, true);
                    var tex2D = tex.Resource as Texture2D;
                    MyRenderProxy.Assert(tex2D != null,
                        "MyTextureArray supports only 2D textures. Inconsistent texture: " + tex.Name);
                    bool consistent = MyResourceUtils.CheckTexturesConsistency(desc, tex2D.Description);
                    if (!consistent)
                    {
                        string errorMsg =
                            "All MyTextureArray has to have the same pixel format, width / height and # of mipmaps. Inconsistent textures: " +
                            tex.Name + " / " + firstTex.Name;
                        MyRenderProxy.Error(errorMsg);
                        MyRender11.Log.WriteLine(errorMsg);
                    }

                    for (int m = 0; m < mipmaps; m++)
                    {
                        MyRender11.RC.CopySubresourceRegion(tex2D,
                            Resource.CalculateSubResourceIndex(m, 0, mipmaps), null, Resource,
                            Resource.CalculateSubResourceIndex(m, i, mipmaps));

                        int sizeX = Resource.CalculateMipSize(m, Size.X);
                        int sizeY = Resource.CalculateMipSize(m, Size.Y);
                        ByteSize += FormatHelper.ComputeScanlineCount(TextureFormat, sizeX) * 4 * FormatHelper.ComputeScanlineCount(TextureFormat, sizeY) * 4 * FormatHelper.SizeOfInBytes(TextureFormat);
                    }

                    i++;
                }

                m_srv = new ShaderResourceView(MyRender11.Device, Resource);
            }
예제 #40
0
            public void OnDeviceInit()
            {
                MyFileTextureParams fileTexParams;
                bool ret = GetCorrectedFileTextureParams(out fileTexParams);
                //MyRenderProxy.Assert(ret, "It is not implemented mechanism, what to do, when none of the textures exist");

                m_size = fileTexParams.Resolution;
                Texture2DDescription desc = new Texture2DDescription();
                desc.ArraySize = m_listSubresourceFilenames.Count;
                desc.BindFlags = BindFlags.ShaderResource;
                desc.CpuAccessFlags = CpuAccessFlags.None;
                desc.Format = fileTexParams.Format;
                desc.Height = (int) Size.Y;
                desc.Width = (int) Size.X;
                var mipmaps = desc.MipLevels = fileTexParams.Mipmaps;
                desc.SampleDescription.Count = 1;
                desc.SampleDescription.Quality = 0;
                desc.Usage = ResourceUsage.Default;
                m_resource = new Texture2D(MyRender11.Device, desc);
                m_resource.DebugName = m_resourceName;
                TextureFormat = fileTexParams.Format;

                // foreach mip
                int i = 0;
                foreach (var path in m_listSubresourceFilenames)
                {
                    bool isUsedCreatedGeneratedTexture = false;
                    ISrvBindable tex = MyManagers.FileTextures.GetTexture(path, m_type, true);
                    var tex2D = tex.Resource as Texture2D;
                    MyRenderProxy.Assert(tex2D != null,
                        "MyFileArrayTexture supports only 2D textures. Inconsistent texture: " + tex.Name);
                    bool consistent = MyResourceUtils.CheckTexturesConsistency(desc, tex2D.Description);
                    if (!consistent)
                    {
                        if (!string.IsNullOrEmpty(path) && MyFileSystem.FileExists(path))
                        {
                            string msg =
                                string.Format(
                                    "Texture {0} cannot be loaded. If this message is displayed on reloading textures, please restart the game. If it is not, please notify developers.", path);
                            MyRenderProxy.Fail(msg);
                        }
                    }

                    if (!consistent && m_recoverySystem.UseErrorTexture) // if the texture cannot be used, error texture will be used
                    {
                        tex = MyManagers.FileTextures.GetTexture(m_recoverySystem.TextureFilepath, m_type, true);
                        tex2D = tex.Resource as Texture2D;
                        MyRenderProxy.Assert(tex2D != null,
                            "MyFileArrayTexture supports only 2D textures. Inconsistent texture: " + m_recoverySystem.TextureFilepath);
                        consistent = MyResourceUtils.CheckTexturesConsistency(desc, tex2D.Description);
                    } 
                    if (!consistent && m_recoverySystem.UseBytePattern) // if the texture cannot be used, byte pattern will be used to generate texture
                    {
                        tex = MyManagers.GeneratedTextures.CreateFromBytePattern("MyFileArrayTexture.Tmp", desc.Width,
                            desc.Height, m_recoverySystem.FormatBytePattern, m_recoverySystem.BytePattern);
                        tex2D = tex.Resource as Texture2D;
                        MyRenderProxy.Assert(tex2D != null);
                        consistent = MyResourceUtils.CheckTexturesConsistency(desc, tex2D.Description);
                        isUsedCreatedGeneratedTexture = true;
                    }
                    if (!consistent)
                    {
                        Texture2DDescription desc1 = desc;
                        Texture2DDescription desc2 = tex2D.Description;
                        string errorMsg = string.Format("Textures ({0}) is not compatible within array texture! Width: ({1},{2}) Height: ({3},{4}) Mipmaps: ({5},{6}) Format: ({7},{8})",
                            path, desc1.Width, desc2.Width, desc1.Height, desc2.Height, desc1.MipLevels, desc2.MipLevels, desc1.Format, desc2.Format);
                        MyRenderProxy.Error(errorMsg);
                        MyRender11.Log.WriteLine(errorMsg);
                    }

                    for (int m = 0; m < mipmaps; m++)
                    {
                        MyRender11.RC.CopySubresourceRegion(tex,
                            Resource.CalculateSubResourceIndex(m, 0, mipmaps), null, Resource,
                            Resource.CalculateSubResourceIndex(m, i, mipmaps));

                        int sizeX = Resource.CalculateMipSize(m, Size.X);
                        int sizeY = Resource.CalculateMipSize(m, Size.Y);
                        ByteSize += FormatHelper.ComputeScanlineCount(TextureFormat, sizeX) * 4 * FormatHelper.ComputeScanlineCount(TextureFormat, sizeY) * 4 * FormatHelper.SizeOfInBytes(TextureFormat);
                    }

                    if (isUsedCreatedGeneratedTexture)
                    {
                        IGeneratedTexture generatedTex = (IGeneratedTexture) tex;
                        MyManagers.GeneratedTextures.DisposeTex(generatedTex);
                    }
                    i++;
                }

                m_srv = new ShaderResourceView(MyRender11.Device, Resource);
            }
예제 #41
0
            public void OnDeviceInit()
            {
                Texture2DDescription desc = new Texture2DDescription();
                desc.Width = Size.X;
                desc.Height = Size.Y;
                desc.Format = m_resourceFormat;
                desc.ArraySize = 1;
                desc.MipLevels = 1;
                desc.BindFlags = BindFlags.ShaderResource | BindFlags.DepthStencil;
                desc.Usage = ResourceUsage.Default;
                desc.CpuAccessFlags = 0;
                desc.SampleDescription.Count = m_samplesCount;
                desc.SampleDescription.Quality = m_samplesQuality;
                desc.OptionFlags = 0;
                m_resource = new Texture2D(MyRender11.Device, desc);
                m_resource.DebugName = Name;

                DepthStencilViewDescription dsvDesc = new DepthStencilViewDescription();
                dsvDesc.Format = m_dsvFormat;
                if (m_samplesCount == 1)
                {
                    dsvDesc.Dimension = DepthStencilViewDimension.Texture2D;
                    dsvDesc.Flags = DepthStencilViewFlags.None;
                    dsvDesc.Texture2D.MipSlice = 0;
                }
                else
                {
                    dsvDesc.Dimension = DepthStencilViewDimension.Texture2DMultisampled;
                    dsvDesc.Flags = DepthStencilViewFlags.None;
                }
                m_dsv = new DepthStencilView(MyRender11.Device, m_resource, dsvDesc);
                if (m_samplesCount == 1)
                {
                    dsvDesc.Dimension = DepthStencilViewDimension.Texture2D;
                    dsvDesc.Flags = DepthStencilViewFlags.ReadOnlyDepth;
                    dsvDesc.Texture2D.MipSlice = 0;
                }
                else
                {
                    dsvDesc.Dimension = DepthStencilViewDimension.Texture2DMultisampled;
                    dsvDesc.Flags = DepthStencilViewFlags.ReadOnlyDepth;
                }
                m_dsv_roDepth = new DepthStencilView(MyRender11.Device, m_resource, dsvDesc);
                if (m_samplesCount == 1)
                {
                    dsvDesc.Dimension = DepthStencilViewDimension.Texture2D;
                    dsvDesc.Flags = DepthStencilViewFlags.ReadOnlyStencil;
                    dsvDesc.Texture2D.MipSlice = 0;
                }
                else
                {
                    dsvDesc.Dimension = DepthStencilViewDimension.Texture2DMultisampled;
                    dsvDesc.Flags = DepthStencilViewFlags.ReadOnlyStencil;
                }
                m_dsv_roStencil = new DepthStencilView(MyRender11.Device, m_resource, dsvDesc);
                dsvDesc.Flags = DepthStencilViewFlags.ReadOnlyStencil | DepthStencilViewFlags.ReadOnlyDepth;
                if (m_samplesCount == 1)
                {
                    dsvDesc.Dimension = DepthStencilViewDimension.Texture2D;
                    dsvDesc.Texture2D.MipSlice = 0;
                }
                else
                {
                    dsvDesc.Dimension = DepthStencilViewDimension.Texture2DMultisampled;
                }
                m_dsv_ro = new DepthStencilView(MyRender11.Device, m_resource, dsvDesc);

                ShaderResourceViewDescription srvDesc = new ShaderResourceViewDescription();
                srvDesc.Format = m_srvDepthFormat;
                if (m_samplesCount == 1)
                {
                    srvDesc.Dimension = ShaderResourceViewDimension.Texture2D;
                    srvDesc.Texture2D.MipLevels = -1;
                    srvDesc.Texture2D.MostDetailedMip = 0;
                }
                else
                {
                    srvDesc.Dimension = ShaderResourceViewDimension.Texture2DMultisampled;
                }
                m_srvDepth.OnDeviceInit(this, srvDesc);
                srvDesc.Format = m_srvStencilFormat;
                if (m_samplesCount == 1)
                {
                    srvDesc.Dimension = ShaderResourceViewDimension.Texture2D;
                    srvDesc.Texture2D.MipLevels = -1;
                    srvDesc.Texture2D.MostDetailedMip = 0;
                }
                else
                {
                    srvDesc.Dimension = ShaderResourceViewDimension.Texture2DMultisampled;
                }
                m_srvStencil.OnDeviceInit(this, srvDesc);
            }
예제 #42
0
 public void Destroy()
 {
     TextureState = FileTextureState.Unloaded;
     if (m_ownsData)
     {
         m_srv.Dispose();
         m_resource.Dispose();
     }
     m_srv = null;
     m_resource = null;
 }
예제 #43
0
 public void OnDeviceEndInternal()
 {
     if (m_srv != null)
     {
         m_srv.Dispose();
         m_srv = null;
     }
     if (m_resource != null)
     {
         m_resource.Dispose();
         m_resource = null;
     }
 }
예제 #44
0
        public void OnDeviceInitInternal()
        {
            {
                Texture2DDescription desc = new Texture2DDescription();
                desc.Width = Size.X;
                desc.Height = Size.Y;
                desc.Format = m_resourceFormat;
                desc.ArraySize = 1;
                desc.MipLevels = m_mipmapLevels;
                desc.BindFlags = m_bindFlags;
                desc.Usage = m_resourceUsage;
                desc.CpuAccessFlags = m_cpuAccessFlags;
                desc.SampleDescription.Count = m_samplesCount;
                desc.SampleDescription.Quality = m_samplesQuality;
                desc.OptionFlags = m_roFlags;
                m_resource = new Texture2D(MyRender11.Device, desc);
            }
            {
                ShaderResourceViewDescription desc = new ShaderResourceViewDescription();
                desc.Format = m_srvFormat;
                desc.Dimension = ShaderResourceViewDimension.Texture2D;
                desc.Texture2D.MipLevels = m_mipmapLevels;
                desc.Texture2D.MostDetailedMip = 0;
                m_srv = new ShaderResourceView(MyRender11.Device, m_resource, desc);
            }

            m_resource.DebugName = m_name;
            m_srv.DebugName = m_name;
        }
예제 #45
0
            unsafe void InitDxObjects(string name, Vector2I size, Format format, byte[] bytePattern)
            {
                Texture2DDescription desc = new Texture2DDescription();
                desc.Format = format;
                desc.ArraySize = 1;
                desc.Height = size.Y;
                desc.Width = size.X;
                desc.MipLevels = MyResourceUtils.GetMipmapsCount(Math.Max(size.X, size.Y));
                desc.BindFlags = BindFlags.ShaderResource;
                desc.CpuAccessFlags = CpuAccessFlags.None;
                desc.OptionFlags = ResourceOptionFlags.None;
                desc.Usage = ResourceUsage.Immutable;
                desc.SampleDescription = new SampleDescription(1, 0);

                Vector2I strides0;
                strides0.X = MyResourceUtils.GetMipmapStride(desc.Width, 0);
                strides0.Y = MyResourceUtils.GetMipmapStride(desc.Height, 0);
                byte[] dataBoxData = CreateTextureDataByPattern(strides0, bytePattern);
                DataBox[] dataBoxes = new DataBox[desc.MipLevels];
                int blocksOffset = 0;
                fixed (void* ptr = dataBoxData)
                {
                    for (int i = 0; i < dataBoxes.Length; i++)
                    {
                        dataBoxes[i].SlicePitch = 0;
                        dataBoxes[i].RowPitch = MyResourceUtils.GetMipmapStride(size.X, i) * bytePattern.Length / 16;
                        dataBoxes[i].DataPointer = new IntPtr(((byte*)ptr) + blocksOffset * bytePattern.Length);

                        Vector2I blocksInMipmap;
                        blocksInMipmap.X = MyResourceUtils.GetMipmapStride(size.X, i) / 4;
                        blocksInMipmap.Y = MyResourceUtils.GetMipmapStride(size.Y, i) / 4;
                        blocksOffset += blocksInMipmap.X * blocksInMipmap.Y;
                    }
                    m_resource = new Texture2D(MyRender11.Device, desc, dataBoxes);
                    m_resource.DebugName = name;
                }

                m_srv = new ShaderResourceView(MyRender11.Device, m_resource);
                m_srv.DebugName = name;
            }
예제 #46
0
            protected void OnDeviceInitInternal()
            {
                m_resource = new Texture2D(MyRender11.Device, m_resourceDesc);
                m_resource.DebugName = m_name;

                m_srv = new ShaderResourceView(MyRender11.Device, m_resource, m_srvDesc);
                m_srv.DebugName = m_name;

                for (int nSlice = 0; nSlice < NumSlices; nSlice++)
                    for (int nMipmap = 0; nMipmap < MipmapLevels; nMipmap++)
                    {
                        m_arraySubresourcesSrv[nSlice, nMipmap].OnDeviceInit();
                    }
            }
예제 #47
0
            protected void OnDeviceEndInternal()
            {
                for (int nSlice = 0; nSlice < NumSlices; nSlice++)
                    for (int nMipmap = 0; nMipmap < MipmapLevels; nMipmap++)
                    {
                        m_arraySubresourcesSrv[nSlice, nMipmap].OnDeviceEnd();
                    }

                if (m_srv != null)
                {
                    m_srv.Dispose();
                    m_srv = null;
                }
                if (m_resource != null)
                {
                    m_resource.Dispose();
                    m_resource = null;
                }
            }
예제 #48
0
            public void OnDeviceInit()
            {
                ISrvBindable tex0 = m_sourceTextures[0];

                Texture2DDescription texDesc = new Texture2DDescription();
                texDesc.ArraySize = m_sourceTextures.Count;
                texDesc.BindFlags = BindFlags.ShaderResource;
                texDesc.CpuAccessFlags = CpuAccessFlags.None;
                texDesc.Format = tex0.Srv.Description.Format;
                texDesc.Height = tex0.Size.X;
                texDesc.MipLevels = tex0.Srv.Description.Texture2D.MipLevels;
                texDesc.OptionFlags = ResourceOptionFlags.None;
                texDesc.SampleDescription.Count = 1;
                texDesc.SampleDescription.Quality = 0;
                texDesc.Usage = ResourceUsage.Default;
                texDesc.Width = tex0.Size.Y;
                m_resource = new Texture2D(MyRender11.Device, texDesc);
                m_resource.DebugName = m_debugName;

                ShaderResourceViewDescription srvDesc = new ShaderResourceViewDescription();
                srvDesc.Format = tex0.Srv.Description.Format;
                srvDesc.Dimension = ShaderResourceViewDimension.Texture2DArray;
                srvDesc.Texture2DArray.ArraySize = m_sourceTextures.Count;
                srvDesc.Texture2DArray.FirstArraySlice = 0;
                srvDesc.Texture2DArray.MipLevels = tex0.Srv.Description.Texture2D.MipLevels;
                srvDesc.Texture2DArray.MostDetailedMip = 0;
                m_srv = new ShaderResourceView(MyRender11.Device, m_resource, srvDesc);
                m_srv.DebugName = m_debugName;

                int i = 0;
                foreach (ISrvBindable tex in m_sourceTextures)
                {
                    Texture2D tex2 = (Texture2D) tex.Resource;
                    if (tex2 == null)
                    {
                        MyRenderProxy.Assert(false, "Array texture is created using resource that is not texture2d");
                        i++;
                        continue;
                    }
                    Texture2DDescription texDesc2 = tex2.Description;
                    MyRenderProxy.Assert(MyArrayTextureManager.CheckArrayCompatible(texDesc, texDesc2),
                        "Incompatible texture is used to create array texture");

                    int mipmaps = tex.Srv.Description.Texture2D.MipLevels;
                    for (int m = 0; m < mipmaps; m++)
                    {
                        MyRender11.RC.CopySubresourceRegion(tex.Resource,
                            Resource.CalculateSubResourceIndex(m, 0, mipmaps), null, Resource,
                            Resource.CalculateSubResourceIndex(m, i, mipmaps));
                    }
                    i++;
                }
            }
예제 #49
0
        static TexId RegisterTexture(string name, string contentPath, MyTextureEnum type, Resource resource, Vector2 size)
        {
            var nameKey = MyStringId.GetOrCompute(name);
            if (!NameIndex.ContainsKey(nameKey))
            {
                var texId = NameIndex[nameKey] = new TexId { Index = Textures.Allocate() };

                Textures.Data[texId.Index] = new MyTextureInfo
                {
                    Name = name,
                    ContentPath = contentPath,
                    Type = type,
                    Resource = resource,
                    Size = size
                };

                resource.DebugName = name;

                Views[texId.Index] = new ShaderResourceView(MyRender11.Device, resource);
                Views[texId.Index].DebugName = name;
            }
            else // reregistered after device reset
            {
                var id = NameIndex[nameKey];
                
                if(Textures.Data[id.Index].Resource == null)
                {
                    Textures.Data[id.Index].Resource = resource;
                    resource.DebugName = name;
                    Views[id.Index] = new ShaderResourceView(MyRender11.Device, resource);
                    Views[id.Index].DebugName = name;
                }
            }

            return NameIndex[nameKey];
        }
예제 #50
0
 private static void SaveScreenshotFromResource(Resource res)
 {
     bool result = MyTextureData.ToFile(res, m_screenshot.Value.SavePath, m_screenshot.Value.Format);
     MyRenderProxy.ScreenshotTaken(result, m_screenshot.Value.SavePath, m_screenshot.Value.ShowNotification);
     m_screenshot = null;
 }
예제 #51
0
            public void OnDeviceInit()
            {
                Texture2DDescription desc = new Texture2DDescription();
                desc.Width = Size.X;
                desc.Height = Size.Y;
                desc.Format = m_resourceFormat;
                desc.ArraySize = 1;
                desc.MipLevels = 1;
                desc.BindFlags = BindFlags.ShaderResource | BindFlags.UnorderedAccess | BindFlags.RenderTarget;
                desc.Usage = ResourceUsage.Default;
                desc.CpuAccessFlags = 0;
                desc.SampleDescription.Count = m_samplesCount;
                desc.SampleDescription.Quality = m_samplesQuality;
                desc.OptionFlags = 0;
                m_resource = new Texture2D(MyRender11.Device, desc);
                m_resource.DebugName = Name;

                m_formatSRgb.Init(this, Format.R8G8B8A8_UNorm_SRgb);
                m_formatSRgb.OnDeviceInit();

                m_formatLinear.Init(this, Format.R8G8B8A8_UNorm);
                m_formatLinear.OnDeviceInit();
            }
예제 #52
0
            public unsafe void Load()
            {
                if (TextureState == FileTextureState.Loaded)
                    return;

                Debug.Assert(m_resource == null);
                Debug.Assert(m_srv == null, "Texture " + Name + " in invalid state");

                Image img = null;

                if (MyFileSystem.FileExists(m_path))
                {
                    try
                    {
                        using (var s = MyFileSystem.OpenRead(m_path))
                        {
                            img = Image.Load(s);
                            ImageFormatInFile = img.Description.Format;
                        }
                    }
                    catch (Exception e)
                    {
                        MyRender11.Log.WriteLine("Error while loading texture: " + m_path + ", exception: " + e);
                    }
                }

                bool loaded = false;
                if (img != null)
                {
                    int skipMipmaps = 0;
                    if (m_type != MyFileTextureEnum.GUI && m_type != MyFileTextureEnum.GPUPARTICLES && img.Description.MipLevels > 1)
                        skipMipmaps = MyRender11.RenderSettings.TextureQuality.MipmapsToSkip(img.Description.Width, img.Description.Height);

                    if (m_skipQualityReduction)
                        skipMipmaps = 0;

                    int totalSize = 0;

                    int targetMipmaps = img.Description.MipLevels - skipMipmaps;
                    var mipmapsData = new DataBox[(img.Description.MipLevels - skipMipmaps) * img.Description.ArraySize];

                    int lastSize = 0;

                    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 };

                            void* data = pixels.DataPointer.ToPointer();

                            lastSize = pixels.BufferStride;
                            totalSize += lastSize;
                        }
                    }

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


                    bool overwriteFormatToSrgb = false;
                    if (MyCompilationSymbols.ReinterpretFormatsStoredInFiles)
                        overwriteFormatToSrgb = (m_type != MyFileTextureEnum.NORMALMAP_GLOSS) && !FormatHelper.IsSRgb(img.Description.Format);

                    m_format = overwriteFormatToSrgb ? MyResourceUtils.MakeSrgb(img.Description.Format) : img.Description.Format;

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

                    try
                    {
                        m_resource = new Texture2D(MyRender11.Device, desc, mipmapsData);
                        m_size = new Vector2I(targetWidth, targetHeight);
                        //m_skippedMipmaps = skipMipmaps;
                        m_byteSize = totalSize;
                        m_ownsData = true;

                        m_srv = new ShaderResourceView(MyRender11.Device, m_resource);
                        m_resource.DebugName = m_name;
                        m_srv.DebugName = m_name;

                        img.Dispose();

                        loaded = true;
                    }
                    catch (SharpDXException)
                    {
                        img.Dispose();
                    }
                }
                if (!loaded)
                {
                    ISrvBindable replacingTexture = MyGeneratedTextureManager.ZeroTex;
                    switch (m_type)
                    {
                        case MyFileTextureEnum.NORMALMAP_GLOSS:
                            replacingTexture = MyGeneratedTextureManager.MissingNormalGlossTex;
                            break;
                        case MyFileTextureEnum.EXTENSIONS:
                            replacingTexture = MyGeneratedTextureManager.MissingExtensionTex;
                            break;
                        case MyFileTextureEnum.ALPHAMASK:
                            replacingTexture = MyGeneratedTextureManager.MissingAlphamaskTex;
                            break;
                        case MyFileTextureEnum.CUBEMAP:
                            replacingTexture = MyGeneratedTextureManager.MissingCubeTex;
                            break;
                    }

                    MyRender11.Log.WriteLine("Could not load texture: " + m_path);

                    m_srv = replacingTexture.Srv;
                    m_resource = replacingTexture.Resource;
                    m_size = replacingTexture.Size;
                    m_ownsData = false;
                    m_byteSize = 0;
                    MyRender11.Log.WriteLine("Missing or invalid texture: " + Name);
                }

                TextureState = FileTextureState.Loaded;
            }
예제 #53
0
            public void OnDeviceEnd()
            {
                m_resource.Dispose();
                m_resource = null;

                m_formatSRgb.OnDeviceEnd();
                m_formatLinear.OnDeviceEnd();
            }
예제 #54
0
파일: Minimap.cs 프로젝트: ndech/Alpha
 private void UpdateOverlayVertexBuffer(DeviceContext deviceContext, Resource overlayVertexBuffer, VertexDefinition.PositionColor[] vertices, int vertexCount)
 {
     var dataBox = deviceContext.MapSubresource(overlayVertexBuffer, 0, MapMode.WriteDiscard, MapFlags.None);
     Utilities.Write(dataBox.DataPointer, vertices, 0, vertexCount);
     deviceContext.UnmapSubresource(overlayVertexBuffer, 0);
 }
예제 #55
0
 public DxTexture(Resource texture, Texture2DDescription descriptor2D)
 {
     Texture = texture;
     Descriptor2D = descriptor2D;
     IsCube = descriptor2D.ArraySize == 6;
 }
예제 #56
0
            public void OnDeviceEnd()
            {
                m_resource.Dispose();
                m_resource = null;

                m_dsv.Dispose();
                m_dsv_roDepth.Dispose();
                m_dsv_roStencil.Dispose();
                m_dsv_ro.Dispose();

                m_srvDepth.OnDeviceEnd();
                m_srvStencil.OnDeviceEnd();
            }
예제 #57
0
            public void OnDeviceEnd()
            {
                ByteSize = 0;

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

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