Esempio n. 1
0
        /// <summary>
        /// Create A shaderViewresource on a TextureArray object created from image files
        /// </summary>
        /// <param name="device">The graphic device</param>
        /// <param name="FileNames">The files names that will be used to create the array, the array's index will be based on the order of the file inside this collection</param>
        /// <param name="MIPfilterFlag">Filter used to create the mipmap lvl from the loaded images</param>
        /// <param name="ArrayTextureView">The create textureArray view that can directly be used inside shaders</param>
        public static void CreateTexture2DFromFiles(Device device, DeviceContext context, string[] FileNames, FilterFlags MIPfilterFlag, string ResourceName, out ShaderResourceView TextureArrayView, SharpDX.DXGI.Format InMemoryArrayFormat = SharpDX.DXGI.Format.R8G8B8A8_UNorm)
        {
            int inputImagesCount = FileNames.Length;

            //1 First loading the textures from files
            Texture2D[] srcTex = new Texture2D[inputImagesCount];

            ImageLoadInformation ImageInfo = new ImageLoadInformation()
            {
                FirstMipLevel  = 0,
                Usage          = ResourceUsage.Staging,
                BindFlags      = BindFlags.None,
                CpuAccessFlags = CpuAccessFlags.Write | CpuAccessFlags.Read,
                OptionFlags    = ResourceOptionFlags.None,
                Format         = InMemoryArrayFormat,
                Filter         = FilterFlags.None,
                MipFilter      = MIPfilterFlag
            };

            for (int imgInd = 0; imgInd < inputImagesCount; imgInd++)
            {
                srcTex[imgInd] = Texture2D.FromFile <Texture2D>(device, FileNames[imgInd], ImageInfo);
            }

            //2 Creation of the TextureArray resource

            CreateTexture2D(context, srcTex, ResourceName, out TextureArrayView, InMemoryArrayFormat);

            //Disposing resources used to create the texture array
            foreach (Texture2D tex in srcTex)
            {
                tex.Dispose();
            }
        }
Esempio n. 2
0
        public override void LoadContent(SharpDX.Direct3D11.DeviceContext context)
        {
            ImageLoadInformation imageLoadParam = new ImageLoadInformation()
            {
                BindFlags = BindFlags.ShaderResource,
                Format    = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
                MipLevels = 1
            };

            _compassPanel =
                new CompassControl()
            {
                FrameName      = "WindRose",
                Bounds         = new UniRectangle(new UniScalar(1.0f, -160), 10, 150, 75),
                CompassTexture = ToDispose(new SpriteTexture(_engine.Device, ClientSettings.TexturePack + @"Gui\WindRose.png", Vector2I.Zero, imageLoadParam)),
                DayCircle      = ToDispose(new SpriteTexture(_engine.Device, ClientSettings.TexturePack + @"Gui\DayCircle.png", Vector2I.Zero, imageLoadParam)),
                MaskArrow      = ToDispose(new SpriteTexture(_engine.Device, ClientSettings.TexturePack + @"Gui\MaskArrow.png", Vector2I.Zero, imageLoadParam)),
                SoulStoneIcon  = ToDispose(new SpriteTexture(_engine.Device, ClientSettings.TexturePack + @"Gui\SoulStoneIcon.png", Vector2I.Zero, imageLoadParam)),
                sampler        = RenderStatesRepo.GetSamplerState(DXStates.Samplers.UVClamp_MinMagMipLinear),
            };

            _dateTime = new LabelControl()
            {
                Color = Color.Tomato, Text = "", Bounds = new UniRectangle(-50, -5, new UniScalar(1.0f, 0.0f), 20.0f)
            };
            _compassPanel.Children.Add(_dateTime);

            _compassPanel.LayoutFlags = S33M3CoreComponents.GUI.Nuclex.Controls.ControlLayoutFlags.Skip;
            _guiScreen.Desktop.Children.Add(_compassPanel);
        }
Esempio n. 3
0
        public static DX11Texture2D FromFile(DX11RenderContext context, string path, ImageLoadInformation loadinfo)
        {
            try
            {
                Texture2D tex = Texture2D.FromFile(context.Device, path, loadinfo);

                if (tex.Description.ArraySize == 1)
                {
                    DX11Texture2D res = new DX11Texture2D();
                    res.context  = context;
                    res.Resource = tex;
                    res.SRV      = new ShaderResourceView(context.Device, res.Resource);
                    res.desc     = res.Resource.Description;
                    res.isowner  = true;
                    return(res);
                }
                else
                {
                    if (tex.Description.OptionFlags.HasFlag(ResourceOptionFlags.TextureCube))
                    {
                        return(new DX11TextureCube(context, tex));
                    }
                    else
                    {
                        return(new DX11TextureArray2D(context, tex));
                    }
                }
            }
            catch
            {
                throw;
            }
        }
Esempio n. 4
0
        protected override bool Load(DX11RenderContext context, string path, out DX11Texture2D result)
        {
            try
            {
                if (Path.GetExtension(path).ToLower() == ".tga")
                {
                    result = null;
                    return(false);
                }
                else
                {
                    ImageLoadInformation info = ImageLoadInformation.FromDefaults();
                    if (this.FInNoMips[0])
                    {
                        info.MipLevels = 1;
                    }
                    result = DX11Texture2D.FromFile(context, path, info);
                }

                #if DEBUG
                result.Resource.DebugName = "FileTexture";
                #endif

                return(true);
            }
            catch
            {
                result = new DX11Texture2D();
                return(false);
            }
        }
Esempio n. 5
0
        static public Texture11 FromStream(Device device, Stream stream)
        {
            try
            {
                ImageLoadInformation loadInfo = new ImageLoadInformation();
                loadInfo.BindFlags      = BindFlags.ShaderResource;
                loadInfo.CpuAccessFlags = CpuAccessFlags.None;
                loadInfo.Depth          = -1;
                loadInfo.Format         = RenderContext11.DefaultTextureFormat;
                loadInfo.Filter         = FilterFlags.Box;
                loadInfo.FirstMipLevel  = 0;
                loadInfo.Height         = -1;
                loadInfo.MipFilter      = FilterFlags.Linear;
                loadInfo.MipLevels      = 0;
                loadInfo.OptionFlags    = ResourceOptionFlags.None;
                loadInfo.Usage          = ResourceUsage.Default;
                loadInfo.Width          = -1;
                if (loadInfo.Format == SharpDX.DXGI.Format.R8G8B8A8_UNorm_SRgb)
                {
                    loadInfo.Filter |= FilterFlags.SRgb;
                }

                Texture2D texture = Texture2D.FromStream <Texture2D>(device, stream, (int)stream.Length, loadInfo);

                return(new Texture11(texture));
            }
            catch
            {
                return(null);
            }
        }
Esempio n. 6
0
        public DX11FileTexturePoolElement(DX11RenderContext context, string path, bool mips, bool async = false)
        {
            this.FileName = path;
            this.DoMips   = mips;
            this.refcount = 1;


            if (async)
            {
                this.m_task           = new FileTexture2dLoadTask(context, path, mips);
                m_task.StatusChanged += task_StatusChanged;

                context.ResourceScheduler.AddTask(m_task);
            }
            else
            {
                try
                {
                    ImageLoadInformation info = ImageLoadInformation.FromDefaults();
                    if (!this.DoMips)
                    {
                        info.MipLevels = 1;
                    }

                    this.Texture = DX11Texture2D.FromFile(context, path, info);
                    this.Status  = eDX11SheduleTaskStatus.Completed;
                }
                catch
                {
                    this.Status = eDX11SheduleTaskStatus.Error;
                }
            }
        }
