Beispiel #1
0
        public IActionResult GetBarcode(string data)
        {
            _logger.LogInformation("GetBarcode " + data);

            System.IO.File.WriteAllText(Environment.CurrentDirectory + @"/mydata/" + "file_" + DateTime.Now.Ticks + ".txt", data);

            var cachedString = _distributedCache.GetString("TEST");

            if (string.IsNullOrEmpty(cachedString))
            {
                _distributedCache.SetString("TEST", "somevaluetocache");
                _logger.LogInformation("Was not found, ... but now set.");
            }
            else
            {
                _logger.LogInformation("Yeah, ... was found : " + cachedString);
            }

            var barcode  = Code128Encoder.Encode(data, true);
            var renderer = new ImageRenderer();
            var stream   = new MemoryStream();

            renderer.Render(barcode, stream);

            return(File(stream.ToArray(), "image/png"));
        }
        public void PlanarRenderTest()
        {
            var plane = new PlaneNoiseMapBuilder();

            plane.SetBounds(-1, 1, -1, 1);
            plane.SetDestSize(256, 256);
            plane.SourceModule   = module;
            plane.DestNoiseMap   = noiseMap;
            plane.EnableSeamless = true;
            plane.Build();

            renderer.SourceNoiseMap   = noiseMap;
            renderer.DestinationImage = textureImage;
            renderer.Render();

            // TODO: Add some asserts
        }
        public void Render_Ean13_IncludeContentAsText()
        {
            var      renderer = new ImageRenderer(imageFormat: ImageFormat.Png, includeEanContentAsText: true);
            IBarcode barcode  = EanEncoder.Encode("978020137962");

            using Stream stream = File.OpenWrite(@"d:\temp\ean-test.png");
            renderer.Render(barcode, stream);
        }
        public IActionResult GetBarcode(string data)
        {
            var barcode  = Code128Encoder.Encode(data, true);
            var renderer = new ImageRenderer();
            var stream   = new MemoryStream();

            renderer.Render(barcode, stream);

            return(File(stream.ToArray(), "image/png"));
        }
Beispiel #5
0
        public static void Main(string[] args)
        {
            // The noise source - a simple Perlin noise generator will do for this sample
            var noiseSource = new Perlin
            {
                Seed = new Random().Next()
            };

            // Create a new, empty, noise map and initialize a new planar noise map builder with it
            var noiseMap        = new NoiseMap();
            var noiseMapBuilder = new PlaneNoiseMapBuilder
            {
                DestNoiseMap = noiseMap,
                SourceModule = noiseSource
            };

            // Set the size of the noise map
            noiseMapBuilder.SetDestSize(1280, 720);

            // Set the bounds of the noise mpa builder
            // These are the coordinates in the noise source from which noise values will be sampled
            noiseMapBuilder.SetBounds(-3, 3, -2, 2);

            // Build the noise map - samples values from the noise module above,
            // using the bounds coordinates we have passed in the builder
            noiseMapBuilder.Build();

            // Create a new image and image renderer
            var image    = new Image();
            var renderer = new ImageRenderer
            {
                SourceNoiseMap   = noiseMap,
                DestinationImage = image
            };

            // The renderer needs to know how to map noise values to colors.
            // In this case, we use one of the predefined gradients, specifically the terrain gradient,
            // which maps lower noise values to blues and greens and higher values to brouns and whites.
            // This simulates the look of a map with water, grass and vegetation, dirt and mountains.
            renderer.BuildTerrainGradient();

            // Before rendering the image, we could set various parameters on the renderer,
            // such as the position and color of the light source.
            // But we aren't going to bother for this sample.

            // Finally, render the image
            renderer.Render();

            // Finally, save the rendered image as a PNG in the current directory
            using (var fs = File.OpenWrite("NoiseMap.png"))
            {
                image.SaveGdiBitmap(fs, ImageFormat.Png);
            }
        }
        public static Bitmap RenderLayer(ImageGraphic layer, int dstWidth, int dstHeight)
        {
            Bitmap    bitmap     = new Bitmap(dstWidth, dstHeight);
            Rectangle clientArea = new Rectangle(0, 0, dstWidth, dstHeight);

            BitmapData bitmapData    = LockBitmap(bitmap);
            int        bytesPerPixel = 4;

            ImageRenderer.Render(layer, bitmapData.Scan0, bitmapData.Width, bytesPerPixel, clientArea);
            bitmap.UnlockBits(bitmapData);
            return(bitmap);
        }
        public void Render_PassNullAsBarcode_ShouldThrowException()
        {
            // Arrange
            var renderer = new ImageRenderer();
            var stream   = new MemoryStream();

            // Act
            Action action = () => renderer.Render(null, stream);

            // Assert
            action.Should().Throw <ArgumentNullException>()
            .And.ParamName.Should().Be("barcode");
        }
        public void Render_PassNullAsOutputStream_ShouldThrowException()
        {
            // Arrange
            var renderer    = new ImageRenderer();
            var barcodeMock = new Mock <IBarcode>();

            // Act
            Action action = () => renderer.Render(barcodeMock.Object, null);

            // Assert
            action.Should().Throw <ArgumentNullException>()
            .And.ParamName.Should().Be("outputStream");
        }
        private async Task <string> Publish(string html)
        {
            _codeFormatter = Substitute.For <ICodeFormatter>();
            _codeFormatter.FormatAsync(Arg.Any <string>(), Arg.Any <string>()).Returns(x => Task.FromResult((string)x[1]));

            _imageProcessor = Substitute.For <IImageProcessor>();
            _imageProcessor.Minimize(Arg.Any <string>()).Returns("minImage");

            _processor = new HtmlProcessor(_codeFormatter, _imageProcessor);
            var renderer = new ImageRenderer("the-post");
            var result   = renderer.Render(html);

            return(await _processor.ProcessAsync(result.Html));
        }
