Beispiel #1
0
        public void AssertThat_FromWorld_ToWorld_AreIdentityFunction()
        {
            //Generate a random load of points
            var rand   = new Random();
            var points = new List <Vector2>();

            for (int i = 0; i < 20; i++)
            {
                points.Add(rand.RandomNormalVector().XZ() * (float)rand.NextDouble() * 50);
            }

            //Calculate OABR
            var oabr = OABR.Fit(points);

            //Draw it
            var svg  = new SvgBuilder(2);
            var hull = points.ConvexHull().ToArray();

            svg.Outline(hull, "green");
            svg.Outline((IReadOnlyList <Vector2>)oabr.Points(new Vector2[4]));
            foreach (var vector2 in points)
            {
                svg.Circle(vector2, 1, oabr.Contains(vector2) ? "red" : "blue");
            }
            Console.WriteLine(svg.ToString());

            //Assert that every point lies within the bounds
            foreach (var vector2 in points)
            {
                var trans = oabr.FromWorld(vector2);
                var world = oabr.ToWorld(trans);

                Assert.IsTrue(vector2.TolerantEquals(world, 0.001f), string.Format("Expected {0} and {1} to be equal", vector2, world));
            }
        }
Beispiel #2
0
        private static void DrawArmature(Armature2D armature, IReadOnlyList <float> solution, Vector2 target)
        {
            var builder = new SvgBuilder(10);

            builder.Outline(new[] {
                new Vector2(-50, -50),
                new Vector2(50, -50),
                new Vector2(50, 50),
                new Vector2(-50, 50),
            });

            var index           = 0;
            var pos             = Vector2.Zero;
            var parentTransform = Matrix4x4.Identity;

            foreach (var bone in armature.Bones)
            {
                builder.Circle(pos, 0.5f, "yellow");

                var localTransform = TriangulationSolver2D.CalculateLocalTransform(bone, ToRadians(solution[index]));
                parentTransform = localTransform * parentTransform;
                var end = Vector2.Transform(new Vector2(0, 0), parentTransform);
                index++;

                builder.Line(pos, end, 2, "red");

                pos = end;
            }

            builder.Circle(target, 0.5f, "blue");

            var str = Regex.Replace(builder.ToString(), "g transform=\"translate\\((.+?), (.+?)\\)\"", "g transform=\"translate(${1}, 100) scale(1, -1)\"");

            Console.WriteLine(str);
        }
Beispiel #3
0
        public void AssertThat_AllPointsLiesInBounds_WithRandomShape()
        {
            //Generate a random load of points
            var rand   = new Random();
            var points = new List <Vector2>();

            for (int i = 0; i < 20; i++)
            {
                points.Add(rand.RandomNormalVector().XZ() * (float)rand.NextDouble() * 50);
            }

            //Calculate OABR
            var oabr = OABR.Fit(points);

            //Draw it
            var svg  = new SvgBuilder(2);
            var hull = points.ConvexHull().ToArray();

            svg.Outline(hull, "green");
            svg.Outline((IReadOnlyList <Vector2>)oabr.Points(new Vector2[4]));
            foreach (var vector2 in points)
            {
                svg.Circle(vector2, 1, oabr.Contains(vector2) ? "red" : "blue");
            }
            Console.WriteLine(svg.ToString());

            //Assert that every point lies within the bounds
            Assert.IsTrue(points.All(p => oabr.Contains(p)));
        }
Beispiel #4
0
        protected virtual SvgBuilder FillSvg(bool[,] sprite, Color background, Color foreground)
        {
            int     side     = sprite.GetLength(0);
            decimal offset   = Options.Border / (decimal)Options.Scale;
            decimal fullSide = side + 2m * offset;

            SvgBuilder svg = new SvgBuilder()
                             .SetViewBox(0, 0, fullSide, fullSide)
                             .Append(new SvgRect {
                PercentageWidth  = 100,
                PercentageHeight = 100,
                Color            = background
            });

            SvgPathBuilder path = new SvgPathBuilder {
                Color = foreground
            };

            for (int y = 0; y < side; ++y)
            {
                for (int x = 0; x < side; ++x)
                {
                    if (sprite[y, x])
                    {
                        path.AppendPoint(x + offset, y + offset)
                        .AppendRelativeHorizontalLine(1)
                        .AppendRelativeVerticalLine(1)
                        .AppendRelativeHorizontalLine(-1)
                        .AppendClosePath();
                    }
                }
            }

            return(svg.Append(path));
        }
        private static SvgBuilder Draw(IEnumerable <Vector2> shape, float scale = 30)
        {
            var svg = new SvgBuilder(scale);

            svg.Outline(shape.ToArray());

            return(svg);
        }
