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

            if (data != null)
            {
                subResourceDatas = new DataBox[data.Length];
                for (int i = 0; i < subResourceDatas.Length; i++)
                {
                    subResourceDatas[i].DataPointer = data[i].DataPointer;
                    subResourceDatas[i].RowPitch = data[i].Pitch;
                }
            }
            device.CreateTexture2D(ref description, subResourceDatas, this);
        }
Esempio n. 2
0
        /// <summary>
        /// Takes a scala field as input anf generates a 2D texture.
        /// </summary>
        /// <param name="device"></param>
        /// <param name="field"></param>
        /// <returns></returns>
        public static Texture2D GenerateTextureFromField(Device device, Field field, Texture2DDescription? description = null)
        {
            System.Diagnostics.Debug.Assert(field.Size.Length == 2);

            Texture2DDescription desc;

            // Either use the given description, or create a render target/shader resource bindable one.
            if (description == null)
                desc = new Texture2DDescription
                {
                    ArraySize = 1,
                    BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                    CpuAccessFlags = CpuAccessFlags.None,
                    Format = Format.R32_Float,
                    Width = field.Size[0],
                    Height = field.Size[1],
                    MipLevels = 1,
                    OptionFlags = ResourceOptionFlags.None,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage = ResourceUsage.Default
                };
            else
                desc = (Texture2DDescription)description;

            // Put field data into stream/rectangle object
            DataRectangle texData = new DataRectangle(field.Size[0] * sizeof(float), field.GetDataStream());

            // Create texture.
            Texture2D tex = new Texture2D(device, desc, texData);

            return tex;
        }
Esempio n. 3
0
        public static Texture2D TextureFromBitmap(Bitmap image)
        {
            BitmapData data = image.LockBits(new Rectangle(0, 0, image.Width, image.Height),
                                             ImageLockMode.ReadWrite, image.PixelFormat);
            int bytes = data.Stride*image.Height;
            DataStream stream = new DataStream(bytes, true, true);
            stream.WriteRange(data.Scan0, bytes);
            stream.Position = 0;
            DataRectangle dRect = new DataRectangle(data.Stride, stream);

            Texture2DDescription texDesc = new Texture2DDescription
                                               {
                                                   ArraySize = 1,
                                                   MipLevels = 1,
                                                   SampleDescription = new SampleDescription(1, 0),
                                                   Format = Format.B8G8R8A8_UNorm,
                                                   CpuAccessFlags = CpuAccessFlags.None,
                                                   BindFlags = BindFlags.ShaderResource,
                                                   Usage = ResourceUsage.Immutable,
                                                   Height = image.Height,
                                                   Width = image.Width
                                               };

            image.UnlockBits(data);
            image.Dispose();
            Texture2D texture = new Texture2D(Game.Context.Device, texDesc, dRect);
            stream.Dispose();
            return texture;
        }
Esempio n. 4
0
        // Based on code from https://simpledevcode.wordpress.com/2015/12/29/flood-fill-algorithm-using-c-net/
        private static IEnumerable <Point> TryToGetPointsInObject(DataRectangle <bool> mask, Point startAt, Rectangle limitTo)
        {
            if (mask == null)
            {
                throw new ArgumentNullException(nameof(mask));
            }
            if ((limitTo.Left < 0) || (limitTo.Right > mask.Width) || (limitTo.Top < 0) || (limitTo.Bottom > mask.Height))
            {
                throw new ArgumentOutOfRangeException(nameof(limitTo));
            }
            if ((startAt.X < limitTo.Left) || (startAt.X > limitTo.Right) || (startAt.Y < limitTo.Top) || (startAt.Y > limitTo.Bottom))
            {
                throw new ArgumentOutOfRangeException(nameof(startAt));
            }

            var valueAtOriginPoint = mask[startAt.X, startAt.Y];

            var pixels = new Stack <Point>();

            pixels.Push(startAt);

            var filledPixels = new HashSet <Point>();

            while (pixels.Count > 0)
            {
                var currentPoint = pixels.Pop();
                if ((currentPoint.X < limitTo.Left) || (currentPoint.X >= limitTo.Right) || (currentPoint.Y < limitTo.Top) || (currentPoint.Y >= limitTo.Bottom))                 // make sure we stay within bounds
                {
                    continue;
                }

                if ((mask[currentPoint.X, currentPoint.Y] == valueAtOriginPoint) && !filledPixels.Contains(currentPoint))
                {
                    filledPixels.Add(new Point(currentPoint.X, currentPoint.Y));
                    pixels.Push(new Point(currentPoint.X - 1, currentPoint.Y));
                    pixels.Push(new Point(currentPoint.X + 1, currentPoint.Y));
                    pixels.Push(new Point(currentPoint.X, currentPoint.Y - 1));
                    pixels.Push(new Point(currentPoint.X, currentPoint.Y + 1));
                }
            }
            return(filledPixels);
        }
Esempio n. 5
0
        public static Texture FromBitmap(Device device, Bitmap bitmap)
        {
            Texture       texture = new Texture(device, bitmap.Width, bitmap.Height, 1, Usage.Dynamic, Format.A8R8G8B8, Pool.Default);
            DataStream    data;
            DataRectangle rec = texture.LockRectangle(0, LockFlags.None, out data);
            BitmapData    bd  = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);

            int bufferSize = bd.Height * bd.Stride;

            //create data buffer
            byte[] bytes = new byte[bufferSize];

            // copy bitmap data into buffer
            Marshal.Copy(bd.Scan0, bytes, 0, bytes.Length);
            data.Write(bytes, 0, bytes.Length);

            texture.UnlockRectangle(0);
            bitmap.UnlockBits(bd);
            return(texture);
        }
Esempio n. 6
0
        public void CombineTwo2x2WithAddition()
        {
            var left = DataRectangle.For(new[, ]
            {
                { 1, 2 },
                { 3, 4 }
            });
            var right = DataRectangle.For(new[, ]
            {
                { 2, 3 },
                { 4, 5 }
            });
            var expected = DataRectangle.For(new[, ]
            {
                { 3, 5 },
                { 7, 9 }
            });

            Assert.Equal(expected, left.CombineWith(right, (x, y) => x + y), DataRectangleTestsEqualityComparer <int> .Default);
        }
        void CreateGradient()
        {
            byte[] data = new byte[4 * GRADIENT_TEXTURE_WIDTH * GRADIENT_TEXTURE_HEIGHT];

            for (int i = 0; i < _stops.Count - 1; i++)
            {
                CreatePartialGradient(data, _stops[i], _stops[i + 1]);
            }
            // If stops don't go up to 1.0 we have to fake the final stop
            if (_stops[_stops.Count - 1].Offset < 1.0)
            {
                CreatePartialGradient(data, _stops[_stops.Count - 1], new GradientStopData(_stops[_stops.Count - 1].Color, 1.0));
            }

            DataRectangle rect = _texture.Surface0.LockRectangle(LockFlags.None);

            rect.Data.Write(data, 0, 4 * GRADIENT_TEXTURE_WIDTH * GRADIENT_TEXTURE_HEIGHT);
            _texture.Surface0.UnlockRectangle();
            rect.Data.Dispose();
        }