Esempio n. 7
0
        protected override void OnInit(object sender, EventArgs e)
        {
            //OdysseyUI.RemoveHooks(Global.FormOwner);

            ImageLoadInformation imageLoadInfo = new ImageLoadInformation()
            {
                BindFlags = BindFlags.None,
                CpuAccessFlags = CpuAccessFlags.Read,
                FilterFlags = FilterFlags.None,
                Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm,
                MipFilterFlags = FilterFlags.None,
                OptionFlags = ResourceOptionFlags.None,
                Usage = ResourceUsage.Staging,
                MipLevels = 1
            };

            // Make texture 3D
            Texture2D sourceTexture = Texture2D.FromFile(Game.Context.Device, "medusa.jpg", imageLoadInfo);
            stereoTexture = Stereo.Make3D(sourceTexture);
            backBuffer = Game.Context.GetBackBuffer();

            stereoSourceBox = new ResourceRegion
                                  {
                                      Front = 0,
                                      Back = 1,
                                      Top = 0,
                                      Bottom = Game.Context.Settings.ScreenHeight,
                                      Left = 0,
                                      Right = Game.Context.Settings.ScreenWidth
                                  };
        }
Esempio n. 8
0
        /// <summary>
        /// Create A shaderViewresource on a TextureArray object created from image files
        /// </summary>
        /// <param name="device">The graphic device</param>
        /// <param name="FileNames">The files names that will be used to create the array, the array's index will be based on the order of the file inside this collection</param>
        /// <param name="MIPfilterFlag">Filter used to create the mipmap lvl from the loaded images</param>
        /// <param name="ArrayTextureView">The create textureArray view that can directly be used inside shaders</param>
        public static void CreateTexture2DFromFiles(Device device, string[] FileNames, FilterFlags MIPfilterFlag, string ResourceName, out Texture2D[] TextureArray, int MaxMipLevels, SharpDX.DXGI.Format InMemoryArrayFormat = SharpDX.DXGI.Format.R8G8B8A8_UNorm)
        {
            int inputImagesCount = FileNames.Length;

            //1 First loading the textures from files
            TextureArray = new Texture2D[inputImagesCount];

            ImageLoadInformation ImageInfo = new ImageLoadInformation()
            {
                FirstMipLevel  = 0,
                MipLevels      = MaxMipLevels,
                Usage          = ResourceUsage.Staging,
                BindFlags      = BindFlags.None,
                CpuAccessFlags = CpuAccessFlags.Write | CpuAccessFlags.Read,
                OptionFlags    = ResourceOptionFlags.None,
                Format         = InMemoryArrayFormat,
                Filter         = FilterFlags.None,
                MipFilter      = MIPfilterFlag
            };

            for (int imgInd = 0; imgInd < inputImagesCount; imgInd++)
            {
                TextureArray[imgInd] = Texture2D.FromFile <Texture2D>(device, FileNames[imgInd], ImageInfo);
            }
        }
Esempio n. 9
0
 public GPUDecoder()
 {
     ilf                = ImageLoadInformation.FromDefaults();
     ilf.BindFlags      = BindFlags.ShaderResource;
     ilf.CpuAccessFlags = CpuAccessFlags.None;
     ilf.FirstMipLevel  = 0;
     ilf.MipLevels      = 1;
     ilf.Usage          = ResourceUsage.Default;
 }
Esempio n. 10
0
 public WICDecoder(MemoryPool mempool)
 {
     mp                 = mempool;
     ilf                = ImageLoadInformation.FromDefaults();
     ilf.BindFlags      = BindFlags.ShaderResource;
     ilf.CpuAccessFlags = CpuAccessFlags.None;
     ilf.FirstMipLevel  = 0;
     ilf.MipLevels      = 1;
     ilf.Usage          = ResourceUsage.Default;
 }
Esempio n. 11
0
        public static Texture GetTexture(string ressource, bool mipmap = true, Format format = Format.BC3_UNorm)
        {
            Texture returnTex;

            lock (list) {
                bool found = list.TryGetValue(ressource, out returnTex);

                if (!found)
                {
                    String currentPath = FindFile(ressource);

                    if (!File.Exists(currentPath))
                    {
                        if (File.Exists(currentPath + ".jpg"))
                        {
                            currentPath = currentPath + ".jpg";
                        }
                        else if (File.Exists(currentPath + ".png"))
                        {
                            currentPath = currentPath + ".png";
                        }
                        else if (File.Exists(currentPath + ".dds"))
                        {
                            currentPath = currentPath + ".dds";
                        }
                        else
                        {
                            currentPath = Main_Path + "error.jpg";
                        }
                    }

                    ImageLoadInformation loadinfo = new ImageLoadInformation();

                    loadinfo.BindFlags      = BindFlags.ShaderResource;
                    loadinfo.CpuAccessFlags = CpuAccessFlags.None;
                    loadinfo.Depth          = 0;
                    loadinfo.Filter         = FilterFlags.None;
                    loadinfo.FirstMipLevel  = 0;
                    loadinfo.Format         = format;
                    loadinfo.MipFilter      = FilterFlags.Linear;
                    loadinfo.MipLevels      = (mipmap ? 0 : 1);
                    loadinfo.OptionFlags    = ResourceOptionFlags.None;
                    loadinfo.Usage          = ResourceUsage.Immutable;


                    Texture2D texture = Texture2D.FromFile <Texture2D>(Display.device, currentPath, loadinfo);

                    returnTex = new Texture(texture);
                    list.Add(ressource, returnTex);
                    listReverse.Add(returnTex, ressource);
                }
            }
            return(returnTex);
        }
Esempio n. 12
0
        static void LoadTexture()
        {
            ImageLoadInformation imageLoadInfo = new ImageLoadInformation
            {
                Format    = SlimDX.DXGI.Format.R16_UNorm,
                BindFlags = BindFlags.ShaderResource,
            };

            _TextureRV1 = ShaderResourceView.FromFile(_Device, "haha.dds", imageLoadInfo);
            _TextureRV2 = ShaderResourceView.FromFile(_Device, "C:\\users\\paul\\desktop\\15000x6000.tif", imageLoadInfo);
        }
Esempio n. 13
0
        protected override void DoProcess()
        {
            ImageLoadInformation info = ImageLoadInformation.FromDefaults();

            if (!this.domips)
            {
                info.MipLevels = 1;
            }

            this.Resource = DX11Texture2D.FromFile(this.Context, path, info);
        }
Esempio n. 14
0
        /// <summary>
        /// DOES NOT WORK
        /// </summary>
        /// <param name="fileName"></param>
        public void DisplayTexture(string fileName)
        {
            ImageLoadInformation loadInfo = new ImageLoadInformation
            {
                OptionFlags = ResourceOptionFlags.TextureCube
            };

            Texture2D          texture             = Texture2D.FromFile(_d3dDevice, fileName);
            ShaderResourceView textureResourceView = new ShaderResourceView(_d3dDevice, texture);

            _d3dDevice.PixelShader.SetShaderResource(textureResourceView, 0);
        }
