public MyPoint GetClosestPoint(int x, int y)
        {
            MyPoint closest = Points.FirstOrDefault();

            if (!Points.Any())
            {
                return(null);
            }

            double closestDistance = Hypothenuse(x, y, closest.X, closest.Y);

            foreach (var point in Points)
            {
                var currentHyp = Hypothenuse(x, y, point.X, point.Y);
                if (currentHyp < closestDistance)
                {
                    closest         = point;
                    closestDistance = currentHyp;
                }
            }

            if (closest == Points.Last())
            {
                return(null);
            }

            return(closest);
        }
Exemplo n.º 2
0
 private void RemovePoint()
 {
     if (Points.Any())
     {
         Points.RemoveAt(Points.Count - 1);
     }
 }
Exemplo n.º 3
0
 private void ThrowIfInvalidGapInterval()
 {
     if (Points.Any() && (Points.First().Type == PointType.Gap || Points.Last().Type == PointType.Gap))
     {
         throw new ExpectedException($"You can only insert manual {nameof(PointType.Gap)} points in between valid timestamps.");
     }
 }
Exemplo n.º 4
0
 /// <summary>
 /// Checks whether the current <see cref="Points"/> collection is not empty.
 /// </summary>
 /// <exception cref="InvalidOperationException">Thrown when <see cref="Points"/> is empty.</exception>
 private void ValidateHasPoints()
 {
     if (!Points.Any())
     {
         throw new InvalidOperationException(Resources.MechanismSurfaceLineBase_SurfaceLine_has_no_Geometry);
     }
 }
Exemplo n.º 5
0
 private void ThrowIfGapsNotSupported(IAquariusClient client)
 {
     if (Points.Any(p => p.Type == PointType.Gap) && client.ServerVersion.IsLessThan(MinimumGapVersion))
     {
         throw new ExpectedException($"You can't insert manual {nameof(PointType.Gap)} points before AQTS v{MinimumGapVersion}");
     }
 }
Exemplo n.º 6
0
        /// <summary>
        /// Render loop
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CompositionTarget_Rendering(object sender, EventArgs e)
        {
            TimeSpan timeSinceLastRender = DateTime.Now.TimeOfDay - LastRenderTime;

            if (timeSinceLastRender.TotalSeconds < (1.0 / FrameLimiter))
            {
                return;
            }

            LastRenderTime = DateTime.Now.TimeOfDay;

            // Stop animation if there is no more points
            if (!Points.Any())
            {
                CompositionTarget.Rendering -= CompositionTarget_Rendering;
                IsBusy    = false;
                IsPlaying = false;
                Demo.PositionPoints.Clear();
                Points.Clear();
                CommandManager.InvalidateRequerySuggested();
                return;
            }

            // Draw points for each player
            foreach (List <PositionPoint> positionPoints in Points)
            {
                if (positionPoints.Any())
                {
                    // get the first point of the list
                    PositionPoint positionPoint = positionPoints.First();

                    // If there is an event at this point, draw it
                    if (positionPoint.Event != null)
                    {
                        if (!string.IsNullOrWhiteSpace(positionPoint.Event.Message))
                        {
                            _events.Add(positionPoint.Event);
                        }

                        _drawService.DrawEvent(positionPoint);
                    }
                    else
                    {
                        // Draw it
                        _drawService.DrawPixel(positionPoint);
                        _drawService.DrawPlayerMarker(positionPoint);
                    }

                    // Remove this point
                    positionPoints.Remove(positionPoint);

                    // If there is no more points remove the list from all the lists
                    if (!positionPoints.Any())
                    {
                        Points.Remove(positionPoints);
                        break;
                    }
                }
            }
        }
Exemplo n.º 7
0
        public Geometry GetGeometry(bool includePending)
        {
            if (!Points.Any())
            {
                return(new EllipseGeometry(PendingPoint, 0.025, 0.025));
            }
            if (Points.Count == 1)
            {
                return(new GeometryGroup
                {
                    Children = new GeometryCollection
                    {
                        new EllipseGeometry(Points.First(), 0.025, 0.025),
                        new EllipseGeometry(PendingPoint, 0.025, 0.025)
                    }
                });
            }

            var pathFigure   = new PathFigure(Points.First(), new List <PathSegment>(), true);
            var pathGeometry = new PathGeometry();

            pathGeometry.Figures.Add(pathFigure);
            foreach (var point in Points.Skip(1))
            {
                pathFigure.Segments.Add(new LineSegment(point, true));
            }
            if (includePending)
            {
                pathFigure.Segments.Add(new LineSegment(PendingPoint, true));
            }

            return(pathGeometry);
        }