Esempio n. 8
0
        /// <summary>
        /// Get DX screen image
        /// </summary>
        /// <param name="rect">Screen rectangle</param>
        public Bitmap GetImage(Rectangle rect)
        {
            lock (lockobj)
            {
                if (s == null)
                {
                    s = Surface.CreateOffscreenPlain(d, rect.Width, rect.Height, Format.A8R8G8B8, Pool.Scratch);
                }

                d.GetFrontBufferData(0, s);
                DataRectangle gsx = s.LockRectangle(rect, LockFlags.None);
                using (bm = new Bitmap(rect.Width, rect.Height, CalculateStride(rect.Width, PixelFormat.Format32bppPArgb), PixelFormat.Format32bppPArgb, gsx.Data.DataPointer))
                {
                    bm = (Bitmap)bm.GetThumbnailImage(pbPreview.Width = (Screen.AllScreens[iScreen].Bounds.Width) / preview_factor,
                                                      pbPreview.Height = Screen.AllScreens[iScreen].Bounds.Height / preview_factor, null, IntPtr.Zero);
                    s.UnlockRectangle();
                    return(bm);
                }
            }
        }
Esempio n. 9
0
        public void Slice6x5Into3x3WithOffset1x1ThenInto2x1With1x1Offset()
        {
            var data = DataRectangle.For(Rotate(new[, ]
            {
                { 1, 2, 3, 4, 5, 6 },
                { 7, 8, 9, 10, 11, 12 },
                { 13, 14, 15, 16, 17, 18 },
                { 19, 20, 21, 22, 23, 24 },
                { 25, 26, 27, 28, 29, 30 }
            }));
            var expected = DataRectangle.For(Rotate(new[, ]
            {
                { 15, 16 }
            }));
            var result = data
                         .Slice(new Rectangle(new Point(1, 1), new Size(3, 3)))
                         .Slice(new Rectangle(new Point(1, 1), new Size(2, 1)));

            Assert.Equal(expected, result, DataRectangleTestsEqualityComparer <int> .Default);
        }
Esempio n. 10
0
        public unsafe void CreateTexture(BinaryReader reader)
        {
            int w = Width;  // + (4 - Width % 4) % 4;
            int h = Height; // + (4 - Height % 4) % 4;

            Image = new Texture(DXManager.Device, w, h, 1, Usage.None, Format.A8R8G8B8, Pool.Managed);
            DataRectangle dataRect = Image.LockRectangle(0, LockFlags.Discard);

            Data = (byte *)dataRect.DataPointer;

            byte[] decomp = DecompressImage(reader.ReadBytes(Length));

            using (var stream = new DataStream(dataRect.DataPointer, Width * Height * 4, false, true))
            {
                stream.Write(decomp, 0, decomp.Length);
            }
            Image.UnlockRectangle(0);

            if (HasMask)
            {
                reader.ReadBytes(12);
                w = Width;  // + (4 - Width % 4) % 4;
                h = Height; // + (4 - Height % 4) % 4;

                MaskImage = new Texture(DXManager.Device, w, h, 1, Usage.None, Format.A8R8G8B8, Pool.Managed);
                DataRectangle midr = MaskImage.LockRectangle(0, LockFlags.Discard);

                decomp = DecompressImage(reader.ReadBytes(Length));

                using (var stream = new DataStream(midr.DataPointer, Width * Height * 4, false, true))
                {
                    stream.Write(decomp, 0, decomp.Length);
                }
                MaskImage.UnlockRectangle(0);
            }

            DXManager.TextureList.Add(this);
            TextureValid = true;

            CleanTime = CMain.Time + Settings.CleanDelay;
        }
Esempio n. 11
0
        private static DataRectangle <double> MedianFilter(this DataRectangle <double> source, int blockSize)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            if (blockSize <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(blockSize));
            }

            var result = new double[source.Width, source.Height];
            var allLocationsInSource = Enumerable.Range(0, source.Width)
                                       .SelectMany(x => Enumerable.Range(0, source.Height).Select(y =>
                                                                                                  new Point(x, y)
                                                                                                  ));

            Parallel.ForEach(
                allLocationsInSource,
                location =>
            {
                var top          = Math.Max(0, location.Y - (blockSize / 2));
                var bottom       = Math.Min(source.Height, top + blockSize);
                var left         = Math.Max(0, location.X - (blockSize / 2));
                var right        = Math.Min(source.Width, left + blockSize);
                var blockWidth   = right - left;
                var blockHeight  = bottom - top;
                var valuesInArea = new List <double>(capacity: blockWidth * blockHeight);
                for (var xInner = left; xInner < right; xInner++)
                {
                    for (var yInner = top; yInner < bottom; yInner++)
                    {
                        valuesInArea.Add(source[xInner, yInner]);
                    }
                }
                valuesInArea.Sort();
                result[location.X, location.Y] = valuesInArea[valuesInArea.Count / 2];
            }
                );
            return(DataRectangle.For(result));
        }
Esempio n. 12
0
        public void Draw()
        {
            if (!initialized)
            {
                return;
            }
#if DEBUG
            //bool wasDirty = surface.IsDirty;
#endif
            if (surface.IsDirty)
            {
                DataRectangle rect = mappableSurface.Map(SharpDX.DXGI.MapFlags.Write);
                surface.CopyTo(rect.DataPointer, rect.Pitch, 4, false, false);
                mappableSurface.Unmap();
                Display.context.CopyResource(mappableTexture, webTex.Tex);
            }
            QuadRenderer.Draw(webTex, position, new Color4(1, 1, 1, 1));
#if DEBUG
            //FontRenderer.Draw(FontManager.Get("default"), "Dirty:"+wasDirty, new Vector2(position.X, position.Y), Color.White);
#endif
        }
        public void VerticalGradient()
        {
            var verticalGradient = DataRectangle
                                   .For(new double[64, 60])
                                   .Transform((value, point) => (double)point.Y);
            var hogs = HistogramOfGradientGenerator.Get(verticalGradient, blockSize: 8);

            Assert.True(
                hogs.Enumerate().Select(pointAndValue => pointAndValue.Item2).All(hog =>
                                                                                  (hog.Degrees10 > 0) &&
                                                                                  (hog.Degrees30 == 0) &&
                                                                                  (hog.Degrees50 == 0) &&
                                                                                  (hog.Degrees70 == 0) &&
                                                                                  (hog.Degrees90 == 0) &&
                                                                                  (hog.Degrees110 == 0) &&
                                                                                  (hog.Degrees130 == 0) &&
                                                                                  (hog.Degrees150 == 0) &&
                                                                                  (hog.Degrees170 == hog.Degrees10)
                                                                                  )
                );
        }
Esempio n. 14
0
        public void MayNotCombineDifferentSizes()
        {
            var left = DataRectangle.For(new[, ]
            {
                { 1, 2 },
                { 3, 4 }
            });
            var right = DataRectangle.For(new[, ]
            {
                { 1, 2, 3 },
                { 4, 5, 6 },
                { 7, 8, 9 }
            });
            var expected = DataRectangle.For(new[, ]
            {
                { 3, 5 },
                { 7, 9 }
            });

            Assert.Throws <ArgumentException>(() => left.CombineWith(right, (x, y) => x + y));
        }