Esempio n. 15
0
        /// <summary>Loads the resources contained in a skin document</summary>
        /// <param name="skinDocument">
        ///   XML document containing a skin description whose resources will be loaded
        /// </param>
        private void loadResources(XDocument skinDocument)
        {
            // Get the resources node containing a list of all resources of the skin
            XElement resources = skinDocument.Element("skin").Element("resources");

            // Load all fonts used by the skin
            foreach (XElement element in resources.Descendants("font"))
            {
                string fontName     = element.Attribute("name").Value;
                string contentPath  = element.Attribute("contentPath").Value;
                string realFontName = element.Attribute("fontName").Value;
                string style        = element.Attribute("fontStyle").Value;
                float  fontSize     = float.Parse(element.Attribute("fontSize").Value, CultureInfo.InvariantCulture);

                var fontStyle = (FontStyle)Enum.Parse(typeof(FontStyle), style);

                var spriteFont = new SpriteFont();
                //External font file ?
                if (realFontName.Contains(".ttf"))
                {
                    using (var fontCollection = new PrivateFontCollection())
                    {
                        fontCollection.AddFontFile("Images\\BebasNeue.ttf");
                        spriteFont.Initialize(fontCollection.Families[0], fontSize, fontStyle, true, _d3dEngine.Device);
                    }
                }
                else
                {
                    spriteFont.Initialize(realFontName, fontSize, fontStyle, true, _d3dEngine.Device);
                }
                this.fonts.Add(fontName, spriteFont);
            }

            // Load all bitmaps used by the skin
            foreach (XElement element in resources.Descendants("bitmap"))
            {
                string bitmapName  = element.Attribute("name").Value;
                string contentPath = element.Attribute("contentPath").Value;

                //Create the SpriteTexture
                ImageLoadInformation imageLoadParam = new ImageLoadInformation()
                {
                    BindFlags = BindFlags.ShaderResource,
                    Format    = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
                    MipLevels = 1
                };

                SpriteTexture bitmap = new SpriteTexture(_d3dEngine.Device, _resourceDirectory + @"\" + contentPath + ".png", Vector2I.Zero, imageLoadParam);

                this.bitmaps.Add(bitmapName, bitmap);
            }
        }
Esempio n. 16
0
            public static Texture2D ToImage(ImportedTexture tex, ImageLoadInformation loadInfo, out byte pixelDepth)
            {
                ushort width, height;

                byte[] data;
                using (Stream stream = new MemoryStream(tex.Data))
                {
                    byte  idLen, descriptor;
                    bool  compressed;
                    short originY;
                    GetImageInfo(stream, out idLen, out compressed, out originY, out width, out height, out pixelDepth, out descriptor);
                    if (compressed)
                    {
                        throw new Exception("Warning! Compressed TGAs are not supported");
                    }
                    stream.Position = idLen + 0x12;
                    BinaryReader reader = new BinaryReader(stream);
                    data = reader.ReadToEnd();
                    if (originY == 0)
                    {
                        Flip((short)height, width, height, (byte)(pixelDepth >> 3), data);
                    }
                }
                byte[] header = DDS.CreateHeader(width, height, pixelDepth, 0, false, pixelDepth == 32 ? DDS.UnityCompatibleFormat.ARGB32 : DDS.UnityCompatibleFormat.RGB24);
                using (BinaryWriter writer = new BinaryWriter(new MemoryStream()))
                {
                    writer.Write(header);
                    writer.Write(data);

                    try
                    {
                        writer.BaseStream.Position = 0;
                        return(Texture2D.FromStream(Gui.Renderer.Device, writer.BaseStream, (int)writer.BaseStream.Length, loadInfo));
                    }
                    catch (Exception e)
                    {
                        Direct3D11Exception d3de = e as Direct3D11Exception;
                        if (d3de != null)
                        {
                            Report.ReportLog("Direct3D11 Exception name=\"" + d3de.ResultCode.Name + "\" desc=\"" + d3de.ResultCode.Description + "\" code=0x" + ((uint)d3de.ResultCode.Code).ToString("X"));
                        }
                        else
                        {
                            Utility.ReportException(e);
                        }
                        return(null);
                    }
                }
            }
Esempio n. 17
0
            public static Texture2D ToImage(ImportedTexture tex, out byte pixelDepth)
            {
                ImageLoadInformation loadInfo = new ImageLoadInformation()
                {
                    BindFlags      = BindFlags.None,
                    CpuAccessFlags = CpuAccessFlags.Read,
                    FilterFlags    = FilterFlags.None,
                    Format         = Format.R8G8B8A8_UNorm,
                    MipFilterFlags = FilterFlags.None,
                    MipLevels      = 1,
                    OptionFlags    = ResourceOptionFlags.None,
                    Usage          = ResourceUsage.Staging,
                };

                return(ToImage(tex, loadInfo, out pixelDepth));
            }
Esempio n. 18
0
        // Static functions
        static public TextureObject CreateTexture3DFromFile(Device device, int width, int height, int depth, Format format, string fileName)
        {
            TextureObject newTexture = new TextureObject();

            // Variables
            newTexture.m_Width     = width;
            newTexture.m_Height    = height;
            newTexture.m_Depth     = depth;
            newTexture.m_TexFormat = format;
            newTexture.m_Mips      = 1;

            BindFlags bindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget | BindFlags.UnorderedAccess;

            ImageLoadInformation imageLoadInfo = new ImageLoadInformation()
            {
                BindFlags      = bindFlags,
                CpuAccessFlags = CpuAccessFlags.None,
                Format         = format,
                Height         = height,
                Width          = width,
                Depth          = depth,
                MipLevels      = 1,
                OptionFlags    = ResourceOptionFlags.None,
                Usage          = ResourceUsage.Default
            };

            newTexture.m_TextureObject3D = Texture3D.FromFile(device, fileName, imageLoadInfo);

            ShaderResourceViewDescription srvViewDesc = new ShaderResourceViewDescription
            {
                ArraySize       = 0,
                Format          = format,
                Dimension       = ShaderResourceViewDimension.Texture3D,
                Flags           = 0,
                FirstArraySlice = 0,
                MostDetailedMip = 0,
                MipLevels       = 1,
            };

            newTexture.m_ShaderResourceView = new ShaderResourceView(device, newTexture.m_TextureObject3D, srvViewDesc);

            newTexture.m_RenderTargetView    = new RenderTargetView(device, newTexture.m_TextureObject3D);
            newTexture.m_UnorderedAccessView = new UnorderedAccessView(device, newTexture.m_TextureObject3D);

            return(newTexture);
        }
Esempio n. 19
0
        static public Texture11 FromStream(Device device, Stream stream)
        {
            byte[] data = null;
            if (SaveStream)
            {
                MemoryStream ms = new MemoryStream();

                stream.CopyTo(ms);
                stream.Seek(0, SeekOrigin.Begin);
                data = ms.GetBuffer();
            }

            try
            {
                ImageLoadInformation loadInfo = new ImageLoadInformation();
                loadInfo.BindFlags      = BindFlags.ShaderResource;
                loadInfo.CpuAccessFlags = CpuAccessFlags.None;
                loadInfo.Depth          = -1;
                loadInfo.Format         = RenderContext11.DefaultTextureFormat;
                loadInfo.Filter         = FilterFlags.Box;
                loadInfo.FirstMipLevel  = 0;
                loadInfo.Height         = -1;
                loadInfo.MipFilter      = FilterFlags.Linear;
                loadInfo.MipLevels      = 0;
                loadInfo.OptionFlags    = ResourceOptionFlags.None;
                loadInfo.Usage          = ResourceUsage.Default;
                loadInfo.Width          = -1;
                if (loadInfo.Format == SharpDX.DXGI.Format.R8G8B8A8_UNorm_SRgb)
                {
                    loadInfo.Filter |= FilterFlags.SRgb;
                }

                Texture2D texture = Texture2D.FromStream <Texture2D>(device, stream, (int)stream.Length, loadInfo);

                Texture11 t11 = new Texture11(texture);
                t11.savedStrem = data;
                return(t11);
            }
            catch
            {
                return(null);
            }
        }
Esempio n. 20
0
        public static ShaderResourceView Load3DTextureFromFile(string fileName)
        {
            if (_textures3D == null)
            {
                _textures3D = new Dictionary <string, Texture3D>();
            }

            Texture3D            texture     = null;
            string               path        = Utils.GetRootPath() + "\\Content\\Textures\\" + fileName;
            ImageInformation?    SrcInfo     = ImageInformation.FromFile(path);
            ImageLoadInformation texLoadInfo = new ImageLoadInformation();

            texLoadInfo.Width          = SrcInfo.Value.Width;
            texLoadInfo.Height         = SrcInfo.Value.Height;
            texLoadInfo.Depth          = SrcInfo.Value.Depth;
            texLoadInfo.FirstMipLevel  = 0;
            texLoadInfo.MipLevels      = SrcInfo.Value.MipLevels;
            texLoadInfo.Usage          = ResourceUsage.Default;
            texLoadInfo.BindFlags      = BindFlags.ShaderResource;
            texLoadInfo.CpuAccessFlags = 0;
            texLoadInfo.OptionFlags    = SrcInfo.Value.OptionFlags;
            texLoadInfo.Format         = SrcInfo.Value.Format;
            texLoadInfo.FilterFlags    = FilterFlags.Triangle;
            texLoadInfo.MipFilterFlags = FilterFlags.Triangle;

            //if (_textures3D.ContainsKey(fileName))
            //  texture = _textures3D[fileName];
            //else
            {
                texture = Texture3D.FromFile(Game.Device, path, texLoadInfo);
                _textures3D[fileName] = texture;
            }
            ShaderResourceViewDescription SRVDesc = new ShaderResourceViewDescription();

            SRVDesc.Format          = texLoadInfo.Format;
            SRVDesc.Dimension       = ShaderResourceViewDimension.Texture3D;
            SRVDesc.MostDetailedMip = 0;
            SRVDesc.MipLevels       = texLoadInfo.MipLevels;
            ShaderResourceView srv = new ShaderResourceView(Game.Device, texture, SRVDesc);

            texture.Dispose();
            return(srv);
        }
Esempio n. 21
0
        private void LoadAllTileTextures()
        {
            Device           device   = t.Device;
            List <Texture2D> textures = new List <Texture2D>();
            List <string>    allFiles = Directory.GetFiles("01.Frontend/Textures/Blocks/", "*.png").ToList();

            allFiles.AddRange(Directory.GetFiles("01.Frontend/Textures/Items/", "*.png"));
            allFiles.AddRange(Directory.GetFiles("01.Frontend/Textures/Gui/", "*.png"));

            ImageLoadInformation info = new ImageLoadInformation()
            {
                BindFlags      = BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                FilterFlags    = FilterFlags.None,
                Format         = SlimDX.DXGI.Format.R8G8B8A8_UNorm,
                MipFilterFlags = FilterFlags.Point,
                OptionFlags    = ResourceOptionFlags.None,
                Usage          = ResourceUsage.Default,
                MipLevels      = 2
            };

            foreach (string filename in allFiles)
            {
                textures.Add(Texture2D.FromFile(device, filename, info));
            }

            var textureArrayDescription = textures[0].Description;

            textureArrayDescription.ArraySize = textures.Count;
            var textureArray = new Texture2D(device, textureArrayDescription);
            var mipLevels    = textureArrayDescription.MipLevels;

            for (int j = 0; j < textures.Count; j++)
            {
                indexMap.Add(Path.GetFileNameWithoutExtension(allFiles[j]), j);
                for (var i = 0; i < mipLevels; i++)
                {
                    // for both textures
                    device.ImmediateContext.CopySubresourceRegion(textures[j], i, textureArray, mipLevels * j + i, 0, 0, 0);
                }
            }
            View = new ShaderResourceView(device, textureArray);
        }
Esempio n. 22
0
            public void SetPosition(DX11RenderContext ctx, int frame)
            {
                int frameindex = frame - this.CurrentFrame;

                frameindex = frameindex < 0 ? 0 : frameindex;
                frameindex = frameindex > Data.FileCount - 1 ? Data.FileCount - 1 : frameindex;

                if (frameindex != CurrentFrame)
                {
                    if (this.Texture == null)
                    {
                        this.Texture.Dispose();
                    }

                    ImageLoadInformation info = ImageLoadInformation.FromDefaults();
                    info.MipLevels = 1;
                    this.Texture   = DX11Texture2D.FromFile(ctx, Data.FilePath[frameindex], info);
                    CurrentFrame   = frameindex;
                }
            }
Esempio n. 23
0
 protected override bool Load(DX11RenderContext context, string path, out DX11Texture3D result)
 {
     try
     {
         if (this.FInNoMips[0])
         {
             ImageLoadInformation loadinfo = new ImageLoadInformation();
             loadinfo.MipLevels = 1;
             result             = DX11Texture3D.FromFile(context, path, loadinfo);
         }
         else
         {
             result = DX11Texture3D.FromFile(context, path);
         }
         return(true);
     }
     catch
     {
         result = null;
         return(false);
     }
 }
Esempio n. 24
0
        public static DX11Texture3D FromFile(DX11RenderContext context, string path, ImageLoadInformation loadinfo)
        {
            DX11Texture3D res = new DX11Texture3D(context);

            try
            {
                res.Resource = Texture3D.FromFile(context.Device, path, loadinfo);

                res.SRV = new ShaderResourceView(context.Device, res.Resource);

                Texture3DDescription desc = res.Resource.Description;

                res.Width  = desc.Width;
                res.Height = desc.Height;
                res.Format = desc.Format;
                res.Depth  = desc.Depth;
            }
            catch
            {
            }
            return(res);
        }
Esempio n. 25
0
        public override void Init()
        {
            TexturedPolygon quad = TexturedPolygon.CreateTexturedQuad("ScreenQuad", Vector3.Zero, 1920, 1080);
            ImageLoadInformation info = new ImageLoadInformation()
            {
                BindFlags = BindFlags.None,
                CpuAccessFlags = CpuAccessFlags.Read,
                FilterFlags = FilterFlags.None,
                Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm,
                MipFilterFlags = FilterFlags.None,
                OptionFlags = ResourceOptionFlags.None,
                Usage = ResourceUsage.Staging,
                MipLevels = 1
            };
            Texture2D tex = Texture2D.FromFile(Game.Context.Device, "medusa.jpg",  info);

            ShaderResourceView srv = new ShaderResourceView(Game.Context.Device,  Make3D(tex));
            quad.DiffuseMapResource = srv;
            rNode = new RenderableNode(quad);
            iMat = new ImageMaterial();
            FixedNode fNode = new FixedNode();
            fNode.Init();
            quad.PositionV3 = Layout.OrthographicTransform(Vector2.Zero, 100, new Size(1920,1080));

            RenderableCollection rCol = new RenderableCollection(iMat.RenderableCollectionDescription);
            MaterialNode mMat = new MaterialNode(iMat);
            rCol.Add(rNode);

            fNode.AppendChild(mMat);
            mMat.AppendChild(rNode);

            rCommand = new RenderCommand(mMat, rCol);
            rCommand.Init();
            DeviceContext.Immediate.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

            Scene.Tree.RootNode.AppendChild(fNode);
            Scene.BuildRenderScene();
        }
Esempio n. 26
0
        public static Texture2D GetMappableTexture(string ressource)
        {
            String currentPath = FindFile(ressource);

            if (!File.Exists(currentPath))
            {
                if (File.Exists(currentPath + ".jpg"))
                {
                    currentPath = currentPath + ".jpg";
                }
                else if (File.Exists(currentPath + ".png"))
                {
                    currentPath = currentPath + ".png";
                }
                else if (File.Exists(currentPath + ".dds"))
                {
                    currentPath = currentPath + ".dds";
                }
                else
                {
                    currentPath = Main_Path + "error.jpg"; //throw new ArgumentNullException("Texture '" + currentPath + "' not found.");
                }
            }

            ImageLoadInformation loadinfo = new ImageLoadInformation();

            loadinfo.BindFlags      = BindFlags.None;
            loadinfo.CpuAccessFlags = CpuAccessFlags.Read;
            loadinfo.Format         = Format.R8G8B8A8_UNorm;
            loadinfo.Usage          = ResourceUsage.Staging;
            loadinfo.MipFilter      = FilterFlags.None;
            loadinfo.Filter         = FilterFlags.None;
            loadinfo.MipLevels      = 1;


            return(Texture2D.FromFile <Texture2D>(Display.device, currentPath, loadinfo));
        }
Esempio n. 27
0
        private static void Main()
        {
            // Device creation
            var form = new RenderForm("Stereo test")
                           {
                               ClientSize = size,
                               //FormBorderStyle = System.Windows.Forms.FormBorderStyle.None,
                               //WindowState = FormWindowState.Maximized
                           };

            form.KeyDown += new KeyEventHandler(form_KeyDown);
               // form.Resize += new EventHandler(form_Resize);

            ModeDescription mDesc = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height,
                                                        new Rational(120000, 1000), Format.R8G8B8A8_UNorm);
            mDesc.ScanlineOrdering = DisplayModeScanlineOrdering.Progressive;
            mDesc.Scaling = DisplayModeScaling.Unspecified;

            var desc = new SwapChainDescription()
                           {
                               BufferCount = 1,
                               ModeDescription = mDesc,
                                   Flags = SwapChainFlags.AllowModeSwitch,
                               IsWindowed = false,
                               OutputHandle = form.Handle,
                               SampleDescription = new SampleDescription(1, 0),
                               SwapEffect = SwapEffect.Discard,
                               Usage = Usage.RenderTargetOutput
                           };

            Device.CreateWithSwapChain(null, DriverType.Hardware, DeviceCreationFlags.Debug, desc, out device,
                                       out swapChain);

            //Stops Alt+enter from causing fullscreen skrewiness.
            factory = swapChain.GetParent<Factory>();
            factory.SetWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

            backBuffer = Resource.FromSwapChain<Texture2D>(swapChain, 0);
            renderView = new RenderTargetView(device, backBuffer);

            ImageLoadInformation info = new ImageLoadInformation()
                                            {
                                                BindFlags = BindFlags.None,
                                                CpuAccessFlags = CpuAccessFlags.Read,
                                                FilterFlags = FilterFlags.None,
                                                Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm,
                                                MipFilterFlags = FilterFlags.None,
                                                OptionFlags = ResourceOptionFlags.None,
                                                Usage = ResourceUsage.Staging,
                                                MipLevels = 1
                                            };

            // Make texture 3D
            sourceTexture = Texture2D.FromFile(device, "medusa.jpg", info);
            ImageLoadInformation info2 = new ImageLoadInformation()
                                            {
                                                BindFlags = BindFlags.ShaderResource,
                                                CpuAccessFlags = CpuAccessFlags.None,
                                                FilterFlags = FilterFlags.None,
                                                Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm,
                                                MipFilterFlags = FilterFlags.None,
                                                OptionFlags = ResourceOptionFlags.None,
                                                Usage = ResourceUsage.Default,
                                                MipLevels = 1
                                            };
            Texture2D tShader = Texture2D.FromFile(device, "medusa.jpg", info2);
            srv = new ShaderResourceView(device, tShader);
            //ResizeDevice(new Size(1920, 1080), true);
            // Create a quad that fills the whole screen

            BuildQuad();
            // Create world view (ortho) projection matrices
            //QuaternionCam qCam = new QuaternionCam();

            // Load effect from file. It is a basic effect that renders a full screen quad through
            // an ortho projectio=n matrix
            effect = Effect.FromFile(device, "Texture.fx", "fx_4_0", ShaderFlags.Debug, EffectFlags.None);
            EffectTechnique technique = effect.GetTechniqueByIndex(0);
            EffectPass pass = technique.GetPassByIndex(0);
            InputLayout layout = new InputLayout(device, pass.Description.Signature, new[]
                                                                                         {
                                                                                             new InputElement(
                                                                                                 "POSITION", 0,
                                                                                                 Format.
                                                                                                     R32G32B32A32_Float,
                                                                                                 0, 0),
                                                                                             new InputElement(
                                                                                                 "TEXCOORD", 0,
                                                                                                 Format.
                                                                                                     R32G32_Float,
                                                                                                 16, 0)
                                                                                         });
            //effect.GetVariableByName("mWorld").AsMatrix().SetMatrix(
            //    Matrix.Translation(Layout.OrthographicTransform(Vector2.Zero, 99, size)));
            //effect.GetVariableByName("mView").AsMatrix().SetMatrix(qCam.View);
            //effect.GetVariableByName("mProjection").AsMatrix().SetMatrix(qCam.OrthoProjection);
            //effect.GetVariableByName("tDiffuse").AsResource().SetResource(srv);

            // Set RT and Viewports
            device.OutputMerger.SetTargets(renderView);
            device.Rasterizer.SetViewports(new Viewport(0, 0, size.Width, size.Height, 0.0f, 1.0f));

            // Create solid rasterizer state
            RasterizerStateDescription rDesc = new RasterizerStateDescription()
                                                   {
                                                       CullMode = CullMode.None,
                                                       IsDepthClipEnabled = true,
                                                       FillMode = FillMode.Solid,
                                                       IsAntialiasedLineEnabled = false,
                                                       IsFrontCounterclockwise = true,
                                                       //IsMultisampleEnabled = true,
                                                   };
            RasterizerState rState = RasterizerState.FromDescription(device, rDesc);
            device.Rasterizer.State = rState;

            Texture2DDescription rtDesc = new Texture2DDescription
                                              {
                                                  ArraySize = 1,
                                                  Width = size.Width,
                                                  Height = size.Height,
                                                  BindFlags = BindFlags.RenderTarget,
                                                  CpuAccessFlags = CpuAccessFlags.None,
                                                  Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm,
                                                  OptionFlags = ResourceOptionFlags.None,
                                                  Usage = ResourceUsage.Default,
                                                  MipLevels = 1,
                                                  SampleDescription = new SampleDescription(1, 0)
                                              };
            rtTex = new Texture2D(device, rtDesc);

            rv = new RenderTargetView(device, rtTex);

            stereoizedTexture = Make3D(sourceTexture);
            //ResizeDevice(new Size(1920, 1080), true);
            Console.WriteLine(form.ClientSize);
            // Main Loop
            MessagePump.Run(form, () =>
            {
            device.ClearRenderTargetView(renderView, Color.Cyan);

            //device.InputAssembler.SetInputLayout(layout);
            //device.InputAssembler.SetPrimitiveTopology(PrimitiveTopology.TriangleList);
            //device.OutputMerger.SetTargets(rv);
            //device.InputAssembler.SetVertexBuffers(0,
            //                                new VertexBufferBinding(vertices, 24, 0));
            //device.InputAssembler.SetIndexBuffer(indices, Format.R16_UInt, 0);
            //for (int i = 0; i < technique.Description.PassCount; ++i)
            //{
            //    // Render the full screen quad
            //    pass.Apply();
            //    device.DrawIndexed(6, 0, 0);
            //}
            ResourceRegion stereoSrcBox = new ResourceRegion { Front = 0, Back = 1, Top = 0, Bottom = size.Height, Left = 0, Right = size.Width };
            device.CopySubresourceRegion(stereoizedTexture, 0, stereoSrcBox, backBuffer, 0, 0, 0, 0);
            //device.CopyResource(rv.Resource, backBuffer);

            swapChain.Present(0, PresentFlags.None);
            });

            // Dispose resources
            vertices.Dispose();
            layout.Dispose();
            effect.Dispose();
            renderView.Dispose();
            backBuffer.Dispose();
            device.Dispose();
            swapChain.Dispose();

            rState.Dispose();
            stereoizedTexture.Dispose();
            sourceTexture.Dispose();
            indices.Dispose();
            srv.Dispose();
        }
