Exemple #1
0
        static void Main(string[] args)
        {
            uint   fieldSize = 255;
            Canvas c         = new Canvas(fieldSize, fieldSize);

            Matrix tr = MatrixOps.CreateTranslationTransform(fieldSize / 2, fieldSize / 2, 0); // the center of the field
            Matrix th = MatrixOps.CreateTranslationTransform(0, fieldSize / 3, 0);             // 12 o'clock

            List <Point> points = new List <Point>();
            Point        hour   = new Point();

            for (int h = 0; h < 12; h++)
            {
                Matrix rot = MatrixOps.CreateRotationZTransform(h * 2 * Math.PI / 12);
                Matrix tf  = (Matrix)(tr * rot * th);
                Console.WriteLine("Hour+tf=" + hour.Transform(tf).ToString());
                Console.WriteLine("hour+seq=" + hour.Transform(th).Transform(rot).Transform(tr).ToString());
                points.Add(hour.Transform(th).Transform(rot).Transform(tr));
            }
            Color red = new Color(255, 0, 0);

            foreach (Point p in points)
            {
                c.WritePixel((uint)p.X, (uint)p.Y, red);
            }
            String ppm = c.ToPPM();

            System.IO.File.WriteAllText(@"ToPPM.ppm", ppm);

            Console.Write("Press Enter to finish ... ");
            Console.Read();
        }
Exemple #2
0
        static void Main(string[] args)
        {
            Point  p   = new Point(0, 1, 0);
            Matrix hq  = MatrixOps.CreateRotationXTransform(Math.PI / 4.0);
            Matrix inv = (Matrix)hq.Inverse();

            Console.WriteLine(hq.ToString());
            Console.WriteLine(inv.ToString());
            Console.WriteLine(p.Transform(inv).ToString());
            Matrix t = MatrixOps.CreateTranslationTransform(5, -3, 2);

            p = new Point(-3, 4, 5);
            Point pt  = p.Transform(t);
            bool  foo = (p.Transform(t).Equals(new Point(2, 1, 7)));

            RayTracerLib.Vector a  = new RayTracerLib.Vector(1, 2, 3);
            RayTracerLib.Vector b  = new RayTracerLib.Vector(2, 3, 4);
            RayTracerLib.Vector ab = a.Cross(b);
            RayTracerLib.Vector ba = b.Cross(a);
            bool foo1 = (a.Cross(b).IsEqual(new RayTracerLib.Vector(-1, 2, -1)));
            bool foo2 = (b.Cross(a).IsEqual(new RayTracerLib.Vector(1, -2, 1)));

            Console.Write("Press Enter to finish ... ");
            Console.Read();
        }
Exemple #3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ShapePoint"/> class.
        /// </summary>
        /// <param name="point">The point.</param>
        /// <param name="featureline">The featureline.</param>
        /// <param name="id">The initial ID of the ShapePoint.</param>
        internal ShapePoint(Point point, Featureline featureline, int id = 0)
        {
            this.UniqueId = Guid.NewGuid().ToString();
            this._id      = id;

            this.Corridor      = featureline.Baseline.CorridorName;
            this.BaselineIndex = featureline.Baseline.Index;
            this.RegionIndex   = featureline.BaselineRegionIndex;

            this.Side = featureline.Side;
            this.Code = featureline.Code;

            var soe = featureline.GetStationOffsetElevationByPoint(point);

            this.Station   = (double)soe["Station"];
            this.Offset    = (double)soe["Offset"];
            this.Elevation = (double)soe["Elevation"];

            this.RegionRelative   = this.Station - featureline.Start;                            // 1.1.0
            this.RegionNormalized = this.RegionRelative / (featureline.End - featureline.Start); // 1.1.0

            this.Point       = point;
            this.Featureline = featureline;

            this.RevitPoint = point.Transform(RevitUtils.DocumentTotalTransform()) as Point;
        }
        protected override void OnRenderCore(DrawingContext dc, RenderState state)
        {
            if (DataSource == null)
            {
                return;
            }
            if (Marker == null)
            {
                return;
            }

            Rect bounds = Rect.Empty;

            using (IPointEnumerator enumerator = DataSource.GetEnumerator(GetContext()))
            {
                Point point = new Point();
                while (enumerator.MoveNext())
                {
                    enumerator.GetCurrent(ref point);
                    enumerator.ApplyMappings(Marker);

                    Point screenPoint = point.Transform(state.Visible, state.Output);

                    bounds = Rect.Union(bounds, point);
                    Marker.Render(dc, screenPoint);
                }
            }

            ContentBounds = bounds;
        }
Exemple #5
0
        private void OnMouseDown(object sender, MouseButtonEventArgs e)
        {
            // dragging
            bool shouldStartDrag = e.ChangedButton == MouseButton.Left && Keyboard.Modifiers == ModifierKeys.None;

            if (shouldStartDrag)
            {
                Point dragStartPointInOutput = e.GetPosition(this);
                dragStartPointInVisible = dragStartPointInOutput.Transform(Viewport.Output, Viewport.Visible);

                isDragging = true;
                CaptureMouse();
            }

            bool shouldStartZoom = e.ChangedButton == MouseButton.Left && IsShiftOrCtrl;

            if (shouldStartZoom)
            {
                // zooming

                zoomStartPoint = e.GetPosition(this);
                if (Viewport.Output.Contains(zoomStartPoint))
                {
                    isZooming = true;
                    AddSelectionAdorner();
                    CaptureMouse();
                    shouldKeepRatioWhileZooming = Keyboard.Modifiers == ModifierKeys.Shift;
                }
            }

            ((IInputElement)Parent).Focus();
        }
Exemple #6
0
        ///-------------------------------------------------------------------------------------------------
        /// <summary>   Calculates the camera point. </summary>
        ///
        /// <remarks>   Kemp, 1/6/2019. </remarks>
        ///
        /// <param name="g">    A Group to point at. </param>
        ///
        /// <returns>   The calculated camera point. </returns>
        ///-------------------------------------------------------------------------------------------------

        static Point CalcCameraPoint(Group g, double cameraY, double cameraZ)
        {
            /// take a first guess at camera location
            Point cameraPoint = new Point(
                g.Bounds.MinCorner.X + (g.Bounds.MaxCorner.X - g.Bounds.MinCorner.X) / 2,
                g.Bounds.MinCorner.Y + (g.Bounds.MaxCorner.Y - g.Bounds.MinCorner.Y) / 2,
                -(2 * Math.Max(g.Bounds.MaxCorner.X - g.Bounds.MinCorner.X, g.Bounds.MaxCorner.Y - g.Bounds.MinCorner.Y)));
            Matrix m1 = MatrixOps.CreateRotationYTransform(cameraY);
            Matrix m2 = MatrixOps.CreateRotationXTransform(cameraZ);
            //Matrix m3 = MatrixOps.CreateTranslationTransform(
            //    g.Bounds.MinCorner.X + (g.Bounds.MaxCorner.X - g.Bounds.MinCorner.X) / 2,
            //    g.Bounds.MinCorner.Y + (g.Bounds.MaxCorner.Y - g.Bounds.MinCorner.Y) / 2,
            //    -(2 * Math.Max(g.Bounds.MaxCorner.X - g.Bounds.MinCorner.X, g.Bounds.MaxCorner.Y - g.Bounds.MinCorner.Y)));
            Matrix m = (Matrix)(m1 * m2);

            cameraPoint = cameraPoint.Transform(m);
            //cameraPoint = cameraPoint.Transform(m3);
            //cameraPoint = cameraPoint.Transform(m2);
            //cameraPoint = cameraPoint.Transform(m1);
            /// Point camera at center of bounding box
            //Point centerPoint = new Point(g.Bounds.MaxCorner.X / 2, g.Bounds.MaxCorner.Y / 2, g.Bounds.MaxCorner.Z/2);
            //RayTracerLib.Vector centerVect = cameraPoint - centerPoint;
            //Ray cameraRay = new Ray(cameraPoint, centerVect);
            return(cameraPoint);
        }