Beispiel #6
0
        private static void DrawTreemap <T>(Node <T> root) where T : ITreemapNode
        {
            var svg = new SvgBuilder(50);

            RecursiveAssert(root, p => {
                svg.Outline(p.Bounds.GetCorners());
            });

            Console.WriteLine(svg.ToString());
        }
Beispiel #7
0
        private int SaveRide(int userId, CreateRideDto model)
        {
            var routeSvgPath = new SvgBuilder(model.Locations.Cast <ILatLng>()).Build();

            Ride ride = new Ride();

            ride.StartUtc        = model.StartUtc;
            ride.EndUtc          = model.EndUtc;
            ride.UserId          = userId;
            ride.AverageSpeedMph = model.Locations.Average(i => i.Mph);
            ride.MaxSpeedMph     = model.Locations.Max(i => i.Mph);
            ride.DistanceMiles   = DistanceHelpers.GetDistanceMile(model.Locations.Cast <ILatLng>().ToList());
            ride.RouteSvgPath    = routeSvgPath;

            ride.RideLocations = model.Locations
                                 .Select(i => new RideLocation {
                AccuracyInMetres = i.AccuracyInMetres,
                Altitude         = i.Altitude,
                Latitude         = i.Latitude,
                Longitude        = i.Longitude,
                Mph       = i.Mph,
                Timestamp = i.Timestamp,
            })
                                 .ToList();

            ride.Jumps = model.Jumps
                         .Select(i => new Jump {
                Airtime   = i.Airtime,
                Number    = i.Number,
                Timestamp = i.Timestamp,
                Latitude  = i.Latitude,
                Longitude = i.Longitude,
            })
                         .ToList();

            ride.AccelerometerReadings = model.AccelerometerReadings
                                         .Select(i => new AccelerometerReading {
                Time = i.Timestamp,
                X    = i.X,
                Y    = i.Y,
                Z    = i.Z,
            })
                                         .ToList();

            context.Rides.Add(ride);

            context.SaveChanges();

            return(ride.RideId);
        }
        private static SvgBuilder Draw(IReadOnlyList <Section> sections, IReadOnlyList <IReadOnlyList <Vector2> > corners = null, IReadOnlyList <Vector2> outline = null, float scale = 30)
        {
            var svg = new SvgBuilder(scale);

            foreach (var section in sections)
            {
                svg.Outline(new[] {
                    section.Inner1, section.Inner2, section.Outer1, section.Outer2
                }, "black", "grey");
            }

            if (corners != null)
            {
                foreach (var corner in corners)
                {
                    svg.Outline(corner, "black", "darkgrey");
                }
            }

            //Draw corner sections vertices
            if (corners != null)
            {
                foreach (var corner in corners)
                {
                    foreach (var vertex in corner)
                    {
                        svg.Circle(vertex, 5f / scale, "black");
                    }
                }
            }

            //Draw wall section vertices
            foreach (var vertex in sections.SelectMany(s => new[] { s.Inner1, s.Inner2, s.Outer1, s.Outer2 }).Distinct())
            {
                svg.Circle(vertex, 5f / scale, "black");
            }

            //Draw outline
            if (outline != null)
            {
                svg.Outline(outline, "red");
            }

            return(svg);
        }
        private static SvgBuilder Draw <TA, TB, TC>(Mesh <TA, TB, TC> mesh, Func <TC, string> faceColor)
        {
            var svg = new SvgBuilder(10);

            foreach (var face in mesh.Faces)
            {
                svg.Outline(face.Vertices.Select(v => v.Position).ToArray(), stroke: "none", fill: faceColor(face.Tag));
            }
            foreach (var edge in mesh.HalfEdges.Where(a => a.IsPrimaryEdge))
            {
                svg.Line(edge.StartVertex.Position, edge.EndVertex.Position, 1, "black");
            }
            foreach (var vertex in mesh.Vertices)
            {
                svg.Circle(vertex.Position, 0.2f, "black");
            }
            return(svg);
        }