Beispiel #10
0
        /// <summary>
        /// Gets the field value.
        ///
        /// </summary>
        /// <param name="args">The arguments.</param><contract><requires name="args" condition="none"/></contract>
        public new void Process(RenderFieldArgs args)
        {
            if (args.FieldTypeKey != "image with cropping")
            {
                return;
            }
            ImageRenderer renderer = CreateRenderer();

            renderer.Item      = args.Item;
            renderer.FieldName = args.FieldName;

            XmlValue xmlValue = new XmlValue(args.FieldValue, "image");
            string   width    = xmlValue.GetAttribute("width");
            string   height   = xmlValue.GetAttribute("height");

            if (string.IsNullOrWhiteSpace(width) || string.IsNullOrWhiteSpace(height))
            {
                string cropRegion = xmlValue.GetAttribute("cropregion");
                try
                {
                    var coordinates = CustomMediaManager.ConvertToIntArray(cropRegion);
                    if ((coordinates[2] - coordinates[0] + coordinates[3] + coordinates[1]) > 0)
                    {
                        xmlValue.SetAttribute("width", (coordinates[2] - coordinates[0]).ToString());
                        xmlValue.SetAttribute("height", (coordinates[3] - coordinates[1]).ToString());
                        renderer.FieldValue = xmlValue.ToString();
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex.Message, ex, this);
                }
            }
            if (renderer.FieldValue == null)
            {
                renderer.FieldValue = args.FieldValue;
            }

            renderer.Parameters = args.Parameters;

            args.WebEditParameters.AddRange(args.Parameters);
            RenderFieldResult renderFieldResult = renderer.Render();

            args.Result.FirstPart             = renderFieldResult.FirstPart;
            args.Result.LastPart              = renderFieldResult.LastPart;
            args.DisableWebEditContentEditing = true;
            args.DisableWebEditFieldWrapping  = true;
            args.WebEditClick = "return Sitecore.WebEdit.editControl($JavascriptParameters, 'webedit:chooseimage')";
        }
Beispiel #11
0
        /// <summary>
        /// Draws an image graphic to the specified destination buffer.
        /// </summary>
        /// <param name="buffer">The destination buffer.</param>
        /// <param name="imageGraphic">The image graphic to be drawn.</param>
        public static void DrawImageGraphic(BitmapBuffer buffer, ImageGraphic imageGraphic)
        {
            const int bytesPerPixel = 4;

            var bounds     = ((IGdiBuffer)buffer).Bounds;
            var bitmapData = buffer.Bitmap.LockBits(bounds, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);

            try
            {
                ImageRenderer.Render(imageGraphic, bitmapData.Scan0, bitmapData.Width, bytesPerPixel, bounds);
            }
            finally
            {
                buffer.Bitmap.UnlockBits(bitmapData);
            }
        }
Beispiel #12
0
        public static byte[] GerarCodBarras128(this string codbar, int?heigthPng = null)
        {
            if (string.IsNullOrWhiteSpace(codbar))
            {
                throw new Exception("Código de barras não informado");
            }

            var bar    = Code128Encoder.Encode(codbar);
            var render = new ImageRenderer(barHeightFor1DBarcode: heigthPng ?? 25);

            using (var ms = new MemoryStream())
            {
                render.Render(bar, ms);
                return(ms.ToArray());
            }
        }
        public void Render_ImageFormatGif_ShouldRenderGif()
        {
            // Arrange
            var      renderer = new ImageRenderer(imageFormat: ImageFormat.Gif);
            IBarcode barcode  = QrEncoder.Encode("Hello", ErrorCorrectionLevel.L, Encoding.Unicode);

            using var stream = new MemoryStream();

            // Act
            renderer.Render(barcode, stream);

            // Assert
            stream.Position = 0;
            using var image = ImageSharp.Image.Load(stream, out IImageFormat imageFormat);
            imageFormat.Name.Should().Be("GIF");
        }
        private static Bitmap Render(ImageGraphic x)
        {
            Bitmap    bmp  = new Bitmap(x.Columns, x.Rows);
            Rectangle rect = new Rectangle(Point.Empty, bmp.Size);

            BitmapData bitmapData = bmp.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);

            try
            {
                ImageRenderer.Render(x, bitmapData.Scan0, bitmapData.Width, 4, rect);
            }
            finally
            {
                bmp.UnlockBits(bitmapData);
            }

            return(bmp);
        }
Beispiel #15
0
        private void RenderImages(IRenderContext context)
        {
            var primaryImgRect   = new Rectd(0, 0, 1, 1);
            var secondaryImgRect = new Rectd(0, 0, 1, 1);

            if (ImageRenderContext != null)
            {
                ImageRenderer?.BeginRender(primaryImgRect, context);
                ImageRenderer?.Render(FromImage(PrimaryImage, BlendMode.None, new Rectd(0, 0, 1, 1)), Camera, context);
                ImageRenderer?.Render(FromImage(SecondaryImage, BlendMode.OverWhereNonZero, SpyGlass), Camera, context);
                foreach (var img in AdditionalImages)
                {
                    ImageRenderer?.Render(img, Camera, context);
                }

                ImageRenderer?.EndRender(primaryImgRect, context);
                //ImageRenderContext?.DrawString("" + ImageRenderer.iy, 0, 0, 12, DicomColors.Yellow);
            }
        }
Beispiel #16
0
        public Bitmap Raster()
        {
            if (this.Map == null)
            {
                this.Render();
            }

            BitmapAdaptater bitmap = new BitmapAdaptater(this.Map.Width, this.Map.Height);
            ImageRenderer   raster = new ImageRenderer();

            raster.NoiseMap        = this.Map;
            raster.Gradient        = this.GradientColor;
            raster.LightBrightness = 2;
            raster.LightContrast   = 8;
            raster.Image           = bitmap;

            raster.Render();

            this.Bitmap = bitmap.Bitmap;
            return(this.Bitmap);
        }
Beispiel #17
0
        private static Bitmap CreateBitmap(Size size, NoiseMap map, NoiseConfig cfg)
        {
            var image    = new SharpNoise.Utilities.Imaging.Image(size.Width, size.Height);
            var renderer = new ImageRenderer
            {
                SourceNoiseMap   = map,
                DestinationImage = image
            };

            if (cfg.OutputGrayscale)
            {
                BuildGrayscaleRenderer(renderer);
            }
            else
            {
                BuildTerrainRenderer(renderer);
            }

            renderer.Render();

            return(image.ToGdiBitmap());
        }
Beispiel #18
0
        public async void SameAsync()
        {
            OverworldTerrainSettings generatorSettings = new OverworldTerrainSettings();

            generatorSettings.Seed = 137;
            OverworldTerrain noiseGen = new OverworldTerrain(generatorSettings, true);

            var map = new NoiseMap();

            PlaneNoiseMapBuilder builder = new PlaneNoiseMapBuilder()
            {
                DestNoiseMap = map,
                SourceModule = noiseGen.Result
            };

            var image    = new SharpNoise.Utilities.Imaging.Image();
            var renderer = new ImageRenderer()
            {
                SourceNoiseMap   = map,
                DestinationImage = image
            };

            //renderer.BuildGrayscaleGradient();
            renderer.BuildTerrainGradient();

            builder.SetBounds(-2024, 2024, -2024, 2024);
            builder.SetDestSize(1024, 1024);
            builder.Build();

            renderer.Render();

            var bmp = renderer.DestinationImage.ToGdiBitmap();

            bmp.Save("terrain.bmp");

            Assert.Equal(0, 0);
        }
