Inheritance: IPixelBuffer
Exemplo n.º 1
0
        private static void SaveFromMemory(PixelBuffer[] pixelBuffers, int count, ImageDescription description, Stream imageStream, Bitmap.CompressFormat imageFormat)
        {
            var colors = pixelBuffers[0].GetPixels<int>();

            using (var bitmap = Bitmap.CreateBitmap(description.Width, description.Height, Bitmap.Config.Argb8888))
            {
                var pixelData = bitmap.LockPixels();
                var sizeToCopy = colors.Length * sizeof(int);

                unsafe
                {
                    fixed (int* pSrc = colors)
                    {
                        // Copy the memory
                        if (description.Format == PixelFormat.R8G8B8A8_UNorm || description.Format == PixelFormat.R8G8B8A8_UNorm_SRgb)
                        {
                            CopyMemoryBGRA(pixelData, (IntPtr)pSrc, sizeToCopy);
                        }
                        else if (description.Format == PixelFormat.B8G8R8A8_UNorm || description.Format == PixelFormat.B8G8R8A8_UNorm_SRgb)
                        {
                            Utilities.CopyMemory(pixelData, (IntPtr)pSrc, sizeToCopy);
                        }
                        else
                        {
                            throw new NotSupportedException(string.Format("Pixel format [{0}] is not supported", description.Format));
                        }
                    }
                }

                bitmap.UnlockPixels();
                bitmap.Compress(imageFormat, 100, imageStream);
            }
        }