Esempio n. 15
0
        public Texture DrawString(string text, System.Drawing.Font font, Brush brush, int width, int height)
        {
            Bitmap   bitmap   = new Bitmap(width, height, PixelFormat.Format32bppArgb);
            Graphics graphics = Graphics.FromImage((Image)bitmap);

            graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
            graphics.DrawString(text, font, brush, 0.0f, 0.0f);
            graphics.Dispose();
            Texture texture = new Texture(this.DeviceMain, width, height, 1, Usage.None, Format.A8R8G8B8, Pool.Managed);

            texture.GetLevelDescription(0);
            DataRectangle dataRectangle = texture.LockRectangle(0, new Rectangle(0, 0, width, height), LockFlags.Discard);
            BitmapData    bitmapdata    = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
            IntPtr        scan0         = bitmapdata.Scan0;

            dataRectangle.Data.WriteRange(scan0, (long)(bitmapdata.Width * bitmapdata.Height * 4));
            bitmap.UnlockBits(bitmapdata);
            texture.UnlockRectangle(0);
            bitmap.Dispose();
            return(texture);
        }
Esempio n. 16
0
        protected override void _WriteDataToTexture(CD3DTexture texture, byte[] data)
        {
            //Lock the texture and fill it with the data
            DataRectangle rect     = texture.D3DTexture.LockRectangle(0, LockFlags.Discard);
            int           rowWidth = 4 * texture.DataSize.Width;

            if (rowWidth == rect.Pitch)
            {
                rect.Data.Write(data, 0, data.Length);
            }
            else
            {
                for (int i = 0; i + rowWidth <= data.Length; i += rowWidth)
                {
                    rect.Data.Write(data, i, rowWidth);
                    //Go to next row
                    rect.Data.Position = rect.Data.Position - rowWidth + rect.Pitch;
                }
            }
            texture.D3DTexture.UnlockRectangle(0);
        }
Esempio n. 17
0
        public void UpdateResource(IPluginOut ForPin, Device OnDevice)
        {
            if (this.runtime != null)
            {
                if (!this.FDepthTex.ContainsKey(OnDevice))
                {
                    Texture t = null;
                    if (OnDevice is DeviceEx)
                    {
                        t = new Texture(OnDevice, 320, 240, 1, Usage.Dynamic, Format.L16, Pool.Default);
                    }
                    else
                    {
                        t = new Texture(OnDevice, 320, 240, 1, Usage.None, Format.L16, Pool.Managed);
                    }
                    this.FDepthTex.Add(OnDevice, t);
                }

                if (this.FInvalidate)
                {
                    Texture       tx   = this.FDepthTex[OnDevice];
                    Surface       srf  = tx.GetSurfaceLevel(0);
                    DataRectangle rect = srf.LockRectangle(LockFlags.Discard);

                    int pos = 0;
                    lock (this.m_lock)
                    {
                        rect.Data.WriteRange(this.rawdepth);
                    }


                    //rect.Data.WriteRange(this.depthimage);

                    srf.UnlockRectangle();


                    this.FInvalidate = false;
                }
            }
        }
Esempio n. 18
0
        Texture2D createTextureFromFile(string filename)
        {
            BitmapImage loadedImage = new BitmapImage();

            loadedImage.BeginInit();
            loadedImage.CacheOption = BitmapCacheOption.OnLoad;
            loadedImage.UriSource   = new Uri(filename);
            loadedImage.EndInit();

            loadedImage.Freeze();

            int stride = loadedImage.PixelWidth * (loadedImage.Format.BitsPerPixel / 8);

            byte[] pixels = new byte[loadedImage.PixelHeight * stride];

            loadedImage.CopyPixels(pixels, stride, 0);

            pinnedArray = GCHandle.Alloc(pixels, GCHandleType.Pinned);
            IntPtr pixelPtr = pinnedArray.AddrOfPinnedObject();

            DataRectangle data = new DataRectangle(pixelPtr, stride);

            var texDesc = new Texture2DDescription
            {
                ArraySize         = 1,
                BindFlags         = BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Height            = loadedImage.PixelHeight,
                MipLevels         = 1,
                OptionFlags       = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                Width             = loadedImage.PixelWidth
            };

            Texture2D texture = new Texture2D(Host.Device, texDesc, data);

            return(texture);
        }
Esempio n. 19
0
        public void UpdateResource(IPluginOut ForPin, Device OnDevice)
        {
            if (this.runtime != null)
            {
                if (!this.FDepthTex.ContainsKey(OnDevice))
                {
                    Texture t = null;
                    if (OnDevice is DeviceEx)
                    {
                        t = new Texture(OnDevice, 640, 480, 1, Usage.Dynamic, Format.A32B32G32R32F, Pool.Default);
                    }
                    else
                    {
                        t = new Texture(OnDevice, 640, 480, 1, Usage.None, Format.A32B32G32R32F, Pool.Managed);
                    }
                    this.FDepthTex.Add(OnDevice, t);
                }

                if (this.FInvalidate)
                {
                    Texture       tx   = this.FDepthTex[OnDevice];
                    Surface       srf  = tx.GetSurfaceLevel(0);
                    DataRectangle rect = srf.LockRectangle(LockFlags.Discard);

                    lock (this.m_lock)
                    {
                        fixed(SkeletonPoint *f = &this.skelpoints[0])
                        {
                            IntPtr ptr = new IntPtr(f);

                            rect.Data.WriteRange(ptr, 640 * 480 * 16);
                        }
                    }
                    srf.UnlockRectangle();

                    this.FInvalidate = false;
                }
            }
        }
Esempio n. 20
0
        private void copyBuffer(Surface1 surface1, Rectangle desktopBounds, Action <IntPtr, int, Rectangle> copyFrameBuffer)
        {
            if (surface1 == null)
            {
                return;
            }

            DataRectangle map    = surface1.Map(MapFlags.Read);
            IntPtr        srcPtr = map.DataPointer;

            Rectangle offsetBounds = desktopBounds;

            offsetBounds.Offset(-this._outputRect.Left, -this._outputRect.Top);

            try
            {
                copyFrameBuffer(srcPtr, map.Pitch, offsetBounds);
            }
            catch { }

            surface1.Unmap();
        }
Esempio n. 21
0
        internal void SetData(DataRectangle data, int arrayIndex, int mipLevel)
        {
            var format = EnumConverter.Convert(Format);

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

                if (!TextureFormatHelper.IsCompressed(Format))
                {
                    GL.TexSubImage3D(TextureTarget.Texture2DArray, mipLevel, 0, 0, 0, Width, Height, ArraySize, format.Item2, format.Item3, data.Pointer);
                }
                else
                {
                    GL.CompressedTexImage3D(TextureTarget.Texture2DArray, mipLevel, format.Item1, Width, Height, ArraySize, 0, data.Size, data.Pointer);
                }

                GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureMaxLevel, this.MipLevels - 1);
            }
            else if (graphicsDevice.OpenGLCapabilities.DirectStateAccess == DirectStateAccess.Extension)
            {
                if (!TextureFormatHelper.IsCompressed(Format))
                {
                    Ext.TextureSubImage3D(TextureID, (OpenTK.Graphics.OpenGL.TextureTarget)TextureTarget.Texture2DArray, mipLevel, 0, 0, 0, Width, Height, ArraySize, (OpenTK.Graphics.OpenGL.PixelFormat)format.Item2, (OpenTK.Graphics.OpenGL.PixelType)format.Item3, data.Pointer);
                }
                else
                {
                    Ext.CompressedTextureImage3D(TextureID, (OpenTK.Graphics.OpenGL.TextureTarget)TextureTarget.Texture2DArray, mipLevel, (OpenTK.Graphics.OpenGL.ExtDirectStateAccess)EnumConverter.Convert(Format).Item1, Width, Height, ArraySize, 0, Marshal.SizeOf(data), data.Pointer);
                }

                OpenTK.Graphics.OpenGL.GL.Ext.TextureParameter(TextureID, (OpenTK.Graphics.OpenGL.TextureTarget)TextureTarget.Texture2DArray, OpenTK.Graphics.OpenGL.TextureParameterName.TextureMaxLevel, this.MipLevels - 1);
            }
            else if (graphicsDevice.OpenGLCapabilities.DirectStateAccess == DirectStateAccess.Core)
            {
                //OpenGL 4.5
            }

            graphicsDevice.CheckGLError("Texture2DArray SetData");
        }