Beispiel #19
0
        public void Generate(RectangleF bounds)
        {
            if (this.Module == null)
            {
                return;
            }

            m_noiseBuilder.SetBounds(bounds.Left, bounds.Right, bounds.Top, bounds.Bottom);
            m_noiseBuilder.Build();

            float min = float.MaxValue;
            float max = float.MinValue;

            foreach (float v in m_noiseBuilder.DestNoiseMap.Data)
            {
                if (v < min)
                {
                    min = v;
                }
                if (v > max)
                {
                    max = v;
                }
            }

            m_imageRenderer.Render();

            var bmp = m_imageRenderer.DestinationImage.ToGdiBitmap();

            this.BeginInvoke(new Action(() =>
            {
                minLabel.Text = String.Format("Min/Max {0:F2}/{1:F2}", min, max);

                pictureBox.Image = bmp;
            }));
        }
Beispiel #20
0
    public async void TerrainBlendAsync()
    {
        OverworldGenerator og       = new OverworldGenerator();
        OverworldTerrain   noiseGen = new OverworldTerrain(true);
        await Task.Run(() =>
        {
            var noise = new SharpNoise.Modules.ScaleBias()
            {
                Scale   = 4,
                Source0 = noiseGen.selectiveBlend
            };

            var map = new NoiseMap();
            PlaneNoiseMapBuilder builder =
                new PlaneNoiseMapBuilder()
            {
                DestNoiseMap = map, SourceModule = noise
            };

            var image = new Image();
            var transitionsRenderer = new ImageRenderer()
            {
                SourceNoiseMap = map, DestinationImage = image
            };
            transitionsRenderer.BuildTerrainGradient();
            builder.SetBounds(-400, 400, -300, 300);
            builder.SetDestSize(800, 600);
            builder.Build();
            transitionsRenderer.Render();

            var bmp = transitionsRenderer.DestinationImage.ToGdiBitmap();
            bmp.Save("_blendedterrain.bmp");

            Assert.Equal(0, 0);
        });
    }
Beispiel #21
0
        public ImagePreviewObject(DicomImageObject img)
        {
            Image        = img;
            ImagePreview = new WriteableBitmap(50, 50, 96, 96, PixelFormats.Bgr32, null);
            var wbContext = new WriteableBitmapRenderContext(ImagePreview);

            wbContext.Resize(ImagePreview, 50, 50);
            var imgRenderer = new ImageRenderer();
            var camera      = new Camera();

            camera.SetAxial();
            camera.SetFOV(512, 512);
            camera.MoveTo(img.Grid.XRange.GetCentre(), img.Grid.YRange.GetCentre(), img.Grid.ZRange.GetCentre());
            var renderableImage = new RenderableImage();

            renderableImage.LUT        = img.LUT;
            renderableImage.ScreenRect = new RT.Core.Utilities.RTMath.Rectd(0, 0, 1, 1);
            renderableImage.Scaling    = img.Grid.Scaling;
            renderableImage.Grid       = img.Grid;
            renderableImage.Units      = "HU";
            imgRenderer.BeginRender(renderableImage.ScreenRect, wbContext);
            imgRenderer.Render(renderableImage, camera, wbContext);
            imgRenderer.EndRender(renderableImage.ScreenRect, wbContext);
        }
Beispiel #22
0
        private void GenerateNoiseMaps()
        {
            tbLogView.Text = "Started\r\n";
            int SizeX;
            int SizeY;

            try
            {
                SizeX = Int32.Parse(tbWidth.Text);
                SizeY = Int32.Parse(tbHeight.Text);

                NoiseBitmapTerrain = new Bitmap(SizeX, SizeY);
                NoiseBitmapHeight  = new Bitmap(SizeX, SizeY);
                tbLogView.AppendText("Size OK \r\n");
            }
            catch (Exception)
            {
                SizeX = 250;
                SizeY = 250;
                MessageBox.Show("Nonparsable size values! Running at 250x250\r\n");
                NoiseBitmapTerrain = new Bitmap(250, 250);
                NoiseBitmapTerrain = new Bitmap(250, 250);
                tbLogView.AppendText("Size was incorrect, going default\r\n");
            }
            tbLogView.AppendText("Loading Perlin from Noiser(legacy)\r\n");
            SharpNoise.Modules.Perlin perlin = new SharpNoise.Modules.Perlin();
            tbLogView.AppendText("Loading OK\r\n");
            try
            {
                perlin.OctaveCount = Int32.Parse(tbOctaves.Text);
                perlin.Seed        = Int32.Parse(tbSeed.Text);
                perlin.Frequency   = Double.Parse(tbFreq.Text);
                tbLogView.AppendText("Settings OK\r\n");
            }
            catch (Exception)
            {
                MessageBox.Show("Wrong octaves count or seed! Running at 1 octave and seed 000000 @ Frequency = 10.");
                perlin.OctaveCount = 1;
                perlin.Seed        = 000000;
                perlin.Frequency   = 10.0;
                tbLogView.AppendText("Setting incorrect, going default\r\n");
            }
            double down, up, right, left;

            try
            {
                down  = Double.Parse(tbTileDown.Text);
                up    = Double.Parse(tbTileUp.Text);
                left  = Double.Parse(tbTileLeft.Text);
                right = Double.Parse(tbTileRight.Text);
                tbLogView.AppendText("Tiles OK\r\n");
            }
            catch (Exception)
            {
                up    = 3;
                left  = -3;
                right = 3;
                down  = -3;
                tbLogView.AppendText("Tiles incorrect, going default\r\n");
            }
            var NoiseMap = new NoiseMap(SizeX, SizeY);

            if (comboModuleSelector.SelectedIndex == 0)
            {
                var NoiseMapBuilder = new PlaneNoiseMapBuilder()
                {
                    DestNoiseMap = NoiseMap, SourceModule = perlin
                };
                tbLogView.AppendText("Module OK, Destination OK\r\n");
                NoiseMapBuilder.SetDestSize(SizeX, SizeY);

                NoiseMapBuilder.SetBounds(left, right, down, up);
                tbLogView.AppendText("Building maps.....\r\n");
                NoiseMapBuilder.Build();
            }
            if (comboModuleSelector.SelectedIndex == 1)
            {
                var GlobeMapBuilder = new SphereNoiseMapBuilder()
                {
                    DestNoiseMap = NoiseMap, SourceModule = perlin
                };
                tbLogView.AppendText("Module OK, Destination OK\r\n");
                GlobeMapBuilder.SetDestSize(SizeX, SizeY);
                GlobeMapBuilder.SetBounds(down, up, left, right);
                GlobeMapBuilder.Build();
                tbLogView.AppendText("Building maps.....\r\n");
            }
            tbLogView.AppendText("Building OK\r\n");

            var ImageTerrain    = new SharpNoise.Utilities.Imaging.Image();
            var RendererTerrain = new ImageRenderer()
            {
                SourceNoiseMap   = NoiseMap,
                DestinationImage = ImageTerrain
            };

            tbLogView.AppendText("Renderer starting\r\n");

            if (chboxLightMap.IsChecked == true)
            {
                RendererTerrain.EnableLight     = true;
                RendererTerrain.LightAzimuth    = Double.Parse(tbLightAzimuth.Text);
                RendererTerrain.LightBrightness = Double.Parse(tbLightBrightness.Text);
                RendererTerrain.LightContrast   = Double.Parse(tbLightContrast.Text);
                RendererTerrain.LightElevation  = Double.Parse(tbLightElevation.Text);
                RendererTerrain.LightIntensity  = Double.Parse(tbLightIntensity.Text);
            }
            Thread ColorBuilder = new Thread(() =>
            {
                RendererTerrain.BuildTerrainGradient();
                RendererTerrain.Render();

                NoiseBitmapTerrain = ImageTerrain.ToGdiBitmap();
                ImageNoiseHolder.Dispatcher.Invoke(new Action(() =>
                {
                    ImageNoiseHolder.Source = BitmapToImageSource(NoiseBitmapTerrain);
                    tbLogView.AppendText("Done! Noise map OK, renderer OK\r\n");
                }));
            });

            ColorBuilder.Start();

            var ImageTerrainHeight    = new SharpNoise.Utilities.Imaging.Image();
            var RendererTerrainHeight = new ImageRenderer()
            {
                SourceNoiseMap   = NoiseMap,
                DestinationImage = ImageTerrainHeight
            };


            Thread heightBuilder = new Thread(() =>
            {
                RendererTerrainHeight.BuildGrayscaleGradient();
                RendererTerrainHeight.Render();
                NoiseBitmapHeight = ImageTerrainHeight.ToGdiBitmap();

                ImageNoiseHeightHolder.Dispatcher.Invoke(new Action(() =>
                {
                    ImageNoiseHeightHolder.Source = BitmapToImageSource(NoiseBitmapHeight);
                    tbLogView.AppendText("Done! Noise map OK, renderer OK\r\n");
                }));
            });

            heightBuilder.Start();

            tbLogView.AppendText("Process status: OK\r\n");
        }