Esempio n. 28
0
File: Util.cs Progetto: kkdevs/sb3u
        public static ShaderResourceView CreateTexture2DArraySRV(Device device, DeviceContext immediateContext, string[] filenames, Format format, FilterFlags filter = FilterFlags.None, FilterFlags mipFilter = FilterFlags.Linear)
        {
            var srcTex = new Texture2D[filenames.Length];

            for (int i = 0; i < filenames.Length; i++)
            {
                var loadInfo = new ImageLoadInformation {
                    FirstMipLevel  = 0,
                    Usage          = ResourceUsage.Staging,
                    BindFlags      = BindFlags.None,
                    CpuAccessFlags = CpuAccessFlags.Write | CpuAccessFlags.Read,
                    OptionFlags    = ResourceOptionFlags.None,
                    Format         = format,
                    FilterFlags    = filter,
                    MipFilterFlags = mipFilter,
                };
                srcTex[i] = Texture2D.FromFile(device, filenames[i], loadInfo);
            }
            var texElementDesc = srcTex[0].Description;

            var texArrayDesc = new Texture2DDescription {
                Width             = texElementDesc.Width,
                Height            = texElementDesc.Height,
                MipLevels         = texElementDesc.MipLevels,
                ArraySize         = srcTex.Length,
                Format            = texElementDesc.Format,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None
            };

            var texArray = new Texture2D(device, texArrayDesc);

            texArray.DebugName = "texture array: + " + filenames.Aggregate((i, j) => i + ", " + j);
            for (int texElement = 0; texElement < srcTex.Length; texElement++)
            {
                for (int mipLevel = 0; mipLevel < texElementDesc.MipLevels; mipLevel++)
                {
                    var mappedTex2D = immediateContext.MapSubresource(srcTex[texElement], mipLevel, 0, MapMode.Read, MapFlags.None);

                    immediateContext.UpdateSubresource(
                        mappedTex2D,
                        texArray,
                        Resource.CalculateSubresourceIndex(mipLevel, texElement, texElementDesc.MipLevels)
                        );
                    immediateContext.UnmapSubresource(srcTex[texElement], mipLevel);
                }
            }
            var viewDesc = new ShaderResourceViewDescription {
                Format          = texArrayDesc.Format,
                Dimension       = ShaderResourceViewDimension.Texture2DArray,
                MostDetailedMip = 0,
                MipLevels       = texArrayDesc.MipLevels,
                FirstArraySlice = 0,
                ArraySize       = srcTex.Length
            };

            var texArraySRV = new ShaderResourceView(device, texArray, viewDesc);

            ReleaseCom(ref texArray);
            for (int i = 0; i < srcTex.Length; i++)
            {
                ReleaseCom(ref srcTex[i]);
            }

            return(texArraySRV);
        }
