示例#1
0
        /// <summary>
        /// Creates a new OSM data layer.
        /// </summary>
        /// <param name="projection"></param>
        public LayerGpx(IProjection projection)
        {
            _projection = projection;

            this.Scene           = new Scene2DSimple();
            this.Scene.BackColor = SimpleColor.FromKnownColor(KnownColor.Transparent).Value;
        }
示例#2
0
        /// <summary>
        /// Initialize this instance.
        /// </summary>
        public void Initialize()
        {
            this.BackgroundColor = UIColor.White;

            var panGesture = new UIPanGestureRecognizer(Pan);

            this.AddGestureRecognizer(panGesture);
            var pinchGesture = new UIPinchGestureRecognizer(Pinch);

            this.AddGestureRecognizer(pinchGesture);

//			// create the renderer
//			_renderer = new MapRenderer<CGContextWrapper> (
//				new CGContextRenderer());
//
            // create the cache renderer.
            _cacheRenderer = new MapRenderer <CGContextWrapper> (
                new CGContextRenderer());
            _cachedScene           = new Scene2DSimple();
            _cachedScene.BackColor = SimpleColor.FromKnownColor(KnownColor.White).Value;

            // create invalidation timer.
            _render = true;
            System.Threading.Timer timer = new System.Threading.Timer(InvalidateSimple,
                                                                      null, 0, 50);
        }
示例#3
0
        public void TestDomainColorNamed()
        {
            // parses the MapCSS.
            var result = this.TestMapCSSParsing(
                "OsmSharp.UI.Test.data.MapCSS.color-named.mapcss");

            // Test the very minimum; no errors during parsing says a lot already!
            var tree = result.Tree as Antlr.Runtime.Tree.CommonTree;
            Assert.NotNull(tree);
            Assert.AreEqual(2, tree.ChildCount);

            // parse into domain.
            var file = MapCSSDomainParser.Parse(tree);
            Assert.IsNotNull(file);
            Assert.AreEqual(1, file.Rules.Count);
            Assert.AreEqual(1, file.Rules[0].Declarations.Count);
            Assert.IsInstanceOf(typeof(DeclarationInt), file.Rules[0].Declarations[0]);

            // get color declaration.
            var declarationInt = file.Rules[0].Declarations[0] as DeclarationInt;
            Assert.IsNotNull(declarationInt);
            Assert.AreEqual(DeclarationIntEnum.Color, declarationInt.Qualifier);

            // instantiate color.
            var simpleColor = new SimpleColor();
            simpleColor.Value = declarationInt.Eval((MapCSSObject)null);
            Assert.AreEqual("#FFFFFF", simpleColor.HexRgb);
        }
        /// <summary>
        /// Draws a polygon on the target. The coordinates given are scene coordinates.
        /// </summary>
        /// <param name="target"></param>
        /// <param name="x">The x coordinate.</param>
        /// <param name="y">The y coordinate.</param>
        /// <param name="color">Color.</param>
        /// <param name="width">Width.</param>
        /// <param name="fill">If set to <c>true</c> fill.</param>
        protected override void DrawPolygon(Target2DWrapper <CGContextWrapper> target, double[] x, double[] y, int color, double width,
                                            bool fill)
        {
            float widthInPixels = this.ToPixels(width);

            SimpleColor simpleColor = SimpleColor.FromArgb(color);

            target.Target.CGContext.SetLineWidth(widthInPixels);
            target.Target.CGContext.SetFillColor(simpleColor.R / 256.0f, simpleColor.G / 256.0f, simpleColor.B / 256.0f,
                                                 simpleColor.A / 256.0f);
            target.Target.CGContext.SetStrokeColor(simpleColor.R / 256.0f, simpleColor.G / 256.0f, simpleColor.B / 256.0f,
                                                   simpleColor.A / 256.0f);
            //target.Target.SetLineDash (0, new float[0]);
            target.Target.CGContext.BeginPath();

            PointF[] points = new PointF[x.Length];
            for (int idx = 0; idx < x.Length; idx++)
            {
                double[] transformed = this.Tranform(x[idx], y[idx]);
                points[idx] = new PointF((float)transformed[0], (float)transformed[1]);
            }

            target.Target.CGContext.AddLines(points);
            target.Target.CGContext.ClosePath();

            //target.Target.DrawPath (CGPathDrawingMode.Stroke);
            target.Target.CGContext.FillPath();
            //target.Target.E
        }
示例#5
0
 public DebugLine(Vector3 a, Vector3 b, int ticksLeft = 100, SimpleColor color = SimpleColor.White)
 {
     this.a         = a;
     this.b         = b;
     this.deathTick = Find.TickManager.TicksGame + ticksLeft;
     this.color     = color;
 }
示例#6
0
        /// <summary>
        /// Initialize this instance.
        /// </summary>
        void Initialize(MapView mapLayout)
        {
            _mapLayout = mapLayout;
            this.SetWillNotDraw(false);

            this.MapMinZoomLevel = 10;
            this.MapMaxZoomLevel = 20;

            _renderer = new MapRenderer <global::Android.Graphics.Canvas>(
                new CanvasRenderer2D());

            // initialize the gesture detection.
            _gestureDetector = new GestureDetector(
                this);
            _scaleGestureDetector = new ScaleGestureDetector(
                this.Context, this);
            this.SetOnTouchListener(this);

            _makerLayer = new LayerPrimitives(
                new WebMercator());

            // initialize all the caching stuff.
            //_previousCache = null;
            _cacheRenderer = new MapRenderer <global::Android.Graphics.Canvas>(
                new CanvasRenderer2D());
            _scene           = new Scene2DSimple();
            _scene.BackColor = SimpleColor.FromKnownColor(KnownColor.White).Value;

            System.Threading.Timer timer = new Timer(InvalidateSimple,
                                                     null, 0, 50);
        }