Exemple #7
0
        public void SkewTest()
        {
            var       p      = new Point(13, 17);
            Matrix3x2 matrix = Matrix3x2Extensions.CreateSkewDegrees(45, 45, Point.Empty);

            var pout = Point.Transform(p, matrix);

            Assert.Equal(new Point(30, 30), pout);
        }
Exemple #8
0
        public void RotateTest()
        {
            var       p      = new Point(13, 17);
            Matrix3x2 matrix = Matrix3x2Extensions.CreateRotationDegrees(45, Point.Empty);

            var pout = Point.Transform(p, matrix);

            Assert.Equal(new Point(-3, 21), pout);
        }
Exemple #9
0
        /// <summary>
        /// Gets a PolyCurve obtained by applying the offset and elevation displacement to each point of the Featureline PolyCurve.
        /// </summary>
        /// <param name="offset">The offset.</param>
        /// <param name="elevation">The elevation.</param>
        /// <returns></returns>
        public PolyCurve GetPolyCurveByOffsetElevation(double offset, double elevation)
        {
            Utils.Log(string.Format("Featureline.GetPolyCurveByOffsetElevation started...", ""));

            double startStation = this.Start; //  soeStart[0];
            double endStation   = this.End;   //  soeEnd[0];

            IList <double> stations = new List <double>()
            {
                startStation
            };

            foreach (double s in this.Baseline.Stations.Where(s => s >= startStation && s <= endStation))
            {
                stations.Add(s);
            }

            stations.Add(endStation);

            Point p = Point.ByCoordinates(offset, 0, elevation);

            CoordinateSystem cs = null;

            IList <Point> points = new List <Point>();

            foreach (double s in stations)
            {
                cs = this.CoordinateSystemByStation(s);
                points.Add(p.Transform(cs) as Point);
            }

            points = Point.PruneDuplicates(points);  // TODO this is slow

            PolyCurve res = null;

            if (points.Count > 1)
            {
                res = PolyCurve.ByPoints(points);
            }

            Utils.Log(string.Format("{0}", res));

            if (p != null)
            {
                p.Dispose();
            }

            if (cs != null)
            {
                cs.Dispose();
            }

            Utils.Log(string.Format("Featureline.GetPolyCurveByOffsetElevation completed.", ""));

            return(res);
        }
		private void MouseWheelZoom(Point mousePos, int wheelRotationDelta) {
			Point zoomTo = mousePos.Transform(Viewport.Output, Viewport.Visible);

			double zoomSpeed = Math.Abs(wheelRotationDelta / Mouse.MouseWheelDeltaForOneLine);
			zoomSpeed *= wheelZoomSpeed;
			if (wheelRotationDelta < 0) {
				zoomSpeed = 1 / zoomSpeed;
			}
			Viewport.Visible = Viewport.Visible.Zoom(zoomTo, zoomSpeed);
		}
Exemple #11
0
        public void TransformWithScaleToPlaneTest()
        {
            //sw transform data: 0.795342405339345, 0.455413697145403, 0.400036026779314, -0.606108810937849, 0.606108810937846, 0.515038074910018, -7.90996665808835E-03, -0.652096981863791, 0.758094294050287, 0.700972369348501, 0.438557054675365, -9.46540940610755E-02, 3, 0, 0, 0
            var matrix = new TransformMatrix(2.38602721601803, 1.36624109143621, 1.20010808033794, 0, -1.81832643281355, 1.81832643281354, 1.54511422473005, 0, -0.023729899974265, -1.95629094559137, 2.27428288215086, 0, 0.700972369348501, 0.438557054675365, -0.0946540940610755, 1);
            var point  = new Point(0, 0, 0);

            var point1 = point.Transform(matrix);

            Assert.That(0.700972369348501, Is.EqualTo(point1.X).Within(0.00001).Percent);
            Assert.That(0.438557054675365, Is.EqualTo(point1.Y).Within(0.00001).Percent);
            Assert.That(-9.46540940610755E-02, Is.EqualTo(point1.Z).Within(0.00001).Percent);
        }
Exemple #12
0
        public void TransformWithScaleTest()
        {
            //sw transform data: 0.8899781799633, 0.258097541614499, -0.375931507327816, 4.48886450650032E-02, -0.869988052665455, -0.491025251655756, -0.453788330318707, 0.420126703783421, -0.7858560326387, 724.374297695573, 431.891671932574, 13.2759519466606, 634.33320578319, 0, 0, 0
            var matrix = new TransformMatrix(564.542711973209, 163.719840977085, -238.46583819816, 0, 28.4743581273473, -551.862310440353, -311.473622003293, 0, -287.853006318067, 266.500318846062, -498.494576467766, 0, 724.374297695573, 431.891671932574, 13.2759519466606, 1);
            var point  = new Point(-0.2, 0.35, -0.7);

            var point1 = point.Transform(matrix);

            Assert.That(822.92888506815, Is.EqualTo(point1.X).Within(0.00001).Percent);
            Assert.That(19.4456718907902, Is.EqualTo(point1.Y).Within(0.00001).Percent);
            Assert.That(300.899555412576, Is.EqualTo(point1.Z).Within(0.00001).Percent);
        }
Exemple #13
0
        public void TransformTest()
        {
            //sw transform data: -0.708267430806948, 0.347623567688267, 0.614422575794384, -0.705944223333632, -0.348767569783138, -0.616444592651635, 8.88178419700125E-16, -0.870355695940025, 0.492423560103246, 0.232454472653307, 0.28957519769969, 5.93062288453039E-02, 1, 0, 0, 0
            var matrix = new TransformMatrix(-0.708267430806948, 0.347623567688267, 0.614422575794384, 0, -0.705944223333632, -0.348767569783138, -0.616444592651635, 0, 8.88178419700125E-16, -0.870355695940025, 0.492423560103246, 0, 0.232454472653307, 0.28957519769969, 0.0593062288453039, 1);
            var point  = new Point(1, 3, 5);

            var point1 = point.Transform(matrix);

            Assert.That(-2.59364562815453, Is.EqualTo(point1.X).Within(0.00001).Percent);
            Assert.That(-4.76088242366158, Is.EqualTo(point1.Y).Within(0.00001).Percent);
            Assert.That(1.28651282720101, Is.EqualTo(point1.Z).Within(0.00001).Percent);
        }
Exemple #14
0
        private void MouseWheelZoom(Point mousePos, int wheelRotationDelta)
        {
            Point zoomTo = mousePos.Transform(Viewport.Output, Viewport.Visible);

            double zoomSpeed = Math.Abs(wheelRotationDelta / Mouse.MouseWheelDeltaForOneLine);

            zoomSpeed *= wheelZoomSpeed;
            if (wheelRotationDelta < 0)
            {
                zoomSpeed = 1 / zoomSpeed;
            }
            Viewport.Visible = Viewport.Visible.Zoom(zoomTo, zoomSpeed);
        }