Esempio n. 29
0
        public override SubscriberBase GetSubscriberInstance(EffectVariable variable, RenderContext context, MMEEffectManager effectManager, int semanticIndex)
        {
            TextureSubscriber subscriber = new TextureSubscriber();
            int    width, height, depth, mip;
            string typeName = variable.GetVariableType().Description.TypeName.ToLower();
            string type;
            Format format;

            TextureAnnotationParser.GetBasicTextureAnnotations(variable, context, Format.B8G8R8A8_UNorm, Vector2.Zero, true,
                                                               out width, out height, out depth, out mip, out format);
            EffectVariable rawTypeVariable   = EffectParseHelper.getAnnotation(variable, "ResourceType", "string");
            EffectVariable rawStringVariable = EffectParseHelper.getAnnotation(variable, "ResourceName", "string");

            if (rawTypeVariable != null)
            {
                switch (rawTypeVariable.AsString().GetString().ToLower())
                {
                case "cube":
                    if (!typeName.Equals("texturecube"))
                    {
                        throw new InvalidMMEEffectShaderException("ResourceTypeにはCubeが指定されていますが、型がtextureCUBEではありません。");
                    }
                    else
                    {
                        type = "texturecube";
                    }
                    break;

                case "2d":
                    if (!typeName.Equals("texture2d") && !typeName.Equals("texture"))
                    {
                        throw new InvalidMMEEffectShaderException("ResourceTypeには2Dが指定されていますが、型がtexture2Dもしくはtextureではありません。");
                    }
                    else
                    {
                        type = "texture2d";
                    }
                    break;

                case "3d":
                    if (!typeName.Equals("texture3d"))
                    {
                        throw new InvalidMMEEffectShaderException("ResourceTypeには3Dが指定されていますが、型がtexture3dではありません。");
                    }
                    else
                    {
                        type = "texture3d";
                    }
                    break;

                default:
                    throw new InvalidMMEEffectShaderException("認識できないResourceTypeが指定されました。");
                }
            }
            else
            {
                type = typeName;
            }
            if (rawStringVariable != null)
            {
                string resourceName          = rawStringVariable.AsString().GetString();
                ImageLoadInformation imgInfo = new ImageLoadInformation();
                Stream stream;
                switch (type)
                {
                case "texture2d":

                    imgInfo.Width          = width;
                    imgInfo.Height         = height;
                    imgInfo.MipLevels      = mip;
                    imgInfo.Format         = format;
                    imgInfo.Usage          = ResourceUsage.Default;
                    imgInfo.BindFlags      = BindFlags.ShaderResource;
                    imgInfo.CpuAccessFlags = CpuAccessFlags.None;
                    stream = effectManager.SubresourceLoader.getSubresourceByName(resourceName);
                    if (stream != null)
                    {
                        subscriber.resourceTexture = Texture2D.FromStream(context.DeviceManager.Device, stream, (int)stream.Length);
                    }
                    break;

                case "texture3d":
                    imgInfo.Width          = width;
                    imgInfo.Height         = height;
                    imgInfo.Depth          = depth;
                    imgInfo.MipLevels      = mip;
                    imgInfo.Format         = format;
                    imgInfo.Usage          = ResourceUsage.Default;
                    imgInfo.BindFlags      = BindFlags.ShaderResource;
                    imgInfo.CpuAccessFlags = CpuAccessFlags.None;
                    stream = effectManager.SubresourceLoader.getSubresourceByName(resourceName);
                    if (stream != null)
                    {
                        subscriber.resourceTexture = Texture3D.FromStream(context.DeviceManager.Device, stream, (int)stream.Length);
                    }
                    break;

                case "texturecube":
                    //TODO CUBEの場合に対応する
                    //imgInfo.Width = width;
                    //imgInfo.Height = height;
                    //imgInfo.Depth = depth;
                    //imgInfo.MipLevels = mip;
                    //imgInfo.Format = format;
                    //imgInfo.Usage=ResourceUsage.Default;
                    //imgInfo.BindFlags=BindFlags.ShaderResource;
                    //imgInfo.CpuAccessFlags=CpuAccessFlags.None;
                    //stream = effectManager.SubresourceLoader.getSubresourceByName(resourceName);
                    //subscriber.resourceTexture=.FromStream(context.DeviceManager.Device, stream, (int)stream.Length);
                    break;
                }
            }
            subscriber.resourceView = new ShaderResourceView(context.DeviceManager.Device, subscriber.resourceTexture);
            return(subscriber);
        }