示例#7
0
        /// <summary>
        /// Adds a new OsmSharpRoute.
        /// </summary>
        /// <param name="route">Stream.</param>
        /// <param name="argb">Stream.</param>
        /// <param name="width"></param>
        public void AddRoute(Route route, int argb, double width)
        {
            if (route != null &&
                route.Segments != null &&
                route.Segments.Length > 0)
            { // there are entries.
                // get x/y.
                var x = new double[route.Segments.Length];
                var y = new double[route.Segments.Length];
                for (int idx = 0; idx < route.Segments.Length; idx++)
                {
                    x[idx] = _projection.LongitudeToX(
                        route.Segments[idx].Longitude);
                    y[idx] = _projection.LatitudeToY(
                        route.Segments[idx].Latitude);
                }

                // set the default color if none is given.
                var color    = SimpleColor.FromArgb(argb);
                var pointsId = _scene.AddPoints(x, y);
                if (pointsId.HasValue)
                {
                    _scene.AddStyleLine(pointsId.Value, 0, float.MinValue, float.MaxValue,
                                        color.Value, (float)width, Renderer.Primitives.LineJoin.Round, null);
                }
            }

            this.RaiseLayerChanged();
        }
示例#8
0
文件: GenDraw.cs 项目: potsh/RimWorld
        private static Material GetLineMat(SimpleColor color)
        {
            switch (color)
            {
            case SimpleColor.White:
                return(LineMatWhite);

            case SimpleColor.Red:
                return(LineMatRed);

            case SimpleColor.Green:
                return(LineMatGreen);

            case SimpleColor.Blue:
                return(LineMatBlue);

            case SimpleColor.Magenta:
                return(LineMatMagenta);

            case SimpleColor.Yellow:
                return(LineMatYellow);

            case SimpleColor.Cyan:
                return(LineMatCyan);

            default:
                return(LineMatWhite);
            }
        }
示例#9
0
        /// <summary>
        /// Builds the scene.
        /// </summary>
        /// <param name="map"></param>
        /// <param name="zoomFactor"></param>
        /// <param name="center"></param>
        /// <param name="view"></param>
        private void BuildScene(Map map, float zoomFactor, GeoCoordinate center, View2D view)
        {
            // build the boundingbox.
            var viewBox = view.OuterBox;
            var box     = new GeoCoordinateBox(map.Projection.ToGeoCoordinates(viewBox.Min [0], viewBox.Min [1]),
                                               map.Projection.ToGeoCoordinates(viewBox.Max [0], viewBox.Max [1]));
            var zoomLevel = (int)map.Projection.ToZoomLevel(zoomFactor);

            if (_lastBox != null && _lastBox.Contains(box) &&
                zoomLevel == _lastZoom)
            {
                return;
            }
            _lastBox  = box;
            _lastZoom = zoomLevel;

            // reset the scene.
            if (_scene2DSimple == null)
            {
                _scene2DSimple = new Scene2DSimple();
            }
            _scene2DSimple.Clear();

            // get from the index.
            this.Scene.BackColor = SimpleColor.FromKnownColor(KnownColor.White).Value;
            lock (_sync) {
                _index.Get(_scene2DSimple, view, zoomFactor);
            }
        }
示例#10
0
        /// <summary>
        /// Initialize implementation from IMapView.
        /// </summary>
        /// <param name="mapLayout"></param>
        void IMapViewSurface.Initialize(MapView mapLayout)
        {
            // create the Open GL 2D target.
            _target = new OpenGLTarget2D();
            this.SetRenderer(_target);

            _mapView = mapLayout;
            this.SetWillNotDraw(false);

            this.MapMinZoomLevel = 10;
            this.MapMaxZoomLevel = 20;

            // create the renderer.
            _renderer = new MapRenderer <OpenGLTarget2D>(
                new OpenGLRenderer2D());

            // initialize the gesture detection.
            this.SetOnTouchListener(this);
            _scaleGestureDetector = new ScaleGestureDetector(
                this.Context, this);
            _rotateGestureDetector = new RotateGestureDetector(
                this.Context, this);
            _moveGestureDetector = new MoveGestureDetector(
                this.Context, this);
            _tagGestureDetector = new TapGestureDetector(
                this.Context, this);

            _makerLayer = new LayerPrimitives(
                new WebMercator());

            _scene           = new Scene2D(new WebMercator(), 16);
            _scene.BackColor = SimpleColor.FromKnownColor(KnownColor.White).Value;
        }
示例#11
0
        /// <summary>
        /// Draws a line on the target. The coordinates given are scene coordinates.
        /// </summary>
        /// <param name="target"></param>
        /// <param name="x">The x coordinate.</param>
        /// <param name="y">The y coordinate.</param>
        /// <param name="color">Color.</param>
        /// <param name="width">Width.</param>
        /// <param name="lineJoin"></param>
        /// <param name="dashes"></param>
        protected override void DrawLine(Target2DWrapper <CGContextWrapper> target, double[] x, double[] y, int color, double width,
                                         LineJoin lineJoin, int[] dashes)
        {
            float widthInPixels = this.ToPixels(width) * _scaleFactor;

            SimpleColor simpleColor = SimpleColor.FromArgb(color);

            target.Target.CGContext.SetLineJoin(CGLineJoin.Round);
            target.Target.CGContext.SetLineWidth(widthInPixels);
            target.Target.CGContext.SetStrokeColor(simpleColor.R / 256.0f, simpleColor.G / 256.0f, simpleColor.B / 256.0f,
                                                   simpleColor.A / 256.0f);
            target.Target.CGContext.SetLineDash(0, new float[0]);
            if (dashes != null && dashes.Length > 1)
            {
                float[] intervals = new float[dashes.Length];
                for (int idx = 0; idx < dashes.Length; idx++)
                {
                    intervals[idx] = dashes[idx];
                }
                target.Target.CGContext.SetLineDash(0.0f, intervals);
            }

            // transform the points all at once.
            double[][] transformed = this.TransformAll(x, y);

            // construct path.
            target.Target.CGContext.BeginPath();
            PointF[] points = new PointF[x.Length];
            for (int idx = 0; idx < x.Length; idx++)
            {
                points[idx] = new PointF((float)transformed[idx][0], (float)transformed[idx][1]);
            }
            target.Target.CGContext.AddLines(points);
            target.Target.CGContext.DrawPath(CGPathDrawingMode.Stroke);
        }