Beispiel #10
0
        public void Area_IsZero_WithSelfIntersection()
        {
            //Figure of 8 shape, one half clockwise the other half anticlockwise. Adding up to nothing
            var shape = new Vector2[] {
                new Vector2(0, 0),
                new Vector2(0, 10),
                new Vector2(20, 10),
                new Vector2(20, 20),
                new Vector2(10, 20),
                new Vector2(10, 0),
            };

            var svgBuilder = new SvgBuilder(10);

            svgBuilder.Outline(shape);
            Console.WriteLine(svgBuilder);

            Assert.AreEqual(0, shape.Area());
        }
Beispiel #11
0
        public void IsConvex_False_WithSelfIntersecting()
        {
            //Figure of 8 shape, one half clockwise the other half anticlockwise. Adding up to nothing
            var shape = new Vector2[] {
                new Vector2(0, 0),
                new Vector2(0, 10),
                new Vector2(20, 10),
                new Vector2(20, 20),
                new Vector2(10, 20),
                new Vector2(10, 0),
            };

            var svgBuilder = new SvgBuilder(10);

            svgBuilder.Outline(shape);
            Console.WriteLine(svgBuilder);

            Assert.IsFalse(shape.IsConvex());
        }
        private void ProcessSvg(string value, TagHelperOutput output)
        {
            output.TagName = "svg";
            output.TagMode = TagMode.StartTagAndEndTag;

            SvgBuilder    svg      = IdenticonManager.Get("qr").CreateSvg(value);
            StringBuilder innerSvg = new StringBuilder(256);

            foreach (var x in ((XElement)svg).Elements())
            {
                innerSvg.Append(x);
            }

            foreach (XAttribute attribute in ((XElement)svg).Attributes())
            {
                output.Attributes.Add(attribute.Name.LocalName, attribute.Value);
            }

            output.Content.SetHtmlContent(innerSvg.ToString());
        }
        public HorizontalBarChart(Point[] points, float width = 200, float barHeight = 20) : base("div")
        {
            var max = points.Select(e => e.Value).Max();

            var builder = SvgBuilder.New();

            float y = 0;

            foreach (var point in points)
            {
                // builder.Tooltip(
                //     0, y,
                //     e => e.Rect(0, 0, (float)(point.Value / max * width), barHeight, x => x.Fill(point.Color)),
                //     e => e.Overlay(25, 0, 300, 50, overlay => overlay.Text(10, 20, point.Label))
                // );
                builder.Rect(0, y, (float)(point.Value / max * width), barHeight, x => x.Fill(point.Color));
                y += barHeight;
            }

            this.HtmlElement.InnerHtml = builder.ToString();
        }
        public static string FloorplanToSvg(IFloorPlanBuilder plan, float scalePosition = 1, bool basic = false)
        {
            var builder = new SvgBuilder(scalePosition);

            builder.Outline(plan.ExternalFootprint, "black", "rgba(10, 10, 10, 0.25)");

            foreach (var room in plan.Rooms)
            {
                builder.Outline(room.OuterFootprint, fill: "cornflowerblue");
            }

            foreach (var room in plan.Rooms)
            {
                if (basic)
                {
                    builder.Outline(room.InnerFootprint, fill: "lightsteelblue");
                }
                else
                {
                    var walls = room.GetWalls();

                    foreach (var facade in walls)
                    {
                        builder.Outline(new[] {
                            facade.Section.Inner1, facade.Section.Inner2, facade.Section.Outer1, facade.Section.Outer2
                        }, facade.IsExternal ? "yellow" : "blue", "dimgray");
                    }

                    var corners = room.GetCorners();

                    foreach (var corner in corners)
                    {
                        builder.Outline(corner, "royalblue", "navyblue");
                    }
                }
            }

            return(builder.ToString());
        }