Exemplo n.º 8
0
        public override bool OnMouseDown(Point point)
        {
            if (!Points.Any <Point>())
            {
                //Move the selection
                if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
                {
                    return(false);
                }
                //Start a new selection (otherwise, add to the selection)
                else if (!(Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)))
                {
                    Document.Selections.Clear();
                }

                Points.Add(point);
                Points.Add(point);

                Preview = new PointCollection(Points);
            }
            else
            {
                if (Points.Last <Point>() == point)
                {
                    point = new Point(point.X + 1, point.Y + 1);
                }

                Points.Add(point);
                Preview = new PointCollection(Points);
            }

            base.OnMouseDown(point);
            return(true);
        }
Exemplo n.º 9
0
 /// <summary>
 /// Проверка - есть ли точка с таким id в расчете
 /// </summary>
 public bool HasPoint(ObjectId idPoint)
 {
     if (Points == null || Points.Count == 0)
     {
         return(false);
     }
     return(Points.Any(p => p.DBPointId == idPoint));
 }
Exemplo n.º 10
0
        public void AddPoint(double x, double y)
        {
            if (Points.Any(p => Math.Abs(p.Item1 - x) < CompareMargin))
            {
                throw new WrongValueException("X values can not be repeated");
            }

            Points.Add(new Tuple <double, double>(x, y));
        }
Exemplo n.º 11
0
        public void AddPoint(Tuple <double, double> point)
        {
            if (Points.Any(p => Math.Abs(p.Item1 - point.Item1) < CompareMargin))
            {
                throw new WrongValueException("X values can not be repeated");
            }

            Points.Add(point);
        }
Exemplo n.º 12
0
        /// <summary>
        ///     Moves the specified blocks.
        /// </summary>
        /// <param name="blocks">The blocks.</param>
        private void Move(int blocks)
        {
            // Store starting point.
            string startPoint = Coordinates();

            for (var i = 0; i < blocks; i++)
            {
                // Move 1 block at a time - required for Part 2
                int x = CurrentPoint.X;
                int y = CurrentPoint.Y;
                switch (CurrentDirection)
                {
                case Direction.East:
                    x++;
                    break;

                case Direction.West:
                    x--;
                    break;

                case Direction.North:
                    y++;
                    break;

                case Direction.South:
                    y--;
                    break;

                default:
                    Console.WriteLine(
                        $"Huh? It seems that you're trying to move in a non-standard direction. ({CurrentDirection})");
                    break;
                }

                // Set current position.
                CurrentPoint = new Point(x, y);

                // If there are any points in our log of previously visited points (X and Y coordinates match),
                // and we have not found a previously-visited block, set this block as our first revisited block.
                if (Points.Any(point => CurrentPoint.X == point.X && CurrentPoint.Y == point.Y) &&
                    FirstRevisitedPoint.X == 0 &&
                    FirstRevisitedPoint.Y == 0)
                {
                    FirstRevisitedPoint = CurrentPoint;
                }

                // Add the current point to our log of positions.
                Points.Add(CurrentPoint);
            }

            // Add the current movement to our log.
            Sb.AppendLine(string.Join(",", CurrentDirection.ToString(), blocks.ToString(), CurrentPoint.X.ToString(),
                                      CurrentPoint.Y.ToString()));
            Console.WriteLine(
                $"Travelled {blocks.ToString().PadLeft(6)} blocks {CurrentDirection.ToString().PadRight(10)} from {startPoint.PadRight(5)} to {Coordinates().PadRight(8)}");
        }
        private void CompressCoordinates()
        {
            double scaleX = 1.0 / 9.5;
            double scaleY = 1.0 / 16.9;

            Points.ForEach(p =>
            {
                p.X = Math.Round(p.X * scaleX, 0);
                p.Y = Math.Round(p.Y * scaleY, 0);
            });

            do
            {
                List <Tuple <double, double> > usedPoints = new List <Tuple <double, double> >();

                double minX = Points.Min(p => p.X);
                double minY = Points.Min(p => p.Y);

                Points.ForEach(p =>
                {
                    double tempX = p.X - minX;
                    double tempY = p.Y - minY;

                    int offsetStart = 0;
                    int offsetEnd   = 0;
                    int offsetX     = 0;
                    int offsetY     = 0;

                    while (usedPoints.Any(pt => pt.Item1 == tempX + offsetX && pt.Item2 == tempY + offsetY))
                    {
                        bool hasFoundFree = false;

                        offsetStart -= 4;
                        offsetEnd   += 4;

                        for (int i = offsetStart; !hasFoundFree && i <= offsetEnd; i++)
                        {
                            for (int j = offsetStart; !hasFoundFree && j <= offsetEnd; j++)
                            {
                                if (!usedPoints.Any(pt => pt.Item1 == tempX + i && pt.Item2 == tempY + j))
                                {
                                    offsetX      = i;
                                    offsetY      = j;
                                    hasFoundFree = true;
                                }
                            }
                        }
                    }

                    p.X = tempX + offsetX;
                    p.Y = tempY + offsetY;

                    usedPoints.Add(Tuple.Create(p.X, p.Y));
                });
            } while (Points.Any(p => p.X < 0 || p.Y < 0));
        }