Beispiel #23
0
        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            nbEnemy = 0;

            gameover = false;

            world = new World(new Vector2(0, 0));

            debugView = new DebugView();
            debugView.LoadContent(GraphicsDevice, Content);

            inputHelper            = new InputHelper(resolutionIndependence);
            inputHelper.ShowCursor = true;

            shadowsRendering = new ShadowsRenderer();

            listGraphicObj = new List <GraphicObj>();

            inputHelper.LoadContent();

            font = Content.Load <SpriteFont>("pixelSpriteFont");

            Texture2D textureCarre  = Content.Load <Texture2D>("carre");
            Texture2D textureCarre2 = Content.Load <Texture2D>("carre2");
            Texture2D textureTotem  = Content.Load <Texture2D>("Totem");

            bouleRouge    = Content.Load <Texture2D>("blood");
            blood1        = Content.Load <Texture2D>("blood1");
            blood2        = Content.Load <Texture2D>("blood2");
            blood3        = Content.Load <Texture2D>("blood3");
            debugNodeBusy = Content.Load <Texture2D>("debugPathFinderNode");
            debugNodeFree = Content.Load <Texture2D>("debugPathFinderNode2");

            particuleSystem = new ParticuleSystem();

            //pathFinder = new PathFinder(2);
            pFinder = new PathFinder();
            pFinder.BuildtNavMeshes(6, 10);

            mapFactory = new MapFactory();
            mapFactory.newMap(listGraphicObj, seedIndexToLoad);
            seedIndexToLoad = -1;
            savedSeeds      = mapFactory.mGen.savedSeeds;
            var treeplanter = new TreePlanter(
                mapFactory.minX * pixelToMeter,
                mapFactory.maxX * pixelToMeter,
                mapFactory.minY * pixelToMeter,
                mapFactory.maxY * pixelToMeter,
                mapFactory.mGen.rand
                );

            frameRateCounter = new FrameRateCounter(font);

            particuleSystem.addParticuleSpawner(new SnowSpawner(new Vector2(100, 100), 0, player, new Vector2(475, -475)));

            snowMarkSpawner = new SnowMarkSpawner(new Vector2(0, 0), 0, player, new Vector2(0, 0));

            var noiseSource = new Perlin
            {
                Seed = mapFactory.mGen.rand.Next()
            };
            var noiseMap        = new NoiseMap();
            var noiseMapBuilder = new PlaneNoiseMapBuilder
            {
                DestNoiseMap   = noiseMap,
                SourceModule   = noiseSource,
                EnableSeamless = true
            };

            //noiseMapBuilder.SetDestSize(300, 300);
            //noiseMapBuilder.SetBounds(-4.5, 4.5, -4.5, 4.5);
            noiseMapBuilder.SetDestSize(256, 256);
            noiseMapBuilder.SetBounds(2, 6, 1, 5);

            noiseMapBuilder.Build();

            textureImageNoise = new SharpNoise.Utilities.Imaging.Image();

            imageRendererNoise = new ImageRenderer
            {
                SourceNoiseMap   = noiseMap,
                DestinationImage = textureImageNoise,
                EnableLight      = true,
                LightContrast    = 1.0,
                LightBrightness  = 2.3,
                EnableWrap       = true
            };

            imageRendererNoise.ClearGradient();

            imageRendererNoise.AddGradientPoint(0.0000, new SharpNoise.Utilities.Imaging.Color(170, 180, 240, 255));
            imageRendererNoise.AddGradientPoint(1.000, new SharpNoise.Utilities.Imaging.Color(170, 180, 240, 255));

            imageRendererNoise.Render();

            renderedmap = createTexture(imageRendererNoise);

            minNoiseX = (int)mapFactory.minX - textureImageNoise.Width * 2;
            maxNoiseX = (int)mapFactory.maxX + textureImageNoise.Width * 2;
            minNoiseY = (int)mapFactory.minY - textureImageNoise.Height * 2;
            maxNoiseY = (int)mapFactory.maxY + textureImageNoise.Height * 2;

            menu = new Menu(font);
        }
    public static NoisePackage Generate()
    {
        // Randomly generate a package to return at the end of the method
        NoisePackage package = new NoisePackage
        {
            Seed        = new Random().Next(),
            OctaveCount = new Random().Next(3, 9),
            Persistence = new Random().NextDouble(),
            Quality     = (byte)NoiseQuality.Best,
            Frequency   = (double)new Random().Next(1, 3)
        };

        // The noise source - a simple Perlin noise generator will do for this sample
        Perlin noiseSource = new Perlin
        {
            Seed        = package.Seed,
            OctaveCount = package.OctaveCount,
            Persistence = package.Persistence,
            Quality     = (NoiseQuality)package.Quality,
            Frequency   = package.Frequency
        };

        // Create a new, empty, noise map and initialize a new planar noise map builder with it
        var noiseMap        = new NoiseMap();
        var noiseMapBuilder = new PlaneNoiseMapBuilder
        {
            DestNoiseMap = noiseMap,
            SourceModule = noiseSource
        };

        // Set the size of the noise map
        noiseMapBuilder.SetDestSize(Program.MapWidth, Program.MapHeight);

        // Set the bounds of the noise mpa builder
        // These are the coordinates in the noise source from which noise values will be sampled
        noiseMapBuilder.SetBounds(-3, 3, -2, 2);

        // Build the noise map - samples values from the noise module above,
        // using the bounds coordinates we have passed in the builder
        noiseMapBuilder.Build();

        // Create a new image and image renderer
        var image    = new Image();
        var renderer = new ImageRenderer
        {
            SourceNoiseMap   = noiseMap,
            DestinationImage = image
        };

        // The renderer needs to know how to map noise values to colors.
        // In this case, we use one of the predefined gradients, specifically the terrain gradient,
        // which maps lower noise values to blues and greens and higher values to brouns and whites.
        // This simulates the look of a map with water, grass and vegetation, dirt and mountains.
        renderer.BuildGrayscaleGradient();

        // Before rendering the image, we could set various parameters on the renderer,
        // such as the position and color of the light source.
        // But we aren't going to bother for this sample.

        // Finally, render the image
        renderer.Render();

        // Finally, save the rendered image as a PNG in the current directory
        using (var fs = File.OpenWrite("NoiseMapGrayscale.png"))
        {
            image.SaveGdiBitmap(fs, ImageFormat.Png);
        }

        renderer.BuildTerrainGradient();

        renderer.Render();

        using (var fs = File.OpenWrite("NoiseMapColor.png"))
        {
            image.SaveGdiBitmap(fs, ImageFormat.Png);
        }

        Process photoViewer = new Process();

        photoViewer.StartInfo.FileName = "NoiseMapColor.png";
        photoViewer.Start();

        Console.WriteLine(
            "\n      Frequency: " + noiseSource.Frequency +
            "\n      Lacunarity: " + noiseSource.Lacunarity +
            "\n      Octaves: " + noiseSource.OctaveCount +
            "\n      Persistence: " + noiseSource.Persistence +
            "\n      Seed: " + noiseSource.Seed + "\n");

        return(package);
    }