Esempio n. 30
0
 public static DX11Texture2D FromMemory(DX11RenderContext context, byte[] data)
 {
     return(FromMemory(context, data, ImageLoadInformation.FromDefaults()));
 }
Esempio n. 31
0
 public static DX11Texture2D FromFile(DX11RenderContext context, string path)
 {
     return(DX11Texture2D.FromFile(context, path, ImageLoadInformation.FromDefaults()));
 }
Esempio n. 32
0
        static public Texture11 FromBitmap(Device device, Bitmap bmp)
        {
            MemoryStream ms = new MemoryStream();

            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

            ms.Seek(0, SeekOrigin.Begin);

            if (IsPowerOf2((uint)bmp.Width) && IsPowerOf2((uint)bmp.Height))
            {
                ImageLoadInformation loadInfo = new ImageLoadInformation();
                loadInfo.BindFlags      = BindFlags.ShaderResource;
                loadInfo.CpuAccessFlags = CpuAccessFlags.None;
                loadInfo.Depth          = -1;
                loadInfo.Format         = RenderContext11.DefaultTextureFormat;
                loadInfo.Filter         = FilterFlags.Box;
                loadInfo.FirstMipLevel  = 0;
                loadInfo.Height         = -1;
                loadInfo.MipFilter      = FilterFlags.Linear;
                loadInfo.MipLevels      = 0;
                loadInfo.OptionFlags    = ResourceOptionFlags.None;
                loadInfo.Usage          = ResourceUsage.Default;
                loadInfo.Width          = -1;
                if (loadInfo.Format == SharpDX.DXGI.Format.R8G8B8A8_UNorm_SRgb)
                {
                    loadInfo.Filter |= FilterFlags.SRgb;
                }

                Texture2D texture = Texture2D.FromStream <Texture2D>(device, ms, (int)ms.Length, loadInfo);

                ms.Dispose();
                return(new Texture11(texture));
            }
            else
            {
                ms.Seek(0, SeekOrigin.Begin);
                ImageLoadInformation ili = new ImageLoadInformation()
                {
                    BindFlags      = BindFlags.ShaderResource,
                    CpuAccessFlags = CpuAccessFlags.None,
                    Depth          = -1,
                    Filter         = FilterFlags.Box,
                    FirstMipLevel  = 0,
                    Format         = RenderContext11.DefaultTextureFormat,
                    Height         = -1,
                    MipFilter      = FilterFlags.None,
                    MipLevels      = 1,
                    OptionFlags    = ResourceOptionFlags.None,
                    Usage          = ResourceUsage.Default,
                    Width          = -1
                };
                if (ili.Format == SharpDX.DXGI.Format.R8G8B8A8_UNorm_SRgb)
                {
                    ili.Filter |= FilterFlags.SRgb;
                }

                Texture2D texture = Texture2D.FromStream <Texture2D>(device, ms, (int)ms.Length, ili);
                ms.Dispose();
                return(new Texture11(texture));
            }
        }