示例#12
0
        public void TestMapCSSWayRendering1()
        {
            // create the data source.
            MemoryDataSource source = new MemoryDataSource(
                Node.Create(1, 1, 1),
                Node.Create(2, -1, -1),
                Way.Create(1, new SimpleTagsCollection(Tag.Create("highway", "residential")), 1, 2));

            // create CSS.
            string css = "canvas { " +
                         "fill-color: white; " +
                         "}  " +
                         "way { " +
                         "   width: 2; " +
                         "   color: black; " +
                         "} ";

            // do the rendering.
            Bitmap rendering = this.Render(source, css);

            // check result.
            Assert.AreEqual(SimpleColor.FromKnownColor(OsmSharp.UI.KnownColor.White).Value,
                            rendering.GetPixel(0, 99).ToArgb());
            Assert.AreEqual(SimpleColor.FromKnownColor(OsmSharp.UI.KnownColor.White).Value,
                            rendering.GetPixel(99, 0).ToArgb());
            for (int x = 0; x < 100; x++)
            {
                Assert.AreEqual(SimpleColor.FromKnownColor(OsmSharp.UI.KnownColor.Black).Value,
                                rendering.GetPixel(x, x).ToArgb());
            }
        }
        public void TestDomainColorNamed()
        {
            // parses the MapCSS.
            AstParserRuleReturnScope <object, IToken> result = this.TestMapCSSParsing(
                "OsmSharp.UI.Unittests.Data.MapCSS.color-named.mapcss");

            // Test the very minimum; no errors during parsing says a lot already!
            var tree = result.Tree as Antlr.Runtime.Tree.CommonTree;

            Assert.NotNull(tree);
            Assert.AreEqual(2, tree.ChildCount);

            // parse into domain.
            MapCSSFile file = MapCSSDomainParser.Parse(tree);

            Assert.IsNotNull(file);
            Assert.AreEqual(1, file.Rules.Count);
            Assert.AreEqual(1, file.Rules[0].Declarations.Count);
            Assert.IsInstanceOf(typeof(DeclarationInt), file.Rules[0].Declarations[0]);

            // get color declaration.
            var declarationInt = file.Rules[0].Declarations[0] as DeclarationInt;

            Assert.IsNotNull(declarationInt);
            Assert.AreEqual(DeclarationIntEnum.Color, declarationInt.Qualifier);

            // instantiate color.
            var simpleColor = new SimpleColor();

            simpleColor.Value = declarationInt.Eval((MapCSSObject)null);
            Assert.AreEqual("#FFFFFF", simpleColor.HexRgb);
        }
示例#14
0
        void mapControl1_MapMouseClick(MapControlEventArgs e)
        {
            if (_router != null)
            {
                var routerPoint = _router.Resolve(Vehicle.Car, e.Position);
                if (routerPoint != null)
                {
                    _points.Add(routerPoint);
                    _layerPrimitives.AddPoint(routerPoint.Location, 15, SimpleColor.FromKnownColor(KnownColor.Black).Value);
                    _layerPrimitives.AddPoint(routerPoint.Location, 7, SimpleColor.FromKnownColor(KnownColor.White).Value);
                }

                if (_points.Count > 1)
                {
                    var tspRouter = new RouterTSPWrapper <RouterTSPAEXGenetic>(
                        new RouterTSPAEXGenetic(), _router);

                    var route = tspRouter.CalculateTSP(Vehicle.Car, _points.ToArray());
                    if (route != null)
                    {
                        _layerRoute.Clear();
                        _layerRoute.AddRoute(route);
                    }
                }
            }
        }
        /// <summary>
        /// Подсчитывает среднеквадратичное отклонение по каждому компоненту RGB.
        /// </summary>
        /// <param name="image">Матрица первого изображения</param>
        /// <param name="imageStart">Левая верхняя сопоставляемая точка в матрице image</param>
        /// <param name="template">Матрица сопоставляемого шаблона</param>
        /// <param name="reservedColor">Точки этого цвета в шаблоне не учитываются</param>
        public static SimpleColor CalculateDifference(SimpleColor[][] image, Point imageStart, 
			SimpleColor[][] template, SimpleColor reservedColor)
        {
            int red = 0, green = 0, blue = 0;
            int uncounted = 0;
            int width = template.GetLength(0);
            int height = template[0].GetLength(0);

            for (int dx = 0; dx < width; ++dx)
                for (int dy = 0; dy < height; ++dy)
                {
                    var templateColor = template[dx][dy];

                    if (reservedColor == templateColor)
                    {
                        ++uncounted;
                        continue;
                    }

                    var imageColor = image[imageStart.X + dx][imageStart.Y + dy];

                    var dR = imageColor.R - templateColor.R;
                    var dG = imageColor.G - templateColor.G;
                    var dB = imageColor.B - templateColor.B;

                    red += dR * dR;
                    green += dG * dG;
                    blue += dB * dB;
                }

            var totalPoints = width * height - uncounted;
            return GetResultSimpleColor(red, green, blue, totalPoints);
        }