Exemplo n.º 2
0
        private static void SaveFromMemory(PixelBuffer[] pixelBuffers, int count, ImageDescription description, Stream imageStream, ImageFormat imageFormat)
        {
            using (var bitmap = new Bitmap(description.Width, description.Height))
            {
                var sourceArea = new Rectangle(0, 0, bitmap.Width, bitmap.Height);

                // Lock System.Drawing.Bitmap
                var bitmapData = bitmap.LockBits(sourceArea, ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

                try
                {
                    // Copy memory
                    if (description.Format == PixelFormat.R8G8B8A8_UNorm || description.Format == PixelFormat.R8G8B8A8_UNorm_SRgb)
                        CopyMemoryBGRA(bitmapData.Scan0, pixelBuffers[0].DataPointer, pixelBuffers[0].BufferStride);
                    else if (description.Format == PixelFormat.B8G8R8A8_UNorm || description.Format == PixelFormat.B8G8R8A8_UNorm_SRgb)
                        Utilities.CopyMemory(bitmapData.Scan0, pixelBuffers[0].DataPointer, pixelBuffers[0].BufferStride);
                    else
                        throw new NotSupportedException(string.Format("Pixel format [{0}] is not supported", description.Format));
                }
                finally
                {
                    bitmap.UnlockBits(bitmapData);
                }

                // Save
                bitmap.Save(imageStream, imageFormat);
            }
        }
Exemplo n.º 3
0
 public virtual void AlphaBlend(int x, int y, int width, int height,
         PixelBuffer bitmap, int srcX, int srcY, int srcWidth, int srcHeight,
         byte alpha)
 {
     if (null != AlphaBlendHandler)
         AlphaBlendHandler(x, y, width, height,
             bitmap, srcX, srcY, srcWidth, srcHeight, alpha);
 }
 private static void SaveFromMemory(PixelBuffer[] pixelBuffers, int count, ImageDescription description, Stream imageStream, Bitmap.CompressFormat imageFormat)
 {
     var colors = pixelBuffers[0].GetPixels<int>();
     using (var bitmap = Bitmap.CreateBitmap(colors, description.Width, description.Height, Bitmap.Config.Argb8888))
     {
         bitmap.Compress(imageFormat, 0, imageStream);
     }
 }
Exemplo n.º 5
0
        protected UISurface(string title, int x, int y, int width, int height, Guid uniqueID)
        {
            fTitle = title;
            fFrame = new RECT(x, y, width, height);
            fBackingBuffer = new PixelBuffer(width, height);
            fGraphDelegate = new GraphPortDelegate();
            fGraphDelegate.AddGraphPort(fBackingBuffer.GraphPort);

            fUniqueID = uniqueID;

            UISurface.gSurfaces.Add(uniqueID, this);
        }
Exemplo n.º 6
0
        public PassiveSpace(string title, RECT aframe)
            : base(title, aframe)
        {
            fBackingBuffer = new PixelBuffer(Frame.Width, aframe.Height);

            fWrappedGraphPort = new GraphPortDelegate();
            fWrappedGraphPort.AddGraphPort(fBackingBuffer.GraphPort);
            fWrappedGraphPort.AddGraphPort(base.GraphPort);

            // Add the channel for commands
            fSessionManager = new SessionManager();
            fControlChannel = new SpaceControlChannel(fSessionManager, fSessionManager.UniqueSessionName, this);
        }
        public MyTileTexture <byte> GetTerrainBlendTexture(MyPlanetMaterialBlendSettings settings)
        {
            MyTileTexture <byte> tex;

            string path     = settings.Texture;
            int    cellSize = settings.CellSize;

            if (!m_ditherTilesets.TryGetValue(path, out tex))
            {
                string fullPath = Path.Combine(MyFileSystem.ContentPath, path) + ".png";
                if (!File.Exists(fullPath))
                {
                    fullPath = Path.Combine(MyFileSystem.ContentPath, path) + ".dds";
                }

                SharpDXImage image = null;
                try
                {
                    image = SharpDXImage.Load(fullPath);
                }
                catch (Exception e)
                {
                    MyLog.Default.WriteLine(e.Message);
                }

                if (image == null)
                {
                    return(MyTileTexture <byte> .Default);
                }

                PixelBuffer buffer = image.GetPixelBuffer(0, 0, 0);

                Debug.Assert(buffer.Format == Format.R8_UNorm);

                if (buffer.Format != Format.R8_UNorm)
                {
                    return(MyTileTexture <byte> .Default);
                }

                tex = new MyTileTexture <byte>(buffer, cellSize);
                image.Dispose();
            }

            return(tex);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Ensures that the given <see cref="PixelBuffer"/> object is unbound.
        /// </summary>
        /// <param name="pbo">The <see cref="PixelBuffer"/> object to ensure is unbound.</param>
        public void UnbindPixelBuffer(PixelBuffer pbo)
        {
            if (pbo == null)
            {
                throw new ArgumentNullException(nameof(pbo));
            }

            if (PixelBufferHandle != pbo.Handle)
            {
                return;
            }

            GL.BindBuffer(BufferTarget.PixelUnpackBuffer, GLHandle.Zero);

            PixelBufferHandle        = GLHandle.Zero;
            PixelBuffer.BoundContext = null;
            PixelBuffer = null;
        }
Exemplo n.º 9
0
        private unsafe void DrawPixels(PixelBuffer pixelBuffer, SKCanvas canvas, SKPaint paint, Rectangle r, int x, int y)
        {
            if (!Monitor.IsEntered(_syncRoot))
            {
                throw new InvalidOperationException();
            }

            r.Offset(-x, -y);

            Rectangle bitmapRect = new Rectangle(0, 0, pixelBuffer.Width, pixelBuffer.Height);

            r.Intersect(bitmapRect);
            if (r.Width == 0 || r.Height == 0)
            {
                return;
            }
            canvas.DrawBitmap(pixelBuffer.Source, new SKPoint(r.X + x, r.Y + y), paint);
        }
Exemplo n.º 10
0
        public PixelBuffer Execute(int width, int height)
        {
            var pixelBuffer = new PixelBuffer(width, height);

            for (int j = height - 1; j >= 0; j--)
            {
                for (int i = 0; i < width; i++)
                {
                    var color = new ColorVector(
                        Convert.ToSingle(i) / Convert.ToSingle(width),
                        Convert.ToSingle(j) / Convert.ToSingle(height),
                        0.2f);
                    pixelBuffer.SetPixelColor(i, j, color);
                }
            }

            return(pixelBuffer);
        }
Exemplo n.º 11
0
        public override void BitBlt(int x, int y, PixelBuffer pixBuff)
        {
            // Create a buffer
            // It has to be big enough for the bitmap data, as well as the x,y, and command
            int dataSize = pixBuff.Pixels.Stride * pixBuff.Pixels.Height;
            BufferChunk chunk = new BufferChunk(dataSize + 128);

            // now put the basic command and simple components in
            chunk += SpaceControlChannel.SC_BitBlt;
            CodecUtils.Pack(chunk, x, y);
            CodecUtils.Pack(chunk, pixBuff.Pixels.Width, pixBuff.Pixels.Height);
            chunk += dataSize;

            // Finally, copy in the data
            chunk.CopyFrom(pixBuff.Pixels.Data, dataSize);

            PackCommand(chunk);
        }
        // Generalized bit block transfer

        // Can transfer from any device context to this one.
        public override void BitBlt(int x, int y, PixelBuffer pixBuff)
        {
            // Create a buffer
            // It has to be big enough for the bitmap data, as well as the x,y, and command
            int         dataSize = pixBuff.Pixels.Stride * pixBuff.Pixels.Height;
            BufferChunk chunk    = new BufferChunk(dataSize + 128);

            // now put the basic command and simple components in
            chunk += GDI32.EMR_BITBLT;
            Pack(chunk, x, y);
            Pack(chunk, pixBuff.Pixels.Width, pixBuff.Pixels.Height);
            chunk += dataSize;

            // Finally, copy in the data
            chunk.CopyFrom(pixBuff.Pixels.Data, dataSize);

            PackCommand(chunk);
        }
Exemplo n.º 13
0
        public void PixelBufferAssign()
        {
            tlog.Debug(tag, $"PixelBufferAssign START");

            using (PixelBuffer pixelBuffer = new PixelBuffer(100, 50, PixelFormat.BGR8888))
            {
                var testingTarget = pixelBuffer.Assign(pixelBuffer);
                Assert.IsNotNull(testingTarget, "Can't create success object PixelData");
                Assert.IsInstanceOf <PixelBuffer>(testingTarget, "Should be an instance of PixelData type.");

                var result = testingTarget.GetPixelFormat();
                Assert.AreEqual(PixelFormat.BGR8888, result, "Should be equal!");

                testingTarget.Dispose();
            }

            tlog.Debug(tag, $"PixelBufferAssign END (OK)");
        }
Exemplo n.º 14
0
        public void PixelBufferRotate()
        {
            tlog.Debug(tag, $"PixelBufferRotate START");

            using (Degree degree = new Degree(30))
            {
                var testingTarget = new PixelBuffer(100, 50, PixelFormat.BGR8888);
                Assert.IsNotNull(testingTarget, "Can't create success object PixelData");
                Assert.IsInstanceOf <PixelBuffer>(testingTarget, "Should be an instance of PixelData type.");

                var result = testingTarget.Rotate(degree);
                Assert.IsTrue(result);

                testingTarget.Dispose();
            }

            tlog.Debug(tag, $"PixelBufferRotate END (OK)");
        }
Exemplo n.º 15
0
        public PixelBuffer Execute(int width, int height)
        {
            var   pixelBuffer     = new PixelBuffer(width, height);
            float aperture        = 0.01f;
            var   lookFrom        = new Vector3(24.0f, 2.0f, 6.0f);
            var   lookAt          = Vector3.UnitY;
            float distanceToFocus = (lookFrom - lookAt).Length();
            var   camera          = new Camera(
                lookFrom,
                lookAt,
                Vector3.UnitY,
                15.0f,
                Convert.ToSingle(width) / Convert.ToSingle(height),
                aperture,
                distanceToFocus);

            var world = CreateRandomScene();

            for (int j = height - 1; j >= 0; j--)
            {
                for (int i = 0; i < width; i++)
                {
                    ColorVector color = new ColorVector(0.0f, 0.0f, 0.0f);
                    for (int sample = 0; sample < _numSamples; sample++)
                    {
                        float u = Convert.ToSingle(i + GetRandom()) / Convert.ToSingle(width);
                        float v = Convert.ToSingle(j + GetRandom()) / Convert.ToSingle(height);
                        var   r = camera.GetRay(u, v);

                        color += GetRayColor(r, world, 0);
                    }

                    color /= Convert.ToSingle(_numSamples);
                    color  = color.ApplyGamma2();

                    pixelBuffer.SetPixelColor(i, j, color);
                }

                Console.Write(".");
            }

            Console.WriteLine();
            return(pixelBuffer);
        }
Exemplo n.º 16
0
        private void onCaptureFinished(object sender, CaptureFinishedEventArgs e)
        {
            log.Debug(tag, $"onCaptureFinished() statue={e.Success} \n");

            if (sender is Capture)
            {
                log.Debug(tag, $"sender is Capture \n");
                PixelBuffer pixelBuffer = capture.GetCapturedBuffer();
                PixelData   pixelData   = PixelBuffer.Convert(pixelBuffer);
                var         url         = pixelData.Url;//capture.GetNativeImageSource().Url;
                capturedImage = new ImageView(url);
                log.Debug(tag, $"url={url} \n");

                capturedImage.Size     = new Size(510, 510);
                capturedImage.Position = new Position(10, 10);
                root.Add(capturedImage);
                done = false;
            }
        }
Exemplo n.º 17
0
        public void PaletteGenerateAsync()
        {
            tlog.Debug(tag, $"PaletteGenerateAsync START");

            try
            {
                using (PixelBuffer buffer = new PixelBuffer(2, 2, PixelFormat.A8))
                {
                    _ = Palette.GenerateAsync(buffer);
                }
            }
            catch (Exception e)
            {
                tlog.Debug(tag, e.Message.ToString());
                Assert.Fail("Caught Exception: Failed!");
            }

            tlog.Debug(tag, $"PaletteGenerateAsync END (OK)");
        }
Exemplo n.º 18
0
        private static void PrepareHeightMap8Bit(MyHeightmapFace map, PixelBuffer imageData)
        {
            int y = 0;

            while (y < map.Resolution)
            {
                int x = 0;
                while (true)
                {
                    if (x >= map.Resolution)
                    {
                        y++;
                        break;
                    }
                    map.SetValue(x, y, (ushort)(imageData.GetPixel <byte>(x, y) * 0x100));
                    x++;
                }
            }
        }
Exemplo n.º 19
0
        public void PixelBufferCrop()
        {
            tlog.Debug(tag, $"PixelBufferCrop START");

            var testingTarget = new PixelBuffer(100, 50, PixelFormat.BGR8888);

            Assert.IsNotNull(testingTarget, "Can't create success object PixelData");
            Assert.IsInstanceOf <PixelBuffer>(testingTarget, "Should be an instance of PixelData type.");

            Assert.AreEqual(100, testingTarget.GetWidth(), "Shoule be equal!");
            Assert.AreEqual(50, testingTarget.GetHeight(), "Shoule be equal!");

            testingTarget.Crop(150, 100, 50, 100);
            Assert.AreEqual(50, testingTarget.GetWidth(), "Shoule be equal!");
            Assert.AreEqual(100, testingTarget.GetHeight(), "Shoule be equal!");

            testingTarget.Dispose();
            tlog.Debug(tag, $"PixelBufferCrop END (OK)");
        }
Exemplo n.º 20
0
        private void LoadFromBitmap(Drawing.Bitmap sourceImage)
        {
            mSourceRect.Size = Interop.Convert(sourceImage.Size);

            Size newSize = GetOGLSize(sourceImage);

            // create a new bitmap of the size OpenGL expects, and copy the source image to it.
            Drawing.Bitmap   textureImage = new Drawing.Bitmap(newSize.Width, newSize.Height);
            Drawing.Graphics g            = Drawing.Graphics.FromImage(textureImage);

            g.Transform = new System.Drawing.Drawing2D.Matrix();
            g.Clear(Drawing.Color.FromArgb(0, 0, 0, 0));
            g.DrawImage(sourceImage, new Drawing.Rectangle(new Drawing.Point(0, 0), sourceImage.Size));
            g.Dispose();

            mTextureSize = Interop.Convert(textureImage.Size);

            mTexCoord = GetTextureCoords(mSourceRect);


            // Rectangle For Locking The Bitmap In Memory
            Rectangle rectangle = new Rectangle(0, 0, textureImage.Width, textureImage.Height);

            // Get The Bitmap's Pixel Data From The Locked Bitmap
            BitmapData bitmapData = textureImage.LockBits(Interop.Convert(rectangle),
                                                          ImageLockMode.ReadOnly, Drawing.Imaging.PixelFormat.Format32bppArgb);

            // use a pixelbuffer to do format conversion.
            PixelBuffer buffer = new PixelBuffer(PixelFormat.RGBA8888, mTextureSize,
                                                 bitmapData.Scan0, PixelFormat.BGRA8888, bitmapData.Stride);

            // Create The GL Texture object
            int textureID;

            GL.GenTextures(1, out textureID);
            AddTextureRef(textureID);

            WritePixels(buffer);

            textureImage.UnlockBits(bitmapData);                                 // Unlock The Pixel Data From Memory
            textureImage.Dispose();                                              // Dispose The Bitmap
        }
Exemplo n.º 21
0
        /// <summary>
        /// Binds the given <see cref="PixelBuffer"/> object to the <see cref="RenderContext"/>.
        /// </summary>
        /// <param name="pbo">The <see cref="PixelBuffer"/> object to bind.</param>
        public void BindPixelBuffer(PixelBuffer pbo)
        {
            if (pbo == null)
            {
                throw new ArgumentNullException(nameof(pbo));
            }

            pbo.EnsureUndisposed();

            if (_pixelBufferHandle == pbo.Handle)
            {
                return;
            }

            GL.BindBuffer(BufferTarget.PixelUnpackBuffer, pbo.Handle);

            _pixelBufferHandle        = pbo.Handle;
            _pixelBuffer              = pbo;
            _pixelBuffer.BoundContext = this;
        }
Exemplo n.º 22
0
    public SwapChain(byte chainSize, int bufferSize)
    {
        if (chainSize < 2)
        {
            throw new System.ArgumentException("Chain size must be 2 or higher");
        }

        buffers = new PixelBuffer[chainSize];

        for (int i = 0; i < chainSize; i++)
        {
            buffers[i] = new PixelBuffer(bufferSize);
        }

        writeCount = new int[bufferSize];

        readIndex  = 0;
        writeIndex = 1;
        swapIndex  = 1;
    }
Exemplo n.º 23
0
        /// <inheritdoc />
        public IHitable GetWorld()
        {
            var globe = PixelBuffer.FromFile(_globeImagePath);

            var list = new HitableList()
            {
                new Sphere(
                    new Vector3(0.0f, -1000.0f, 0.0f),
                    1000.0f,
                    new LambertianMaterial(new VectorNoiseTexture(VectorNoiseMode.Marble, 3.0f))),
                new Sphere(
                    new Vector3(0.0f, 2.0f, 0.0f),
                    2.0f,
                    new LambertianMaterial(new ImageTexture(globe))),
                new Sphere(new Vector3(0.0f, 7.0f, 0.0f), 2.0f, new DiffuseLight(new ColorTexture(4.0f, 4.0f, 4.0f))),
                new XyRect(3.0f, 5.0f, 1.0f, 3.0f, -2.0f, new DiffuseLight(new ColorTexture(4.0f, 4.0f, 4.0f)))
            };

            return(new BvhNode(list, 0.0f, 1.0f));
        }
Exemplo n.º 24
0
        public static PixelBuffer Render(RendererParameters textParameters, ref EmbeddedItemInfo[] embeddedItemLayout)
        {
            int count  = 0;
            int length = 0;

            global::System.IntPtr returnItem = IntPtr.Zero;
            PixelBuffer           ret        = new PixelBuffer(Interop.TextUtils.TextUtils_Render(RendererParameters.getCPtr(textParameters), ref returnItem, ref count, ref length), true);

            embeddedItemLayout = new EmbeddedItemInfo[count];
            for (int i = 0; i < count; i++)
            {
                IntPtr p = new IntPtr((returnItem.ToInt32() + i * length));
                embeddedItemLayout[i] = new EmbeddedItemInfo(p, false);
            }
            if (NDalicPINVOKE.SWIGPendingException.Pending)
            {
                throw NDalicPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Exemplo n.º 25
0
            public Image(BinaryReader bin)
            {
                offset   = bin.ReadUInt32();
                unknown4 = bin.ReadBytes(12);

                //Read actual image data
                long co = bin.BaseStream.Position;

                bin.BaseStream.Seek(offset, SeekOrigin.Begin);

                pixelBuffer = new PixelBuffer(bin);
                clutBuffer  = null;

                if (pixelBuffer.HasClut)
                {
                    clutBuffer = new ClutBuffer(bin);
                }

                bin.BaseStream.Seek(co, SeekOrigin.Begin);
            }
Exemplo n.º 26
0
        public static void Main(string[] args)
        {
            int       numThreads    = Environment.ProcessorCount / 2;
            const int RayTraceDepth = 50;
            const int NumSamples    = 1000;
            var       renderConfig  = new RenderConfig(numThreads, RayTraceDepth, NumSamples);

            string globeImagePath = Path.Combine(OutputDirectory, "globetex.jpg");
            // var scene = new ManySpheresScene();
            // var scene = new NoiseSpheresScene();
            // var scene = new ImageTextureScene(globeImagePath);
            // var scene = new LightsScene(globeImagePath);
            var scene = new CornellBoxScene();
            // var scene = new CornellBoxWithSmokeScene();
            IRenderer renderer    = new PerPixelRenderer();
            var       pixelBuffer = new PixelBuffer(Width, Height);

            string name = scene.GetType().Name.ToLowerInvariant();

            Console.WriteLine($"Executing {name} at resolution ({pixelBuffer.Width},{pixelBuffer.Height})");
            Console.WriteLine($"  Num Threads   = {numThreads}");
            Console.WriteLine($"  RayTraceDepth = {RayTraceDepth}");
            Console.WriteLine($"  Num Samples   = {NumSamples}");

            var sw           = Stopwatch.StartNew();
            var rendererData = renderer.Render(pixelBuffer, scene, renderConfig);

            sw.Stop();
            Console.WriteLine();
            Console.WriteLine($"Render complete: {sw.ElapsedMilliseconds}ms");
            Console.WriteLine($"Total Pixel Color Time: {rendererData.GetTotalPixelColorMilliseconds()}ms");
            Console.WriteLine($"Per Pixel Avg Time:     {rendererData.GetAveragePixelColorMilliseconds()}ms");

            string outputPath = Path.Combine(OutputDirectory, $"{name}.png");

            Console.WriteLine($"Saving image to {outputPath}");
            pixelBuffer.SaveAsFile(outputPath);


            // RunExecutors();
        }
Exemplo n.º 27
0
        private void VerifyCopyResult(PixelBuffer result, PixelBuffer srcBuffer, Point destPt)
        {
            for (int j = 0; j < srcBuffer.Height; j++)
            {
                for (int i = 0; i < srcBuffer.Width; i++)
                {
                    int x = i + destPt.X;
                    int y = j + destPt.Y;

                    var resultPx = result.GetPixel(x, y);
                    var srcPx    = srcBuffer.GetPixel(i, j);

                    if (resultPx.A == 0 && srcPx.A == 0)
                    {
                        continue;
                    }

                    Assert.AreEqual(srcPx, resultPx);
                }
            }
        }
Exemplo n.º 28
0
        public void ColorCutQuantizerFromBitmapWithMaxColorLessThan1()
        {
            tlog.Debug(tag, $"ColorCutQuantizerFromBitmapWithMaxColorLessThan1 START");

            using (PixelBuffer pixelBuffer = new PixelBuffer(100, 200, PixelFormat.RGBA8888))
            {
                using (Rectangle region = new Rectangle())
                {
                    try
                    {
                        ColorCutQuantizer.FromBitmap(pixelBuffer, region, 0);
                    }
                    catch (ArgumentNullException e)
                    {
                        tlog.Debug(tag, e.Message.ToString());
                        tlog.Debug(tag, $"ColorCutQuantizerFromBitmapWithMaxColorLessThan1 END (OK)");
                        Assert.Pass("Caught ArgumentNullException : Passed!");
                    }
                }
            }
        }
Exemplo n.º 29
0
        public unsafe void Render(DrawingContext drawingContext)
        {
            lock (_syncRoot)
            {
                if (ViewPixels != null)
                {
                    WriteableBitmap surface;
                    surface = GetSurface(ViewPixels);
                    drawingContext.DrawImage(surface, new Rect(0, 0, surface.Width, surface.Height));

                    PixelBuffer pixelBuffer = PopupPixels;
                    if (pixelBuffer == null)
                    {
                        return;
                    }

                    surface = GetSurface(pixelBuffer);
                    drawingContext.DrawImage(surface, new Rect(_popupBounds.X, _popupBounds.Y, surface.Width, surface.Height));
                }
            }
        }
Exemplo n.º 30
0
        public void PaletteGenerate()
        {
            tlog.Debug(tag, $"PaletteGenerate START");

            try
            {
                using (PixelBuffer buffer = ImageLoader.LoadImageFromFile(image_path))
                {
                    var testingTarget = Palette.Generate(buffer);
                    Assert.IsNotNull(testingTarget, "Can't create success object Palette");
                    Assert.IsInstanceOf <Palette>(testingTarget, "Should be an instance of Palette type.");
                }
            }
            catch (Exception e)
            {
                tlog.Debug(tag, e.Message.ToString());
                Assert.Fail("Caught Exception: Failed!");
            }

            tlog.Debug(tag, $"PaletteGenerate END (OK)");
        }
Exemplo n.º 31
0
        public void PixelBufferApplyGaussianBlur()
        {
            tlog.Debug(tag, $"PixelBufferApplyGaussianBlur START");

            var testingTarget = new PixelBuffer(100, 50, PixelFormat.BGR8888);

            Assert.IsNotNull(testingTarget, "Can't create success object PixelData");
            Assert.IsInstanceOf <PixelBuffer>(testingTarget, "Should be an instance of PixelData type.");

            try
            {
                testingTarget.ApplyGaussianBlur(1.0f);
            }
            catch (Exception e)
            {
                Assert.Fail("Fail!");
            }

            testingTarget.Dispose();
            tlog.Debug(tag, $"PixelBufferApplyGaussianBlur END (OK)");
        }
Exemplo n.º 32
0
        private MyHeightmapFace GetHeightMap(string folderName, string faceName, MyModContext context)
        {
            string          path = this.GetPath(folderName, faceName, context);
            MyHeightmapFace map  = null;

            try
            {
                using (Image image = this.LoadTexture(path))
                {
                    if (image == null)
                    {
                        object[] args = new object[] { path };
                        MyLog.Default.Error("Could not load texture {0}, no suitable format found. ", args);
                    }
                    else
                    {
                        PixelBuffer imageData = image.GetPixelBuffer(0, 0, 0);
                        map = new MyHeightmapFace(imageData.Height);
                        if (imageData.Format == Format.R16_UNorm)
                        {
                            PrepareHeightMap(map, imageData);
                        }
                        else if (imageData.Format == Format.R8_UNorm)
                        {
                            PrepareHeightMap8Bit(map, imageData);
                        }
                        else
                        {
                            MyLog.Default.Error($"Heighmap texture {path}: Invalid format {imageData.Format} (expecting R16_UNorm or R8_UNorm).", Array.Empty <object>());
                        }
                        image.Dispose();
                    }
                }
            }
            catch (Exception exception)
            {
                MyLog.Default.WriteLine(exception.Message);
            }
            return(map);
        }
Exemplo n.º 33
0
        public PixelBuffer Execute(int width, int height)
        {
            var pixelBuffer     = new PixelBuffer(width, height);
            var lowerLeftCorner = new Vector3(-2.0f, -1.0f, -1.0f);
            var horizontal      = new Vector3(4.0f, 0.0f, 0.0f);
            var vertical        = new Vector3(0.0f, 2.0f, 0.0f);
            var origin          = Vector3.Zero;

            for (int j = height - 1; j >= 0; j--)
            {
                for (int i = 0; i < width; i++)
                {
                    float u     = Convert.ToSingle(i) / Convert.ToSingle(width);
                    float v     = Convert.ToSingle(j) / Convert.ToSingle(height);
                    var   r     = new Ray(origin, lowerLeftCorner + (u * horizontal) + (v * vertical));
                    var   color = GetRayColor(r);
                    pixelBuffer.SetPixelColor(i, j, color);
                }
            }

            return(pixelBuffer);
        }
Exemplo n.º 34
0
        public override PixelBuffer ReadPixels(PixelFormat format, Geometry.Rectangle rect)
        {
            BitmapData data = mImage.LockBits(Interop.Convert(rect), ImageLockMode.ReadOnly,
                                              System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            if (format == PixelFormat.Any)
            {
                format = PixelFormat.BGRA8888;
            }

            PixelBuffer buffer = new PixelBuffer(format, rect.Size);

            byte[] bytes = new byte[4 * rect.Width * rect.Height];

            Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);

            mImage.UnlockBits(data);

            buffer.SetData(bytes, PixelFormat.BGRA8888);

            return(buffer);
        }
Exemplo n.º 35
0
        public void Draw(CefPaintEventArgs e)
        {
            lock (_syncRoot)
            {
                PixelBuffer pixelBuffer;
                if (e.PaintElementType == CefPaintElementType.View)
                {
                    if (ViewPixels == null || ViewPixels.Width != e.Width || ViewPixels.Height != e.Height)
                    {
                        if (ViewPixels != null)
                        {
                            ViewPixels.Dispose();
                        }

                        ViewPixels = new PixelBuffer(e.Width, e.Height);
                    }
                    pixelBuffer = ViewPixels;
                }
                else if (e.PaintElementType == CefPaintElementType.Popup)
                {
                    if (PopupPixels == null || PopupPixels.Width != e.Width || PopupPixels.Height != e.Height)
                    {
                        if (PopupPixels != null)
                        {
                            PopupPixels.Dispose();
                        }
                        PopupPixels = new PixelBuffer(e.Width, e.Height);
                    }
                    pixelBuffer = PopupPixels;
                }
                else
                {
                    return;
                }

                Marshal.Copy(e.Buffer, pixelBuffer.DIB, 0, pixelBuffer.Size);
                pixelBuffer.AddDirtyRects(e.DirtyRects);
            }
        }
Exemplo n.º 36
0
        public void PaletteGenerateAsyncWithRectangle()
        {
            tlog.Debug(tag, $"PaletteGenerateAsyncWithRectangle START");

            try
            {
                using (PixelBuffer buffer = new PixelBuffer(2, 2, PixelFormat.A8))
                {
                    using (Rectangle region = new Rectangle(1, 1, 1, 1))
                    {
                        _ = Palette.GenerateAsync(buffer, region);
                    }
                }
            }
            catch (Exception e)
            {
                tlog.Debug(tag, e.Message.ToString());
                Assert.Fail("Caught Exception: Failed!");
            }

            tlog.Debug(tag, $"PaletteGenerateAsyncWithRectangle END (OK)");
        }
Exemplo n.º 37
0
        private unsafe void DrawPixels(PixelBuffer pixelBuffer, Graphics g, Rectangle r, int x, int y)
        {
            if (!Monitor.IsEntered(_syncRoot))
            {
                throw new InvalidOperationException();
            }

            r.Offset(-x, -y);

            Rectangle bitmapRect = new Rectangle(0, 0, pixelBuffer.Width, pixelBuffer.Height);

            r.Intersect(bitmapRect);
            if (r.Width == 0 || r.Height == 0)
            {
                return;
            }

            //g.DrawImage(pixelBuffer.Source, new Point(r.X + x, r.Y + y));

            IntPtr hdc = g.GetHdc();

            try
            {
                BitmapData DIB = pixelBuffer.Source.LockBits(new Rectangle(0, 0, pixelBuffer.Width, pixelBuffer.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
                try
                {
                    NativeMethods.SetDIBitsToDevice(hdc, r.X + x, r.Y + y, r.Width, r.Height, r.X, bitmapRect.Height, r.Bottom, bitmapRect.Height, DIB.Scan0, ref pixelBuffer.DIBInfo, 0);
                }
                finally
                {
                    pixelBuffer.Source.UnlockBits(DIB);
                }
            }
            finally
            {
                g.ReleaseHdc(hdc);
            }
        }
Exemplo n.º 38
0
        public static void SaveFromMemory(PixelBuffer[] pixelBuffers, int count, ImageDescription description, System.IO.Stream imageStream)
        {
            var stream = new BinarySerializationWriter(imageStream);

            // Write magic code
            stream.Write(MagicCode);

            // Write image header
            imageDescriptionSerializer.Serialize(ref description, ArchiveMode.Serialize, stream);

            // Write total size
            int totalSize = 0;
            foreach (var pixelBuffer in pixelBuffers)
                totalSize += pixelBuffer.BufferStride;

            stream.Write(totalSize);

            // Write buffers contiguously
            foreach (var pixelBuffer in pixelBuffers)
            {
                stream.Serialize(pixelBuffer.DataPointer, pixelBuffer.BufferStride);
            }
        }
Exemplo n.º 39
0
 public virtual void OnCopyPixels(int x, int y, int width, int height, PixelBuffer pixBuff)
 {
     if (null != OnCopyPixelsEvent)
         OnCopyPixelsEvent(x, y, width, height, pixBuff);
 }
Exemplo n.º 40
0
 public virtual PixelBuffer CreateBitmap(int width, int height)
 {
     PixelBuffer newOne = new PixelBuffer(width, height);
     
     return newOne;
 }
Exemplo n.º 41
0
	// Generalized bit block transfer
	// Can transfer from any device context to this one.
    public virtual void BitBlt(int x, int y, PixelBuffer bitmap)
    {
        bool retValue = BitBlt(x, y, bitmap.Width, bitmap.Height, 
            bitmap.DCHandle, 0, 0, TernaryRasterOps.SRCCOPY);
    }
Exemplo n.º 42
0
 public virtual void DrawBitmap(PixelBuffer img, Rectangle srcRect, Rectangle dstRect)
 {
     AlphaBlend(dstRect.Left, dstRect.Top, dstRect.Width, dstRect.Height,
             img.DCHandle, srcRect.Left, srcRect.Top, srcRect.Width, srcRect.Height,
             img.Alpha);
 }
Exemplo n.º 43
0
 /// <summary>
 /// DrawImage, will draw the supplied image graphic on the screen.  It will use
 /// the Image's frame and size to determine where to display it.
 /// </summary>
 /// <param name="img"></param>
 public virtual void DrawBitmap(PixelBuffer img, Point origin)
 {
     DrawBitmap(img, new Rectangle(0, 0, img.Width, img.Height),
         new Rectangle(origin.x, origin.y, img.Width, img.Height));
 }
Exemplo n.º 44
0
 public static void SavePngFromMemory(PixelBuffer[] pixelBuffers, int count, ImageDescription description, Stream imageStream)
 {
     SaveFromMemory(pixelBuffers, count, description, imageStream, Bitmap.CompressFormat.Png);
 }
Exemplo n.º 45
0
        /// <summary>
        /// Saves this instance to a stream.
        /// </summary>
        /// <param name="pixelBuffers">The buffers to save.</param>
        /// <param name="count">The number of buffers to save.</param>
        /// <param name="description">Global description of the buffer.</param>
        /// <param name="imageStream">The destination stream.</param>
        /// <param name="fileType">Specify the output format.</param>
        /// <remarks>This method support the following format: <c>dds, bmp, jpg, png, gif, tiff, wmp, tga</c>.</remarks>
        internal static void Save(PixelBuffer[] pixelBuffers, int count, ImageDescription description, Stream imageStream, ImageFileType fileType)
        {
            foreach (var loadSaveDelegate in loadSaveDelegates)
            {
                if (loadSaveDelegate.FileType == fileType)
                {
                    loadSaveDelegate.Save(pixelBuffers, count, description, imageStream);
                    return;
                }

            }
            throw new NotSupportedException("This file format is not yet implemented.");
        }
 private static void PrepareHeightMap8Bit(MyHeightmapFace map, PixelBuffer imageData)
 {
     for (int y = 0; y < map.Resolution; y++)
     {
         for (int x = 0; x < map.Resolution; x++)
         {
             map.SetValue(x, y, (ushort)(imageData.GetPixel<byte>(x, y) * 256));
         }
     }
 }
Exemplo n.º 47
0
 private static void SaveToWICMemory(PixelBuffer[] pixelBuffer, int count, WICFlags flags, ImageFileType fileType, Stream stream)
 {
     if (count > 1)
         EncodeMultiframe(pixelBuffer, count, flags, GetContainerFormatFromFileType(fileType), stream);
     else
         EncodeSingleFrame(pixelBuffer[0], flags, GetContainerFormatFromFileType(fileType), stream);
 }
Exemplo n.º 48
0
        private bool SetShaderParameters(DeviceContext deviceContext, Matrix worldMatrix, Matrix viewMatrix, Matrix projectionMatrix, ShaderResourceView texture, Vector4 pixelColor)
        {
            try
            {
                DataStream mappedResource;

                #region Matrix Constant Buffer
                // Transpose the matrices to prepare them for shader.
                worldMatrix.Transpose();
                viewMatrix.Transpose();
                projectionMatrix.Transpose();

                // Lock the constant buffer so it can be written to.
                deviceContext.MapSubresource(ConstantMatrixBuffer, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None, out mappedResource);

                // Copy the matrices into the constant buffer.
                var matrixBuffer = new MatrixBuffer()
                {
                    world = worldMatrix,
                    view = viewMatrix,
                    projection = projectionMatrix
                };

                mappedResource.Write(matrixBuffer);

                // Unlock the constant buffer.
                deviceContext.UnmapSubresource(ConstantMatrixBuffer, 0);

                // Set the position of the constant buffer in the vertex shader.
                var bufferNumber = 0;

                // Finally set the constant buffer in the vertex shader with the updated values.
                deviceContext.VertexShader.SetConstantBuffer(bufferNumber, ConstantMatrixBuffer);

                // Set shader resource in the pixel shader.
                deviceContext.PixelShader.SetShaderResource(0, texture);
                #endregion

                #region Pixel Constant Shader
                // Lock the pixel constant buffer so it can be written to.
                deviceContext.MapSubresource(ConstantPixelBuffer, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None, out mappedResource);

                // Copy the matrices into the constant buffer.
                var pixelBuffer = new PixelBuffer()
                {
                    pixelColor = pixelColor
                };

                mappedResource.Write(pixelBuffer);

                // Unlock the constant buffer.
                deviceContext.UnmapSubresource(ConstantPixelBuffer, 0);

                // Set the position of the constant buffer in the vertex shader.
                bufferNumber = 0;

                // Finally set the constant buffer in the vertex shader with the updated values.
                deviceContext.PixelShader.SetConstantBuffer(bufferNumber, ConstantPixelBuffer);
                #endregion

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
Exemplo n.º 49
0
 public virtual void OnAlphaBlend(int x, int y, int width, int height,
         PixelBuffer bitmap, int srcX, int srcY, int srcWidth, int srcHeight,
         byte alpha)
 {
     if (null != OnAlphaBlendEvent)
         OnAlphaBlendEvent(x, y, width, height,
             bitmap, srcX, srcY, srcWidth, srcHeight, alpha);
 }
Exemplo n.º 50
0
 public static void SaveWmpFromMemory(PixelBuffer[] pixelBuffers, int count, ImageDescription description, Stream imageStream)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 51
0
 public virtual void ScaleBitmap(PixelBuffer aBitmap, RECT aFrame)
 {
     AlphaBlend(aFrame.Left, aFrame.Top, aFrame.Width, aFrame.Height,
         aBitmap, 0, 0, aBitmap.Width, aBitmap.Height, aBitmap.Alpha);
 }
Exemplo n.º 52
0
        public void DisplayUpdateHandler(uint sessionId, int sample)
        {
            if (Session.IsPaused()) return;
            // after first 10 frames have been rendered only update every third.
            if (sample > 10 && sample < (Settings.Samples-2) && sample % 3 != 0) return;
            if (CancelRender) return;
            if (State != State.Rendering) return;
            lock (DisplayLock)
            {
                if (Session.Scene.TryLock())
                {
                    // copy display buffer data into ccycles pixel buffer
                    Session.DrawNogl(RenderDimension.Width, RenderDimension.Height);
                    // copy stuff into renderwindow dib
                    using (var channel = RenderWindow.OpenChannel(RenderWindow.StandardChannels.RGBA))
                    {
                        if (CancelRender) return;
                        if (channel != null)
                        {
                            if (CancelRender) return;
                            var pixelbuffer = new PixelBuffer(CSycles.session_get_buffer(Client.Id, sessionId));
                            var size = RenderDimension;
                            var rect = new Rectangle(0, 0, RenderDimension.Width, RenderDimension.Height);
                            if (CancelRender) return;
                            channel.SetValues(rect, size, pixelbuffer);
                        }
                    }
                    SaveRenderedBuffer(sample);
                    //PassRendered?.Invoke(this, new PassRenderedEventArgs(sample, View));

                    if(CancelRender || sample >= maxSamples) Session.Cancel("done");

                    Session.Scene.Unlock();
                    //sdd.WriteLine(string.Format("display update, sample {0}", sample));
                    // now signal whoever is interested
                }
            }
        }
Exemplo n.º 53
0
 private static void EncodeSingleFrame( PixelBuffer pixelBuffer, WICFlags flags, Guid guidContainerFormat, Stream stream )
 {
     using (var encoder = new BitmapEncoder(Factory, guidContainerFormat, stream))
     {
         using (var frame = new BitmapFrameEncode(encoder))
         {
             if (guidContainerFormat == ContainerFormatGuids.Bmp)
             {
                 try
                 {
                     frame.Options.Set("EnableV5Header32bppBGRA", true);
                 }
                 catch
                 {
                 }
             }
             EncodeImage(pixelBuffer, flags, frame);
             encoder.Commit();
         }
     }
 }
 public static void SavePngFromMemory(PixelBuffer[] pixelBuffers, int count, ImageDescription description, Stream imageStream)
 {
     WICHelper.SavePngToWICMemory(pixelBuffers, count, description, imageStream);
 }
Exemplo n.º 55
0
        /// <summary>
        /// Allocates PixelBuffers 
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="pixelSize"></param>
        /// <param name="imageDesc"></param>
        /// <param name="pitchFlags"></param>
        /// <param name="output"></param>
        private static unsafe void SetupImageArray(IntPtr buffer, int pixelSize, int rowStride, ImageDescription imageDesc, PitchFlags pitchFlags, PixelBuffer[] output)
        {
            int index = 0;
            var pixels = (byte*)buffer;
            for (uint item = 0; item < imageDesc.ArraySize; ++item)
            {
                int w = imageDesc.Width;
                int h = imageDesc.Height;
                int d = imageDesc.Depth;

                for (uint level = 0; level < imageDesc.MipLevels; ++level)
                {
                    int rowPitch, slicePitch;
                    int widthPacked;
                    int heightPacked;
                    ComputePitch(imageDesc.Format, w, h, out rowPitch, out slicePitch, out widthPacked, out heightPacked, pitchFlags);

                    if (rowStride > 0)
                    {
                        // Check that stride is ok
                        if (rowStride < rowPitch)
                            throw new InvalidOperationException(string.Format("Invalid stride [{0}]. Value can't be lower than actual stride [{1}]", rowStride, rowPitch));

                        if (widthPacked != w || heightPacked != h)
                            throw new InvalidOperationException("Custom strides is not supported with packed PixelFormats");

                        // Override row pitch
                        rowPitch = rowStride;

                        // Recalculate slice pitch
                        slicePitch = rowStride * h;
                    }

                    for (uint zSlice = 0; zSlice < d; ++zSlice)
                    {
                        // We use the same memory organization that Direct3D 11 needs for D3D11_SUBRESOURCE_DATA
                        // with all slices of a given miplevel being continuous in memory
                        output[index] = new PixelBuffer(w, h, imageDesc.Format, rowPitch, slicePitch, (IntPtr)pixels);
                        ++index;

                        pixels += slicePitch;
                    }

                    if (h > 1)
                        h >>= 1;

                    if (w > 1)
                        w >>= 1;

                    if (d > 1)
                        d >>= 1;
                }
            }
        }
Exemplo n.º 56
0
        //-------------------------------------------------------------------------------------
        // Encodes an image array
        //-------------------------------------------------------------------------------------
        private static void EncodeMultiframe( PixelBuffer[] images, int count, WICFlags flags, Guid guidContainerFormat, Stream stream )
        {
            if ( images.Length < 2 )
                throw new ArgumentException("Cannot encode to multiple frame. Image doesn't have multiple frame");

            using (var encoder = new BitmapEncoder(Factory, guidContainerFormat))
            {
                using (var eInfo = encoder.EncoderInfo)
                {
                    if (!eInfo.IsMultiframeSupported)
                        throw new NotSupportedException("Cannot encode to multiple frame. Format is not supporting multiple frame");
                }

                encoder.Initialize(stream);

                for (int i = 0; i < Math.Min(images.Length, count); i++)
                {
                    var pixelBuffer = images[i];
                    using (var frame = new BitmapFrameEncode(encoder))
                        EncodeImage(pixelBuffer, flags, frame);
                }

                encoder.Commit();
            }
        }
        private static void PrepareHeightMap(MyHeightmapFace map, PixelBuffer imageData)
        {
            IntPtr mapData = imageData.DataPointer;
            var rowStride = imageData.RowStride;

            for (int y = 0; y < map.Resolution; y++)
            {
                Utilities.Read(mapData, map.Data, map.GetRowStart(y), imageData.Width);
                //imageData.GetPixels<ushort>(map.Data, y, map.GetRowStart(y), imageData.Width); this has a bug, see sharpdx source and be amused
                mapData += rowStride;
            }
        }
Exemplo n.º 58
0
 public static void SaveTiffToWICMemory(PixelBuffer[] pixelBuffers, int count, ImageDescription description, Stream imageStream)
 {
     SaveToWICMemory(pixelBuffers, count, WICFlags.AllFrames, ImageFileType.Tiff, imageStream);
 }
        private unsafe void ReadChannelsFromImage(byte[][] streams, PixelBuffer buffer)
        {
            byte* data = (byte*)buffer.DataPointer.ToPointer();

            int dim = buffer.Width;

            for (int i = 0; i < 4; ++i)
            {
                if (streams[i] != null)
                {
                    int j = 0, k = dim + 3;
                    for (int y = 0; y < dim; y++)
                    {
                        for (int x = 0; x < dim; x++)
                        {
                            streams[i][k] = data[j * 4 + i];
                            ++j;
                            ++k;
                        }
                        k += 2;
                    }
                }
            }
        }
Exemplo n.º 60
0
 public static void SaveWmpToWICMemory(PixelBuffer[] pixelBuffers, int count, ImageDescription description, Stream imageStream)
 {
     SaveToWICMemory(pixelBuffers, 1, WICFlags.None, ImageFileType.Wmp, imageStream);
 }