Esempio n. 22
0
        public TextureArray2D(ImageData image)
        {
            Size = image.Size;
            Debug.Assert(Size.Depth == 1);
            LayerMipmap = image.LayerMipmap;
            Format      = image.Format.DxgiFormat;

            var data = new DataRectangle[LayerMipmap.Layers * LayerMipmap.Mipmaps];

            foreach (var lm in LayerMipmap.Range)
            {
                var mip = image.GetMipmap(lm);
                var idx = GetSubresourceIndex(lm);
                data[idx].DataPointer = mip.Bytes;
                // The distance (in bytes) from the beginning of one line of a texture to the next line.
                data[idx].Pitch = (int)(mip.ByteSize / mip.Size.Height);
            }

            handle = new Texture2D(Device.Get().Handle, CreateTextureDescription(false), data);

            CreateTextureViews(false);
        }
        // permuted gradient texture for optimized version
        private void GeneratePermGradTexture()
        {
            if (permGradTexture != null)
            {
                permGradTexture.Dispose();
            }
            //NormalizedByte4
            permGradTexture = new Texture(MyMinerGame.Static.GraphicsDevice, 256, 1, 0, Usage.Dynamic, Format.Q8W8V8U8, Pool.Default);


            NormalizedByte4[] data = new NormalizedByte4[256 * 1];
            for (int x = 0; x < 256; x++)
            {
                for (int y = 0; y < 1; y++)
                {
                    //data[x + (y * 256)] = new NormalizedByte4(g3[perm[x] % 16, 0], g3[perm[x] % 16, 1], g3[perm[x] % 16, 2], 1);
                    data[x + (y * 256)] = new NormalizedByte4(g3[perm[x] % 16, 0], g3[perm[x] % 16, 1], g3[perm[x] % 16, 2], 1);
                }
            }

            /*
             * byte[] data = new byte[256 * 1 * 4];
             * for (int x = 0; x < 256; x++)
             * {
             *  for (int y = 0; y < 1; y++)
             *  {
             *      data[(x + (y * 256)) * 4 + 0] = (byte)(255.0f * ((g3[perm[x] % 16, 0] + 1) / 2.0f));
             *      data[(x + (y * 256)) * 4 + 1] = (byte)(255.0f * ((g3[perm[x] % 16, 1] + 1) / 2.0f));
             *      data[(x + (y * 256)) * 4 + 2] = (byte)(255.0f * ((g3[perm[x] % 16, 2] + 1) / 2.0f));
             *      data[(x + (y * 256)) * 4 + 3] = 1;
             *  }
             * } */

            SharpDX.DataStream ds;
            DataRectangle      dr = permGradTexture.LockRectangle(0, LockFlags.None, out ds);

            ds.WriteRange(data);
            permGradTexture.UnlockRectangle(0);
        }
Esempio n. 24
0
 public void MainLoop(bool newScreen)
 {
     if (device != null)
     {
         try
         {
             if (newScreen)
             {
                 unsafe
                 {
                     DataRectangle drt = texture.LockRectangle(0, LockFlags.Discard);
                     fixed(uint *screenPTR = screen)
                     {
                         imageScaler.PerformScale(screenPTR, (uint *)drt.Data.DataPointer);
                     }
                     texture.UnlockRectangle(0);
                 }
             }
             device.Clear(ClearFlags.Target, Color.Black, 1.0f, 0);
             device.BeginScene();
             device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2);
             DrawMessageEvent(this, null);
             device.EndScene();
             device.Present();
         }
         catch (Direct3D9Exception e)
         {
             if (e.ResultCode == SlimDX.Direct3D9.ResultCode.DeviceLost)
             {
                 Create();
             }
         }
         catch (NullReferenceException e)
         {
             //thrown for some reason on every minimize, should look into in the future.
         }
     }
 }