示例#16
0
        /// <summary>
        /// Recodes the given byte.
        /// </summary>
        internal override byte Recode(byte codedByte)
        {
            // Get key byte
            byte keyByte;
            switch (_colorTracker) {
                case ColorCode.Blue:
                    // Set source information and next color
                    keyByte = _currentColor.Blue;
                    _colorTracker = ColorCode.Red;
                    break;
                case ColorCode.Green:
                    // Set source information and next color
                    keyByte = _currentColor.Green;
                    _colorTracker = ColorCode.Blue;
                    break;
                case ColorCode.Red:
                    // Color code red always sets the new color and updates the position information
                    _currentColor = _imageData.GetNextColor();

                    // Set source information and next color
                    keyByte = _currentColor.Red;
                    _colorTracker = ColorCode.Green;
                    break;
                default:
                    throw new Exception("Bonk");
            }

            // Return the recoded byte
            return (byte)(keyByte - codedByte);
        }
示例#17
0
        public static Color ToUnityColor(this SimpleColor color)
        {
            switch (color)
            {
            case SimpleColor.White:
                return(Color.white);

            case SimpleColor.Red:
                return(Color.red);

            case SimpleColor.Green:
                return(Color.green);

            case SimpleColor.Blue:
                return(Color.blue);

            case SimpleColor.Magenta:
                return(Color.magenta);

            case SimpleColor.Yellow:
                return(Color.yellow);

            case SimpleColor.Cyan:
                return(Color.cyan);

            default:
                throw new ArgumentException();
            }
        }
示例#18
0
        /// <summary>
        /// Initialize implementation from IMapView.
        /// </summary>
        /// <param name="mapLayout"></param>
        void IMapViewSurface.Initialize(MapView mapLayout)
        {
            _mapView = mapLayout;
            this.SetWillNotDraw(false);

            this.MapMinZoomLevel = 10;
            this.MapMaxZoomLevel = 20;

            _renderer = new MapRenderer <global::Android.Graphics.Canvas>(
                new CanvasRenderer2D());

            // initialize the gesture detection.
            this.SetOnTouchListener(this);
            _scaleGestureDetector = new ScaleGestureDetector(
                this.Context, this);
            _rotateGestureDetector = new RotateGestureDetector(
                this.Context, this);
            _moveGestureDetector = new MoveGestureDetector(
                this.Context, this);
            _tagGestureDetector = new TapGestureDetector(
                this.Context, this);

            _makerLayer = new LayerPrimitives(
                new WebMercator());

            // initialize all the caching stuff.
            _backgroundColor = SimpleColor.FromKnownColor(KnownColor.White).Value;
            _cacheRenderer   = new MapRenderer <global::Android.Graphics.Canvas>(
                new CanvasRenderer2D());
        }
示例#19
0
        /// <summary>
        /// Adds a new OsmSharpRoute.
        /// </summary>
        /// <param name="route">Stream.</param>
        /// <param name="argb">Stream.</param>
        public void AddRoute(OsmSharpRoute route, int argb)
        {
            if (route.Entries != null && route.Entries.Length > 0)
            {             // there are entries.
                // get x/y.
                var x = new double[route.Entries.Length];
                var y = new double[route.Entries.Length];
                for (int idx = 0; idx < route.Entries.Length; idx++)
                {
                    x[idx] = _projection.LongitudeToX(
                        route.Entries[idx].Longitude);
                    y[idx] = _projection.LatitudeToY(
                        route.Entries[idx].Latitude);
                }

                // set the default color if none is given.
                SimpleColor blue = new SimpleColor()
                {
                    Value = argb
                };
                SimpleColor color = SimpleColor.FromArgb(argb);
                this.Scene.AddLine(float.MinValue, float.MaxValue, x, y,
                                   color.Value, 4);
            }
        }
示例#20
0
        /// <summary>
        /// Draws a polygon on the target. The coordinates given are scene coordinates.
        /// </summary>
        /// <param name="target"></param>
        /// <param name="x">The x coordinate.</param>
        /// <param name="y">The y coordinate.</param>
        /// <param name="color">Color.</param>
        /// <param name="width">Width.</param>
        /// <param name="fill">If set to <c>true</c> fill.</param>
        protected override void DrawPolygon(Target2DWrapper <CGContextWrapper> target, double[] x, double[] y, int color, double width,
                                            bool fill)
        {
            float widthInPixels = this.ToPixels(width) * _scaleFactor;

            SimpleColor simpleColor = SimpleColor.FromArgb(color);

            target.Target.CGContext.SetLineWidth(widthInPixels);
            target.Target.CGContext.SetFillColor(simpleColor.R / 256.0f, simpleColor.G / 256.0f, simpleColor.B / 256.0f,
                                                 simpleColor.A / 256.0f);
            target.Target.CGContext.SetStrokeColor(simpleColor.R / 256.0f, simpleColor.G / 256.0f, simpleColor.B / 256.0f,
                                                   simpleColor.A / 256.0f);

            // transform the points all at once.
            double[][] transformed = this.TransformAll(x, y);

            // build the path.
            target.Target.CGContext.BeginPath();
            PointF[] points = new PointF[x.Length];
            for (int idx = 0; idx < x.Length; idx++)
            {
                points[idx] = new PointF((float)transformed[idx][0], (float)transformed[idx][1]);
            }

            target.Target.CGContext.AddLines(points);
            target.Target.CGContext.ClosePath();
            target.Target.CGContext.FillPath();
        }