Beispiel #15
0
 public virtual void EditScale(float scale)
 {
     SvgBuilder.EditScale(ref _start, scale);
     SvgBuilder.EditScale(ref _end, scale);
 }
Beispiel #16
0
 public virtual void EditOffset(float dx, float dy)
 {
     SvgBuilder.EditOffset(ref _start, dx, dy);
     SvgBuilder.EditOffset(ref _end, dx, dy);
 }
Beispiel #17
0
        public async Task <IActionResult> Get([FromRoute, Required] string ifc, [FromQuery] string bg = "white", string text = "black")
        {
            _redis.UseDatabse(RedisDatabase.NameIds);
            var uid = await _redis.GetString(ifc.ToLower());

            if (uid == default)
            {
                try
                {
                    var lookup = await Client.GetUserStatsAsync(ifcNames : new[] { ifc });

                    if (lookup.Count < 1)
                    {
                        throw new Exception("User not found");
                    }

                    uid = lookup.First().UserId.ToString();
                    _redis.SetString(ifc.ToLower(), uid);
                }
                catch
                {
                    return(Content(SvgBuilder.Generate("<text x=\"0\" y=\"15\" fill =\"red\" class=\"bold\">Failed to Load Stats. Ensure you've enabled username display in-flight.</text>"), "image/svg+xml"));
                }
            }

            _redis.UseDatabse(RedisDatabase.Responses);
            var cached = await _redis.GetString($"{uid}_{bg}_{text}");

            if (cached != default)
            {
                return(Content(cached, "image/svg+xml; charset=utf-8"));
            }

            _redis.UseDatabse(RedisDatabase.Misc);
            var sessions = await _redis.GetObject <List <SessionInfo> >("sessions");

            if (sessions == default)
            {
                sessions = await Client.GetSessionsAsync();

                _redis.SetObject("sessions", sessions);
            }

            var flights = await _redis.GetObject <List <FlightEntry> >("flights");

            if (flights == default)
            {
                var flightsSessions = new List <List <FlightEntry> >();
                foreach (var s in sessions)
                {
                    flightsSessions.Add(await Client.GetFlightsAsync(s.Id));
                }
                flights = flightsSessions.SelectMany(x => x).ToList();
                _redis.SetObject("flights", flights, TimeSpan.FromMinutes(10));
            }

            var atc = await _redis.GetObject <List <AtcEntry> >("atc");

            if (atc == default)
            {
                var atcSessions = new List <List <AtcEntry> >();
                foreach (var s in sessions)
                {
                    atcSessions.Add(await Client.GetAtcFacilitiesAsync(s.Id));
                }
                atc = atcSessions.SelectMany(x => x).ToList();
                _redis.SetObject("atc", atc, TimeSpan.FromMinutes(10));
            }

            var status   = "Not Active";
            var flight   = flights.FirstOrDefault(f => f.UserId.ToString() == uid);
            var stations = atc.GroupBy(a => a.UserId).FirstOrDefault(g => g.Any(a => a.UserId.ToString() == uid));

            if (flight != default)
            {
                try
                {
                    _redis.UseDatabse(RedisDatabase.FlightPlans);
                    var fpl = await _redis.GetObject <FlightPlanInfo>(flight.FlightId.ToString());

                    if (fpl == default)
                    {
                        fpl = await flight.GetFlightPlan();

                        _redis.SetObject(flight.FlightId.ToString(), fpl, TimeSpan.FromHours(24));
                    }
                    if (fpl.Waypoints.Length < 2)
                    {
                        throw new Exception("Not Enough Waypoints");
                    }

                    if (fpl.Waypoints.First().Length != 4 && fpl.Waypoints.Last().Length != 4)
                    {
                        throw new Exception("Invalid Departure/Arrival Waypoints");
                    }

                    if (fpl.Waypoints.First().Length != 4)
                    {
                        status = $"Flying to {fpl.Waypoints.Last()}";
                    }
                    else if (fpl.Waypoints.Last().Length != 4)
                    {
                        status = $"Flying from {fpl.Waypoints.First()}";
                    }
                    else
                    {
                        status = $"Flying from {fpl.Waypoints.First()} to {fpl.Waypoints.Last()}";
                    }
                }
                catch
                {
                    status = "Flying";
                }
            }
            else if (stations != default && stations.Any())
            {
                if (stations.Any(s => s.AirportName == null))
                {
                    status = $"Controlling {string.Join(", ", stations.Select(s => s.Type.ToString()).ToArray())}";
                }
                else
                {
                    status = $"Controlling {stations.First().AirportName} {string.Join(", ", stations.Select(s => s.Type.ToString()).ToArray())}";
                }
            }

            _redis.UseDatabse(RedisDatabase.Stats);
            var stats = await _redis.GetObject <Models.UserStats>(uid);

            if (stats == default)
            {
                stats = (await Client.GetUserStatsAsync(new[] { Guid.Parse(uid) })).Select(x => new Models.UserStats {
                    AtcOperations = x.AtcOperations,
                    AtcRank       = x.AtcRank.ToString(),
                    FlightTime    = $"{Math.Floor(x.FlightTime / 60)}:{x.FlightTime % 60}",
                    Grade         = x.Grade,
                    LandingCount  = x.LandingCount,
                    OnlineFlights = x.OnlineFlights,
                    Xp            = x.Xp,
                }).FirstOrDefault();
                _redis.SetObject(uid, stats, TimeSpan.FromHours(24));
            }

            _redis.UseDatabse(RedisDatabase.Responses);
            var data = SvgBuilder.FromData(status, stats, ifc, bg, text);

            _redis.SetString($"{uid}_{bg}_{text}", data, TimeSpan.FromMinutes(10));

            return(Content(data, "image/svg+xml; charset=utf-8"));
        }