Esempio n. 33
0
        static public Texture11 FromFile(Device device, string fileName, LoadOptions options = LoadOptions.AssumeSRgb)
        {
            try
            {
                ImageLoadInformation loadInfo = new ImageLoadInformation();
                loadInfo.BindFlags      = BindFlags.ShaderResource;
                loadInfo.CpuAccessFlags = CpuAccessFlags.None;
                loadInfo.Depth          = -1;
                loadInfo.Filter         = FilterFlags.Box;
                loadInfo.FirstMipLevel  = 0;
                loadInfo.Format         = SharpDX.DXGI.Format.R8G8B8A8_UNorm;

                loadInfo.Height      = -1;
                loadInfo.MipLevels   = -1;
                loadInfo.OptionFlags = ResourceOptionFlags.None;
                loadInfo.Usage       = ResourceUsage.Default;
                loadInfo.Width       = -1;

                bool shouldPromoteSRgb = RenderContext11.sRGB && (options & LoadOptions.AssumeSRgb) == LoadOptions.AssumeSRgb;

                if (fileName.EndsWith(".png", StringComparison.InvariantCultureIgnoreCase) ||
                    fileName.EndsWith(".jpg", StringComparison.InvariantCultureIgnoreCase) ||
                    fileName.EndsWith(".jpeg", StringComparison.InvariantCultureIgnoreCase))
                {
                    loadInfo.Filter = FilterFlags.Box;
                    if (shouldPromoteSRgb)
                    {
                        loadInfo.Format = promoteFormatToSRGB(loadInfo.Format);
                    }
                    if (isSRGBFormat(loadInfo.Format))
                    {
                        loadInfo.Filter |= FilterFlags.SRgb;
                    }
                }
                else
                {
                    // Promote image format to sRGB
                    ImageInformation?info = ImageInformation.FromFile(fileName);
                    if (info.HasValue && shouldPromoteSRgb)
                    {
                        loadInfo.Format = promoteFormatToSRGB(info.Value.Format);
                    }
                    if (isSRGBFormat(loadInfo.Format))
                    {
                        loadInfo.Filter |= FilterFlags.SRgb;
                    }
                }

                Texture2D texture = Texture2D.FromFile <Texture2D>(device, fileName, loadInfo);

                return(new Texture11(texture));
            }
            catch (Exception e)
            {
                try
                {
                    ImageLoadInformation ili = new ImageLoadInformation()
                    {
                        BindFlags      = BindFlags.ShaderResource,
                        CpuAccessFlags = CpuAccessFlags.None,
                        Depth          = -1,
                        Filter         = FilterFlags.Box,
                        FirstMipLevel  = 0,
                        Format         = RenderContext11.DefaultTextureFormat,
                        Height         = -1,
                        MipFilter      = FilterFlags.None,
                        MipLevels      = 1,
                        OptionFlags    = ResourceOptionFlags.None,
                        Usage          = ResourceUsage.Default,
                        Width          = -1
                    };
                    if (ili.Format == SharpDX.DXGI.Format.R8G8B8A8_UNorm_SRgb)
                    {
                        ili.Filter |= FilterFlags.SRgb;
                    }

                    Texture2D texture = Texture2D.FromFile <Texture2D>(device, fileName, ili);
                    return(new Texture11(texture));
                }
                catch
                {
                    return(null);
                }
            }
        }