示例#21
0
        /// <summary>
        /// Raises the draw frame event.
        /// </summary>
        /// <param name="gl">Gl.</param>
        public void OnDrawFrame(IGL10 gl)
        {
            // Replace the current matrix with the identity matrix
            gl.GlMatrixMode(GL10.GlProjection);
            gl.GlLoadIdentity();             // OpenGL docs
            gl.GlOrthof(_left, _right, _bottom, _top, -1, 1);

            for (int idx = 0; idx < _triangles.Count; idx++)
            {
                gl.GlVertexPointer(3, GL10.GlFloat, 0, _triangles[idx].Vertices);
                gl.GlEnableClientState(GL10.GlVertexArray);
                gl.GlColorPointer(4, GL10.GlUnsignedByte, 0, _triangles[idx].Colors);
                gl.GlEnableClientState(GL10.GlColorArray);

                gl.GlDrawArrays(GL10.GlTriangleStrip, 0, _triangles[idx].Count);
            }

            for (int idx = 0; idx < _lines.Count; idx++)
            {
                gl.GlVertexPointer(3, GL10.GlFloat, 0, _lines[idx].Vertices);
                gl.GlEnableClientState(GL10.GlVertexArray);

                SimpleColor color = new SimpleColor()
                {
                    Value = _lines[idx].Color
                };
                gl.GlColor4f(color.R / 255f, color.G / 255f, color.B / 255f, color.A / 255f);
                gl.GlLineWidth(_lines [idx].Width);
                gl.GlDrawArrays(GL10.GlLineStrip, 0, _lines[idx].Count);
            }
        }
示例#22
0
        /// <summary>
        /// Adds a new OsmSharpRoute.
        /// </summary>
        /// <param name="route">Stream.</param>
        public void AddRoute(Route route)
        {
            // set the default color if none is given.
            var blue            = SimpleColor.FromKnownColor(KnownColor.Blue);
            var transparantBlue = SimpleColor.FromArgb(128, blue.R, blue.G, blue.B);

            this.AddRoute(route, transparantBlue.Value);
        }
示例#23
0
        public void WriteGridColor(SimpleColor color)
        {
            if (ClientsCount == 0)
            {
                return;
            }

            EnqueueWrite(new ColorSocketObject(SocketConstants.SocketAction.GridColor, color.A, color.R, color.G, color.B));
        }
示例#24
0
        /// <summary>
        /// Draws the backcolor.
        /// </summary>
        /// <param name="target"></param>
        /// <param name="backColor"></param>
        protected override void DrawBackColor(Target2DWrapper <CGContextWrapper> target, int backColor)
        {
            SimpleColor backColorSimple = SimpleColor.FromArgb(backColor);

            target.Target.CGContext.SetFillColor(backColorSimple.R / 256.0f, backColorSimple.G / 256.0f, backColorSimple.B / 256.0f,
                                                 backColorSimple.A / 256.0f);
            target.Target.CGContext.FillRect(new RectangleF(0, 0,
                                                            target.Width * _scaleFactor, target.Height * _scaleFactor));
        }
        /// <param name="reservedColor">Points in template which match reservedColor are considered transparent</param>
        /// <exception cref="System.ArgumentException"></exception>
        public ImageSearcher(SimpleColor[][] template, SimpleColor reservedColor)
        {
            CheckSize(template);
            CheckTransparentDistribution(template, reservedColor);

            this.template = template;
            this.reservedColor = reservedColor;
            InitializeSmallPictureTemplate();
        }
        private void connection_OnGridColorReceived(SimpleColor gridColor)
        {
            if (gridPen != null)
            {
                gridPen.Dispose();
            }
            gridPen = new Pen(Color.FromArgb(gridColor.A, gridColor.R, gridColor.G, gridColor.B));

            RefreshMapPictureBox();
        }
示例#27
0
        public Gene(FastImage src, int minx, int miny, int maxx, int maxy, int minsz, int maxsz)
        {
            x  = _rnd.Next(minx, maxx);
            y  = _rnd.Next(miny, maxy);
            sz = _rnd.Next(minsz, maxsz);
            //color = new SimpleColor(_rnd.Next(0, 256), _rnd.Next(0, 256), _rnd.Next(0, 256));
            SimpleColor sc = src.GetPixel(_rnd.Next(0, src.width), _rnd.Next(0, src.height));

            color = new SimpleColor(sc.GetR(), sc.GetG(), sc.GetB());
        }
示例#28
0
        public void SetGridColor(SimpleColor gridColor)
        {
            if (gridPen != null)
            {
                gridPen.Dispose();
            }
            gridPen = new Pen(Color.FromArgb(gridColor.A, gridColor.R, gridColor.G, gridColor.B));

            RefreshAll();
        }
示例#29
0
        public override void DrawGhost(ThingDef def, IntVec3 center, Rot4 rot, Color ghostCol, Thing thing = null)
        {
            base.DrawGhost(def, center, rot, ghostCol);
            SimpleColor circleColor = SimpleColor.Red;

            if (ghostCol == Designator_Place.CanPlaceColor)
            {
                circleColor = SimpleColor.Green;
            }
            GenDraw.DrawCircleOutline(center.ToVector3Shifted() + new Vector3(0, AltitudeLayer.MetaOverlays.AltitudeFor(), 3).RotatedBy(rot.AsAngle), 1.5f, circleColor);
        }
示例#30
0
 /// <summary>
 /// Returns the canvas color.
 /// </summary>
 /// <returns></returns>
 public override SimpleColor GetCanvasColor()
 {
     if (_mapCSSFile != null &&
         _mapCSSFile.CanvasFillColor.HasValue)
     { // instantiate the simple color.
         return(new SimpleColor()
         {
             Value = _mapCSSFile.CanvasFillColor.Value
         });
     }
     return(SimpleColor.FromKnownColor(KnownColor.Black));
 }