Exemplo n.º 14
0
        /// <inheritdoc/>
        public override string ToString()
        {
            // If there is a specific configuration object, we include it
            var objectPart = ConfigurationObject == null ? "" : $"{ConfigurationObject.Id}";

            // If there are points, include them
            var pointsPart = Points.Any() ? $"({Points.Select(point => point.ToString()).Ordered().ToJoinedString()})" : "";

            // Construct the final string including the points
            return($"{objectPart}{pointsPart}");
        }
Exemplo n.º 15
0
        //--------------------------------------------------------------------------------------------------

        void _UpdateTrihedron()
        {
            if (!Points.Any())
            {
                return;
            }

            // Calc Center
            var center = new XY();

            Points.ForEach(i => center.Add(_Sketch.Points[i].Coord));
            center.Divide(Points.Count);
            _Center2D = center.ToPnt();

            //Debug.WriteLine("MoveSketchPointAction - Center {0} {1}", center.X(), center.Y());

            // Project center point onto sketch plane
            var center3D = ElSLib.Value(center.X, center.Y, _Sketch.Plane);

            //Debug.WriteLine("MoveSketchPointAction - Center3D {0} {1} {2}", center3D.X(), center3D.Y(), center3D.Z());

            // Calculate center point on working plane
            if (_Sketch.Plane.Location.IsEqual(WorkspaceController.Workspace.WorkingPlane.Location, 0.00001))
            {
                _Center2DOnWorkingPlane = _Center2D;
            }
            else
            {
                double u = 0, v = 0;
                ElSLib.Parameters(WorkspaceController.Workspace.WorkingPlane, _Sketch.Plane.Location, ref u, ref v);
                _Center2DOnWorkingPlane = _Center2D.Translated(new Vec2d(u, v));
            }


            // Use plane from sketch, but translate it to center position
            var plane = _Sketch.Plane;

            plane.Location = center3D;
            _GizmoPlane    = new Geom_Plane(plane);
            _GeomPlane     = new Geom_Plane(plane);

            // Create Gizmo
            if (Gizmo == null)
            {
                Gizmo = new AIS_TranslationGizmo2D(_GizmoPlane);
                Gizmo.SetLength(100);
                WorkspaceController.Workspace.AisContext.Display(Gizmo, false);
            }
            else
            {
                Gizmo.SetComponent(_GeomPlane);
                WorkspaceController.Workspace.AisContext.Redisplay(Gizmo, false);
            }
        }
Exemplo n.º 16
0
 public void Log()
 {
     for (var rowIndex = BoundingRect.MinYValue; rowIndex <= BoundingRect.MaxYValue; rowIndex++)
     {
         for (var columnIndex = BoundingRect.MinXValue; columnIndex <= BoundingRect.MaxXValue; columnIndex++)
         {
             var printChar = Points.Any(p => p.xPosition == columnIndex && p.yPosition == rowIndex) ? '#' : '.';
             System.Console.Write($"{printChar}");
         }
         System.Console.WriteLine("");
     }
 }
Exemplo n.º 17
0
 private void PointsPropertyChanged()
 {
     if (Points == null || !Points.Any())
     {
         if (_children.Count > 4)
         {
             _children.RemoveRange(_children.Count - 4, 4);
         }
         else if (_children.Count > 1)
         {
             _children.RemoveRange(1, _children.Count - 1);
         }
     }
 }