Exemple #15
0
 internal static Point Translate(this Visual fromElement, Visual toElement, Point fromPoint)
 {
     if (fromElement == toElement)
     {
         return(fromPoint);
     }
     else
     {
         var transform = fromElement.TransformToVisual(toElement);
         if (transform.HasValue)
         {
             return(fromPoint.Transform(transform.Value));
         }
         else
         {
             return(fromPoint);
         }
     }
 }
        /// <summary>
        /// Gets a PolyCurve obtained by applying the offset and elevation displacement to each point of the Featureline PolyCurve.
        /// </summary>
        /// <param name="offset">The offset.</param>
        /// <param name="elevation">The elevation.</param>
        /// <returns></returns>
        public PolyCurve GetPolyCurveByOffsetElevation(double offset, double elevation)
        {
            Utils.Log(string.Format("Featureline.GetPolyCurveByOffsetElevation started...", ""));

            //double[] soeStart = this.GetStationOffsetElevationByPoint(this.Curve.StartPoint);
            //double[] soeEnd = this.GetStationOffsetElevationByPoint(this.Curve.EndPoint);
            double startStation = this.Start; //  soeStart[0];
            double endStation   = this.End;   //  soeEnd[0];

            IList <double> stations = new List <double>()
            {
                startStation
            };

            foreach (double s in this.Baseline.Stations.Where(s => s >= startStation && s <= endStation))
            {
                stations.Add(s);
            }

            stations.Add(endStation);

            Point p = Point.ByCoordinates(offset, 0, elevation);

            IList <Point> points = new List <Point>();

            foreach (double s in stations)
            {
                points.Add(p.Transform(this.CoordinateSystemByStation(s)) as Point);
            }

            p.Dispose();

            points = Point.PruneDuplicates(points);

            Utils.Log(string.Format("Featureline.GetPolyCurveByOffsetElevation completed.", ""));

            return(PolyCurve.ByPoints(points));
        }
Exemple #17
0
        private void OnMouseUp(object sender, MouseButtonEventArgs e)
        {
            if (isDragging && e.ChangedButton == MouseButton.Left)
            {
                isDragging = false;
                ReleaseMouseCapture();
                Point endPointInOutput  = e.GetPosition(this);
                Point endPointInVisible = endPointInOutput.Transform(Viewport.Output, Viewport.Visible);

                Vector mouseShift  = -(endPointInVisible - dragStartPointInVisible);
                Vector outputShift = endPointInOutput - dragStartPointInOutput;

                int time      = e.Timestamp;
                int deltaTime = time - dragStartTimestamp;

                double seconds = deltaTime / 1000.0;

                // mouse moved short enough and for rather long distance.
                bool shouldStartAnimation = seconds < 1 && outputShift.Length > 20;
                if (shouldStartAnimation)
                {
                    Rect moveTo = Viewport.Visible;
                    moveTo.Offset(mouseShift * 2);

                    //if (dragAnimation == null) {
                    dragAnimation = new RectAnimation(moveTo,
                                                      TimeSpan.FromSeconds(1));
                    dragAnimation.DecelerationRatio = 0.2;
                    //}
                    //else {
                    //    dragAnimation.To = moveTo;
                    //    dragAnimation.Duration = TimeSpan.FromSeconds(1);
                    //    AnimationClock clock = dragAnimation.CreateClock();
                    //    clock.Controller.Begin();
                    //}

                    BeginAnimation(VisibleRectProperty, dragAnimation);
                    shouldApplyAnimation = true;
                    Debug.WriteLine("Starting animation");
                }
                else if (dragAnimation != null)
                {
                    StopDragAnimation();
                }

                // focusing on LMB click
                if (endPointInVisible == dragStartPointInVisible)
                {
                    //Keyboard.Focus(Parent as IInputElement);
                }
            }
            else if (isZooming && e.ChangedButton == MouseButton.Left)
            {
                isZooming = false;
                if (zoomRect.HasValue)
                {
                    Rect output = Viewport.Output;

                    Point p1         = zoomRect.Value.TopLeft.Transform(output, Viewport.Visible);
                    Point p2         = zoomRect.Value.BottomRight.Transform(output, Viewport.Visible);
                    Rect  newVisible = new Rect(p1, p2);
                    Viewport.Visible = newVisible;

                    zoomRect = null;
                    ReleaseMouseCapture();
                    RemoveSelectionAdorner();
                }
            }
        }
Exemple #18
0
        /// <summary>
        /// Gets a PolyCurve obtained by applying the offset and elevation displacement to each point of the Featureline PolyCurve only for the station interval specified.
        /// </summary>
        /// <param name="startStation">The start station.</param>
        /// <param name="endStation">The end station.</param>
        /// <param name="offset">The offset.</param>
        /// <param name="elevation">The elevation.</param>
        /// <returns></returns>
        public PolyCurve GetPolyCurveByStationsOffsetElevation(double startStation, double endStation, double offset, double elevation)
        {
            Utils.Log(string.Format("Featureline.GetPolyCurveByStationsOffsetElevation started...", ""));

            if (startStation == endStation)
            {
                return(null);
            }

            double sStation = this.Start < this.End ? this.Start : this.End;  // soeStart[0] < soeEnd[0] ? soeStart[0] : soeEnd[0];
            double eStation = this.Start < this.End ? this.End : this.Start;  // soeStart[0] < soeEnd[0] ? soeEnd[0] : soeStart[0];

            double min = startStation < endStation ? startStation : endStation;
            double max = endStation > startStation ? endStation : startStation;

            startStation = min;
            endStation   = max;

            if (startStation < sStation)
            {
                startStation = sStation;
            }

            if (endStation > eStation)
            {
                endStation = eStation;
            }

            IList <double> stations = new List <double>()
            {
                startStation
            };

            foreach (double s in this.Baseline.Stations.Where(s => s >= startStation && s <= endStation))
            {
                stations.Add(s);
            }

            stations.Add(endStation);

            Point p = Point.ByCoordinates(offset, 0, elevation);

            IList <Point> points = new List <Point>();

            CoordinateSystem cs = null;

            foreach (double s in stations)
            {
                cs = this.CoordinateSystemByStation(s);
                points.Add(p.Transform(cs) as Point);
            }

            p.Dispose();

            if (cs != null)
            {
                cs.Dispose();
            }

            points = Point.PruneDuplicates(points);

            PolyCurve res = null;

            if (points.Count > 1)
            {
                res = PolyCurve.ByPoints(points);
            }

            foreach (var item in points)
            {
                if (item != null)
                {
                    item.Dispose();
                }
            }

            points.Clear();

            Utils.Log(string.Format("Featureline.GetPolyCurveByStationsOffsetElevation completed.", ""));

            return(res);
        }