示例#31
0
文件: Utils.cs 项目: aauger/GA-Image
        public static SimpleColor Blend(SimpleColor a, SimpleColor b)
        {
            int    rval, gval, bval;
            double aval;

            rval = RGBClamp((int)(a.GetA() * (a.GetR() - b.GetR()) + b.GetR()));
            gval = RGBClamp((int)(a.GetA() * (a.GetG() - b.GetG()) + b.GetG()));
            bval = RGBClamp((int)(a.GetA() * (a.GetB() - b.GetB()) + b.GetB()));
            aval = a.GetA() + b.GetA() * (1 - a.GetA());

            return(new SimpleColor(rval, gval, bval, aval));
        }
示例#32
0
        /// <summary>
        /// Draws the backcolor.
        /// </summary>
        /// <param name="target"></param>
        /// <param name="backColor"></param>
        protected override void DrawBackColor(Target2DWrapper <CGContextWrapper> target, int backColor)
        {
            var backColorSimple = SimpleColor.FromArgb(backColor);

            target.Target.CGContext.SetFillColor(backColorSimple.R / 256.0f, backColorSimple.G / 256.0f, backColorSimple.B / 256.0f,
                                                 backColorSimple.A / 256.0f);
            _rectangle.X      = 0;
            _rectangle.Y      = 0;
            _rectangle.Width  = target.Width * _scaleFactor;
            _rectangle.Height = target.Height * _scaleFactor;
            target.Target.CGContext.FillRect(_rectangle);
        }