Exemplo n.º 18
0
 /// <summary>
 /// Проверка есть ли уже такая точка в списке точек инсоляции
 /// </summary>
 /// <param name="dubl">Дублируется ли эта точка - т.е. если такая точка только одна, то ок, а две и больше - дубликаты</param>
 public bool HasPoint(Point3d pt, bool dubl = false)
 {
     if (Points == null || Points.Count == 0)
     {
         return(false);
     }
     if (dubl)
     {
         return(Points.Where(p => p.Point.IsEqualTo(pt, TolerancePoints)).Skip(1).Any());
     }
     else
     {
         return(Points.Any(p => p.Point.IsEqualTo(pt, TolerancePoints)));
     }
 }
Exemplo n.º 19
0
        //--------------------------------------------------------------------------------------------------

        void Sketch_ElementsChanged(Sketch sketch, Sketch.ElementType types)
        {
            if (types.HasFlag(Sketch.ElementType.Point))
            {
                // Check for lost points
                var lostPoints = Points.Where(i => !_Sketch.Points.ContainsKey(i)).ToArray();
                foreach (var lostPoint in lostPoints)
                {
                    Points.Remove(lostPoint);
                }

                if (!Points.Any())
                {
                    RaiseFinished();
                }

                UpdateTrihedron();
            }
        }
        private void btn_AddNew_Click(object sender, RoutedEventArgs e)
        {
            var point = new WeatherData();

            if (Points.Any())
            {
                point.TimeRate = Points.Last().TimeRate + 10;
                if (point.TimeRate > 100)
                {
                    point.TimeRate = 100;
                }
            }
            Points.Add(point);

            lb_WeatherParamList.Items.Refresh();
            if (Points.Count == 1)
            {
                CurrentPoint = Points[0];
            }
            SetPointDescription();
        }
Exemplo n.º 21
0
        /// <summary>
        /// Update the bounds of the stroke
        /// </summary>
        public void UpdateBounds()
        {
            if (!Points.Any())
            {
                return;
            }

            foreach (var point in Points)
            {
                var pointRect = ToRect(point);

                if (BoundingRect.IsEmpty)
                {
                    BoundingRect = pointRect;
                }
                else
                {
                    BoundingRect = Rectangle.Union(BoundingRect, pointRect);
                }
            }
        }
        private void LoadLines(Lines lines)
        {
            lines.LineEntity.ForEach(e =>
            {
                if (Points.Any(p => p.Id == e.FirstEnd) && Points.Any(p => p.Id == e.SecondEnd))
                {
                    GridPoint first = Points.Single(p => p.Id == e.FirstEnd);
                    GridPoint last  = Points.Single(p => p.Id == e.SecondEnd);

                    if (!Lines.Any(l => (l.Points.First() == first && l.Points.Last() == last) || (l.Points.First() == last && l.Points.Last() == first)))
                    {
                        GridPoint breakPoint = new GridPoint()
                        {
                            X = last.X, Y = first.Y, Type = GridPointType.Intersection
                        };
                        Points.Add(breakPoint);

                        GridLine lineStart = new GridLine()
                        {
                            Id = e.Id,
                        };

                        lineStart.Points.Add(first);
                        lineStart.Points.Add(breakPoint);

                        Lines.Add(lineStart);

                        GridLine lineEnd = new GridLine()
                        {
                            Id = e.Id,
                        };

                        lineEnd.Points.Add(breakPoint);
                        lineEnd.Points.Add(last);

                        Lines.Add(lineEnd);
                    }
                }
            });
        }
Exemplo n.º 23
0
        /// <summary>
        /// Sets the geometry of the surface line.
        /// </summary>
        /// <param name="points">The collection of points defining the surface line geometry.</param>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="points"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentException">Thrown when any element of <paramref name="points"/> is <c>null</c>.</exception>
        public void SetGeometry(IEnumerable <Point3D> points)
        {
            if (points == null)
            {
                throw new ArgumentNullException(nameof(points), Resources.MechanismSurfaceLineBase_Collection_of_points_for_geometry_is_null);
            }

            if (points.Any(p => p == null))
            {
                throw new ArgumentException(Resources.MechanismSurfaceLineBase_A_point_in_the_collection_was_null);
            }

            Points = points.Select(p => new Point3D(p)).ToArray();

            if (Points.Any())
            {
                StartingWorldPoint = Points.First();
                EndingWorldPoint   = Points.Last();
            }

            LocalGeometry = new RoundedPoint2DCollection(numberOfDecimalPlaces, Points.ProjectToLZ());
        }