Exemple #19
0
        public Dictionary <string, object> GetStationOffsetElevationByPoint(Point point)
        {
            Utils.Log(string.Format("Featureline.GetStationOffsetElevationByPoint started...", ""));

            Utils.Log(string.Format("Point: X: {0} Y: {1} Z: {2}", point.X, point.Y, point.Z));

            Point flatPt = Point.ByCoordinates(point.X, point.Y);

            Curve flatPC = this.Curve.PullOntoPlane(Plane.XY());

            AeccAlignment alignment = this._baseline.Alignment.InternalElement as AeccAlignment;

            double station   = 0;
            double offset    = 0;
            double elevation = 0;

            double alStation = 0;
            double alOffset  = 0;

            Point ortho = null;

            CoordinateSystem cs = null;

            Point result = null;

            alignment.StationOffset(point.X, point.Y, out alStation, out alOffset);

            Utils.Log(string.Format("The point is at station {0}", alStation));

            // 20190414 -- START

            if (Math.Abs(alStation - this.Start) <= 0.00001)
            {
                alStation = this.Start;
                Utils.Log(string.Format("Station rounded to {0}", alStation));
            }

            if (Math.Abs(alStation - this.End) <= 0.00001)
            {
                alStation = this.End;
                Utils.Log(string.Format("Station rounded to {0}", alStation));
            }

            // 20190414 -- END

            if (this.Start <= Math.Round(alStation, 5) && Math.Round(alStation, 5) <= this.End ||
                Math.Abs(this.Start - alStation) < 0.0001 ||
                Math.Abs(this.End - alStation) < 0.0001)
            {
                // the point is in the featureline range

                Utils.Log(string.Format("The point is inside the featureline station range.", ""));

                // 20190205 -- START

                ortho = flatPC.ClosestPointTo(flatPt);

                Utils.Log(string.Format("Orthogonal Point at Z = 0: {0}", ortho));

                double orStation = 0;
                double orOffset  = 0;
                double error     = 0;

                alignment.StationOffset(ortho.X, ortho.Y, out orStation, out orOffset);

                cs = this.CoordinateSystemByStation(orStation, true).Inverse();  // 20191117

                Utils.Log(string.Format("CoordinateSystem: {0}", cs));

                if (cs == null)
                {
                    var message = "The Point is not compatible with the Featureline and its Baseline.";

                    Utils.Log(string.Format("ERROR: {0}", message));
                    return(null);
                }

                result = point.Transform(cs) as Point;

                Utils.Log(string.Format("Result: {0}", result));

                station   = orStation;
                offset    = result.X;
                elevation = result.Z;
                error     = result.Y;

                // 20190205 -- END


                Utils.Log(string.Format("Final Margin: {0}", error));
            }
            else
            {
                Utils.Log(string.Format("The point is outside the featureline station range.", ""));

                try
                {
                    station   = alStation;
                    offset    = alOffset;                                                                  // offset from alignment
                    elevation = point.Z - this._baseline.PointByStationOffsetElevation(alStation, 0, 0).Z; // Absolute elevation
                }
                catch (Exception ex)
                {
                    var message = "The Point is not compatible with the Alignment.";

                    Utils.Log(string.Format("ERROR: {0} {1}", message, ex.Message));
                    return(null);
                }
            }

            Utils.Log(string.Format("Station: {0} Offset: {1} Elevation: {2}", station, offset, elevation));

            if (ortho != null)
            {
                ortho.Dispose();
            }
            if (cs != null)
            {
                cs.Dispose();
            }
            if (result != null)
            {
                result.Dispose();
            }
            if (flatPt != null)
            {
                flatPt.Dispose();
            }
            if (flatPC != null)
            {
                flatPC.Dispose();
            }

            Utils.Log(string.Format("Featureline.GetStationOffsetElevationByPoint completed.", ""));

            return(new Dictionary <string, object>
            {
                { "Station", Math.Round(station, 5) },
                { "Offset", Math.Round(offset, 5) },
                { "Elevation", Math.Round(elevation, 5) }
            });
        }
Exemple #20
0
        void CreateAnchor(Document doc, float margin, bool snap, bool autoMirror)
        {
            if (doc.CurrentObjectIndex == -1 ||
                doc.CurrentMaterialIndex == -1)
            {
                return;
            }

            var targetObject   = doc.Objects[doc.CurrentObjectIndex];
            var targetBoneFace = bone == null ? null : bone.Faces.FirstOrDefault(_ => _.Material == doc.CurrentMaterialIndex && _.PointCount == 3);
            var targetBone     = targetBoneFace == null ? null : new Bone(doc, targetBoneFace);
            var beginToEnd     = targetBone == null ? Point.Zero : targetBone.End.Point - targetBone.Begin.Point;
            var unit           = new Point(0, 1, 0);
            var axis           = Point.GetCrossProduct(unit, beginToEnd).Normalize();
            var angle          = Point.GetCrossingAngle(unit, beginToEnd);

            if (axis == Point.Zero)
            {
                axis = new Point(0, 1, 0);
            }

            var targetBoneMatrix = targetBone == null || !snap
                                ? Matrix.Identity
                                : Matrix.CreateFromAxisAngle(axis, angle) * Matrix.CreateTranslation(targetBone.Begin.Point);
            var targetBoneInverseMatrix = targetBone == null || !snap
                                ? Matrix.Identity
                                : Matrix.Invert(targetBoneMatrix);
            var anchorName = "anchor|" + targetObject.Name.Split(':').Last();

            while (doc.Objects.Any(_ => _.Name == anchorName))
            {
                anchorName = anchorName.Replace("|", "_|");
            }

            var vertices = targetObject.Vertices
                           .Where(_ => _.IsSelected)
                           .Select(_ => Point.Transform(_.Point, targetBoneInverseMatrix))
                           .ToArray();

            if (!vertices.Any())
            {
                return;
            }

            var min = vertices.Aggregate(vertices.First(), (x, y) => new Point(Math.Min(x.X, y.X), Math.Min(x.Y, y.Y), Math.Min(x.Z, y.Z))) - margin;
            var max = vertices.Aggregate(vertices.First(), (x, y) => new Point(Math.Max(x.X, y.X), Math.Max(x.Y, y.Y), Math.Max(x.Z, y.Z))) + margin;
            var obj = new Metasequoia.Object
            {
                Name = anchorName,
            };
            var newVertices = new[]
            {
                new Point(min.X, max.Y, max.Z),
                new Point(min.X, min.Y, max.Z),
                new Point(max.X, max.Y, max.Z),
                new Point(max.X, min.Y, max.Z),
                new Point(max.X, max.Y, min.Z),
                new Point(max.X, min.Y, min.Z),
                new Point(min.X, max.Y, min.Z),
                new Point(min.X, min.Y, min.Z),
            }.Select(_ => Point.Transform(_, targetBoneMatrix)).Select(obj.AddVertex).ToArray();

            foreach (var i in new[]
            {
                new[] { 0, 2, 3, 1 },
                new[] { 2, 4, 5, 3 },
                new[] { 4, 6, 7, 5 },
                new[] { 6, 0, 1, 7 },
                new[] { 6, 4, 2, 0 },
                new[] { 1, 3, 5, 7 },
            })
            {
                obj.Faces[obj.AddFace(i.Select(_ => newVertices[_]))].Material = doc.CurrentMaterialIndex;
            }

            if (autoMirror && doc.Materials[doc.CurrentMaterialIndex].Name.EndsWith("[]"))
            {
                obj.MirrorType = ObjectMirror.Normal;
                obj.MirrorAxis = ObjectMirrorAxis.X;
            }

            doc.AddObject(obj);
        }