示例#33
0
 private static Material GetLineMat(SimpleColor color)
 {
     return(color switch
     {
         SimpleColor.White => LineMatWhite,
         SimpleColor.Red => LineMatRed,
         SimpleColor.Green => LineMatGreen,
         SimpleColor.Blue => LineMatBlue,
         SimpleColor.Magenta => LineMatMagenta,
         SimpleColor.Yellow => LineMatYellow,
         SimpleColor.Cyan => LineMatCyan,
         _ => LineMatWhite,
     });
 public static Color ToUnityColor(this SimpleColor color)
 {
     return(color switch
     {
         SimpleColor.White => Color.white,
         SimpleColor.Red => Color.red,
         SimpleColor.Green => Color.green,
         SimpleColor.Blue => Color.blue,
         SimpleColor.Magenta => Color.magenta,
         SimpleColor.Yellow => Color.yellow,
         SimpleColor.Cyan => Color.cyan,
         _ => throw new ArgumentException(),
     });
        public ImageViewerForm(Bitmap image, SimpleColor differences)
        {
            InitializeComponent();

            this.MinimumSize = this.Size;
            this.MaximizeBox = false;
            this.MaximumSize = this.Size;

            this.pictureBox.SizeMode = PictureBoxSizeMode.Zoom;
            this.pictureBox.Image = new Bitmap(image);
            this.pictureBox.BorderStyle = BorderStyle.FixedSingle;

            this.redLabel.Text = differences.R.ToString();
            this.greenLabel.Text = differences.G.ToString();
            this.blueLabel.Text = differences.B.ToString();
        }
        public static bool Equals(SimpleColor[][] left, SimpleColor[][] right)
        {
            if (object.ReferenceEquals(left, right))
                return true;

            int width = Width(left);
            int heigth = Height(left);

            if (width != Width(right) || heigth != Height(right))
                return false;

            for (int x = 0; x < width; ++x)
                for (int y = 0; y < heigth; ++y)
                    if (left[x][y] != right[x][y])
                        return false;

            return true;
        }
        /// <summary>
        /// Searches for subpictures that match template
        /// </summary>
        public IEnumerable<Point> GetPositions(SimpleColor[][] source)
        {
            var smallPicturePositions = GetSmallPicturePositions(source);

            foreach (var pos in smallPicturePositions)
            {
                if (ImageComparer.Equals(
                    source,
                    pos,
                    template,
                    reservedColor,
                    maxDifference))
                {
                    yield return pos;
                }
            }
        }
 private static bool IsAllPointsHasOneColor(SimpleColor[][] image, Point start, Point delta, SimpleColor color)
 {
     while (start.X >= 0 && start.X < ImageComparer.Width(image) &&
         start.Y >= 0 && start.Y < ImageComparer.Height(image))
     {
         if (image[start.X][start.Y] != color)
             return false;
         start.X += delta.X;
         start.Y += delta.Y;
     }
     return true;
 }
        private static void SmartInsert(SimpleColor[] minValues, Point[] positions, SimpleColor value, Point pos)
        {
            int indexOfMax = 0;

            for (int i = 1; i < minValues.Length; ++i)
                if (Compare(minValues[i], minValues[indexOfMax]) > 0)
                    indexOfMax = i;

            if (Compare(value, minValues[indexOfMax]) < 0)
            {
                minValues[indexOfMax] = value;
                positions[indexOfMax] = pos;
            }
        }
示例#40
0
            public ImageData(Bitmap keyFile)
            {
                int index = 0;
                int width = keyFile.Width;
                int height = keyFile.Height;

                _length = width * height;
                _colors = new SimpleColor[_length];
                _currentIndex = -1;

                for (int x = 0; x < width; x++)
                    for (int y = 0; y < height; y++) {
                        Color pixel = keyFile.GetPixel(x, y);
                        _colors[index++] = new SimpleColor(pixel.R, pixel.G, pixel.B);
                    }
            }
        private void Learn(SimpleColor[][] image, int elementsLeft, List<Rectangle> invalidRegions)
        {
            int width = ImageComparer.Width(image);
            int height = ImageComparer.Height(image);

            int maxX = width - this.Width + 1;
            int maxY = height - this.Height + 1;

            var differences = ImageConverter.CreateMatrix<SimpleColor>(maxX, maxY);
            Parallel.For(0, maxX, x =>
                {
                    for (int y = 0; y < maxY; ++y)
                        differences[x][y] = ImageComparer.CalculateDifference(
                            image,
                            new Point(x, y),
                            this.template,
                            this.reservedColor);
                });

            var bestPositions = new List<Point>();

            while (elementsLeft > 0)
            {
                var position = FindMin(differences, bestPositions);
                bestPositions.Add(position);
                --elementsLeft;
            }

            var minDiffs = bestPositions.Select(pos => differences[pos.X][pos.Y]).ToArray();
            UpdateAdmissibleDifference(minDiffs);
            UpdateAdmissibleDifferenceForSmallTemplate(image, bestPositions.ToArray());
        }
 /// <exception cref="System.ArgumentException">Invalid template</exception>
 /// <exception cref="System.ArgumentNullException"></exception>
 public BitmapSearcher(Bitmap template, SimpleColor transparentColor)
 {
     if (object.ReferenceEquals(template, null))
         throw new ArgumentNullException("template");
     searcher = new ImageSearcher(Converter.ToMatrix(template), transparentColor);
 }
 public static int Width(SimpleColor[][] image)
 {
     return image.Length;
 }
 public static int Height(SimpleColor[][] image)
 {
     return image[0].Length;
 }
        /// <summary>
        /// Сопоставляет с шаблоном часть изображения
        /// </summary>
        /// <param name="image">Изображение, часть которого будет сопоставляться с шаблоном</param>
        /// <param name="imageStart">Левая верхняя сопоставляемая точка изображения</param>
        /// <param name="template">Сопоставляемый шаблон</param>
        /// <param name="reservedColor">Не учитываемый цвет в шаблоне</param>
        /// <param name="admissibleDifference">Содержит максимальные допустимые отклонения</param>
        /// <returns>Результат сравнения</returns>
        public static bool Equals(SimpleColor[][] image, Point imageStart, 
			SimpleColor[][] template, SimpleColor reservedColor, SimpleColor admissibleDifference)
        {
            SimpleColor diff = CalculateDifference(image, imageStart, template, reservedColor);
            return (diff.R <= admissibleDifference.R && diff.G <= admissibleDifference.G && diff.B <= admissibleDifference.B);
        }
        private void UpdateAdmissibleDifferenceForSmallTemplate(SimpleColor[][] sourceMatrix, Point[] positions)
        {
            foreach (var position in positions)
            {
                SimpleColor simpleColor = ImageComparer.CalculateDifference(
                        sourceMatrix,
                        new Point(position.X + smallPictureRegion.Left, position.Y + smallPictureRegion.Top),
                        smallPictureTemplate,
                        reservedColor);

                smallPictureMaxDifference.R = Math.Max(smallPictureMaxDifference.R, simpleColor.R);
                smallPictureMaxDifference.G = Math.Max(smallPictureMaxDifference.G, simpleColor.G);
                smallPictureMaxDifference.B = Math.Max(smallPictureMaxDifference.B, simpleColor.B);
            }
        }
 private void UpdateAdmissibleDifference(SimpleColor[] differences)
 {
     foreach (var difference in differences)
     {
         maxDifference.R = Math.Max(maxDifference.R, difference.R);
         maxDifference.G = Math.Max(maxDifference.G, difference.G);
         maxDifference.B = Math.Max(maxDifference.B, difference.B);
     }
 }
        private Point FindMin(SimpleColor[][] differences, List<Point> taken)
        {
            int width = ImageComparer.Width(differences);
            int height = ImageComparer.Height(differences);

            SimpleColor min = (SimpleColor)Color.White;
            Point pos = new Point();
            object locker = new object();

            Parallel.For(0, width, x =>
                {
                    Point localPos = new Point();
                    SimpleColor localMin;
                    localPos.X = x;
                    lock (locker)
                        localMin = min;

                    for (int y = 0; y < height; ++y)
                    {
                        bool valid = true;
                        foreach (var p in taken)
                            if (IsConflicted(p, x, y))
                            {
                                valid = false;
                                break;
                            }

                        if (valid && Compare(differences[x][y], localMin) < 0)
                        {
                            localMin = differences[x][y];
                            localPos.Y = y;
                        }
                    }

                    lock (locker)
                        if (Compare(localMin, min) < 0)
                        {
                            min = localMin;
                            pos = localPos;
                        }
                });

            if (min == (SimpleColor)Color.White)
                throw new InvalidOperationException("Cant find all subpictures. State may be corrupted now.");
            return pos;
        }
        /// <summary>
        /// Searches for potential positions of template
        /// </summary>
        private IEnumerable<Point> GetSmallPicturePositions(SimpleColor[][] source)
        {
            int maxX = source.GetLength(0) - template.GetLength(0);
            int maxY = source[0].GetLength(0) - template[0].GetLength(0);
            var verticals = new List<Point>[maxX];

            Parallel.For(0, maxX, x =>
                {
                    verticals[x] = new List<Point>();
                    for (int y = 0; y < maxY; ++y)
                    {
                        if (ImageComparer.Equals(
                            source,
                            new Point(x + smallPictureRegion.Left, y + smallPictureRegion.Top),
                            smallPictureTemplate,
                            reservedColor,
                            smallPictureMaxDifference))
                        {
                            verticals[x].Add(new Point(x, y));
                        }
                    }
                });

            for (int x = 0; x < maxX; ++x)
                foreach (var p in verticals[x])
                    yield return p;
        }
        private static Tiling CreateTiling(double offsetX, double offsetY, double width, SimpleColor color)
        {
            Tiling tiling = new Tiling(new Rect(0, 0, width, 2));
            tiling.Position.Translate(offsetX, offsetY);
            var tilingEditor = new FixedContentEditor(tiling);
            tilingEditor.GraphicProperties.IsStroked = false;
            tilingEditor.GraphicProperties.FillColor = color;
            tilingEditor.DrawRectangle(new Rect(0, 0, width, 1));
            LinearGradient gradient = new LinearGradient(new Point(0, 0), new Point(width, 0));
            gradient.GradientStops.Add(new GradientStop(color, 0));
            gradient.GradientStops.Add(new GradientStop(RgbColors.White, .5));
            gradient.GradientStops.Add(new GradientStop(color, 1));
            tilingEditor.GraphicProperties.FillColor = gradient;
            tilingEditor.DrawRectangle(new Rect(0, 1, width, 1));

            return tiling;
        }
 private static void UniteDifferences(ref SimpleColor left, SimpleColor right)
 {
     left.R = Math.Max(left.R, right.R);
     left.G = Math.Max(left.G, right.G);
     left.B = Math.Max(left.B, right.B);
 }
示例#52
0
        /// <summary>
        /// Translates a lineair ring.
        /// </summary>
        /// <param name="scene">The scene to add primitives to.</param>
        /// <param name="projection">The projection used to convert the objects.</param>
        /// <param name="lineairRing"></param>
        private void TranslateLineairRing(Scene2D scene, IProjection projection, LineairRing lineairRing)
        {
            // build the rules.
            List<MapCSSRuleProperties> rules =
                this.BuildRules(new MapCSSObject(lineairRing));

            // validate what's there.
            if (rules.Count == 0)
            {
                return;
            }

            // get x/y.
            double[] x = null, y = null;
            if (lineairRing.Coordinates != null &&
                lineairRing.Coordinates.Count > 0)
            { // pre-calculate x/y.
                x = new double[lineairRing.Coordinates.Count];
                y = new double[lineairRing.Coordinates.Count];
                for (int idx = 0; idx < lineairRing.Coordinates.Count; idx++)
                {
                    x[idx] = projection.LongitudeToX(
                        lineairRing.Coordinates[idx].Longitude);
                    y[idx] = projection.LatitudeToY(
                        lineairRing.Coordinates[idx].Latitude);
                }

                // simplify.
                if (x.Length > 2)
                {
                    double[][] simplified = SimplifyCurve.Simplify(new double[][] { x, y }, 0.0001);
                    x = simplified[0];
                    y = simplified[1];
                }
            }
            // add the z-index.
            foreach (var rule in rules)
            {
                float minZoom = (float)projection.ToZoomFactor(rule.MinZoom);
                float maxZoom = (float)projection.ToZoomFactor(rule.MaxZoom);

                int zIndex;
                if (!rule.TryGetProperty<int>("zIndex", out zIndex))
                {
                    zIndex = 0;
                }

                // interpret the results.
                if (x != null)
                { // there is a valid interpretation of this way.
                    int color;
                    int fillColor;
                    if (rule.TryGetProperty("fillColor", out fillColor))
                    { // render as an area.
                        float fillOpacity;
                        if(rule.TryGetProperty("fillOpacity", out fillOpacity))
                        {
                            SimpleColor simpleFillColor = new SimpleColor() { Value = fillColor };
                            fillColor = SimpleColor.FromArgb((int)(255 * fillOpacity),
                                simpleFillColor.R, simpleFillColor.G, simpleFillColor.B).Value;
                        }
                        uint? pointsId = scene.AddPoints(x, y);
                        if (pointsId.HasValue)
                        {
                            scene.AddStylePolygon(pointsId.Value, this.CalculateSceneLayer(OffsetArea, zIndex), minZoom, maxZoom, fillColor, 1, true);
                            if (rule.TryGetProperty("color", out color))
                            {
                                scene.AddStylePolygon(pointsId.Value, this.CalculateSceneLayer(OffsetCasing, zIndex), minZoom, maxZoom, color, 1, false);
                            }
                        }
                    }
                }
            }
        }
        private static void CheckTransparentDistribution(SimpleColor[][] template, SimpleColor transparent)
        {
            int width = ImageComparer.Width(template);
            int height = ImageComparer.Height(template);

            bool badTransparentDistribution =
                IsAllPointsHasOneColor(template, new Point(0, 0), new Point(1, 0), transparent) ||
                IsAllPointsHasOneColor(template, new Point(0, 0), new Point(0, 1), transparent) ||
                IsAllPointsHasOneColor(template, new Point(width - 1, height - 1), new Point(-1, 0), transparent) ||
                IsAllPointsHasOneColor(template, new Point(width - 1, height - 1), new Point(0, -1), transparent);

            if (badTransparentDistribution)
                throw BadTransparentDistributionException;
        }
 /// <summary>
 /// Updates maximal admissible differences
 /// </summary>
 /// <param name="elements">Count of elements on the image that should match template</param>
 public void Learn(SimpleColor[][] image, int elements)
 {
     Learn(image, elements, new List<Rectangle>());
 }
 private static void CheckSize(SimpleColor[][] template)
 {
     if (template.GetLength(0) < smallTemplateWidth || template[0].GetLength(0) < smallTemplateHeight)
         throw new ArgumentException(
             string.Format("To small size of template. Required at least: width = {0}, height = {1}",
                 smallTemplateWidth, smallTemplateHeight));
 }
 // A simple comparator
 private static int Compare(SimpleColor leftDifference, SimpleColor rightDifference)
 {
     return (leftDifference.R + leftDifference.G + leftDifference.B)
         .CompareTo(rightDifference.R + rightDifference.G + rightDifference.B);
 }