Exemplo n.º 24
0
        public void  DumpPoints()
        {
            int maxX = Points.Max(p => p.X);
            int maxY = Points.Max(p => p.Y);

            Debug.WriteLine("---------------------------------");
            for (int y = 0; y <= maxY; y++)
            {
                for (int x = 0; x <= maxX; x++)
                {
                    if (Points.Any(p => p.X == x && p.Y == y))
                    {
                        Debug.Write("#");
                    }
                    else
                    {
                        Debug.Write(" ");
                    }
                }
                Debug.WriteLine(".");
            }
            Debug.WriteLine("---------------------------------");
        }
Exemplo n.º 25
0
        public void WriteTo(BinaryWriter writer)
        {
            writer.Write(SRID);

            if (SRID == -1)
            {
                return;
            }

            writer.Write(Version);

            var properties = SerializationProperties.None;

            if (ZValues.Any())
            {
                properties |= SerializationProperties.HasZValues;
            }
            if (MValues.Any())
            {
                properties |= SerializationProperties.HasMValues;
            }
            if (IsValid)
            {
                properties |= SerializationProperties.IsValid;
            }
            if (Shapes.First().Type == OpenGisType.Point && Points.Any())
            {
                properties |= SerializationProperties.IsSinglePoint;
            }
            if (Shapes.First().Type == OpenGisType.LineString && Points.Count == 2)
            {
                properties |= SerializationProperties.IsSingleLineSegment;
            }
            if (IsLargerThanAHemisphere)
            {
                properties |= SerializationProperties.IsLargerThanAHemisphere;
            }
            writer.Write((byte)properties);

            if (!properties.HasFlag(SerializationProperties.IsSinglePoint) &&
                !properties.HasFlag(SerializationProperties.IsSingleLineSegment))
            {
                writer.Write(Points.Count);
            }

            foreach (var point in Points)
            {
                point.WriteTo(writer);
            }

            foreach (var z in ZValues)
            {
                writer.Write(z);
            }

            foreach (var m in MValues)
            {
                writer.Write(m);
            }

            if (properties.HasFlag(SerializationProperties.IsSinglePoint) ||
                properties.HasFlag(SerializationProperties.IsSingleLineSegment))
            {
                return;
            }

            writer.Write(Figures.Count);

            if (Version == 1)
            {
                for (var shapeIndex = 0; shapeIndex < Shapes.Count; shapeIndex++)
                {
                    var shape = Shapes[shapeIndex];
                    if (shape.FigureOffset == -1 || shape.IsCollection())
                    {
                        continue;
                    }

                    var nextShapeIndex = shapeIndex + 1;
                    while (nextShapeIndex < Shapes.Count && Shapes[nextShapeIndex].FigureOffset == -1)
                    {
                        nextShapeIndex++;
                    }

                    var lastFigureIndex = nextShapeIndex >= Shapes.Count
                        ? Figures.Count - 1
                        : Shapes[nextShapeIndex].FigureOffset - 1;

                    if (Shapes[shapeIndex].Type == OpenGisType.Polygon)
                    {
                        // NB: Although never mentioned in MS-SSCLRT (v20170816), exterior rings must be first
                        writer.Write((byte)LegacyFigureAttribute.ExteriorRing);
                        writer.Write(Figures[shape.FigureOffset].PointOffset);

                        for (var figureIndex = shape.FigureOffset + 1; figureIndex <= lastFigureIndex; figureIndex++)
                        {
                            writer.Write((byte)LegacyFigureAttribute.InteriorRing);
                            writer.Write(Figures[figureIndex].PointOffset);
                        }

                        continue;
                    }

                    for (var figureIndex = shape.FigureOffset; figureIndex <= lastFigureIndex; figureIndex++)
                    {
                        writer.Write((byte)LegacyFigureAttribute.Stroke);
                        writer.Write(Figures[figureIndex].PointOffset);
                    }
                }
            }
            else
            {
                foreach (var figure in Figures)
                {
                    figure.WriteTo(writer);
                }
            }

            writer.Write(Shapes.Count);

            foreach (var shape in Shapes)
            {
                shape.WriteTo(writer);
            }

            if (Segments.Any())
            {
                writer.Write(Segments.Count);

                foreach (var segment in Segments)
                {
                    segment.WriteTo(writer);
                }
            }
        }
