示例#1
0
        static Texture2D ConvertFromBitmap(Bitmap image)
        {
            System.Drawing.Imaging.BitmapData data = image.LockBits(new System.Drawing.Rectangle(0, 0, image.Width, image.Height),
                                        System.Drawing.Imaging.ImageLockMode.ReadWrite, image.PixelFormat);
            int bytes = data.Stride * image.Height;
            DataStream stream = new SlimDX.DataStream(bytes, true, true);
            stream.WriteRange(data.Scan0,bytes);
            stream.Position = 0;
            DataRectangle dRect = new SlimDX.DataRectangle(data.Stride, stream);

            SlimDX.DXGI.SampleDescription sampleDesc = new SlimDX.DXGI.SampleDescription();
            sampleDesc.Count = 1;
            sampleDesc.Quality = 0;

            Texture2DDescription texDesc = new Texture2DDescription()
            {
                ArraySize = 1,
                MipLevels = 1,
                SampleDescription = sampleDesc,
                Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm,
                CpuAccessFlags = CpuAccessFlags.Write,
                BindFlags = BindFlags.ShaderResource,
                Usage = ResourceUsage.Dynamic,
                Height = image.Height,
                Width = image.Width
            };

            image.UnlockBits(data);
            image.Dispose();

            return new Texture2D(RenderForm11.Device, texDesc, dRect);
        }
 public override SlimDX.Direct3D9.Texture ToTexture9(SlimDX.Direct3D9.Device device)
 {
     SlimDX.Direct3D9.Texture t = new SlimDX.Direct3D9.Texture(device, Size.Width, Size.Height, 1, SlimDX.Direct3D9.Usage.Dynamic, Data[0, 0].Format9, SlimDX.Direct3D9.Pool.Default);
     SlimDX.DataRectangle     r = t.LockRectangle(0, SlimDX.Direct3D9.LockFlags.None);
     TextureUtil.WriteTexture(r, Data, Data[0, 0].Size);
     t.UnlockRectangle(0);
     return(t);
 }
 public override void WriteRect(SlimDX.DataRectangle rect, System.Drawing.Rectangle r)
 {
     for (int y = 0; y < r.Height; y++)
     {
         for (int x = 0; x < r.Width; x++)
         {
             rect.Data.Write(Data[r.Y + y, r.X + x]);
         }
         if (rect.Pitch > r.Width * Data[0, 0].Size)
         {
             rect.Data.Seek((rect.Pitch - r.Width * Data[0, 0].Size), System.IO.SeekOrigin.Current);
         }
     }
 }
        // SlimDX.Direct3D10
        private SlimDX.Direct3D10.ShaderResourceView GetTexture(SlimDX.Direct3D10.Device device, int width, int height, SlimDX.Color4 color)
        {
            //create the texture
            SlimDX.Direct3D10.Texture2D            texture = null;
            SlimDX.Direct3D10.Texture2DDescription desc2   = new SlimDX.Direct3D10.Texture2DDescription();
            desc2.SampleDescription = new SlimDX.DXGI.SampleDescription(1, 0);
            desc2.Width             = width;
            desc2.Height            = height;
            desc2.MipLevels         = 1;
            desc2.ArraySize         = 1;
            desc2.Format            = SlimDX.DXGI.Format.R8G8B8A8_UNorm;
            desc2.Usage             = SlimDX.Direct3D10.ResourceUsage.Dynamic;
            desc2.BindFlags         = SlimDX.Direct3D10.BindFlags.ShaderResource;
            desc2.CpuAccessFlags    = SlimDX.Direct3D10.CpuAccessFlags.Write;
            texture = new SlimDX.Direct3D10.Texture2D(device, desc2);


            // fill the texture with rgba values
            SlimDX.DataRectangle rect = texture.Map(0, SlimDX.Direct3D10.MapMode.WriteDiscard, SlimDX.Direct3D10.MapFlags.None);
            if (rect.Data.CanWrite)
            {
                for (int row = 0; row < texture.Description.Height; row++)
                {
                    int rowStart = row * rect.Pitch;
                    rect.Data.Seek(rowStart, System.IO.SeekOrigin.Begin);
                    for (int col = 0; col < texture.Description.Width; col++)
                    {
                        rect.Data.WriteByte((byte)color.Red);
                        rect.Data.WriteByte((byte)color.Green);
                        rect.Data.WriteByte((byte)color.Blue);
                        rect.Data.WriteByte((byte)color.Alpha);
                    }
                }
            }
            texture.Unmap(0);

            // create shader resource that is what the renderer needs
            SlimDX.Direct3D10.ShaderResourceViewDescription desc = new SlimDX.Direct3D10.ShaderResourceViewDescription();
            desc.Format          = texture.Description.Format;
            desc.Dimension       = SlimDX.Direct3D10.ShaderResourceViewDimension.Texture2D;
            desc.MostDetailedMip = 0;
            desc.MipLevels       = 1;


            SlimDX.Direct3D10.ShaderResourceView srv = new SlimDX.Direct3D10.ShaderResourceView(device, texture, desc);

            return(srv);
        }