Exemple #21
0
        public static Point BottomLeft(this Polyline polyline, List <Panel> panelsAsSpace)
        {
            if (polyline == null)
            {
                BH.Engine.Reflection.Compute.RecordError("Cannot query the bottom left corner of a null polyline.");
                return(null);
            }

            if (panelsAsSpace == null)
            {
                BH.Engine.Reflection.Compute.RecordError("Cannot query the bottom left corner of a polyline without knowing the space it belongs to.");
                return(null);
            }

            Vector normal = polyline.Normal();

            if (!polyline.NormalAwayFromSpace(panelsAsSpace))
            {
                normal = polyline.Flip().Normal();
            }
            if (normal == null)
            {
                return(null);
            }

            Point centre = polyline.Centroid();

            if (centre == null)
            {
                centre = polyline.ControlPoints.CullDuplicates().Average();
            }

            Line line = new Line
            {
                Start = centre,
                End   = centre.Translate(normal),
            };

            List <Point> pnts = polyline.DiscontinuityPoints();

            bool            wasFlat   = false;
            TransformMatrix transform = null;

            if (pnts.Min(x => Math.Round(x.Z, 6)) == pnts.Max(x => Math.Round(x.Z, 6)))
            {
                //All the points are on the same Z level - we're looking at a floor/roof
                transform = BH.Engine.Geometry.Create.RotationMatrix(polyline.Centroid(), new Vector {
                    X = 1, Y = 0, Z = 0
                }, 1.5708);
                polyline = polyline.Transform(transform);
                pnts     = polyline.ControlPoints;
                line.End = line.Start.Translate(polyline.Normal());
                wasFlat  = true;
            }

            Point leftMost = null;

            foreach (Point p in pnts)
            {
                if (IsLeft(line, p) && (leftMost == null || leftMost.Z > p.Z))
                {
                    leftMost = p;
                }
            }

            if (wasFlat && leftMost != null)
            {
                leftMost = leftMost.Transform(transform.Invert());
            }

            return(leftMost);
        }
        /// <summary>
        /// Gets a PolyCurve obtained by applying the offset and elevation displacement to each point of the Featureline PolyCurve only for the station interval specified.
        /// </summary>
        /// <param name="startStation">The start station.</param>
        /// <param name="endStation">The end station.</param>
        /// <param name="offset">The offset.</param>
        /// <param name="elevation">The elevation.</param>
        /// <returns></returns>
        public PolyCurve GetPolyCurveByStationsOffsetElevation(double startStation, double endStation, double offset, double elevation)
        {
            Utils.Log(string.Format("Featureline.GetPolyCurveByStationsOffsetElevation started...", ""));

            if (startStation == endStation)
            {
                return(null);
            }

            //double[] soeStart = this.GetStationOffsetElevationByPoint(this.Curve.StartPoint);
            //double[] soeEnd = this.GetStationOffsetElevationByPoint(this.Curve.EndPoint);
            double sStation = this.Start < this.End ? this.Start : this.End;  // soeStart[0] < soeEnd[0] ? soeStart[0] : soeEnd[0];
            double eStation = this.Start < this.End ? this.End : this.Start;  // soeStart[0] < soeEnd[0] ? soeEnd[0] : soeStart[0];

            double min = startStation < endStation ? startStation : endStation;
            double max = endStation > startStation ? endStation : startStation;

            startStation = min;
            endStation   = max;

            //if (endStation < sStation || startStation > eStation)
            //{
            //    return null;
            //}

            if (startStation < sStation)
            {
                startStation = sStation;
            }

            if (endStation > eStation)
            {
                endStation = eStation;
            }

            IList <double> stations = new List <double>()
            {
                startStation
            };

            foreach (double s in this.Baseline.Stations.Where(s => s >= startStation && s <= endStation))
            {
                stations.Add(s);
            }

            stations.Add(endStation);

            Point p = Point.ByCoordinates(offset, 0, elevation);

            IList <Point> points = new List <Point>();

            foreach (double s in stations)
            {
                points.Add(p.Transform(this.CoordinateSystemByStation(s)) as Point);
            }

            p.Dispose();

            points = Point.PruneDuplicates(points);

            Utils.Log(string.Format("Featureline.GetPolyCurveByStationsOffsetElevation completed.", ""));

            return(PolyCurve.ByPoints(points));
        }
        /// <inheritdoc/>
        protected override void OnFrameApply(
            ImageFrame <TPixel> source,
            ImageFrame <TPixel> destination,
            Rectangle sourceRectangle,
            Configuration configuration)
        {
            int height = this.TargetDimensions.Height;
            int width  = this.TargetDimensions.Width;

            Rectangle sourceBounds = source.Bounds();
            var       targetBounds = new Rectangle(0, 0, width, height);

            // Since could potentially be resizing the canvas we might need to re-calculate the matrix
            Matrix3x2 matrix = this.GetProcessingMatrix(sourceBounds, targetBounds);

            // Convert from screen to world space.
            Matrix3x2.Invert(matrix, out matrix);

            if (this.Sampler is NearestNeighborResampler)
            {
                Parallel.For(
                    0,
                    height,
                    configuration.ParallelOptions,
                    y =>
                {
                    Span <TPixel> destRow = destination.GetPixelRowSpan(y);

                    for (int x = 0; x < width; x++)
                    {
                        var point = Point.Transform(new Point(x, y), matrix);
                        if (sourceBounds.Contains(point.X, point.Y))
                        {
                            destRow[x] = source[point.X, point.Y];
                        }
                    }
                });

                return;
            }

            int maxSourceX = source.Width - 1;
            int maxSourceY = source.Height - 1;

            (float radius, float scale, float ratio)xRadiusScale = this.GetSamplingRadius(source.Width, destination.Width);
            (float radius, float scale, float ratio)yRadiusScale = this.GetSamplingRadius(source.Height, destination.Height);
            float      xScale    = xRadiusScale.scale;
            float      yScale    = yRadiusScale.scale;
            var        radius    = new Vector2(xRadiusScale.radius, yRadiusScale.radius);
            IResampler sampler   = this.Sampler;
            var        maxSource = new Vector4(maxSourceX, maxSourceY, maxSourceX, maxSourceY);
            int        xLength   = (int)MathF.Ceiling((radius.X * 2) + 2);
            int        yLength   = (int)MathF.Ceiling((radius.Y * 2) + 2);

            MemoryManager memoryManager = configuration.MemoryManager;

            using (Buffer2D <float> yBuffer = memoryManager.Allocate2D <float>(yLength, height))
                using (Buffer2D <float> xBuffer = memoryManager.Allocate2D <float>(xLength, height))
                {
                    Parallel.For(
                        0,
                        height,
                        configuration.ParallelOptions,
                        y =>
                    {
                        ref TPixel destRowRef = ref MemoryMarshal.GetReference(destination.GetPixelRowSpan(y));
                        ref float ySpanRef    = ref MemoryMarshal.GetReference(yBuffer.GetRowSpan(y));
                        ref float xSpanRef    = ref MemoryMarshal.GetReference(xBuffer.GetRowSpan(y));
Exemple #24
0
 public virtual bool ContainsPointOnScreen(Point point, Camera camera)
 {
     return(BoundingRect.Contains(point.Transform(camera.GetMatrix().Invert())));
 }
Exemple #25
0
        /***************************************************/
        /**** Public Methods                            ****/
        /***************************************************/

        public static List <Point> PointGrid(this Panel panel)
        {
            List <ICurve> curves = panel.ExternalEdgeCurves();

            List <PolyCurve> joined = BH.Engine.Geometry.Compute.IJoin(curves);
            List <PolyCurve> joinedOpeningCurves = BH.Engine.Geometry.Compute.IJoin(panel.InternalEdgeCurves());

            Plane plane = joined.First().FitPlane();

            Vector z = Vector.ZAxis;

            double angle = plane.Normal.Angle(z);

            Vector axis = plane.Normal.CrossProduct(z);

            TransformMatrix matrix = Engine.Geometry.Create.RotationMatrix(Point.Origin, axis, angle);

            List <PolyCurve> rotated = BH.Engine.Geometry.Compute.IJoin(curves.Select(x => x.IRotate(Point.Origin, axis, angle)).ToList());

            BoundingBox bounds = rotated.First().Bounds();

            for (int i = 1; i < rotated.Count; i++)
            {
                bounds += rotated[i].Bounds();
            }

            double xMin = bounds.Min.X;
            double yMin = bounds.Min.Y;
            double zVal = bounds.Min.Z;

            int steps = 9;

            double xStep = (bounds.Max.X - xMin) / steps;
            double yStep = (bounds.Max.Y - yMin) / steps;

            List <Point>    pts       = new List <Point>();
            TransformMatrix transpose = matrix.Transpose();

            for (int i = 0; i < steps; i++)
            {
                double x = xMin + xStep * i;
                for (int j = 0; j < steps; j++)
                {
                    Point pt = new Point {
                        X = x, Y = yMin + yStep * j, Z = zVal
                    };
                    bool isInside = false;

                    pt = pt.Transform(transpose);

                    foreach (PolyCurve crv in joined)
                    {
                        List <Point> list = new List <Point> {
                            pt
                        };
                        if (crv.IsContaining(list, true, 1E-3))
                        {
                            if (!joinedOpeningCurves.Any(c => c.IsContaining(list, false)))
                            {
                                isInside = true;
                                break;
                            }
                        }
                    }
                    if (isInside)
                    {
                        pts.Add(pt);
                    }
                }
            }

            return(pts);
        }
		private void OnMouseDown(object sender, MouseButtonEventArgs e) {
			// dragging
			bool shouldStartDrag = e.ChangedButton == MouseButton.Left && Keyboard.Modifiers == ModifierKeys.None;

			if (shouldStartDrag) {
				dragStartPointInOutput = e.GetPosition(this);
				dragStartPointInVisible = dragStartPointInOutput.Transform(Viewport.Output, Viewport.Visible);	

				dragStartTimestamp = e.Timestamp;

				isDragging = true;
				CaptureMouse();
			}

			bool shouldStartZoom = e.ChangedButton == MouseButton.Left && IsShiftOrCtrl;
			if (shouldStartZoom) {
				// zooming

				zoomStartPoint = e.GetPosition(this);
				if (Viewport.Output.Contains(zoomStartPoint)) {
					isZooming = true;
					AddSelectionAdorner();
					CaptureMouse();
					shouldKeepRatioWhileZooming = Keyboard.Modifiers == ModifierKeys.Shift;
				}
			}

			(Parent as IInputElement).Focus();
		}
Exemple #27
0
 /// <summary>
 /// Converts the specified point from control to screen (abstract scene) coordinates.
 /// </summary>
 /// <param name="point">The point in the control coordinates to convert.</param>
 /// <returns>Converted point in the screen coordinates.</returns>
 public PointF PointAtScreen(Point point)
 {
     return(point.Transform(transformInvers));
 }
Exemple #28
0
        public static Point BottomRight(this Polyline polyline, List <Panel> panelsAsSpace)
        {
            Vector normal = polyline.Normal();

            if (!polyline.NormalAwayFromSpace(panelsAsSpace))
            {
                normal = polyline.Flip().Normal();
            }

            Point centre = polyline.Centroid();

            if (centre == null)
            {
                centre = polyline.Centre();
            }

            if (normal == null)
            {
                return(null);
            }

            Line line = new Line
            {
                Start = centre,
                End   = centre.Translate(normal),
            };

            List <Point> pnts = polyline.DiscontinuityPoints();

            bool            wasFlat   = false;
            TransformMatrix transform = null;

            if (pnts.Min(x => Math.Round(x.Z, 6)) == pnts.Max(x => Math.Round(x.Z, 6)))
            {
                //All the points are on the same Z level - we're looking at a floor/roof
                transform = BH.Engine.Geometry.Create.RotationMatrix(polyline.Centroid(), new Vector {
                    X = 1, Y = 0, Z = 0
                }, 1.5708);
                polyline = polyline.Transform(transform);
                pnts     = polyline.ControlPoints;
                line.End = line.Start.Translate(polyline.Normal());
                wasFlat  = true;
            }

            Point rightMost = null;

            foreach (Point p in pnts)
            {
                if (!IsLeft(line, p) && (rightMost == null || rightMost.Z > p.Z))
                {
                    rightMost = p;
                }
            }

            if (wasFlat && rightMost != null)
            {
                rightMost = rightMost.Transform(transform.Invert());
            }

            return(rightMost);
        }
        /// <inheritdoc/>
        protected override void OnFrameApply(
            ImageFrame <TPixel> source,
            ImageFrame <TPixel> destination,
            Rectangle sourceRectangle,
            Configuration configuration)
        {
            int height = this.TargetDimensions.Height;
            int width  = this.TargetDimensions.Width;

            Rectangle sourceBounds = source.Bounds();
            var       targetBounds = new Rectangle(0, 0, width, height);

            // Since could potentially be resizing the canvas we might need to re-calculate the matrix
            Matrix3x2 matrix = this.GetProcessingMatrix(sourceBounds, targetBounds);

            // Convert from screen to world space.
            Matrix3x2.Invert(matrix, out matrix);

            if (this.Sampler is NearestNeighborResampler)
            {
                ParallelHelper.IterateRows(
                    targetBounds,
                    configuration,
                    rows =>
                {
                    for (int y = rows.Min; y < rows.Max; y++)
                    {
                        Span <TPixel> destRow = destination.GetPixelRowSpan(y);

                        for (int x = 0; x < width; x++)
                        {
                            var point = Point.Transform(new Point(x, y), matrix);
                            if (sourceBounds.Contains(point.X, point.Y))
                            {
                                destRow[x] = source[point.X, point.Y];
                            }
                        }
                    }
                });

                return;
            }

            int maxSourceX = source.Width - 1;
            int maxSourceY = source.Height - 1;

            (float radius, float scale, float ratio)xRadiusScale = this.GetSamplingRadius(source.Width, destination.Width);
            (float radius, float scale, float ratio)yRadiusScale = this.GetSamplingRadius(source.Height, destination.Height);
            float      xScale    = xRadiusScale.scale;
            float      yScale    = yRadiusScale.scale;
            var        radius    = new Vector2(xRadiusScale.radius, yRadiusScale.radius);
            IResampler sampler   = this.Sampler;
            var        maxSource = new Vector4(maxSourceX, maxSourceY, maxSourceX, maxSourceY);
            int        xLength   = (int)MathF.Ceiling((radius.X * 2) + 2);
            int        yLength   = (int)MathF.Ceiling((radius.Y * 2) + 2);

            MemoryAllocator memoryAllocator = configuration.MemoryAllocator;

            using (Buffer2D <float> yBuffer = memoryAllocator.Allocate2D <float>(yLength, height))
                using (Buffer2D <float> xBuffer = memoryAllocator.Allocate2D <float>(xLength, height))
                {
                    ParallelHelper.IterateRows(
                        targetBounds,
                        configuration,
                        rows =>
                    {
                        for (int y = rows.Min; y < rows.Max; y++)
                        {
                            ref TPixel destRowRef = ref MemoryMarshal.GetReference(destination.GetPixelRowSpan(y));
                            ref float ySpanRef    = ref MemoryMarshal.GetReference(yBuffer.GetRowSpan(y));
                            ref float xSpanRef    = ref MemoryMarshal.GetReference(xBuffer.GetRowSpan(y));

                            for (int x = 0; x < width; x++)
                            {
                                // Use the single precision position to calculate correct bounding pixels
                                // otherwise we get rogue pixels outside of the bounds.
                                var point = Vector2.Transform(new Vector2(x, y), matrix);

                                // Clamp sampling pixel radial extents to the source image edges
                                Vector2 maxXY = point + radius;
                                Vector2 minXY = point - radius;

                                // max, maxY, minX, minY
                                var extents = new Vector4(
                                    MathF.Floor(maxXY.X + .5F),
                                    MathF.Floor(maxXY.Y + .5F),
                                    MathF.Ceiling(minXY.X - .5F),
                                    MathF.Ceiling(minXY.Y - .5F));

                                int right  = (int)extents.X;
                                int bottom = (int)extents.Y;
                                int left   = (int)extents.Z;
                                int top    = (int)extents.W;

                                extents = Vector4.Clamp(extents, Vector4.Zero, maxSource);

                                int maxX = (int)extents.X;
                                int maxY = (int)extents.Y;
                                int minX = (int)extents.Z;
                                int minY = (int)extents.W;

                                if (minX == maxX || minY == maxY)
                                {
                                    continue;
                                }

                                // It appears these have to be calculated on-the-fly.
                                // Precalculating transformed weights would require prior knowledge of every transformed pixel location
                                // since they can be at sub-pixel positions on both axis.
                                // I've optimized where I can but am always open to suggestions.
                                if (yScale > 1 && xScale > 1)
                                {
                                    CalculateWeightsDown(
                                        top,
                                        bottom,
                                        minY,
                                        maxY,
                                        point.Y,
                                        sampler,
                                        yScale,
                                        ref ySpanRef,
                                        yLength);

                                    CalculateWeightsDown(
                                        left,
                                        right,
                                        minX,
                                        maxX,
                                        point.X,
                                        sampler,
                                        xScale,
                                        ref xSpanRef,
                                        xLength);
                                }
                                else
                                {
                                    CalculateWeightsScaleUp(minY, maxY, point.Y, sampler, ref ySpanRef);
                                    CalculateWeightsScaleUp(minX, maxX, point.X, sampler, ref xSpanRef);
                                }

                                // Now multiply the results against the offsets
                                Vector4 sum = Vector4.Zero;
                                for (int yy = 0, j = minY; j <= maxY; j++, yy++)
                                {
                                    float yWeight = Unsafe.Add(ref ySpanRef, yy);

                                    for (int xx = 0, i = minX; i <= maxX; i++, xx++)
                                    {
                                        float xWeight = Unsafe.Add(ref xSpanRef, xx);

                                        // Values are first premultiplied to prevent darkening of edge pixels
                                        var current = source[i, j].ToVector4();
                                        Vector4Utils.Premultiply(ref current);
                                        sum += current * xWeight * yWeight;
                                    }
                                }

                                ref TPixel dest = ref Unsafe.Add(ref destRowRef, x);

                                // Reverse the premultiplication
                                Vector4Utils.UnPremultiply(ref sum);
                                dest.FromVector4(sum);
                            }
        public Dictionary <string, object> GetStationOffsetElevationByPoint(Point point)
        {
            Utils.Log(string.Format("Featureline.GetStationOffsetElevationByPoint started...", ""));

            Utils.Log(string.Format("Point: X: {0} Y: {1} Z: {2}", point.X, point.Y, point.Z));

            Point flatPt = Point.ByCoordinates(point.X, point.Y);

            Curve flatPC = this.Curve.PullOntoPlane(Plane.XY());

            AeccAlignment alignment = this._baseline.Alignment.InternalElement as AeccAlignment;

            double station   = 0;
            double offset    = 0;
            double elevation = 0;

            double alStation = 0;
            double alOffset  = 0;

            //Point start = null; //  c.PointAtParameter(0);
            //Point end = null; // c.PointAtParameter(1);

            //Vector dir = null; // Vector.ByTwoPoints(start, end).Normalized();

            //Vector test = null;

            Point ortho = null;

            //Line l = null;

            CoordinateSystem cs = null;

            Point result = null;

            alignment.StationOffset(point.X, point.Y, out alStation, out alOffset);

            Utils.Log(string.Format("The point is at station {0}", alStation));

            // 20190414 -- START

            if (Math.Abs(alStation - this.Start) <= 0.00001)
            {
                alStation = this.Start;
                Utils.Log(string.Format("Station rounded to {0}", alStation));
            }

            if (Math.Abs(alStation - this.End) <= 0.00001)
            {
                alStation = this.End;
                Utils.Log(string.Format("Station rounded to {0}", alStation));
            }

            // 20190414 -- END

            if (this.Start <= Math.Round(alStation, 5) && Math.Round(alStation, 5) <= this.End ||
                Math.Abs(this.Start - alStation) < 0.0001 ||
                Math.Abs(this.End - alStation) < 0.0001)
            {
                // the point is in the featureline range

                Utils.Log(string.Format("The point is inside the featureline station range.", ""));

                // 20190205 -- START

                ortho = flatPC.ClosestPointTo(flatPt);

                Utils.Log(string.Format("Orthogonal Point at Z = 0: {0}", ortho));

                double orStation = 0;
                double orOffset  = 0;
                double error     = 0;

                alignment.StationOffset(ortho.X, ortho.Y, out orStation, out orOffset);

                cs = this.CoordinateSystemByStation(orStation, false).Inverse();

                Utils.Log(string.Format("CoordinateSystem: {0}", cs));

                result = point.Transform(cs) as Point;

                Utils.Log(string.Format("Result: {0}", result));

                station   = orStation;
                offset    = result.X;
                elevation = result.Z;
                error     = result.Y;

                // 20190205 -- END

                #region UNDER REVIEW
                //Dictionary<double, Point> cpts = new Dictionary<double, Point>();

                //foreach (Curve c in this._polycurve.Curves())
                //{
                //    start = c.PointAtParameter(0);
                //    end = c.PointAtParameter(1);

                //    start = Point.ByCoordinates(start.X, start.Y, 0);
                //    end = Point.ByCoordinates(end.X, end.Y, 0);

                //    Point q = Point.ByCoordinates(point.X, point.Y, 0);

                //    // Utils.Log(string.Format("Curve Start: {0} End: {1}", start, end));

                //    dir = Vector.ByTwoPoints(start, end).Normalized();

                //    test = null;

                //    ortho = null;

                //    if (start.DistanceTo(q) > 0)
                //    {
                //        test = Vector.ByTwoPoints(start, q);

                //        ortho = start.Translate(dir, test.Dot(dir)) as Point;
                //    }
                //    else
                //    {
                //        test = Vector.ByTwoPoints(end, q);

                //        ortho = end.Translate(dir.Reverse(), test.Dot(dir)) as Point;
                //    }

                //    if (ortho != null)
                //    {
                //        l = Line.ByStartPointEndPoint(start, end);

                //        double par = l.ParameterAtPoint(ortho);

                //        if (par >= 0 && par <= 1)
                //        {
                //            double orStation = 0;
                //            double orOffset = 0;

                //            alignment.StationOffset(ortho.X, ortho.Y, out orStation, out orOffset);

                //            CoordinateSystem cs = this.CoordinateSystemByStation(orStation, false).Inverse();

                //            Point result = point.Transform(cs) as Point;

                //            //Utils.Log(string.Format("OrStation: {0}", orStation));

                //            cpts[orStation] = result;
                //        }
                //    }
                //    else
                //    {
                //        Utils.Log(string.Format("No projection was found", ""));
                //    }
                //}

                //double error = double.MaxValue;

                //foreach (double s in cpts.Keys)
                //{
                //    double margin = cpts[s].Y;

                //    if (margin < error)
                //    {
                //        station = s;
                //        offset = cpts[s].X;
                //        elevation = cpts[s].Z;
                //        error = margin;
                //    }
                //}
                #endregion

                Utils.Log(string.Format("Final Margin: {0}", error));

                #region TEST CODE
                //Point projection = this._polycurve.ClosestPointTo(point);

                //int count = 0;

                ////while (true)
                ////{
                //    // The station and offset from the alignment of the point sitting on the featureline
                //double flStation = 0;
                //double flOffset = 0;

                //    // The X and Y from the alignment of the point on the featureline at station and offset
                //    double x = 0;
                //    double y = 0;

                //alignment.StationOffset(projection.X, projection.Y, out flStation, out flOffset);

                //    alignment.PointLocation(flStation, flOffset, out x, out y);

                //CoordinateSystem cs = this.CoordinateSystemByStation(flStation).Inverse();

                //Point result = point.Transform(cs) as Point;

                //station = flStation;
                //offset = result.X;
                //elevation = result.Z;

                //    Utils.Log(string.Format("Station: {0}", station));

                //    Utils.Log(string.Format("Margin: {0}", result.Y));

                //    Utils.Log(string.Format("X: {0} Y: {1}", x, y));

                //    // tolerance
                //    if (Math.Abs(result.Y) > 0.0001 && count < 10)
                //    {
                //        projection = projection.Translate(cs.YAxis, -result.Y) as Point;
                //    }
                //    else
                //    {
                //        cs.Dispose();
                //        result.Dispose();

                //        //break;
                //    }

                //    ++count;
                ////}
                #endregion
            }
            else
            {
                Utils.Log(string.Format("The point is outside the featureline station range.", ""));

                station   = alStation;
                offset    = alOffset;                                                                  // offset from alignment
                elevation = point.Z - this._baseline.PointByStationOffsetElevation(alStation, 0, 0).Z; // Absolute elevation
            }

            Utils.Log(string.Format("Station: {0} Offset: {1} Elevation: {2}", station, offset, elevation));

            //start.Dispose();
            //end.Dispose();
            //dir.Dispose();
            //test.Dispose();
            ortho.Dispose();
            //l.Dispose();
            cs.Dispose();
            result.Dispose();
            flatPt.Dispose();
            flatPC.Dispose();

            #region OLD CODE
            //double[] soe = this._baseline.GetStationOffsetElevationByPoint(point);

            //double station = soe[0];
            //double offset = soe[1] - this._baseline.GetStationOffsetElevationByPoint(PointAtStation(station))[1];
            //double elevation = point.Z - PointAtStation(station).Z;
            #endregion
            Utils.Log(string.Format("Featureline.GetStationOffsetElevationByPoint completed.", ""));

            return(new Dictionary <string, object>
            {
                { "Station", Math.Round(station, 5) },
                { "Offset", Math.Round(offset, 5) },
                { "Elevation", Math.Round(elevation, 5) }
            });
        }
 public bool ContainsPointOnScreen(Point point, Camera camera)
 {
     return(new Rectangle(Position.ToPoint(), Size.ToPoint()).Contains(point.Transform(camera.GetMatrix(ParallaxMultiplier).Invert())));
 }
Exemple #32
0
        /// <inheritdoc/>
        protected override void OnApply(
            ImageFrame <TPixel> source,
            ImageFrame <TPixel> destination,
            Rectangle sourceRectangle,
            Configuration configuration)
        {
            int height = this.targetDimensions.Height;
            int width  = this.targetDimensions.Width;

            Rectangle sourceBounds = source.Bounds();
            var       targetBounds = new Rectangle(0, 0, width, height);

            // Since could potentially be resizing the canvas we might need to re-calculate the matrix
            Matrix3x2 matrix = this.GetProcessingMatrix(sourceBounds, targetBounds);

            if (this.Sampler is NearestNeighborResampler)
            {
                Parallel.For(
                    0,
                    height,
                    configuration.ParallelOptions,
                    y =>
                {
                    Span <TPixel> destRow = destination.GetPixelRowSpan(y);

                    for (int x = 0; x < width; x++)
                    {
                        var point = Point.Transform(new Point(x, y), matrix);
                        if (sourceBounds.Contains((int)point.X, (int)point.Y))
                        {
                            destRow[x] = source[point.X, point.Y];
                        }
                    }
                });

                return;
            }

            int        maxSourceX   = source.Width - 1;
            int        maxSourceY   = source.Height - 1;
            var        xRadiusScale = this.GetSamplingRadius(source.Width, destination.Width);
            var        yRadiusScale = this.GetSamplingRadius(source.Height, destination.Height);
            var        xScale       = xRadiusScale.scale;
            var        yScale       = yRadiusScale.scale;
            var        radius       = new Vector2((float)xRadiusScale.radius, (float)yRadiusScale.radius);
            IResampler sampler      = this.Sampler;
            var        maxSource    = new Vector4(maxSourceX, maxSourceY, maxSourceX, maxSourceY);
            int        xLength      = (int)MathF.Ceiling((radius.X * 2) + 2);
            int        yLength      = (int)MathF.Ceiling((radius.Y * 2) + 2);

            using (var yBuffer = new Buffer2D <float>(yLength, height))
                using (var xBuffer = new Buffer2D <float>(xLength, height))
                {
                    Parallel.For(
                        0,
                        height,
                        configuration.ParallelOptions,
                        y =>
                    {
                        Span <TPixel> destRow = destination.GetPixelRowSpan(y);
                        Span <float> ySpan    = yBuffer.GetRowSpan(y);
                        Span <float> xSpan    = xBuffer.GetRowSpan(y);

                        for (int x = 0; x < width; x++)
                        {
                            // Use the single precision position to calculate correct bounding pixels
                            // otherwise we get rogue pixels outside of the bounds.
                            var point = Vector2.Transform(new Vector2(x, y), matrix);

                            // Clamp sampling pixel radial extents to the source image edges
                            Vector2 maxXY = point + radius;
                            Vector2 minXY = point - radius;

                            // max, maxY, minX, minY
                            var extents = new Vector4(
                                (float)MathF.Floor(maxXY.X + .5F),
                                (float)MathF.Floor(maxXY.Y + .5F),
                                (float)MathF.Ceiling(minXY.X - .5F),
                                (float)MathF.Ceiling(minXY.Y - .5F));

                            int right  = (int)extents.X;
                            int bottom = (int)extents.Y;
                            int left   = (int)extents.Z;
                            int top    = (int)extents.W;

                            extents = Vector4.Clamp(extents, Vector4.Zero, maxSource);

                            int maxX = (int)extents.X;
                            int maxY = (int)extents.Y;
                            int minX = (int)extents.Z;
                            int minY = (int)extents.W;

                            if (minX == maxX || minY == maxY)
                            {
                                continue;
                            }

                            // It appears these have to be calculated on-the-fly.
                            // Precalulating transformed weights would require prior knowledge of every transformed pixel location
                            // since they can be at sub-pixel positions on both axis.
                            // I've optimized where I can but am always open to suggestions.
                            if (yScale > 1 && xScale > 1)
                            {
                                CalculateWeightsDown(top, bottom, minY, maxY, point.Y, sampler, (float)yScale, ySpan);
                                CalculateWeightsDown(left, right, minX, maxX, point.X, sampler, (float)xScale, xSpan);
                            }
                            else
                            {
                                CalculateWeightsScaleUp(minY, maxY, point.Y, sampler, ySpan);
                                CalculateWeightsScaleUp(minX, maxX, point.X, sampler, xSpan);
                            }

                            // Now multiply the results against the offsets
                            Vector4 sum = Vector4.Zero;
                            for (int yy = 0, j = minY; j <= maxY; j++, yy++)
                            {
                                float yWeight = ySpan[yy];

                                for (int xx = 0, i = minX; i <= maxX; i++, xx++)
                                {
                                    float xWeight = xSpan[xx];
                                    var vector    = source[i, j].ToVector4();

                                    // Values are first premultiplied to prevent darkening of edge pixels
                                    Vector4 mupltiplied = vector.Premultiply();
                                    sum += mupltiplied * xWeight * yWeight;
                                }
                            }

                            ref TPixel dest = ref destRow[x];

                            // Reverse the premultiplication
                            dest.PackFromVector4(sum.UnPremultiply());
                        }
                    });
                }
        }