Exemplo n.º 26
0
        //--------------------------------------------------------------------------------------------------

        protected override bool MakeInternal(MakeFlags flags)
        {
            if (!Segments.Any() || !Points.Any())
            {
                var makeVertex = new BRepBuilderAPI_MakeVertex(Pnt.Origin);
                BRep      = makeVertex.Vertex();
                HasErrors = false;
                return(base.MakeInternal(flags));
            }

            // Create edges
            var freeSegmentEdges = new Dictionary <SketchSegment, TopoDS_Edge>();

            foreach (var segmentKvp in _Segments)
            {
                var segment = segmentKvp.Value;
                if (segment.IsAuxilliary)
                {
                    continue;
                }

                var segEdge = segment.MakeEdge(_Points);
                if (segEdge == null)
                {
                    Messages.Warning($"The segment {segmentKvp.Key} of type {segment.GetType().Name} failed creating an edge.");
                    continue;
                }
                freeSegmentEdges.Add(segment, segEdge);
                AddNamedSubshape("seg", segEdge, segmentKvp.Key);
            }

            // Create wires
            var wires = new List <TopoDS_Wire>();

            while (freeSegmentEdges.Any())
            {
                var nextSegmentEdge = freeSegmentEdges.First();
                var frontSegment    = nextSegmentEdge.Key;
                freeSegmentEdges.Remove(nextSegmentEdge.Key);

                var makeWire = new BRepBuilderAPI_MakeWire(nextSegmentEdge.Value);

                if ((frontSegment.StartPoint != -1) || (frontSegment.EndPoint != -1))
                {
                    var backSegment = frontSegment;
                    while (freeSegmentEdges.Any())
                    {
                        nextSegmentEdge = freeSegmentEdges.FirstOrDefault(kvp => kvp.Key.IsConnected(frontSegment));
                        if (nextSegmentEdge.Value != null)
                        {
                            frontSegment = nextSegmentEdge.Key;
                        }
                        else
                        {
                            nextSegmentEdge = freeSegmentEdges.FirstOrDefault(kvp => kvp.Key.IsConnected(backSegment));
                            if (nextSegmentEdge.Value != null)
                            {
                                backSegment = nextSegmentEdge.Key;
                            }
                            else
                            {
                                // disconnected segment
                                break;
                            }
                        }

                        makeWire.Add(nextSegmentEdge.Value);
                        freeSegmentEdges.Remove(nextSegmentEdge.Key);
                    }
                }

                // Get wire shape
                var wire = makeWire.Wire();
                if (wire == null)
                {
                    Messages.Error("Error when creating a wire.");
                    return(false);
                }

                wires.Add(wire);
            }

            // Create resulting shape
            var builder = new TopoDS_Builder();
            var shape   = new TopoDS_Compound();

            builder.MakeCompound(shape);

            foreach (var wire in wires)
            {
                builder.Add(shape, wire);
            }

            BRep = shape;

            return(base.MakeInternal(flags));
        }