Beispiel #18
0
 public override void EditOffset(float dx, float dy)
 {
     SvgBuilder.EditOffset(ref _controlPoint, dx, dy);
     base.EditOffset(dx, dy);
 }
        static void Main(string[] args)
        {
            Stopwatch w = new Stopwatch();

            w.Start();

            var ssk = StraightSkeleton.Generate(new Vector2[] {
                new Vector2(-10, 10),
                new Vector2(-1, 10),
                new Vector2(0, 11),
                new Vector2(1, 10),
                new Vector2(10, 10),
                new Vector2(10, -2),
                new Vector2(5, 0),
                new Vector2(7, -10),
                new Vector2(-7, -10),
                new Vector2(-5, 0),
                new Vector2(-10, -2),
            }, new Vector2[][] {
                new Vector2[] {
                    new Vector2(2, 2),
                    new Vector2(2, -2),
                    new Vector2(-2, -2),
                    new Vector2(-2, 2)
                }
            });

            w.Stop();

            Stopwatch w2 = new Stopwatch();

            w2.Start();

            //Extract data from result
            var builder = new SvgBuilder(30);

            //Draw outline
            foreach (var edge in ssk.Borders)
            {
                builder.Circle(edge.Start.Position, 0.2f, "blue");
                builder.Circle(edge.End.Position, 0.2f, "blue");
                builder.Line(edge.Start.Position, edge.End.Position, 2, "blue");
            }

            //Draw offsets
            for (var i = 1; i < 10; i++)
            {
                var offset = ssk.Offset(i / 2f);
                foreach (var polygon in offset)
                {
                    builder.Outline(polygon, "green");
                }
            }

            //Draw spokes
            foreach (var edge in ssk.Spokes)
            {
                builder.Line(edge.Start.Position, edge.End.Position, 4, "lime");
            }

            //Draw straight skeleton
            foreach (var edge in ssk.Skeleton)
            {
                builder.Circle(edge.Start.Position, 0.2f, "hotpink");
                builder.Circle(edge.End.Position, 0.2f, "hotpink");
                builder.Line(edge.Start.Position, edge.End.Position, 2, "hotpink");
            }

            Console.WriteLine(builder);
            Console.Title = string.Format("Elapsed: {0}ms {1}ms", w.ElapsedMilliseconds, w2.ElapsedMilliseconds);
            Console.ReadLine();
        }
Beispiel #20
0
 public override void EditScale(float scale)
 {
     SvgBuilder.EditScale(ref _controlPoint, scale);
     base.EditScale(scale);
 }