Esempio n. 34
0
        public void CreateShaders(string code)
        {
            UpdateRenderer = true;
            // load and compile the vertex shader
            using (var bytecode = ShaderBytecode.Compile(code, "VShader", "vs_5_0", ShaderFlags.None, EffectFlags.None))
            {
                inputSignature = ShaderSignature.GetInputSignature(bytecode);
                vertexShader = new VertexShader(device, bytecode);
            }

            // load and compile the pixel shader
            using (var bytecode = ShaderBytecode.Compile(code, "PShader", "ps_5_0", ShaderFlags.None, EffectFlags.None))
                pixelShader = new PixelShader(device, bytecode);

            string compilationError = "";
            //ShaderBytecode compiledShader = ShaderBytecode.CompileFromFile("vteffect.fx", "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null, out compilationError);

            //fx = new Effect(device, compiledShader);

            // create test vertex data, making sure to rewind the stream afterward
            vertices = new DataStream(20 * 4, true, true);

            vertices.Write(new Vector3(-1f, -1f, 0.5f)); vertices.Write(new Vector2(0f, 1f));
            vertices.Write(new Vector3(-1f, 1f, 0.5f)); vertices.Write(new Vector2(0f, 0f));
            vertices.Write(new Vector3(1f, -1f, 0.5f)); vertices.Write(new Vector2(1f, 1f));
            vertices.Write(new Vector3(1f, 1f, 0.5f)); vertices.Write(new Vector2(1f, 0f));
            vertices.Position = 0;

            // create the vertex layout and buffer
            var elements = new[] {
            new InputElement("POSITION", 0, Format.R32G32B32_Float, 0),
            new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0)
            };
            layout = new InputLayout(device, inputSignature, elements);
            vertexBuffer = new SlimDX.Direct3D11.Buffer(device, vertices, 20 * 4, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0);

            List<int> indices = new List<int>();
            indices.Add(0);
            indices.Add(1);
            indices.Add(2);
            indices.Add(2);
            indices.Add(1);
            indices.Add(3);
            var ibd = new BufferDescription(sizeof(int) * indices.Count, ResourceUsage.Immutable, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
            indexBuffer = new SlimDX.Direct3D11.Buffer(device, new DataStream(indices.ToArray(), false, false), ibd);

            // configure the Input Assembler portion of the pipeline with the vertex data
            context.InputAssembler.InputLayout = layout;
            context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, 20, 0));
            context.InputAssembler.SetIndexBuffer(indexBuffer, Format.R32_UInt, 0);

            // set the shaders
            context.VertexShader.Set(vertexShader);
            context.PixelShader.Set(pixelShader);

            SamplerDescription sampleDesc = new SamplerDescription();
            sampleDesc.Filter = Filter.MinMagMipPoint;
            sampleDesc.AddressU = TextureAddressMode.Clamp;
            sampleDesc.AddressV = TextureAddressMode.Clamp;
            sampleDesc.AddressW = TextureAddressMode.Clamp;
            sampleDesc.MipLodBias = 0.0f;
            sampleDesc.ComparisonFunction = Comparison.Always;
            sampleDesc.BorderColor = new Color4(0, 0, 0, 0);
            sampleDesc.MinimumLod = 0;
            sampleDesc.MaximumLod = 1;

            sampleState = SamplerState.FromDescription(device, sampleDesc);

            SamplerDescription indSampleDesc = new SamplerDescription();
            sampleDesc.Filter = Filter.MinMagMipPoint;
            sampleDesc.AddressU = TextureAddressMode.Wrap;
            sampleDesc.AddressV = TextureAddressMode.Wrap;
            sampleDesc.AddressW = TextureAddressMode.Wrap;
            sampleDesc.MipLodBias = 0.0f;
            sampleDesc.ComparisonFunction = Comparison.Always;
            sampleDesc.BorderColor = new Color4(0, 0, 0, 0);
            sampleDesc.MinimumLod = 0;
            sampleDesc.MaximumLod = 1;

            indSampleState = SamplerState.FromDescription(device, sampleDesc);

            ImageLoadInformation loadInfo = new ImageLoadInformation() { Width = 2, Height = 2 };
            loadInfo.BindFlags = BindFlags.ShaderResource;
            loadInfo.CpuAccessFlags = CpuAccessFlags.None;
            loadInfo.Depth = 4;
            loadInfo.FilterFlags = FilterFlags.Point;
            loadInfo.FirstMipLevel = 0;
            loadInfo.Format = Format.R8G8B8A8_SInt;
            loadInfo.MipLevels = 0;
            loadInfo.Usage = ResourceUsage.Default;
            texture = new Texture2D(device, new Texture2DDescription
            {
                BindFlags = BindFlags.ShaderResource,
                ArraySize = 1024,
                Width = 128,
                Height = 128,
                Usage = ResourceUsage.Default,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = Format.R8G8B8A8_UNorm,
                SampleDescription = new SampleDescription(1, 0),
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None
            });//Texture2D.FromFile(device,"Tourism_Industrial_d.png");
            resourceView = new ShaderResourceView(device, texture);
            device.ImmediateContext.PixelShader.SetShaderResource(resourceView, 0);
            context.PixelShader.SetShaderResource(resourceView, 0);
            context.PixelShader.SetSampler(sampleState, 0);
            context.PixelShader.SetSampler(indSampleState, 1);
            if (currentEntry != null) SetTexture(currentEntry);
        }
Esempio n. 35
0
        // Static functions
        static public TextureObject CreateTexture3DFromFile(Device device, int width, int height, int depth, Format format, string fileName)
        {
            TextureObject newTexture = new TextureObject();

            // Variables
            newTexture.m_Width = width;
            newTexture.m_Height = height;
            newTexture.m_Depth = depth;
            newTexture.m_TexFormat = format;
            newTexture.m_Mips = 1;

            BindFlags bindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget | BindFlags.UnorderedAccess;

            ImageLoadInformation imageLoadInfo = new ImageLoadInformation()
            {
                BindFlags = bindFlags,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = format,
                Height = height,
                Width = width,
                Depth = depth,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                Usage = ResourceUsage.Default
            };

            newTexture.m_TextureObject3D = Texture3D.FromFile(device, fileName, imageLoadInfo);

            ShaderResourceViewDescription srvViewDesc = new ShaderResourceViewDescription
            {
                ArraySize = 0,
                Format = format,
                Dimension = ShaderResourceViewDimension.Texture3D,
                Flags = 0,
                FirstArraySlice = 0,
                MostDetailedMip = 0,
                MipLevels = 1,
            };

            newTexture.m_ShaderResourceView = new ShaderResourceView(device, newTexture.m_TextureObject3D, srvViewDesc);

            newTexture.m_RenderTargetView = new RenderTargetView(device, newTexture.m_TextureObject3D);
            newTexture.m_UnorderedAccessView = new UnorderedAccessView(device, newTexture.m_TextureObject3D);

            return newTexture;
        }
Esempio n. 36
0
        public ShaderResourceView CreateTexArray(string arrayName, params string[] filenames)
        {
            if (_textures.ContainsKey(arrayName))
                return _textures[arrayName];

            //
            // Load the texture elements individually from file.  These textures
            // won't be used by the GPU (0 bind flags), they are just used to
            // load the image data from file.  We use the STAGING usage so the
            // CPU can read the resource.
            //

            int arraySize = filenames.Length;

            var srcTex = new Texture2D[arraySize];
            for(int i = 0; i < arraySize; ++i)
            {
                var loadInfo = new ImageLoadInformation
                                   {
                                       Usage = ResourceUsage.Staging,
                                       BindFlags = BindFlags.None,
                                       CpuAccessFlags = CpuAccessFlags.Read | CpuAccessFlags.Write,
                                       OptionFlags = ResourceOptionFlags.None,
                                       Format = Format.R8G8B8A8_UNorm,
                                       FilterFlags = FilterFlags.None,
                                       MipFilterFlags = FilterFlags.None
                                   };

                srcTex[i] = Texture2D.FromFile(_dxDevice, filenames[i], loadInfo);
            }

            //
            // Create the texture array.  Each element in the texture
            // array has the same format/dimensions.
            //
            var texElementDesc = srcTex[0].Description;
            var texArrayDesc = new Texture2DDescription
                                   {
                                       Width = texElementDesc.Width,
                                       Height = texElementDesc.Height,
                                       MipLevels = texElementDesc.MipLevels,
                                       ArraySize = arraySize,
                                       Format = Format.R8G8B8A8_UNorm,
                                       SampleDescription = new SampleDescription(1, 0),
                                       Usage = ResourceUsage.Default,
                                       BindFlags = BindFlags.ShaderResource,
                                       CpuAccessFlags = CpuAccessFlags.None,
                                       OptionFlags = ResourceOptionFlags.None
                                   };

            var texArray = new Texture2D(_dxDevice, texArrayDesc);

            //
            // Copy individual texture elements into texture array.
            //

            // for each texture element...
            for (int i = 0; i < arraySize; ++i)
            {
                // for each mipmap level...
                for (int j = 0; j < texElementDesc.MipLevels; ++j)
                {
                    var mappedTex2D = srcTex[i].Map(j, MapMode.Read, MapFlags.None);

                    _dxDevice.UpdateSubresource(
                        new DataBox(mappedTex2D.Pitch, 0, mappedTex2D.Data), texArray,
                        Resource.CalculateSubresourceIndex(j, i, texElementDesc.MipLevels));

                    srcTex[i].Unmap(j);
                }
            }

            //
            // Create a resource view to the texture array.
            //

            var viewDesc = new ShaderResourceViewDescription();
            viewDesc.Format = texArrayDesc.Format;
            viewDesc.Dimension = ShaderResourceViewDimension.Texture2DArray;
            viewDesc.MostDetailedMip = 0;
            viewDesc.MipLevels = texArrayDesc.MipLevels;
            viewDesc.FirstArraySlice = 0;
            viewDesc.ArraySize = arraySize;

            var texArrayRV = new ShaderResourceView(_dxDevice, texArray, viewDesc);

            //
            // Cleanup--we only need the resource view.
            //
            texArray.Dispose();

            for(int i = 0; i < arraySize; ++i)
                srcTex[i].Dispose();

            _textures.Add(arrayName, texArrayRV);

            return texArrayRV;
        }