Esempio n. 25
0
        // This updates a dynamic texture
        public void UpdateTexture()
        {
            if (!dynamictexture)
            {
                throw new Exception("The image must be a dynamic image to support direct updating.");
            }

            lock (this)
            {
                if ((texture != null) && !texture.Disposed)
                {
                    // Lock the bitmap and texture
                    BitmapData    bmpdata = bitmap.LockBits(new Rectangle(0, 0, bitmap.Size.Width, bitmap.Size.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
                    DataRectangle texdata = texture.LockRectangle(0, LockFlags.Discard);

                    // Copy data
                    int *bp = (int *)bmpdata.Scan0.ToPointer();
                    int *tp = (int *)texdata.Data.DataPointer.ToPointer();
                    for (int y = 0; y < bmpdata.Height; y++)
                    {
                        for (int x = 0; x < bmpdata.Width; x++)
                        {
                            *tp = *bp;
                            bp++;
                            tp++;
                        }

                        // Skip extra data in texture
                        int extrapitch = (texdata.Pitch >> 2) - bmpdata.Width;
                        tp += extrapitch;
                    }

                    // Unlock
                    texture.UnlockRectangle(0);
                    bitmap.UnlockBits(bmpdata);
                }
            }
        }
Esempio n. 26
0
        public void LoadTextureIntoSlot(int slot, string path)
        {
            var img = Pfim.Pfim.FromFile(path);

            if (img.Width != 1024 || img.Height != 1024)
            {
                throw new Exception("Terrain textures must be 1024x1024px.");
            }

            textureData[slot] = new DataRectangle(1024 * 4, new DataStream(img.Data, true, true));

            Texture2DDescription d = new Texture2DDescription()
            {
                ArraySize         = 16,
                BindFlags         = BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Height            = 1024,
                MipLevels         = 1,
                OptionFlags       = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Immutable,
                Width             = 1024,
            };

            texArray = new Texture2D(Renderer.viewport.Device, d, textureData);

            ShaderResourceViewDescription texArraySrvd = new ShaderResourceViewDescription
            {
                Dimension       = ShaderResourceViewDimension.Texture2DArray,
                MipLevels       = 1,
                MostDetailedMip = 0,
                FirstArraySlice = 0,
                ArraySize       = 16
            };

            texArraySRV = new ShaderResourceView(Renderer.viewport.Device, texArray, texArraySrvd);
        }
Esempio n. 27
0
        private void GeneFrmTx(ref CTexture tex, byte[] bytearray)
        {
            //ポインタを使用し、データを直接バッファにコピーする
            if (tex == null || tex.texture == null)
            {
                GeneFrmTx(ref tex, new Bitmap(FrameSize.Width, FrameSize.Height));
            }

            DataRectangle data = tex.texture.LockRectangle(0, LockFlags.Discard);

            if (tex.szテクスチャサイズ.Width == FrameSize.Width)
            {
                Marshal.Copy(bytearray, 0, data.DataPointer, FrameSize.Width * FrameSize.Height * 4);
            }
            else
            {
                tex.Dispose();
                GeneFrmTx(ref tex, new Bitmap(FrameSize.Width, FrameSize.Height));
                Marshal.Copy(bytearray, 0, data.DataPointer, FrameSize.Width * FrameSize.Height * 4);
            }

            tex.texture.UnlockRectangle(0);
        }
        public static Texture2D CreateTex2DFromBitmap(SharpDX.WIC.BitmapSource bsource, SharpDX.Direct3D11.Device device)
        {
            Texture2DDescription desc;

            desc.Width                     = bsource.Size.Width;
            desc.Height                    = bsource.Size.Height;
            desc.ArraySize                 = 1;
            desc.BindFlags                 = BindFlags.ShaderResource;
            desc.Usage                     = ResourceUsage.Default;
            desc.CpuAccessFlags            = CpuAccessFlags.None;
            desc.Format                    = SharpDX.DXGI.Format.R8G8B8A8_UNorm;
            desc.MipLevels                 = 1;
            desc.OptionFlags               = ResourceOptionFlags.None;
            desc.SampleDescription.Count   = 1;
            desc.SampleDescription.Quality = 0;

            using (DataStream s = new DataStream(bsource.Size.Height * bsource.Size.Width * 4, true, true))
            {
                bsource.CopyPixels(bsource.Size.Width * 4, s);
                DataRectangle rect = new DataRectangle(s.DataPointer, bsource.Size.Width * 4);
                return(new Texture2D(device, desc, rect));
            }
        }
        private void GeneratePermTexture()
        {
            if (permTexture != null)
            {
                permTexture.Dispose();
            }

            permTexture = new Texture(MyMinerGame.Static.GraphicsDevice, 256, 1, 0, Usage.Dynamic, Format.L8, Pool.Default);
            byte[] data = new byte[256 * 1];
            for (int x = 0; x < 256; x++)
            {
                for (int y = 0; y < 1; y++)
                {
                    data[x + (y * 256)] = (byte)(perm[x]);// / 255.0);
                }
            }

            SharpDX.DataStream ds;
            DataRectangle      dr = permTexture.LockRectangle(0, LockFlags.None, out ds);

            ds.WriteRange(data);
            permTexture.UnlockRectangle(0);
        }
Esempio n. 30
0
        private void loop()
        {
            _isRunning = true;

            Stopwatch sw = new Stopwatch();

            sw.Start();
            int ticks = 0;

            while (!quit)
            {
                Surface s = Surface.CreateOffscreenPlain(d, s_width, s_height, Format.A8R8G8B8, Pool.Scratch);
                Surface b = Surface.CreateOffscreenPlain(d, c_width, c_height, Format.A8R8G8B8, Pool.Scratch);
                d.GetFrontBufferData(0, s);
                Surface.FromSurface(b, s, Filter.Triangle, 0);
                s.Dispose();

                DataRectangle dr = b.LockRectangle(LockFlags.None);
                DataStream    ds = dr.Data;
                c_array = removeAlpha(ds);

                b.UnlockRectangle();
                b.Dispose();
                ds.Dispose();

                ticks++;

                if (sw.ElapsedMilliseconds >= 1000)
                {
                    setUPSDelegate(ticks);
                    ticks = 0;
                    sw.Restart();
                }
            }

            _isRunning = false;
        }
Esempio n. 31
0
        // TODO: Test this method:
        public override void WritePixels(PixelBuffer buffer, Point startPoint)
        {
            Direct3D.Surface surf       = mTexture.Value.GetSurfaceLevel(0);
            Rectangle        updateRect = new Rectangle(startPoint, buffer.Size);

            int         pixelPitch  = mDisplay.GetPixelPitch(surf.Description.Format);
            PixelFormat pixelFormat = mDisplay.GetPixelFormat(surf.Description.Format);

            surf.Dispose();

            // This should probably only lock the region of the surface we intend to update.
            // However, as is usually the case with DirectX, doing so gives weird errors
            // with no real explanation as to what is wrong.
            DataRectangle stm = mTexture.Value.LockRectangle
                                    (0, LockFlags.None);

            if (buffer.PixelFormat != pixelFormat)
            {
                buffer = buffer.ConvertTo(pixelFormat);
            }

            unsafe
            {
                for (int i = 0; i < buffer.Height; i++)
                {
                    int    startIndex = buffer.GetPixelIndex(0, i);
                    int    rowStride  = buffer.RowStride;
                    IntPtr dest       = (IntPtr)
                                        ((byte *)stm.Data.DataPointer + (i + updateRect.Top) * stm.Pitch
                                         + updateRect.Left * pixelPitch);

                    Marshal.Copy(buffer.Data, startIndex, dest, rowStride);
                }
            }

            mTexture.Value.UnlockRectangle(0);
        }
Esempio n. 32
0
        static unsafe SharpDX.Direct3D11.Texture2D CreateTex2DFromBitmap(BitmapSource bsource, GraphicsDevice device)
        {
            Texture2DDescription desc;

            desc.Width                     = bsource.Size.Width;
            desc.Height                    = bsource.Size.Height;
            desc.ArraySize                 = 1;
            desc.BindFlags                 = BindFlags.ShaderResource;
            desc.Usage                     = ResourceUsage.Default;
            desc.CpuAccessFlags            = CpuAccessFlags.None;
            desc.Format                    = SharpDX.DXGI.Format.R8G8B8A8_UNorm;
            desc.MipLevels                 = 1;
            desc.OptionFlags               = ResourceOptionFlags.None;
            desc.SampleDescription.Count   = 1;
            desc.SampleDescription.Quality = 0;

            using (DataStream s = new DataStream(bsource.Size.Height * bsource.Size.Width * 4, true, true))
            {
                bsource.CopyPixels(bsource.Size.Width * 4, s);

                // XNA blacks out any pixels with an alpha of zero.
                var data = (byte *)s.DataPointer;
                for (var i = 0; i < s.Length; i += 4)
                {
                    if (data[i + 3] == 0)
                    {
                        data[i + 0] = 0;
                        data[i + 1] = 0;
                        data[i + 2] = 0;
                    }
                }

                DataRectangle rect = new DataRectangle(s.DataPointer, bsource.Size.Width * 4);

                return(new SharpDX.Direct3D11.Texture2D(device._d3dDevice, desc, rect));
            }
        }
Esempio n. 33
0
        public Texture2D Texture2DFromBitmap(Bitmap bmp)
        {
            Texture2D texture;

            System.Drawing.Imaging.BitmapData bitmapData = bmp.LockBits(
                new Rectangle(0, 0, bmp.Width, bmp.Height),
                System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

            DataStream    dataStream    = new DataStream(bitmapData.Scan0, bitmapData.Stride * bitmapData.Height, true, false);
            DataRectangle dataRectangle = new DataRectangle(bitmapData.Stride, dataStream);

            try
            {
                //Load the texture
                texture = new Texture2D(DeviceManager.Instance.device, new Texture2DDescription()
                {
                    BindFlags         = BindFlags.ShaderResource,
                    CpuAccessFlags    = CpuAccessFlags.None,
                    Format            = Format.B8G8R8A8_UNorm,
                    OptionFlags       = ResourceOptionFlags.None,
                    MipLevels         = 1,
                    Usage             = ResourceUsage.Immutable,
                    Width             = bmp.Width,
                    Height            = bmp.Height,
                    ArraySize         = 1,
                    SampleDescription = new SampleDescription(1, 0)
                }, dataRectangle);
            }
            finally
            {
                //Free bitmap-access resources
                dataStream.Dispose();
                bmp.UnlockBits(bitmapData);
            }

            return(texture);
        }
Esempio n. 34
0
 public void lock_texture()
 {
     texture_data = texture.LockRectangle(0, LockFlags.Discard | LockFlags.DoNotWait);
 }
Esempio n. 35
0
        public void clear_screen()
        {
            for (int y = 0; y < 256; y++)
            {
                for (int x = 0; x < 256; )
                {
                    data_copy[(y << 8) | x] = 0x00000000;
                    ++x;
                }
            }

            texture_data = texture.LockRectangle(0, LockFlags.Discard | LockFlags.DoNotWait);
            texture_data.Data.WriteRange<int>(data_copy);
            texture.UnlockRectangle(0);
        }
Esempio n. 36
0
        //creation functions
        public Terrain(int q, StreamReader file)
        {
            quadSize = q;
            //loading effect
            effect = ResourceManager.mainManager.LoadEffect("Resources\\Effects\\Terrain.fx", ResourceManager.mainManager.GetDefaultEffectPool());
            technique = effect.GetTechniqueByName("Render");
            pass = technique.GetPassByIndex(0);
            //creating layout
            D3D10.InputElement[] elements = new SlimDX.Direct3D10.InputElement[1];
            elements[0] = new SlimDX.Direct3D10.InputElement("TEXCOORD", 0, SlimDX.DXGI.Format.R32G32_Float, 0, 0, D3D10.InputClassification.PerVertexData, 0);
            layout = new SlimDX.Direct3D10.InputLayout(Game.gameClass.GetDevice(), elements, pass.Description.Signature);

            //loading texture
            D3D10.ImageLoadInformation load = new SlimDX.Direct3D10.ImageLoadInformation();
            load.BindFlags = D3D10.BindFlags.ShaderResource;
            load.CpuAccessFlags = D3D10.CpuAccessFlags.None;
            load.MipLevels = 1;
            load.Usage=D3D10.ResourceUsage.Default;
            load.OptionFlags = D3D10.ResourceOptionFlags.None;
            load.FilterFlags = D3D10.FilterFlags.Point;
            load.Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm;
            normalTexture = D3D10.Texture2D.FromFile(Game.gameClass.GetDevice(), Path.GetDirectoryName(Game.gameClass.GetLvLFilePath()) + "\\normals.png", load);
            Globals.mapSize = normalTexture.Description.Width;

            if (Game.gameClass.GetEngineState() != EngineState.play)
            {
                D3D10.Texture2DDescription desc = new SlimDX.Direct3D10.Texture2DDescription();
                desc.ArraySize = 1;
                desc.BindFlags = D3D10.BindFlags.None;
                desc.CpuAccessFlags = D3D10.CpuAccessFlags.Write;
                desc.Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm;
                desc.Height = Globals.mapSize;
                desc.Width = Globals.mapSize;
                desc.Usage = D3D10.ResourceUsage.Staging;
                desc.MipLevels = 1;
                SlimDX.DXGI.SampleDescription sampleDescription = new SlimDX.DXGI.SampleDescription();
                sampleDescription.Count = 1;
                sampleDescription.Quality = 0;
                desc.SampleDescription = sampleDescription;
                normalTexUpdater = new SlimDX.Direct3D10.Texture2D(Game.gameClass.GetDevice(), desc);
                normalData = normalTexUpdater.Map(0, D3D10.MapMode.Write, D3D10.MapFlags.DoNotWait);
                normalTexUpdater.Unmap(0);
            }

               // LoadTextureArray(file);
            //setting up vertices and creating vertex buffer
            LoadVertexInfo();
            CreateVertexBuffer();

            //constant buffer variables
            effect.GetVariableByName("mapSize").AsScalar().Set(Globals.mapSize);
            using(D3D10.ShaderResourceView normalView=new D3D10.ShaderResourceView(Game.gameClass.GetDevice(),normalTexture))
                effect.GetVariableByName("normalMap").AsResource().SetResource(normalView);
              //  using (D3D10.ShaderResourceView texturesView = new D3D10.ShaderResourceView(Game.gameClass.GetDevice(), textures))
            //    effect.GetVariableByName("textures").AsResource().SetResource(texturesView);

            orientations=effect.GetVariableByName("orientations").AsVector();
               // effect.GetVariableByName("texCoordMul").AsScalar().Set(TextureInfo.texCoordMul);
            heightMul = effect.GetVariableByName("heightMul").AsScalar();
            heightMul.Set(Globals.heightMultiplier);

            //handles edit mode
            if (Game.gameClass.GetEngineState() != EngineState.play)
            {
                techniqueEdit = effect.GetTechniqueByName("Edit");
                passEdit = techniqueEdit.GetPassByIndex(0);
                mousePick = effect.GetVariableByName("mousePick").AsVector();
                pickOptions = effect.GetVariableByName("pickOpt").AsVector();
            }
            Globals.SetMap(map);
        }
Esempio n. 37
0
        public void SetTexture(crVTMapEntry vtEntry)
        {
            currentEntry = vtEntry;
            if (vtEntry == null || vtPage == null) return;
            var tiles = vtPage.GetTiles(vtEntry);
            if (tiles.Count == 0) return;
            mainForm.tileListSource.DataSource = tiles;
            var uniqueTiles = (from tile in tiles select tile.TDXTile.Texture.Name).Distinct();
            Format textureformat = Format.BC3_UNorm;
            if (tiles[0].TDXTile.Texture == null) tiles[0].TDXTile.GetTextureFromZAD();
            if (tiles[0].TDXTile.Texture == null)
            {
                return;
            }
            switch (tiles[0].TDXTile.Texture.Format)
            {
                case ToxicRagers.Helpers.D3DFormat.DXT1:
                    textureformat = Format.BC1_UNorm;
                    break;
                case ToxicRagers.Helpers.D3DFormat.DXT5:
                    textureformat = Format.BC3_UNorm;
                    break;
                case ToxicRagers.Helpers.D3DFormat.ATI2:
                    textureformat = Format.BC5_UNorm;
                    break;
                case ToxicRagers.Helpers.D3DFormat.A8R8G8B8:
                    textureformat = Format.B8G8R8A8_UNorm_SRGB;
                    break;
                case ToxicRagers.Helpers.D3DFormat.A8:
                    textureformat = Format.A8_UNorm;
                    break;

            }
            List<ShaderResourceView> resourceViews = new List<ShaderResourceView>();
            List<DataRectangle> rects = new List<DataRectangle>();
            List<Int32> TileRows = new List<int>();
            List<Int32> TileCols = new List<int>();

            List<float> IndirectionData = new List<float>();
            int divisor = vtPage.GetDivisor();

            var cb = new VTConstantBuffer();
            cb.Width = vtEntry.Width / vtPage.GetDivisor();
            cb.Height = vtEntry.Height / vtPage.GetDivisor();
            cb.TilesX = (int)Math.Ceiling(cb.Width / 120.0f) + 1;
            cb.TilesY = (int)Math.Ceiling(cb.Height / 120.0f) + 1;
            cb.ViewportWidth = targetControl.ClientSize.Width;
            cb.ViewportHeight = targetControl.ClientSize.Height;
            cb.PosOffsetX = vtEntry.Column / divisor - tiles[0].Column * 120;
            cb.PosOffsetY = vtEntry.Row / divisor - tiles[0].Row * 120;
            float widthRatio = (float)cb.Height / cb.Width;
            float heightRatio = (float)cb.Width / cb.Height;
            float polyWidth = 1f;
            float polyHeight = 1f;
            if (cb.ViewportWidth > cb.ViewportHeight)
            {
                polyWidth = cb.ViewportWidth / cb.ViewportHeight;
            }
            else if (cb.ViewportWidth < cb.ViewportHeight)
            {
                polyHeight = cb.ViewportHeight / cb.ViewportWidth;
            }
            if (cb.Width > cb.Height)
            {
                if (cb.ViewportWidth > cb.Width)
                {
                    //polyWidth = (float)cb.Width / cb.ViewportWidth;
                    //polyHeight = (float)cb.Height / cb.ViewportHeight;
                }
                cb.TextureWidth = cb.ViewportWidth < cb.Width ? cb.ViewportWidth : cb.Width;
                cb.TextureHeight = (int)(cb.TextureWidth * ((float)cb.Height / cb.Width));
                polyHeight = (1f - ((float)cb.TextureHeight / cb.ViewportHeight) * widthRatio) * 2 - 1;
                polyWidth = ((float)cb.TextureWidth / cb.ViewportWidth) * 2 - 1;
            }
            else if (cb.Width < cb.Height)
            {
                if (cb.ViewportHeight > cb.Height)
                {
                    //polyHeight = (float)cb.Height / cb.ViewportHeight;
                    //polyWidth = (float)cb.Height / cb.ViewportHeight;
                }
                cb.TextureHeight = cb.ViewportHeight < cb.Height ? cb.ViewportHeight : cb.Height;
                cb.TextureWidth = (int)(cb.TextureHeight * ((float)cb.Width / cb.Height));
                polyHeight = (1f - ((float)cb.TextureHeight / cb.ViewportHeight)) * 2 - 1;
                polyWidth = ((float)cb.TextureWidth / cb.ViewportWidth) * heightRatio * 2 - 1;

            }
            else
            {
                if (cb.ViewportWidth < cb.ViewportHeight)
                {
                    if (cb.ViewportWidth < cb.Width)
                    {
                        cb.TextureWidth = cb.ViewportWidth;
                        cb.TextureHeight = (int)Math.Floor(cb.ViewportWidth * widthRatio);
                        //polyWidth = (float)cb.Width / cb.ViewportWidth;
                        //polyHeight = (float)cb.Height / cb.ViewportHeight; // polyWidth;
                    }
                }
                cb.TextureHeight = cb.ViewportHeight < cb.Height ? cb.ViewportHeight : cb.Height;
                cb.TextureWidth = cb.ViewportWidth < cb.Width ? cb.ViewportWidth : cb.Width;
                polyHeight = (1f - ((float)cb.TextureHeight / cb.ViewportHeight)) * 2 - 1;
                polyWidth = ((float)cb.TextureWidth / cb.ViewportWidth) * 2 - 1;
            }

            var mappedData = context.MapSubresource(vertexBuffer, 0, MapMode.WriteDiscard, SlimDX.Direct3D11.MapFlags.None);

            mappedData.Data.Write(new Vector3(-1f, polyHeight, 0.5f)); mappedData.Data.Write(new Vector2(0f, 1f));
            mappedData.Data.Write(new Vector3(-1f, 1f, 0.5f)); mappedData.Data.Write(new Vector2(0f, 0f));
            mappedData.Data.Write(new Vector3(polyWidth, polyHeight, 0.5f)); mappedData.Data.Write(new Vector2(1f, 1f));
            mappedData.Data.Write(new Vector3(polyWidth, 1f, 0.5f)); mappedData.Data.Write(new Vector2(1f, 0f));

            context.UnmapSubresource(vertexBuffer, 0);
            if (cb.PosOffsetX > 0 || cb.PosOffsetY > 0)
            {
                Console.Write("");
            }
            //cb.PosX = vtEntry.Column / vtPage.GetDivisor();
            //cb.PosY = vtEntry.Row / vtPage.GetDivisor();

            for (int y = 0; y <= cb.TilesY; y++)
            {
                for (int x = 0; x <= cb.TilesX; x++)
                {
                    IndirectionData.Add(0);
                }
            }
            int vtDivisor = vtPage.GetDivisor();
            foreach (var tile in tiles)
            {
                //using (MemoryStream stream = new MemoryStream())
                {
                    /*var dds = tile.GetDDS();
                    BinaryWriter bw = new BinaryWriter(stream);
                    dds.Save(bw);
                    stream.Seek(0, SeekOrigin.Begin);
                    Texture2D tex = Texture2D.FromStream(device, stream, (int)stream.Length);*/
                    DataRectangle rect = new DataRectangle(128 * 4, new DataStream(tile.TDXTile.Texture.DecompressToBytes(), false, false));
                    rects.Add(rect);
                    TileRows.Add(tile.Row);
                    TileCols.Add(tile.Column);

                    int indIndex = (((tile.Row * 120 - (vtEntry.Row / vtDivisor)) / 120) * cb.TilesX) + (tile.Column * 120 - vtEntry.Column / vtDivisor) / 120;
                    IndirectionData[indIndex] = (float)((rects.Count - 1) / tiles.Count);
                    //resourceViews.Add(new ShaderResourceView(device, tex));
                    //bw.Dispose();
                }
            }
            Texture2D textureArray = new Texture2D(device, new Texture2DDescription
            {
                BindFlags = BindFlags.ShaderResource,
                ArraySize = rects.Count,
                Width = 128,
                Height = 128,
                Usage = ResourceUsage.Default,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = Format.B8G8R8A8_UNorm,
                SampleDescription = new SampleDescription(1, 0),
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None
            }
                , rects.ToArray());
            ShaderResourceView resourceView = new ShaderResourceView(device, textureArray);
            context.PixelShader.SetShaderResource(resourceView, 0);
            //cb.TilePosX = TileCols.ToArray();
            //cb.TilePosY = TileRows.ToArray();
            int sizeOfCB = ((sizeof(Int32) * 10 + 15) / 16) * 16;
            using (DataStream data = new DataStream(sizeOfCB, true, true))
            {
                data.Write(cb);
                data.Position = 0;
                context.PixelShader.SetConstantBuffer(new SlimDX.Direct3D11.Buffer(device, data, new BufferDescription
                {
                    Usage = ResourceUsage.Default,
                    SizeInBytes = sizeOfCB,// + cb.TilePosX.Length + cb.TilePosY.Length),
                    BindFlags = BindFlags.ConstantBuffer
                }), 0);
            }
            Texture2D inderectionTexture = new Texture2D(device, new Texture2DDescription
            {
                BindFlags = BindFlags.ShaderResource,
                ArraySize = 1,
                Width = cb.TilesX,
                Height = cb.TilesY,
                Usage = ResourceUsage.Default,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = Format.R32_Float,
                SampleDescription = new SampleDescription(1, 0),
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None
            }
                , new DataRectangle(cb.TilesX * 4, new DataStream(IndirectionData.ToArray(), true, true)));
            ShaderResourceView indresourceview = new ShaderResourceView(device, inderectionTexture);
            context.PixelShader.SetShaderResource(indresourceview, 1);
            UpdateRenderer = true;
            //fx.GetVariableByName("shaderTexture").AsResource().SetResourceArray(resourceViews.ToArray());
            /*fx.GetVariableByName("Width").AsScalar().Set(vtEntry.Width);
            fx.GetVariableByName("Height").AsScalar().Set(vtEntry.Height);
            fx.GetVariableByName("TilesX").AsScalar().Set((int)(vtEntry.Width / 128.0f));
            fx.GetVariableByName("TilesY").AsScalar().Set((int)(vtEntry.Height / 128.0f));
            device.ImmediateContext.PixelShader.SetShaderResource(resourceView, 0);*/
            //context.PixelShader.SetShaderResource(resourceView, 0);
            //context.PixelShader.SetSampler(sampleState, 0);
        }
Esempio n. 38
0
        static void Main()
        {
            var form = new RenderForm("SlimDX - Conway's game of life Direct3D 11 Sample");
            var desc = new SwapChainDescription()
            {
                BufferCount = 1,
                ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed = true,
                OutputHandle = form.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect = SwapEffect.Discard,
                Usage = Usage.RenderTargetOutput
            };

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

            device.Factory.SetWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

            Texture2D backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
            var renderView = new RenderTargetView(device, backBuffer);
            var bytecode = ShaderBytecode.CompileFromFile("Render.fx", "fx_5_0", ShaderFlags.None, EffectFlags.None);
            var effect = new Effect(device, bytecode);
            var technique = effect.GetTechniqueByIndex(0);
            var pass = technique.GetPassByIndex(0);
            String errors;
            var computeByteCode = ShaderBytecode.CompileFromFile("compute.fx", "CS", "cs_5_0", ShaderFlags.None, EffectFlags.None, null, null, out errors);
            var compute = new ComputeShader(device, computeByteCode);

            // shader variable handles
            var conwayResourceH = effect.GetVariableByName("tex").AsResource();
            var resolutionInvH = effect.GetVariableByName("resolutionInv").AsVector();
            resolutionInvH.Set(new Vector2(1.0f / form.ClientSize.Width, 1.0f / form.ClientSize.Height));
            EffectVectorVariable lightPosSSH = effect.GetVariableByName("lightPosSS").AsVector();

            // create texture, fill it with random data
            Texture2DDescription textureDesc = new Texture2DDescription()
            {
                Width = form.ClientSize.Width,
                Height = form.ClientSize.Height,
                MipLevels = 1,
                ArraySize = 1,
                CpuAccessFlags = CpuAccessFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                OptionFlags = ResourceOptionFlags.None,
                BindFlags = BindFlags.UnorderedAccess | BindFlags.ShaderResource,
                Format = Format.R32_Float
            };

            var random = new Random();
            var data = new float[form.ClientSize.Width * form.ClientSize.Height];
            for (int i = 0; i < form.ClientSize.Width; ++i)
            {
                for (int j = 0; j < form.ClientSize.Height; ++j)
                    data[i * form.ClientSize.Height + j] = (float)random.Next(2);
            }

            DataStream ds = new DataStream(data, true, false);
            DataRectangle dataRect = new DataRectangle(4 * form.ClientSize.Width, ds);

            Texture2D conwayTex = new Texture2D(device, textureDesc, dataRect);

            // Create SRV and UAV over the same texture
            UnorderedAccessView conwayUAV = new UnorderedAccessView(device, conwayTex);
            ShaderResourceView conwaySRV = new ShaderResourceView(device, conwayTex);

            // On the more typical setup where you switch shaders, 
            // you will have to set the texture after every
            conwayResourceH.SetResource(conwaySRV);

            device.ImmediateContext.OutputMerger.SetTargets(renderView);
            device.ImmediateContext.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f));
            device.ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;

            Vector2 lightPosSS;
            float angle = 0;

            MessagePump.Run(form, () =>
            {
                // this does the light rotation
                angle += 0.002f;
                lightPosSS = new Vector2((float)Math.Sin(angle) * 0.5f + 0.5f, (float)Math.Cos(angle) * 0.5f + 0.5f);
                lightPosSSH.Set(lightPosSS);

                device.ImmediateContext.ComputeShader.Set(compute);
                device.ImmediateContext.ComputeShader.SetUnorderedAccessView(conwayUAV, 0);
                device.ImmediateContext.Dispatch(form.ClientSize.Width / 16 + 1, form.ClientSize.Height / 16 + 1, 1);

                // After running the CS you have to unset UAV from the shader, so you can use it as SRV
                device.ImmediateContext.ComputeShader.SetUnorderedAccessView(null, 0);

                device.ImmediateContext.ClearRenderTargetView(renderView, Color.Black);

                for (int i = 0; i < technique.Description.PassCount; ++i)
                {
                    pass.Apply(device.ImmediateContext);
                    // No vertices are send as they are created in the vertex shader on the fly.
                    device.ImmediateContext.Draw(4, 0);
                }

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

            computeByteCode.Dispose();
            conwayUAV.Dispose();
            conwaySRV.Dispose();
            conwayTex.Dispose();
            ds.Dispose();
            bytecode.Dispose();
            effect.Dispose();
            renderView.Dispose();
            backBuffer.Dispose();
            device.Dispose();
            swapChain.Dispose();
        }
Esempio n. 39
0
 /// <summary>
 ///   Initializes a new instance of the <see cref = "T:SharpDX.Direct3D10.Texture2D" /> class.
 /// </summary>
 /// <param name = "device">The device with which to associate the texture.</param>
 /// <param name = "description">The description of the texture.</param>
 /// <param name = "data">The initial texture data.</param>
 public Texture2D(Device device, Texture2DDescription description, DataRectangle data)
     : this(device, description, new[] {data})
 {
 }
Esempio n. 40
0
        private void CopyTextureDataToImage(ImageData destination, DataRectangle source)
        {
            int pitch = source.Pitch;

            /* Todo: be portable to 64bit :) */
            int destDataPointer = destination.Scan0.ToInt32();
            int sourceDataPointer = source.Data.DataPointer.ToInt32();

            int rowByteSize = destination.Stride;

            int sourceByteOffset = 0;
            for (int y = 0; y < Height; ++y)
            {
                var destPointer = new IntPtr(destDataPointer + (y * rowByteSize));
                var sourcePointer = new IntPtr(sourceDataPointer + sourceByteOffset);

                CopyMemory(destPointer, sourcePointer, rowByteSize);

                sourceByteOffset += rowByteSize + (pitch - rowByteSize);
            }
        }
Esempio n. 41
0
        public void clear_screen()
        {
            texture_data = texture.LockRectangle(0, LockFlags.None);

            for (int y = 0; y < 256; y++)
            {
                for (int x = 0; x < 224; x++)
                {
                    set_pixel(x, y, 0x00000000);
                }
            }

            write_data();
            texture.UnlockRectangle(0);
        }
Esempio n. 42
0
 public void lock_texture()
 {
     texture_data = texture.LockRectangle(0, LockFlags.None);
 }