Beispiel #25
0
    public async void BiomesAsync()
    {
        await Task.Run(() =>
        {
            var map     = new NoiseMap();
            var builder = new PlaneNoiseMapBuilder()
            {
                DestNoiseMap = map, SourceModule = noiseGen.FinalBiomes
            };
            var image          = new Image();
            var biomesRenderer = new ImageRenderer()
            {
                SourceNoiseMap = map, DestinationImage = image
            };

            biomesRenderer.AddGradientPoint((int)Biomes.TheVoid, new Color(0, 0, 0, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.Plains, new Color(86, 125, 70, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.SunflowerPlains, new Color(255, 196, 63, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.SnowyPlains, new Color(200, 200, 255, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.IceSpikes, new Color(100, 100, 255, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.Desert, new Color(128, 128, 0, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.Swamp, new Color(0, 128, 0, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.Forest, new Color(32, 255, 32, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.FlowerForest, new Color(96, 255, 0, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.BirchForest, new Color(182, 255, 182, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.DarkForest, new Color(0, 100, 0, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.OldGrowthBirchForest, new Color(150, 255, 150, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.OldGrowthPineTaiga, new Color(1, 121, 111, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.OldGrowthSpruceTaiga, new Color(105, 193, 126, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.Taiga, new Color(118, 128, 120, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.SnowyTaiga, new Color(218, 228, 220, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.Savanna, new Color(209, 163, 110, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.SavannaPlateau, new Color(224, 190, 146, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.WindsweptHills, new Color(11, 102, 35, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.WindsweptGravellyHills, new Color(128, 164, 128, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.WindsweptForest, new Color(11, 102, 35, 196));
            biomesRenderer.AddGradientPoint((int)Biomes.WindsweptSavanna, new Color(209, 163, 110, 196));
            biomesRenderer.AddGradientPoint((int)Biomes.Jungle, new Color(41, 171, 135, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.SparseJungle, new Color(41, 171, 135, 196));
            biomesRenderer.AddGradientPoint((int)Biomes.BambooJungle, new Color(221, 202, 133, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.Badlands, new Color(167, 161, 143, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.ErodedBadlands, new Color(167, 161, 143, 196));
            biomesRenderer.AddGradientPoint((int)Biomes.WoodedBadlands, new Color(167, 224, 143, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.Meadow, new Color(48, 186, 143, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.Grove, new Color(120, 127, 86, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.SnowySlopes, new Color(144, 184, 212, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.FrozenPeaks, new Color(144, 184, 255, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.JaggedPeaks, new Color(128, 128, 128, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.StonyPeaks, new Color(128, 128, 128, 196));
            biomesRenderer.AddGradientPoint((int)Biomes.River, new Color(38, 102, 145, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.FrozenRiver, new Color(186, 218, 232, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.Beach, new Color(248, 220, 172, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.SnowyBeach, new Color(248, 220, 255, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.StonyShore, new Color(170, 170, 170, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.WarmOcean, new Color(60, 181, 177, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.LukewarmOcean, new Color(40, 181, 177, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.DeepLukewarmOcean, new Color(40, 181, 177, 128));
            biomesRenderer.AddGradientPoint((int)Biomes.Ocean, new Color(0, 105, 148, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.DeepOcean, new Color(0, 105, 148, 128));
            biomesRenderer.AddGradientPoint((int)Biomes.ColdOcean, new Color(107, 197, 198, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.DeepColdOcean, new Color(107, 197, 198, 128));
            biomesRenderer.AddGradientPoint((int)Biomes.FrozenOcean, new Color(163, 191, 203, 255));
            biomesRenderer.AddGradientPoint((int)Biomes.DeepFrozenOcean, new Color(163, 191, 203, 128));
            biomesRenderer.AddGradientPoint((int)Biomes.MushroomFields, new Color(119, 103, 84, 255));


            builder.SetBounds(-400, 400, -300, 300);
            builder.SetDestSize(800, 600);
            builder.Build();
            biomesRenderer.Render();

            var bmp = biomesRenderer.DestinationImage.ToGdiBitmap();
            bmp.Save("_biomes.bmp");

            Assert.Equal(0, 0);
        });
    }
Beispiel #26
0
        /*
         * m - height map of moisture texture
         * function biome(e, m) {
         * if (e < 0.1) return OCEAN;
         * if (e < 0.12) return BEACH;
         *
         * if (e > 0.8) {
         * if (m < 0.1) return SCORCHED;
         * if (m < 0.2) return BARE;
         * if (m < 0.5) return TUNDRA;
         * return SNOW;
         * }
         *
         * if (e > 0.6) {
         * if (m < 0.33) return TEMPERATE_DESERT;
         * if (m < 0.66) return SHRUBLAND;
         * return TAIGA;
         * }
         *
         * if (e > 0.3) {
         * if (m < 0.16) return TEMPERATE_DESERT;
         * if (m < 0.50) return GRASSLAND;
         * if (m < 0.83) return TEMPERATE_DECIDUOUS_FOREST;
         * return TEMPERATE_RAIN_FOREST;
         * }
         *
         * if (m < 0.16) return SUBTROPICAL_DESERT;
         * if (m < 0.33) return GRASSLAND;
         * if (m < 0.66) return TROPICAL_SEASONAL_FOREST;
         * return TROPICAL_RAIN_FOREST;
         * }
         */
        void Generating()
        {
            //var mountain = BuildHeightMap(
            //   new ImprovedPerlin(),
            //   new SumFractal() {
            //       Frequency = 2,
            //       Lacunarity = 1,
            //       OctaveCount = 6,
            //   }, 0.1f);


            var map = new NoiseMap();

            try {
                var rectangle = new Rectangle(0, 0, width, height);
                var tree      = CreateNoiseTree();
                var builder   = new PlaneNoiseMapBuilder()
                {
                    DestNoiseMap = map,
                };
                builder.SourceModule = tree;
                builder.SetDestSize(width, height);
                builder.SetBounds(6.0, 10.0, 1.0, 5.0);
                builder.EnableSeamless = false;

                builder.Build();

                var image    = new SharpNoise.Utilities.Imaging.Image();
                var renderer = new ImageRenderer()
                {
                    SourceNoiseMap   = map,
                    DestinationImage = image,
                };
                renderer.BuildTerrainGradient();

                renderer.Render();

                Texture = renderer.DestinationImage.ToGdiBitmap();
            } catch (Exception ex) {
                ex.ToString();
            } finally {
                ClearNoiseTree();
            }

            var resources = Path.Combine("../../../../D3DLab.Wpf.Engine.App/Resources/terrain/");

            // using (var bitmap = new System.Drawing.Bitmap(Path.Combine(resources, "mask_circular_256x256.png"))) {
            HeightMap = new Vector3[height * width];
            var index = HeightMap.Length - 1;

            for (var x = 0; x < width; x++)
            {
                for (var y = 0; y < height; y++)
                {
                    //MakeIsland(ref e, x, y, 200f);
                    //var index = height * y + x;

                    var e = map.GetValue(x, y);

                    ReScale(ref e);

                    Redistribution(ref e);

                    HeightMap[index] = new Vector3(x, e * terrainParams.Correction, y);

                    MaxHeight = Math.Max(HeightMap[index].Y, MaxHeight);
                    MinHeight = Math.Min(HeightMap[index].Y, MinHeight);

                    index--;
                }
            }
            //}
            IsGenerated = true;
        }
Beispiel #27
0
        public async Task Render(D2D.RenderTarget renderTarget, FrameworkElement rootElement, FrameworkElement fe)
        {
            var textBlock = fe as TextBlock;

            if (textBlock != null)
            {
                await TextBlockRenderer.Render(this, renderTarget, rootElement, textBlock);

                return;
            }

            var rectangle = fe as Jupiter.Shapes.Rectangle;

            if (rectangle != null)
            {
                await RectangleRenderer.Render(this, renderTarget, rootElement, rectangle);

                return;
            }

            var border = fe as Border;

            if (border != null)
            {
                await BorderRenderer.Render(this, renderTarget, rootElement, border);

                return;
            }

            var image = fe as Image;

            if (image != null)
            {
                await ImageRenderer.Render(this, renderTarget, rootElement, image);

                return;
            }

            var ellipse = fe as Ellipse;

            if (ellipse != null)
            {
#pragma warning disable 4014
                EllipseRenderer.Render(this, renderTarget, rootElement, ellipse);
#pragma warning restore 4014
                return;
            }

            var line = fe as Line;

            if (line != null)
            {
                await LineRenderer.Render(this, renderTarget, rootElement, line);

                return;
            }

            var path = fe as Jupiter.Shapes.Path;

            if (path != null)
            {
                await PathRenderer.Render(this, renderTarget, rootElement, path);

                return;
            }

            await FrameworkElementRenderer.Render(this, renderTarget, rootElement, fe);
        }
Beispiel #28
0
        /// <summary>
        ///
        /// </summary>
        protected void GenerateNoise()
        {
            EnabledInterface(false);

            // Parse input ------------------------------------------------------------------------------------
            int    seed        = ParseInt(_tbxSeed.Text, PrimitiveModule.DefaultSeed);
            double frequency   = ParseDouble(_tbxFrequency.Text, FilterModule.DEFAULT_FREQUENCY);
            double lacunarity  = ParseDouble(_tbxLacunarity.Text, FilterModule.DEFAULT_LACUNARITY);
            double gain        = ParseDouble(_tbxGain.Text, FilterModule.DEFAULT_GAIN);
            double offset      = ParseDouble(_tbxOffset.Text, FilterModule.DEFAULT_OFFSET);
            double exponent    = ParseDouble(_tbxExponent.Text, FilterModule.DEFAULT_SPECTRAL_EXPONENT);
            var    octaveCount = (int)_nstpOctave.Value;
            bool   seamless    = _chkbx.Checked;

            GradientColor gradient  = GradientColors.Grayscale;
            NoiseQuality  quality   = PrimitiveModule.DefaultQuality;
            var           primitive = NoisePrimitive.ImprovedPerlin;
            var           filter    = NoiseFilter.SumFractal;

            try
            {
                quality = (NoiseQuality)Enum.Parse(typeof(NoiseQuality), _cbxQuality.Text);
            }
            catch
            {
                MessageBox.Show(
                    String.Format("Unknown quality '{0}'", _cbxQuality.Text),
                    "Libnoise Error",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error
                    );

                EnabledInterface(true);

                return;
            }

            try
            {
                primitive = (NoisePrimitive)Enum.Parse(typeof(NoisePrimitive), _cbxPrimitive.Text);
            }
            catch
            {
                MessageBox.Show(
                    String.Format("Unknown primitive '{0}'", _cbxPrimitive.Text),
                    "Libnoise Error",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error
                    );

                EnabledInterface(true);

                return;
            }

            try
            {
                filter = (NoiseFilter)Enum.Parse(typeof(NoiseFilter), _cbxFilter.Text);
            }
            catch
            {
                MessageBox.Show(
                    String.Format("Unknown filter '{0}'", _cbxFilter.Text),
                    "Libnoise Error",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error
                    );

                EnabledInterface(true);

                return;
            }

            switch (_cbxGradient.Text)
            {
            case "Grayscale":
                gradient = GradientColors.Grayscale;
                break;

            case "Terrain":
                gradient = GradientColors.Terrain;
                break;
            }

            // Create module tree ------------------------------------------------------------------------------------

            PrimitiveModule pModule = null;

            switch (primitive)
            {
            case NoisePrimitive.Constant:
                pModule = new Constant(offset);
                break;

            case NoisePrimitive.Cylinders:
                pModule  = new Cylinders(offset);
                seamless = false;
                break;

            case NoisePrimitive.Spheres:
                pModule  = new Spheres(offset);
                seamless = false;
                break;

            case NoisePrimitive.BevinsGradient:
                pModule = new BevinsGradient();
                break;

            case NoisePrimitive.BevinsValue:
                pModule = new BevinsValue();
                break;

            case NoisePrimitive.ImprovedPerlin:
                pModule = new ImprovedPerlin();
                break;

            case NoisePrimitive.SimplexPerlin:
                pModule = new SimplexPerlin();
                break;
            }

            pModule.Quality = quality;
            pModule.Seed    = seed;

            FilterModule fModule = null;
            ScaleBias    scale   = null;

            switch (filter)
            {
            case NoiseFilter.Pipe:
                fModule = new Pipe();
                break;

            case NoiseFilter.SumFractal:
                fModule = new SumFractal();
                break;

            case NoiseFilter.SinFractal:
                fModule = new SinFractal();
                break;

            case NoiseFilter.MultiFractal:
                fModule = new MultiFractal();
                // Used to show the difference with our gradient color (-1 + 1)
                scale = new ScaleBias(fModule, 1, -0.8);
                break;

            case NoiseFilter.Billow:
                fModule = new Billow();
                ((Billow)fModule).Bias  = -0.2;
                ((Billow)fModule).Scale = 2;
                break;

            case NoiseFilter.HeterogeneousMultiFractal:
                fModule = new HeterogeneousMultiFractal();
                // Used to show the difference with our gradient color (-1 + 1)
                scale = new ScaleBias(fModule, -1, 2);
                break;

            case NoiseFilter.HybridMultiFractal:
                fModule = new HybridMultiFractal();
                // Used to show the difference with our gradient color (-1 + 1)
                scale = new ScaleBias(fModule, 0.7, -2);
                break;

            case NoiseFilter.RidgedMultiFractal:
                fModule = new RidgedMultiFractal();
                // Used to show the difference with our gradient color (-1 + 1)
                scale = new ScaleBias(fModule, 0.9, -1.25);
                break;

            case NoiseFilter.Voronoi:
                fModule = new Voronoi();
                break;
            }

            fModule.Frequency   = frequency;
            fModule.Lacunarity  = lacunarity;
            fModule.OctaveCount = octaveCount;
            fModule.Offset      = offset;
            fModule.Offset      = offset;
            fModule.Gain        = gain;
            fModule.Primitive3D = (IModule3D)pModule;

            IModule3D finalModule;

            if (scale == null)
            {
                finalModule = (IModule3D)fModule;
            }
            else
            {
                finalModule = scale;
            }

            NoiseMapBuilder projection;

            switch (_cbxProjection.Text)
            {
            case "Spherical":
                projection = new NoiseMapBuilderSphere();
                ((NoiseMapBuilderSphere)projection).SetBounds(-90, 90, -180, 180);      // degrees
                break;

            case "Cylindrical":
                projection = new NoiseMapBuilderCylinder();
                ((NoiseMapBuilderCylinder)projection).SetBounds(-180, 180, -10, 10);
                break;

            case "Planar":
            default:
                double bound = 2;
                projection = new NoiseMapBuilderPlane(bound, bound * 2, bound, bound * 2, seamless);
                //projection = new NoiseMapBuilderPlane(-bound, bound, -bound, bound, seamless);
                //projection = new NoiseMapBuilderPlane(0, bound, 0, bound, seamless);
                break;
            }

            int width  = 0;
            int height = 0;

            switch (_cbxSize.Text)
            {
            case "256 x 256":
                width  = 256;
                height = 256;
                break;

            case "512 x 512":
                width  = 512;
                height = 512;
                break;

            case "1024 x 1024":
                width  = 1024;
                height = 1024;
                break;

            case "256 x 128":
                width  = 256;
                height = 128;
                break;

            case "512 x 256":
                width  = 512;
                height = 256;
                break;

            case "1024 x 512":
                width  = 1024;
                height = 512;
                break;

            case "2048 x 1024":
                width  = 2048;
                height = 1024;
                break;

            default:

            case "128 x 128":
                width  = 128;
                height = 128;
                break;
            }

            // ------------------------------------------------------------------------------------------------
            // 0 - Initializing
            _prbarRenderProgression.Visible = true;
            _lblProgressPercent.Visible     = true;
            _prbarRenderProgression.Value   = 0;
            ;
            _lblProgressPercent.Text = "";

            _lblLog.Text = String.Format("Create a {0} image with a {1} projection\n", _cbxSize.Text,
                                         _cbxProjection.Text);

            var      watchDog = new Stopwatch();
            TimeSpan ts;
            double   elaspedTime = 0;

            //
            // ------------------------------------------------------------------------------------------------
            // 1 - Build the noise map
            watchDog.Reset();

            _prbarRenderProgression.Value = 0;
            _lblLog.Text += "Building noise map ... ";

            var noiseMap = new NoiseMap();

            /*
             *          // ShapeFilter test
             *          Bitmap bmpShape = new Bitmap("smileyShape.bmp");
             *          BitmapAdaptater bmShapeAdaptater = new BitmapAdaptater(bmpShape);
             *
             *          ShapeFilter shapeFilter = new ShapeFilter();
             *          shapeFilter.Shape = bmShapeAdaptater;
             *
             *          projection.Filter = shapeFilter;
             */

            projection.SetSize(width, height);
            projection.SourceModule = finalModule;
            projection.NoiseMap     = noiseMap;
            projection.CallBack     = delegate(int line)
            {
                line++;

                watchDog.Stop();

                //Process message
                Application.DoEvents();

                _prbarRenderProgression.Value = (line * 100 / height);
                _lblProgressPercent.Text      = String.Format("{0} % - {1} line(s)", _prbarRenderProgression.Value, line);

                watchDog.Start();
            };

            watchDog.Start();
            projection.Build();
            watchDog.Stop();

            ts           = watchDog.Elapsed;
            elaspedTime += ts.TotalMilliseconds;

            _lblLog.Text += String.Format("{0:00}:{1:00} {2:00},{3:0000}\n",
                                          ts.Hours, ts.Minutes,
                                          ts.Seconds, ts.Milliseconds * 10
                                          );

            // ------------------------------------------------------------------------------------------------
            // 2 - Render image
            // Create a renderer, BitmapAdaptater create a System.Drawing.Bitmap on the fly
            watchDog.Reset();
            _prbarRenderProgression.Value = 0;
            _lblLog.Text += "Rendering image ... ";

            var renderer = new ImageRenderer();

            renderer.NoiseMap        = noiseMap;
            renderer.Gradient        = gradient;
            renderer.LightBrightness = 2;
            renderer.LightContrast   = 8;
            //renderer.LightEnabled = true;

            // Libnoise image struct strategy
            //Graphics.Tools.Noise.Renderer.Image image = new Graphics.Tools.Noise.Renderer.Image();
            //renderer.Image = image;

            // Dotnet Bitmap Strategy
            var bmpAdaptater = new BitmapAdaptater(width, height);

            renderer.Image = bmpAdaptater;

            renderer.CallBack = delegate(int line)
            {
                line++;

                watchDog.Stop();

                //Process message
                Application.DoEvents();

                _prbarRenderProgression.Value = (line * 100 / height);
                _lblProgressPercent.Text      = String.Format("{0} % - {1} line(s)", _prbarRenderProgression.Value, line);

                watchDog.Start();
            };

            // Render the texture.
            watchDog.Start();
            renderer.Render();
            watchDog.Stop();

            ts           = watchDog.Elapsed;
            elaspedTime += ts.TotalMilliseconds;

            _lblLog.Text += String.Format("{0:00}:{1:00} {2:00},{3:0000}\n",
                                          ts.Hours, ts.Minutes,
                                          ts.Seconds, ts.Milliseconds * 10
                                          );

            //----------------------------------------
            // Normalmap rendering test
            //

            /*
             *          BitmapAdaptater nmapAdaptater = new BitmapAdaptater(width, height);
             *          NormalMapRenderer nmap = new NormalMapRenderer();
             *          nmap.Image = nmapAdaptater;
             *          nmap.BumpHeight = 30.0;
             *          nmap.NoiseMap = noiseMap;
             *          nmap.Render();
             *          nmapAdaptater.Bitmap.Save("normalMap.png", ImageFormat.Png);
             */
            //----------------------------------------

            /*
             *          Heightmap8 heightmap8 = new Heightmap8();
             *          Heightmap8Renderer heightmapRenderer = new Heightmap8Renderer();
             *          heightmapRenderer.Heightmap = heightmap8;
             */

            /*
             *          Heightmap16 heightmap16 = new Heightmap16();
             *          Heightmap16Renderer heightmapRenderer = new Heightmap16Renderer();
             *          heightmapRenderer.Heightmap = heightmap16;
             */

            /*
             *          Heightmap32 heightmap32 = new Heightmap32();
             *          Heightmap32Renderer heightmapRenderer = new Heightmap32Renderer();
             *          heightmapRenderer.Heightmap = heightmap32;
             */

            /*
             *          heightmapRenderer.NoiseMap = noiseMap;
             *          heightmapRenderer.ExactFit();
             *          heightmapRenderer.Render();
             */

            /*
             *          Heightmap16RawWriter rawWriter = new Heightmap16RawWriter();
             *          rawWriter.Heightmap = heightmap16;
             *          rawWriter.Filename = "heightmap16.raw";
             *          rawWriter.WriteFile();
             */

            // ------------------------------------------------------------------------------------------------
            // 3 - Painting

            // Save the file
            //bmpAdaptater.Bitmap.Save("rendered.png",ImageFormat.Png);
            _imageRendered.Width  = width;
            _imageRendered.Height = height;

            //_imageRendered.Image = _bitmap;
            _imageRendered.Image = bmpAdaptater.Bitmap;

            if (_imageRendered.Width > _panImageViewport.Width)
            {
                _imageRendered.Left = 0;
            }
            else
            {
                _imageRendered.Left = (_panImageViewport.Width - _imageRendered.Width) / 2;
            }

            if (_imageRendered.Height > _panImageViewport.Height)
            {
                _imageRendered.Top = 0;
            }
            else
            {
                _imageRendered.Top = (_panImageViewport.Height - _imageRendered.Height) / 2;
            }

            if (_imageRendered.Width > _panImageViewport.Width || _imageRendered.Height > _panImageViewport.Height)
            {
                _imageRendered.Anchor        = (AnchorStyles.Left | AnchorStyles.Top);
                _panImageViewport.AutoScroll = true;
            }
            else
            {
                _panImageViewport.AutoScroll = false;
            }

            // ----------------------------------------------------------------

            ts = TimeSpan.FromMilliseconds(elaspedTime);

            // Format and display the TimeSpan value.
            _lblLog.Text += String.Format("Duration : {0:00}:{1:00} {2:00},{3:0000}\n",
                                          ts.Hours, ts.Minutes,
                                          ts.Seconds, ts.Milliseconds * 10
                                          );

            EnabledInterface(true);

            _prbarRenderProgression.Value   = 0;
            _lblProgressPercent.Text        = "";
            _prbarRenderProgression.Visible = false;
            _lblProgressPercent.Visible     = false;
        }
Beispiel #29
0
 public override void Render(Context c)
 {
     ImageRenderer.Render(c, image);
     AbsoluteBound = new Rectangle(ParentSection.AbsoluteDrawingStartPoint.X + image.Location.X,
                                   ParentSection.AbsoluteDrawingStartPoint.Y + image.Location.Y, image.Width, image.Height);
 }
        public void Throw_when_filename_is_not_available()
        {
            Action act = () => _renderer.Render("<figure><img src=\"data:image/jpeg;base64,DATA\"></figure>");

            act.Should().Throw <InvalidOperationException>();
        }