示例#5
0
        /// <summary>
        /// Sets the data to the texture.
        /// </summary>
        /// <typeparam name="T">Type of data in the array.</typeparam>
        /// <param name="data">Array of data.</param>
        /// <param name="mipLevel">Mip map level to access.</param>
        /// <param name="subimage">Rectangle representing a sub-image of the 2D texture to write to, if null the whole image is written to.</param>
        /// <param name="startIndex">Starting index in the array to start reading from.</param>
        /// <param name="elementCount">Number of elements to write.</param>
        /// <exception cref="System.ArgumentException">Thrown if the format byte size of the type to write and the texture do not match, the subimage
        /// dimensions are invalid, or if the total size to write and the total size in the texture do not match</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if there was an error writing to the texture.</exception>
        public override void SetData <T>(T[] data, int mipLevel, Math.Rectangle?subimage, int startIndex, int elementCount)
        {
            if (_texture2D == null || _texture2D.Disposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            if (mipLevel < 0 || mipLevel >= _mipCount)
            {
                throw new ArgumentOutOfRangeException("mipLevel", String.Format("Mip level is out of range. Must be between 0 and {0}.", _mipCount.ToString()));
            }

            //Throws null or out of range exception
            D3D10Helper.CheckArrayBounds(data, startIndex, elementCount);

            int           formatSize = D3D10Helper.FormatSize(base.Format);
            SurfaceFormat format     = base.Format;
            int           elemSize   = MemoryHelper.SizeOf <T>();

            CheckSizes(formatSize, elemSize);

            //Calc subresource dimensions
            int width  = (int)MathHelper.Max(1, base.Width >> mipLevel);
            int height = (int)MathHelper.Max(1, base.Height >> mipLevel);

            //Get the dimensions, if its null we copy the whole texture
            Rectangle rect;

            if (subimage.HasValue)
            {
                rect = subimage.Value;
                CheckRectangle(rect, ref width, ref height);
            }
            else
            {
                rect = new Rectangle(0, 0, width, height);
            }

            CheckTotalSize(base.Format, ref formatSize, ref width, ref height, elemSize, elementCount);

            //Create staging for non-dynamic textures
            if (_usage == D3D.ResourceUsage.Default)
            {
                CreateStaging();
            }

            try {
                if (_usage == D3D.ResourceUsage.Default)
                {
                    SDX.DataRectangle dataRect = _staging.Map(mipLevel, D3D.MapMode.Write, D3D.MapFlags.None);
                    SDX.DataStream    ds       = dataRect.Data;
                    int row   = rect.Y;
                    int col   = rect.X;
                    int pitch = dataRect.Pitch;

                    int index = startIndex;
                    int count = elementCount;
                    //Compute the actual number of elements based on the format size and the element size we're copying the bytes into
                    int actWidth = (int)MathHelper.Floor(width * (formatSize / elemSize));
                    //Go row by row
                    for (int i = row; i < height; i++)
                    {
                        //Set the position
                        ds.Position = (i * pitch) + (col * formatSize);
                        //Break if we've run out of elements or on the very last row that isn't complete
                        if (count <= 0)
                        {
                            break;
                        }
                        else if (count < actWidth)
                        {
                            ds.WriteRange <T>(data, index, count);
                            break;
                        }
                        //Otherwise, copy the whole row and increment/decrement the index and count
                        ds.WriteRange <T>(data, index, actWidth);
                        index += actWidth;
                        count -= actWidth;
                    }
                    _staging.Unmap(mipLevel);

                    //Do resource copy
                    if (format == SurfaceFormat.DXT1 || format == SurfaceFormat.DXT3 || format == SurfaceFormat.DXT5)
                    {
                        _graphicsDevice.CopyResource(_staging, _texture2D);
                    }
                    else
                    {
                        D3D.ResourceRegion region = new D3D.ResourceRegion();
                        region.Left   = col;
                        region.Right  = col + width;
                        region.Top    = row;
                        region.Bottom = row + height;
                        region.Front  = 0;
                        region.Back   = 1;
                        _graphicsDevice.CopySubresourceRegion(_staging, mipLevel, region, _texture2D, mipLevel, col, row, 0);
                    }
                }
                else
                {
                    SDX.DataRectangle dataRect = _texture2D.Map(mipLevel, D3D.MapMode.WriteDiscard, D3D.MapFlags.None);
                    SDX.DataStream    ds       = dataRect.Data;
                    int row   = rect.Y;
                    int col   = rect.X;
                    int pitch = dataRect.Pitch;

                    int index = startIndex;
                    int count = elementCount;
                    //Compute the actual number of elements based on the format size and the element size we're copying the bytes into
                    int actWidth = (int)MathHelper.Floor(width * (formatSize / elemSize));
                    //Go row by row
                    for (int i = row; i < height; i++)
                    {
                        //Set the position
                        ds.Position = (i * pitch) + (col * formatSize);
                        //Break if we've run out of elements or on the very last row that isn't complete
                        if (count <= 0)
                        {
                            break;
                        }
                        else if (count < actWidth)
                        {
                            ds.WriteRange <T>(data, index, count);
                            break;
                        }
                        //Otherwise, copy the whole row and increment/decrement the index and count
                        ds.WriteRange <T>(data, index, actWidth);
                        index += actWidth;
                        count -= actWidth;
                    }
                    _texture2D.Unmap(mipLevel);
                }
            } catch (Exception e) {
                throw new TeslaException("Error writing to D3D10 Texture2D.", e);
            }
        }
        /// <summary>
        /// Gets the back buffer data.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="subimage">The rectangle representing the sub-image. Null value means to grab the whole back buffer.</param>
        /// <param name="data">The data.</param>
        /// <param name="startIndex">The starting index in the array.</param>
        /// <param name="elementCount">The number of eleemnts to read</param>
        public override void GetBackBufferData <T>(Rectangle?subimage, T[] data, int startIndex, int elementCount)
        {
            if (_backBuffer.Disposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            //Throws null or out of range exception
            D3D10Helper.CheckArrayBounds(data, startIndex, elementCount);

            //Calc subresource dimensions
            int width  = _presentParams.BackBufferWidth;
            int height = _presentParams.BackBufferHeight;

            //Get the dimensions, if its null we copy the whole texture
            Rectangle rect;

            if (subimage.HasValue)
            {
                rect = subimage.Value;
                CheckRectangle(rect, width, height);
            }
            else
            {
                rect = new Rectangle(0, 0, width, height);
            }

            if (elementCount > rect.Width * rect.Height)
            {
                throw new ArgumentOutOfRangeException("elementCount", "Number of elements to read is larger than contained in the specified subimage.");
            }

            //Create staging
            CreateStaging();

            try {
                int row        = rect.Y;
                int col        = rect.X;
                int rectWidth  = rect.Width;
                int rectHeight = rect.Height;

                //Do resource copy
                if (row == 0 && col == 0 && rectWidth == width && rectHeight == height)
                {
                    _graphicsDevice.CopyResource(_backBuffer, _staging);
                }
                else
                {
                    D3D.ResourceRegion region = new D3D.ResourceRegion();
                    region.Left   = col;
                    region.Right  = col + rectWidth;
                    region.Top    = row;
                    region.Bottom = row + rectHeight;
                    region.Front  = 0;
                    region.Back   = 1;
                    _graphicsDevice.CopySubresourceRegion(_backBuffer, 0, region, _staging, 0, col, row, 0);
                }

                SDX.DataRectangle dataRect = _staging.Map(0, D3D.MapMode.Read, D3D.MapFlags.None);
                SDX.DataStream    ds       = dataRect.Data;
                int elemSize   = MemoryHelper.SizeOf <T>();
                int formatSize = D3D10Helper.FormatSize(_presentParams.BackBufferFormat);
                int pitch      = dataRect.Pitch;

                int index = startIndex;
                int count = elementCount;

                //Compute the actual number of elements based on the format size and the element size we're copying the bytes into
                int actWidth = (int)MathHelper.Floor(rectWidth * (formatSize / elemSize));
                //Go row by row
                for (int i = row; i < height; i++)
                {
                    //Set the position
                    ds.Position = (i * pitch) + (col * formatSize);
                    //Break if we've run out of elements or on the very last row that isn't complete
                    if (count <= 0)
                    {
                        break;
                    }
                    else if (count < actWidth)
                    {
                        ds.ReadRange <T>(data, index, count);
                        break;
                    }
                    //Otherwise, copy the whole row and increment/decrement the index and count
                    ds.ReadRange <T>(data, index, actWidth);
                    index += actWidth;
                    count -= actWidth;
                }
                _staging.Unmap(0);
            } catch (Exception e) {
                throw new TeslaException("Error reading from D3D10 Texture2D.", e);
            }
        }
示例#7
0
        internal void Reload(Sprite Sprite, ResourceLoadType LoadType)
        {
            if (Sprite.internalFrames != null)
            {
                Sprite.internalFrames[0].loading = true;
            }

            if (LoadType == ResourceLoadType.Delayed)
            {
                delayLoader.Enqueue(Sprite);
                return;
            }

            for (int i = 0; i < Sprite.internalFrames.Length; i++)
            {
                if (Sprite.internalFrames[i].HasSystemCopy)
                {
                    SlimDX.Direct3D9.Texture            tex  = engine.Device.CreateTexture(MakePowerOfTwo(Sprite.internalFrames[i].size.x), MakePowerOfTwo(Sprite.internalFrames[i].size.y));
                    SlimDX.Direct3D9.SurfaceDescription desc = tex.GetLevelDescription(0);
                    MemoryUsage += desc.Width * desc.Height * 4;

                    Sprite.internalFrames[i].texture = tex;
                    Sprite.internalFrames[i].RestoreFromSystemCopy();
                    Sprite.internalFrames[i].loading = false;
                    Sprite.internalFrames[i].loaded  = true;
                }
            }

            ResourceID id = Sprite.ID;

            if (id.File == "" || !spriteProcessors.ContainsKey(id.Format))
            {
                return;
            }

            ResourceID realid = (string)id;

            // check replacements
            if (replacement != null)
            {
                ResourceID newid = GetReplacementID(id);
                if (newid != null)
                {
                    if (CheckReplacementID(newid))
                    {
                        id = newid;
                    }
                }
            }

            engine.IncreaseLoadingCount();

            ISpriteProcessor loader = GetSpriteProcessor(id, true);

            if (loader is ISpriteAnimationProcessor)
            {
                ISpriteAnimationProcessor loaderAni = (ISpriteAnimationProcessor)loader;
                loader.Process(id);
                Log.Debug("reload \"" + id + "\"");

                for (int i = 0; i < loaderAni.FrameCount; i++)
                {
                    if (!loaderAni.SetFrame(i))
                    {
                        SpriteFrame[] frames = new SpriteFrame[i];
                        for (int j = 0; j < i; j++)
                        {
                            frames[j] = Sprite.Frames[j];
                        }
                        Sprite.internalFrames = frames;
                        Sprite.ani.frameCount = i;
                        break;
                    }

                    SlimDX.Direct3D9.Texture tex = engine.Device.CreateTexture(MakePowerOfTwo(loaderAni.FrameSize.x), MakePowerOfTwo(loaderAni.FrameSize.y));

                    SlimDX.Direct3D9.SurfaceDescription desc = tex.GetLevelDescription(0);
                    MemoryUsage += desc.Width * desc.Height * 4;

                    SlimDX.DataRectangle data = tex.LockRectangle(0, SlimDX.Direct3D9.LockFlags.Discard);
                    loader.Render(data.Data, data.Pitch);
                    tex.UnlockRectangle(0);

                    Sprite.Frames[i].Texture   = tex;
                    Sprite.Frames[i].Width     = loaderAni.FrameSize.x;
                    Sprite.Frames[i].Height    = loaderAni.FrameSize.y;
                    Sprite.Frames[i].TimeStamp = System.Diagnostics.Stopwatch.GetTimestamp();
                }
            }
            else
            {
                loader.Process(id);
                Log.Debug("reload \"" + id + "\"");

                SlimDX.Direct3D9.Texture tex = engine.Device.CreateTexture(MakePowerOfTwo(loader.Size.x), MakePowerOfTwo(loader.Size.y));

                SlimDX.Direct3D9.SurfaceDescription desc = tex.GetLevelDescription(0);
                MemoryUsage += desc.Width * desc.Height * 4;

                SlimDX.DataRectangle data = tex.LockRectangle(0, SlimDX.Direct3D9.LockFlags.Discard);
                loader.Render(data.Data, data.Pitch);
                tex.UnlockRectangle(0);

                Sprite.Frame.Texture   = tex;
                Sprite.Frame.Width     = loader.Size.x;
                Sprite.Frame.Height    = loader.Size.y;
                Sprite.Frame.TimeStamp = System.Diagnostics.Stopwatch.GetTimestamp();
            }

            if (Sprite.internalFrames != null)
            {
                Sprite.internalFrames[0].loading = false;
                Sprite.internalFrames[0].loaded  = true;
            }

            engine.DecreaseLoadingCount();
        }
示例#8
0
        public Font GetFont(String File, PixelColor ForeColor, PixelColor BackColor)
        {
            ResourceInfoFont info;

            info.Name = File;
            if (BackColor != PixelColor.Black)
            {
                info.Fore = ForeColor;
                info.Back = BackColor;
            }
            else
            {
                info.Fore = PixelColor.White;
                info.Back = PixelColor.Black;
            }

            Font font = new Font(engine);

            font.Info              = new FontInfo();
            font.Info.Font         = File.ToLower();
            font.Info.ForeColor    = ForeColor;
            font.Info.BackColor    = BackColor;
            font.Info.UseBackColor = !(BackColor.a == 255 && BackColor.r == 0 && BackColor.g == 0 && BackColor.b == 0);

            if (fonts.ContainsKey(info))
            {
                font.charInfo = fonts[info].charInfo;
                font.sprite   = fonts[info].sprite;
                font.offset   = fonts[info].offset;
                font.height   = fonts[info].height;
                return(font);
            }

            FilePath path = File;

            if (!fontProcessors.ContainsKey(path.Extension))
            {
                return(null);
            }

            engine.IncreaseLoadingCount();

            IFontProcessor processor = (IFontProcessor)Activator.CreateInstance(fontProcessors[path.Extension].GetType());

            processor.Process((string)path);
            Log.Debug("load \"" + path.FullPath + "\"");

            SlimDX.Direct3D9.Texture tex = engine.Device.CreateTexture(MakePowerOfTwo(processor.Size.x), MakePowerOfTwo(processor.Size.y));

            SlimDX.Direct3D9.SurfaceDescription desc = tex.GetLevelDescription(0);
            MemoryUsage += desc.Width * desc.Height * 4;

            SlimDX.DataRectangle   data       = tex.LockRectangle(0, SlimDX.Direct3D9.LockFlags.Discard);
            System.IO.MemoryStream systemCopy = new System.IO.MemoryStream();
            processor.Render(systemCopy, data.Pitch, ForeColor, BackColor);
            processor.Render(data.Data, data.Pitch, ForeColor, BackColor);
            tex.UnlockRectangle(0);

            //// debug output
            //System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(processor.Size.x, processor.Size.y, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            //System.Drawing.Imaging.BitmapData bmpdata = bmp.LockBits(new System.Drawing.Rectangle(0, 0, processor.Size.x, processor.Size.y), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            //byte[] bytes = new byte[processor.Size.y * bmpdata.Stride];
            //systemCopy.Seek(0, System.IO.SeekOrigin.Begin);

            //for (int y = 0; y < processor.Size.y; y++)
            //{
            //    systemCopy.Read(bytes, y * bmpdata.Stride, processor.Size.x * 4);
            //}

            //System.Runtime.InteropServices.Marshal.Copy(bytes, 0, bmpdata.Scan0, bytes.Length);

            //bmp.UnlockBits(bmpdata);

            //bmp.Save("c:\\font.png");
            //bmp.Dispose();

            SpriteFrame frame = new SpriteFrame(this, tex, processor.Size, systemCopy.ToArray());

            font.sprite            = new Sprite(this, "", frame);
            font.sprite.Resolution = processor.Factor;

            font.charInfo = processor.CharInfo;
            font.offset   = processor.Offset;
            font.height   = processor.Size.y;

            engine.DecreaseLoadingCount();

            fonts.Add(info, font);
            return(font);
        }
 public virtual void WriteRect(SlimDX.DataRectangle rect, System.Drawing.Rectangle r)
 {
     throw new NotImplementedException();
 }