Exemplo n.º 27
0
        public void Render()
        {
            try
            {
                double CanvasWidth  = (ActualWidth - 24) * Zoom;
                double CanvasHeight = Height - 14;

                CanvasPlot.Children.Clear();

                if (CanvasWidth <= 0 || CanvasHeight <= 0)
                {
                    return;
                }

                #region Determine axis range

                ValueMin = double.MaxValue;
                ValueMax = -double.MaxValue;

                if (!double.IsNaN(AxisMin))
                {
                    ValueMin = AxisMin;
                }
                else if (Points != null && Points.Count > 0)
                {
                    foreach (var point in Points)
                    {
                        if (!double.IsNaN(point.Value))
                        {
                            ValueMin = Math.Min(ValueMin, point.Value);
                        }
                    }
                }
                else
                {
                    ValueMin = 0;
                }

                if (!double.IsNaN(AxisMax))
                {
                    ValueMax = AxisMax;
                }
                else if (Points != null && Points.Count > 0 && Points.Any(v => !double.IsNaN(v.Value)))
                {
                    foreach (var point in Points)
                    {
                        if (!double.IsNaN(point.Value))
                        {
                            ValueMax = Math.Max(ValueMax, point.Value);
                        }
                    }
                }
                else
                {
                    ValueMax = 1;
                }

                double Range = ValueMax - ValueMin;

                if (ValueMin == ValueMax) // Range = 0, probably only one point
                {
                    ValueMax += 1;
                    ValueMin -= 1;
                }
                else // Make sure there are a few pixels left to draw the points at the extremes
                {
                    if (double.IsNaN(AxisMax))
                    {
                        ValueMax += Range / CanvasHeight * PointRadius;
                    }
                    if (double.IsNaN(AxisMin))
                    {
                        ValueMin -= Range / CanvasHeight * PointRadius;
                    }
                }

                Range = ValueMax - ValueMin;

                Dispatcher.Invoke(() =>
                {
                    string FloatFormat = "F0";
                    if (Math.Max(ValueMax, ValueMin) < 100)
                    {
                        FloatFormat = "F1";
                    }
                    if (Math.Max(ValueMax, ValueMin) < 10)
                    {
                        FloatFormat = "F2";
                    }

                    TextLineBottom.Text = ValueMin.ToString(FloatFormat, CultureInfo.InvariantCulture);
                    TextLineCenter.Text = ((ValueMin + ValueMax) * 0.5).ToString(FloatFormat, CultureInfo.InvariantCulture);
                    TextLineTop.Text    = ValueMax.ToString(FloatFormat, CultureInfo.InvariantCulture);
                });

                #endregion

                #region Adjust range highlight

                double RangeHighlightClampedMin = Math.Max(ValueMin, RangeHighlightMin);
                double RangeHighlightClampedMax = Math.Min(ValueMax, RangeHighlightMax);

                PanelRangeHighlight.Margin = new Thickness(0, 7 + (ValueMax - RangeHighlightClampedMax) / Range * CanvasHeight, 0, 0);
                PanelRangeHighlight.Height = Math.Max(0, RangeHighlightClampedMax - RangeHighlightClampedMin) / Range * CanvasHeight;

                #endregion

                if (Range < 0 || Points == null || Points.Count == 0)
                {
                    ImagePlot.Source = null;
                    return;
                }

                float[] HistogramBins = new float[50];

                DrawingGroup DGroup = new DrawingGroup();
                using (DrawingContext DContext = DGroup.Open())
                {
                    DContext.PushClip(new RectangleGeometry(new Rect(new Size(CanvasWidth, CanvasHeight))));

                    Pen OutlinePen = new Pen(Brushes.Transparent, 0);
                    OutlinePen.Freeze();

                    SolidColorBrush BackgroundBrush = new SolidColorBrush(Colors.Transparent);
                    BackgroundBrush.Freeze();
                    DContext.DrawRectangle(BackgroundBrush, OutlinePen, new Rect(new Size(CanvasWidth, CanvasHeight)));

                    SolidColorBrush[] ColorBrushes = PointColors.Count > 0
                                                         ? PointColors.Select(c =>
                    {
                        SolidColorBrush Brush = new SolidColorBrush(Color.FromArgb(255, c.R, c.G, c.B));
                        Brush.Freeze();
                        return(Brush);
                    }).ToArray()
                                                         : new[] { new SolidColorBrush(Color.FromArgb(150, Colors.DeepSkyBlue.R, Colors.DeepSkyBlue.G, Colors.DeepSkyBlue.B)) };

                    StepX   = (CanvasWidth - PointRadius * 2) / Points.Count;
                    OffsetX = StepX / 2 + PointRadius;
                    StepY   = CanvasHeight / Range;

                    PointCenters = new System.Windows.Point[Points.Count];

                    for (int i = 0; i < Points.Count; i++)
                    {
                        if (double.IsNaN(Points[i].Value))
                        {
                            continue;
                        }

                        double X = i * StepX + OffsetX;
                        double Y = (ValueMax - Points[i].Value) * StepY;

                        DContext.DrawEllipse(ColorBrushes[Points[i].ColorID], OutlinePen, new System.Windows.Point(X, Y), PointRadius, PointRadius);

                        PointCenters[i] = new System.Windows.Point(X, Y);

                        HistogramBins[Math.Max(0, Math.Min(HistogramBins.Length - 1, (int)((Points[i].Value - ValueMin) / Range * (HistogramBins.Length - 1) + 0.5)))]++;
                    }
                }

                DrawingImage Plot = new DrawingImage(DGroup);
                Plot.Freeze();
                Dispatcher.Invoke(() => ImagePlot.Source = Plot);

                Dispatcher.Invoke(() =>
                {
                    float[] HistogramConv = new float[HistogramBins.Length];
                    float[] ConvKernel    = { 0.11f, 0.37f, 0.78f, 1f, 0.78f, 0.37f, 0.11f };
                    for (int i = 0; i < HistogramBins.Length; i++)
                    {
                        float Sum     = 0;
                        float Samples = 0;
                        for (int j = 0; j < ConvKernel.Length; j++)
                        {
                            int ij = i - 3 + j;
                            if (ij < 0 || ij >= HistogramBins.Length)
                            {
                                continue;
                            }
                            Sum     += ConvKernel[j] * HistogramBins[ij];
                            Samples += ConvKernel[j];
                        }
                        HistogramConv[i] = Sum / Samples;
                    }

                    float HistogramMax = MathHelper.Max(HistogramConv);
                    if (HistogramMax > 0)
                    {
                        HistogramConv = HistogramConv.Select(v => v / HistogramMax * 16).ToArray();
                    }

                    Polygon HistogramPolygon = new Polygon()
                    {
                        Stroke  = Brushes.Transparent,
                        Fill    = Brushes.Gray,
                        Opacity = 0.15
                    };
                    PointCollection HistogramPoints = new PointCollection(HistogramConv.Length);

                    HistogramPoints.Add(new System.Windows.Point(16, 0));
                    HistogramPoints.Add(new System.Windows.Point(16, CanvasHeight));
                    for (int i = 0; i < HistogramConv.Length; i++)
                    {
                        double X = 15 - HistogramConv[i];
                        double Y = CanvasHeight - (i / (float)(HistogramConv.Length - 1) * CanvasHeight);
                        HistogramPoints.Add(new System.Windows.Point(X, Y));
                    }

                    HistogramPolygon.Points = HistogramPoints;

                    CanvasHistogram.Children.Clear();
                    CanvasHistogram.Children.Add(HistogramPolygon);
                    Canvas.SetRight(HistogramPolygon, 0);
                });
            }
            catch
            {
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// コンストラクタ
        /// </summary>
        public MouseViewModel()
        {
            ClickCommand = new DelegateCommand <object>(
                (_id) => {
                // 変換
                var id = int.Parse(_id.ToString());
                // ランダム値
                Random rnd = new System.Random();
                // 要素取得
                var pt = Points.First(x => x.Coordinate.Id == id);
                // クリックイベント発行
                mousePositionModel.ClickMouse(pt.Coordinate.X + rnd.Next(-20, 10), pt.Coordinate.Y + rnd.Next(-20, 10));
                // クリックが完了するまでSleepする
                System.Threading.Thread.Sleep(100);
                // Windowをアクティブにする
                WindowManager.ShowOrActivate <Views.Mouse>();
            }
                );

            SaveCommand = new DelegateCommand(SavePoints);

            LoadCommand = new DelegateCommand(
                () => {
                LoadPoints();
            }
                );

            AddCommand = new DelegateCommand(
                () => {
                var id = Points.Count() + 1;
                Points.Add(new CoordinateDispInfo(new Models.Coordinate(id, 0, 0)));
                Subscribe?.RaiseCanExecuteChanged();
            }
                );

            DeleteCommand = new DelegateCommand(
                () => {
                for (int index = 0; index < Points.Count; index++)
                {
                    if (Points[index].IsSelected)
                    {
                        Points.RemoveAt(index);
                        Subscribe?.RaiseCanExecuteChanged();
                    }
                }
            }
                );

            StopCommand = new DelegateCommand(() => { State = "停止中"; Subscription?.Dispose(); });

            var mousemove = Observable.FromEvent <EventHandler <Models.MousePosition.MouseEventArgs>, Models.MousePosition.MouseEventArgs>(
                h => (s, e) => h(e),
                h => mousePositionModel.Publish += h,
                h => mousePositionModel.Publish -= h
                );

            mousemove.Subscribe(s =>
            {
                //Console.WriteLine("x:{0},y:{1}", s.Value.X, s.Value.Y);
                PosX = (int)s.Value.X;
                PosY = (int)s.Value.Y;
                //Console.WriteLine("ClickPos => x:{0},y:{1}", s.Value.X, s.Value.Y);
            });

            // マウス自動クリックイベント購読開始
            Subscribe = new DelegateCommand(
                () =>
            {
                Subscription?.Dispose();

                State = "実行中";

                Subscription = this.Source.ObserveOnDispatcher().
                               Where(i => Points.Any(x => x.Coordinate.Id == i)).
                               Subscribe(
                    i =>
                {
                    Console.WriteLine($"{i} times");
                    ClickCommand?.Execute(i);
                }
                    ,
                    ex => Console.WriteLine("OnError({0})", ex.Message),
                    () =>
                {
                    Console.WriteLine("Completed()");
                    State = "停止中";
                }
                    );
            },
                CanExecute
                );

            Dispose = new DelegateCommand(() => Subscription?.Dispose());

            //LoadPoints();

            mousePositionModel.Start();
        }
Exemplo n.º 29
0
 public bool IsCheckersLeft(CheckerColor color)
 {
     return(Points.Any(p => p.Color == color));
 }
Exemplo n.º 30
0
 public bool Intersect(PointType point) => Points.Any(p => (p.Position - point.Position).magnitude < IntersectSize);