public override Schematic WriteSchematic() { float minX = _blocks.MinBy(t => t.X).X; float minY = _blocks.MinBy(t => t.Y).Y; float minZ = _blocks.MinBy(t => t.Z).Z; Schematic schematic = new Schematic(); List <Voxel> list = Quantization.ApplyQuantization(_blocks, _colorLimit); list.ApplyOffset(new Vector3(minX, minY, minZ)); HashSet <Voxel> hashSet = list.ToHashSet(); if (_holes) { hashSet = FillHoles(hashSet.To3DArray(schematic), schematic); } if (_flood) { hashSet = FillInvisiblesVoxels(hashSet.To3DArray(schematic), schematic); } if (_lonely) { hashSet = FixLonelyVoxels(hashSet.To3DArray(schematic), schematic); } schematic.Blocks = hashSet; return(schematic); }
public PLYToSchematic(string path, int scale) : base(path, scale) { FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read); DataHeader header = ReadDataHeader(new StreamReader(stream)); DataBody body; Console.WriteLine("[LOG] Start reading PLY data..."); body = header.binary ? ReadDataBodyBinary(header, new BinaryReader(stream)) : ReadDataBodyAscii(header, new StreamReader(stream)); Console.WriteLine("[LOG] Done."); List <Vector3> bodyVertices = body.vertices; List <Color> bodyColors = body.colors; Vector3 minX = bodyVertices.MinBy(t => t.X); Vector3 minY = bodyVertices.MinBy(t => t.Y); Vector3 minZ = bodyVertices.MinBy(t => t.Z); float min = Math.Abs(Math.Min(minX.X, Math.Min(minY.Y, minZ.Z))); for (int i = 0; i < bodyVertices.Count; i++) { bodyVertices[i] += new Vector3(min, min, min); bodyVertices[i] = new Vector3((float)Math.Truncate(bodyVertices[i].X * scale), (float)Math.Truncate(bodyVertices[i].Y * scale), (float)Math.Truncate(bodyVertices[i].Z * scale)); } HashSet <Vector3> set = new HashSet <Vector3>(); List <Vector3> vertices = new List <Vector3>(); List <Color> colors = new List <Color>(); Console.WriteLine("[LOG] Start to voxelize data..."); using (ProgressBar progressbar = new ProgressBar()) { for (int i = 0; i < bodyVertices.Count; i++) { if (!set.Contains(bodyVertices[i])) { set.Add(bodyVertices[i]); vertices.Add(bodyVertices[i]); colors.Add(bodyColors[i]); } progressbar.Report(i / (float)bodyVertices.Count); } } Console.WriteLine("[LOG] Done"); minX = vertices.MinBy(t => t.X); minY = vertices.MinBy(t => t.Y); minZ = vertices.MinBy(t => t.Z); min = Math.Min(minX.X, Math.Min(minY.Y, minZ.Z)); for (int i = 0; i < vertices.Count; i++) { float max = Math.Max(vertices[i].X, Math.Max(vertices[i].Y, vertices[i].Z)); if (/*max - min < 8000 && */ max - min >= 0) { vertices[i] -= new Vector3(min, min, min); _blocks.Add(new Block((ushort)vertices[i].X, (ushort)vertices[i].Y, (ushort)vertices[i].Z, colors[i].ColorToUInt())); } } }
public void Test_MaxOrMinValue() { var u1 = new User { Name = "AB", Email = "234" }; var u2 = new User { Name = "BC", Email = "123" }; var list = new List <User> { u1, u2 }; Assert.AreEqual(u1.Name, list.Min(u => u.Name)); // User需要继承IComparable<User>接口 Assert.AreEqual(u2.Name, list.Max(u => u.Name)); Assert.AreEqual(u2.Email, list.Min(u => u.Email)); Assert.AreEqual(u1.Email, list.Max(u => u.Email)); Assert.AreEqual(u1.Name, list.MinBy(u => u.Name).Name); // User不需要继承IComparable接口即可实现 Assert.AreEqual(u2.Name, list.MaxBy(u => u.Name).Name); Assert.AreEqual(u2.Email, list.MinBy(u => u.Email).Email); Assert.AreEqual(u1.Email, list.MaxBy(u => u.Email).Email); var list2 = new List <int> { 1, 2, 3 }; Assert.AreEqual(1, list2.Min()); Assert.AreEqual(3, list2.Max()); }
public override Schematic WriteSchematic() { float minX = _blocks.MinBy(t => t.X).X; float minY = _blocks.MinBy(t => t.Y).Y; float minZ = _blocks.MinBy(t => t.Z).Z; float maxX = _blocks.MaxBy(t => t.X).X; float maxY = _blocks.MaxBy(t => t.Y).Y; float maxZ = _blocks.MaxBy(t => t.Z).Z; Schematic schematic = new Schematic() { Length = (ushort)(Math.Abs(maxZ - minZ)), Width = (ushort)(Math.Abs(maxX - minX)), Heigth = (ushort)(Math.Abs(maxY - minY)), Blocks = new HashSet <Block>() }; LoadedSchematic.LengthSchematic = schematic.Length; LoadedSchematic.WidthSchematic = schematic.Width; LoadedSchematic.HeightSchematic = schematic.Heigth; /* * List<Block> list = Quantization.ApplyQuantization(_blocks); * list.ApplyOffset(new Vector3(minX, minY, minZ)) * * foreach (Block t in list) { * schematic.Blocks.Add(t); * } */ return(schematic); }
public void TestMinBy() { List <IntWrapper> data = new List <IntWrapper>(Enumerable.Range(0, 100).Select(o => new IntWrapper(o))); var expected = data[0]; var expectedMax = data[99]; Assert.AreEqual(expected, data.MinBy(v => v.Data)); Assert.AreEqual(expected, data.MinBy(v => v.Data, null)); Assert.AreEqual(expectedMax, data.MinBy(v => v.Data, new ReverseIntComparer())); }
public void MinByOnEmptyEnumerableThrowsInvalidOperation() { var sut = new List <int>(); var ex = Assert.Throws <InvalidOperationException>(() => sut.MinBy(i => i)); Assert.NotNull(ex.Message); var ex2 = Assert.Throws <InvalidOperationException>(() => sut.MinBy(i => i, Comparer <int> .Default)); Assert.Equal(ex.Message, ex2.Message); }
public void MinByWithNullSelectorThrowsArgumentNullException() { var sut = new List <int>(); Func <int, int> selector = null; var ex = Assert.Throws <ArgumentNullException>(() => sut.MinBy(selector)); Assert.Equal("selector", ex.ParamName); var ex2 = Assert.Throws <ArgumentNullException>(() => sut.MinBy(selector, Comparer <int> .Default)); Assert.Equal(ex.ParamName, ex2.ParamName); }
public void Should_Get_Lowest_Resistance_Band() { //ARRANGE var lowestBand = _bands.MinBy(x => x.MaxResistanceAmount); var sut = new ResistanceBandService(_repo.Object); //ACT var result = sut.GetLowestResistanceBand(); //ASSERT Assert.IsNotNull(result); Assert.IsTrue(result.MaxResistanceAmount == lowestBand.MaxResistanceAmount); _repo.Verify(x => x.Get(), Times.Once); }
protected void VoxelizeData(BodyDataDTO data) { Vector3 minX = data.BodyVertices.MinBy(t => t.X); Vector3 minY = data.BodyVertices.MinBy(t => t.Y); Vector3 minZ = data.BodyVertices.MinBy(t => t.Z); float min = Math.Abs(Math.Min(minX.X, Math.Min(minY.Y, minZ.Z))); for (int i = 0; i < data.BodyVertices.Count; i++) { data.BodyVertices[i] += new Vector3(min, min, min); data.BodyVertices[i] = new Vector3((float)Math.Truncate(data.BodyVertices[i].X * _scale), (float)Math.Truncate(data.BodyVertices[i].Y * _scale), (float)Math.Truncate(data.BodyVertices[i].Z * _scale)); } HashSet <Vector3> set = new HashSet <Vector3>(); List <Vector3> vertices = new List <Vector3>(); List <Color> colors = new List <Color>(); Console.WriteLine("[LOG] Started to voxelize data..."); using (ProgressBar progressbar = new ProgressBar()) { for (int i = 0; i < data.BodyVertices.Count; i++) { if (!set.Contains(data.BodyVertices[i])) { set.Add(data.BodyVertices[i]); vertices.Add(data.BodyVertices[i]); colors.Add(data.BodyColors[i]); } progressbar.Report(i / (float)data.BodyVertices.Count); } } Console.WriteLine("[LOG] Done."); minX = vertices.MinBy(t => t.X); minY = vertices.MinBy(t => t.Y); minZ = vertices.MinBy(t => t.Z); min = Math.Min(minX.X, Math.Min(minY.Y, minZ.Z)); for (int i = 0; i < vertices.Count; i++) { float max = Math.Max(vertices[i].X, Math.Max(vertices[i].Y, vertices[i].Z)); if (/*max - min < 8000 && */ max - min >= 0) { vertices[i] -= new Vector3(min, min, min); _blocks.Add(new Voxel((ushort)vertices[i].X, (ushort)vertices[i].Y, (ushort)vertices[i].Z, colors[i].ColorToUInt())); } } }
public void GeneratePrivatePaths() { Dijkstra <Voxel, Edge <Voxel> > dijkstra = new EasyGraph.Dijkstra <Voxel, Edge <Voxel> >(_voxelGrid.VoxelGraph); int createdPaths = 0; while (createdPaths < _targetPrivateAmount) { // get a random voxel for boundary var origin = GetRandomBoundaryVoxel(); //_privateNode.AddRange(dijkstra.DijkstraCalculateWeights(origin)); //var origin = GetRandomBoundaryVoxel(_privateNode); //var origin = _privateNode.GetRandomBoundaryVoxel().ToList(); dijkstra.DijkstraCalculateWeights(origin); // try to connect to the closest point in the public path of this layer // if none available, use the closest point Voxel target; var targetsOnLayer = _publicPath.Where(v => v.Index.y == origin.Index.y).ToList(); if (targetsOnLayer.Count > 0) { target = targetsOnLayer.MinBy(v => dijkstra.VertexWeight(v)); } else { target = _publicPath.MinBy(v => dijkstra.VertexWeight(v)); } var path = dijkstra.GetShortestPath(origin, target); foreach (var voxel in path) { if (!_publicPath.Contains(voxel)) { voxel.SetAsPrivatePath(); //voxel.SetAsPrivateVoxel(); if (!_privatePath.Contains(voxel)) { _privatePath.Add(voxel); } } } createdPaths++; // createdPaths = createdPaths + 1; Debug.Log("private path " + _privatePath.Count); } }
public void Extension_CollectionExtension_MinBy() { var a = new TestModel { Prop1 = 1, Prop2 = "xyz" }; var b = new TestModel { Prop1 = 2, Prop2 = "abc" }; var c = new List <TestModel> { a, b }; Assert.That(c.MinBy(x => x.Prop1), Is.SameAs(a)); Assert.That(c.MinBy(x => x.Prop2), Is.SameAs(b)); }
public void BreakCycles(List <ChangeSet> changes) { do { var cycles = FindCycles(changes); cycles.Sort((x, y) => x.Count.CompareTo(y.Count)); if (cycles.Count == 0) { break; } List <ChangeSet> cycle = cycles.First(); // Grab the smallest cycle first and break it so we hopefully // don't break too much. ChangeSet candidate = cycle.MinBy(c => c.Id); Logger.LogError("Will remove branches from oldest changeset {candidate} due to a cycle: {cycle}", candidate, string.Join("; ", cycle)); foreach (var br in candidate.GetBranchedFrom()) { if (cycle.Contains(br)) { candidate.RemoveBranchedFrom(br); break; } } } while (true); }
public T ExtractMin() { var item = items.MinBy(t => t.Item1); items.Remove(item); return(item.Item2); }
Polyline Pivot() { Point first = null; Point second = _points.MinBy(p => p.Position.DistanceToSquared(_box.Max)).First(); _start = second.Index; Polyline pl = new Polyline() { second.Position }; while (true) { var next = FindNext(first, second); if (next == null) { break; } first = second; second = next; pl.Add(next.Position); } pl.Add(pl[0]); return(pl); }
public static Color GetClosestColor(LabColor lc) { //ColorPair select = (ColorPair)(Colors.OrderBy(x => DeltaE.Distance(x.LAB, lc)).ToList().First()); ColorPair select = Colors.MinBy(x => DeltaE.Distance(x.LAB, lc)); return(select.Color); }
static void AddToClusters(List <Cluster> clusters, int[] values) { foreach (var v in values) { clusters.MinBy(c => Math.Abs(c.Center - v)).Values.Add(v); } }
private CultureObject GetCultureToSpawn() { List <IFaction> factionsAtWar = new List <IFaction>(); foreach (IFaction faction in Campaign.Current.Factions) { if (Hero.MainHero.Clan.IsAtWarWith(faction) && !faction.IsBanditFaction) { factionsAtWar.Add(faction); } } if (factionsAtWar.Count == 0) { // The player isn't at war with anyone, we'll spawn bandits. List <Settlement> hideouts = Settlement.FindAll((s) => { return(s.IsHideout()); }).ToList(); Settlement closestHideout = hideouts.MinBy((s) => { return(MobileParty.MainParty.GetPosition().DistanceSquared(s.GetPosition())); }); return(closestHideout.Culture); } else { // Pick one of the factions to spawn prisoners of return(RandomSelection <IFaction> .GetRandomElement(factionsAtWar).Culture); } }
public override bool StackEffect(ParsedLog log, BuffStackItem stackItem, List <BuffStackItem> stacks, List <BuffSimulationItemWasted> wastes) { if (stacks.Count <= 1) { throw new InvalidOperationException("Queue logic based must have a >1 capacity"); } BuffStackItem first = stacks[0]; stacks.RemoveAt(0); BuffStackItem minItem = stacks.MinBy(x => x.TotalBoonDuration()); if (minItem.TotalBoonDuration() > stackItem.TotalBoonDuration() + GeneralHelper.ServerDelayConstant) { stacks.Insert(0, first); return(false); } wastes.Add(new BuffSimulationItemWasted(minItem.Src, minItem.Duration, minItem.Start)); if (minItem.Extensions.Count > 0) { foreach ((AgentItem src, long value) in minItem.Extensions) { wastes.Add(new BuffSimulationItemWasted(src, value, minItem.Start)); } } stacks[stacks.IndexOf(minItem)] = stackItem; stacks.Insert(0, first); Sort(log, stacks); return(true); }
public static IntVec3 GetCellToTeleportFrom(Map oldMap, IntVec3 originPosition, Map newMap) { IntVec3 position = originPosition; var oldMapZIndex = ZTracker.GetZIndexFor(oldMap); var newMapZIndex = ZTracker.GetZIndexFor(newMap); var maps = oldMapZIndex > newMapZIndex?ZTracker.GetAllMapsFromToBelow(oldMap, newMap) : ZTracker.GetAllMapsFromToUpper(oldMap, newMap); foreach (var otherMap in maps) { var stairs = new List <Building_Stairs>(); var otherMapZIndex = ZTracker.GetZIndexFor(otherMap); if (otherMap == oldMap) { if (oldMapZIndex > newMapZIndex) { Map lowerMap = ZTracker.GetLowerLevel(otherMap.Tile, otherMap); if (lowerMap != null) { stairs = ZTracker.stairsUp[lowerMap]; } } else if (oldMapZIndex < newMapZIndex) { Map upperMap = ZTracker.GetUpperLevel(otherMap.Tile, otherMap); if (upperMap != null) { stairs = ZTracker.stairsDown[upperMap]; } } } else if (otherMapZIndex > oldMapZIndex) { Map lowerMap = ZTracker.GetLowerLevel(otherMap.Tile, otherMap); if (lowerMap != null) { stairs = ZTracker.stairsUp[lowerMap]; } } else if (otherMapZIndex < oldMapZIndex) { Map upperMap = ZTracker.GetUpperLevel(otherMap.Tile, otherMap); if (upperMap != null) { stairs = ZTracker.stairsDown[upperMap]; } } if (stairs != null && stairs.Any()) { var selectedStairs = stairs.MinBy(x => IntVec3Utility.DistanceTo(position, x.Position)); position = selectedStairs.Position; } else { return(IntVec3.Invalid); } } return(position); }
public static Pawn PawnWithSpareBed(Pawn sleepyPawn) { TraverseParms traverseParams = TraverseParms.For(sleepyPawn, Danger.Deadly, TraverseMode.ByPawn, false); Predicate <Pawn> surplusFinder = delegate(Pawn p) { int count = p.CountBeds(); Log.Message(p + " has " + count + " beds"); if (count > 1 || (count > 0 && SingleInvBedIsSpare(p, sleepyPawn))) { Log.Message(p + " has can spare some"); if (sleepyPawn.Map.reachability.CanReach(sleepyPawn.Position, p, PathEndMode.ClosestTouch, traverseParams)) { Log.Message(sleepyPawn + " can reach " + p); return(true); } } return(false); }; List <Pawn> surplusPawns = sleepyPawn.Map.mapPawns.SpawnedPawnsInFaction(sleepyPawn.Faction).FindAll(surplusFinder); if (surplusPawns.NullOrEmpty()) { return(null); } Log.Message("surplusPawns are " + surplusPawns.ToStringSafeEnumerable()); Pawn generousPawn = surplusPawns.MinBy(p => DistanceTo(p, sleepyPawn)); Log.Message("generousPawn is " + generousPawn); return(generousPawn); }
/* * Removes extra columns that do not appear close to hint lines */ public List <float> HealColumnsViaWidthHints(List <float> dividers, List <double> columnWidthHints) { if (columnWidthHints.Count - 1 >= dividers.Count) { return(dividers); } else { List <float> hintOffsets = new List <float>(); float totalHintWidth = 0; foreach (var cw in columnWidthHints) { totalHintWidth += (float)cw; hintOffsets.Add(totalHintWidth); } hintOffsets.Remove(hintOffsets.Last()); float hintCoeff = (rightEdgeX - leftEdgeX) / totalHintWidth; return(dividers.OrderBy(div => { float offset = div - leftEdgeX; float closestHint = hintOffsets.MinBy(hint => Math.Abs(hint * hintCoeff - offset)); return Math.Abs(offset - closestHint * hintCoeff); }).Take(columnWidthHints.Count - 1).OrderBy(x => x).ToList()); } }
private List <List <int> > GenerateProspectiveRoads() { List <int> ancientSites = Find.World.genData.ancientSites; List <List <int> > list = new List <List <int> >(); for (int i = 0; i < ancientSites.Count; i++) { for (int j = 0; j < ancientSites.Count; j++) { List <int> list2 = new List <int>(); list2.Add(ancientSites[i]); List <int> list3 = ancientSites; float ang = Find.World.grid.GetHeadingFromTo(i, j); int current = ancientSites[i]; while (true) { list3 = list3.Where((int idx) => idx != current && Math.Abs(Find.World.grid.GetHeadingFromTo(current, idx) - ang) < maximumSiteCurve).ToList(); if (list3.Count == 0) { break; } int num = list3.MinBy((int idx) => Find.World.grid.ApproxDistanceInTiles(current, idx)); ang = Find.World.grid.GetHeadingFromTo(current, num); current = num; list2.Add(current); } list.Add(list2); } } return(list); }
public override bool StackEffect(ParsedLog log, BoonStackItem stackItem, List <BoonStackItem> stacks, List <BoonSimulationItemWasted> wastes) { if (stacks.Count <= 1) { throw new InvalidOperationException("Queue logic based must have a >1 capacity"); } BoonStackItem first = stacks[0]; stacks.RemoveAt(0); BoonStackItem minItem = stacks.MinBy(x => x.TotalBoonDuration()); if (minItem.TotalBoonDuration() >= stackItem.TotalBoonDuration()) { stacks.Insert(0, first); return(false); } wastes.Add(new BoonSimulationItemWasted(minItem.Src, minItem.BoonDuration, minItem.Start, minItem.ApplicationTime)); if (minItem.Extensions.Count > 0) { foreach ((ushort src, long value, long time) in minItem.Extensions) { wastes.Add(new BoonSimulationItemWasted(src, value, minItem.Start, time)); } } stacks[stacks.IndexOf(minItem)] = stackItem; stacks.Insert(0, first); Sort(log, stacks); return(true); }
public void FactionForceJoin(string PlayerName) { long id = 0; foreach (var identity in MySession.Static.Players.GetAllIdentities()) { if (identity.DisplayName == PlayerName) { id = identity.IdentityId; } } // Check if player is already in a faction var playerFaction = MyAPIGateway.Session.Factions.TryGetPlayerFaction(id); if (playerFaction != null) { Context.Respond(PlayerName + " is already in a faction!"); return; } if (Context.Player.PromoteLevel > MyPromoteLevel.None) { Context.Respond("You need to join a faction manually"); return; } // Work out which faction to assign player (one with least amount of players) var pairs = new List <KeyValuePair <string, int> >(); foreach (string Tag in Plugin.Config.FactionTags) { try { IMyFaction tempFaction = MyAPIGateway.Session.Factions.TryGetFactionByTag(Tag); int playerCount = tempFaction.Members.Count; var pair = new KeyValuePair <string, int>(Tag, playerCount); pairs.Add(pair); } catch (Exception) { Plugin.Logger.Warn(Tag + " doesn't exist!"); } } var minFactionPair = pairs.MinBy(e => e.Value); // Put player in faction IMyFaction targetFaction = MyAPIGateway.Session.Factions.TryGetFactionByTag(minFactionPair.Key); MyAPIGateway.Session.Factions.SendJoinRequest(targetFaction.FactionId, id); // Adds player to faction MyAPIGateway.Session.Factions.AcceptJoin(targetFaction.FactionId, id); // Accept player to faction // Report back to player Context.Respond("Added to faction: " + minFactionPair.Key); Plugin.Logger.Info("Assigned " + PlayerName + " to faction " + targetFaction.Tag); }
//------------------------------------------------------------------ public Car FindClosestPolice(Car punisher) { List <Car> polices = new List <Car>(); // ToDo: Convert to LINQ manually // Find all Polices foreach (var lane in lanes) { foreach (var car in lane.Cars) { if (car is Police) { polices.Add(car); } } } // Find nearest Police var closestPolice = polices.MinBy(police => { var distance = police.Position - punisher.Position; return(distance.Length()); }); return(closestPolice); }
public void MinBy_WhenSelectorIsNull_ThrowsArgumentNullException() { IEnumerable <int> values = new List <int>(); Func <int, int> selector = null; Assert.Throws <ArgumentNullException>(() => values.MinBy(selector)); }
public int IndexOfBadChildren() { var indexOfBad = -1; if (_children.Count > 0) { var min = _children.MinBy(p => p._sumOfChildren); var max = _children.MaxBy(p => p._sumOfChildren); if (min._sumOfChildren != max._sumOfChildren) { if ((_sumOfChildren - _value) / 3 > (double)(min._sumOfChildren * _children.Count)) { _goodValueOfChild = max._sumOfChildren; return(_children.IndexOf(min)); } else { _goodValueOfChild = min._sumOfChildren; return(_children.IndexOf(max)); } } else { _goodValueOfChild = max._sumOfChildren; return(indexOfBad); } } else { _goodValueOfChild = -1; return(indexOfBad); } }
public void Test_MinBy_EmptySourceThrowsException() { // Arrange. IEnumerable <TestContainer <int> > items = new List <TestContainer <int> >(); // Act/Assert. Assert.Throws <InvalidOperationException>(() => items.MinBy(item => item.Item)); }
public void MinByWithNullComparerThrowsArgumentNullException() { var sut = new List <int>(); var ex = Assert.Throws <ArgumentNullException>(() => sut.MinBy(i => i, null)); Assert.Equal("comparer", ex.ParamName); }
public void MinByWithDefaultComparerReturnsExpectedResult() { var sut = new List <Tuple <int, string> >(); sut.Add(new Tuple <int, string>(0, "zero")); sut.Add(new Tuple <int, string>(1, "one")); sut.Add(new Tuple <int, string>(2, "two")); var expectedByItem1 = sut.First(); var expectedByItem2 = sut[1]; Assert.Equal(expectedByItem1, sut.MinBy(t => t.Item1)); Assert.Equal(expectedByItem2, sut.MinBy(t => t.Item2)); Assert.Equal(expectedByItem1, sut.MinBy(t => t.Item1, Comparer <int> .Default)); Assert.Equal(expectedByItem2, sut.MinBy(t => t.Item2, Comparer <string> .Default)); }
List<CPos> UpdateEdgeCells() { var edgeCells = new List<CPos>(); var unProjected = new List<MPos>(); var bottom = Bounds.Bottom - 1; for (var u = Bounds.Left; u < Bounds.Right; u++) { unProjected = Unproject(new PPos(u, Bounds.Top)); if (unProjected.Any()) edgeCells.Add(unProjected.MinBy(x => x.V).ToCPos(Grid.Type)); unProjected = Unproject(new PPos(u, bottom)); if (unProjected.Any()) edgeCells.Add(unProjected.MaxBy(x => x.V).ToCPos(Grid.Type)); } for (var v = Bounds.Top; v < Bounds.Bottom; v++) { unProjected = Unproject(new PPos(Bounds.Left, v)); if (unProjected.Any()) edgeCells.Add((v == bottom ? unProjected.MaxBy(x => x.V) : unProjected.MinBy(x => x.V)).ToCPos(Grid.Type)); unProjected = Unproject(new PPos(Bounds.Right - 1, v)); if (unProjected.Any()) edgeCells.Add((v == bottom ? unProjected.MaxBy(x => x.V) : unProjected.MinBy(x => x.V)).ToCPos(Grid.Type)); } return edgeCells; }
//------------------------------------------------------------------ public Car FindClosestPolice(Car punisher) { List <Car> polices = new List <Car>(); // ToDo: Convert to LINQ manually // Find all Polices foreach (var lane in lanes) foreach (var car in lane.Cars) if (car is Police) polices.Add (car); // Find nearest Police var closestPolice = polices.MinBy (police => { var distance = police.Position - punisher.Position; return distance.Length(); }); return closestPolice; }
/// <summary> /// Finds humps in contour. Hump scale is determined by <paramref name="scale"/>. /// <para>For each peak a closest valley is found. Next for that valley a closet point is found. Those three point make hump.</para> /// <para>Hump searching will be successful even when only one peak and one valley are found; it can be successful where peak and valley search against convex hull does not give good results.</para> /// <para></para>Peaks and valleys can be obtained by using <see cref="FindExtremaIndices"/>. /// </summary> /// <param name="contour">Contour.</param> /// <param name="peaks">Peaks.</param> /// <param name="valeys">Valleys.</param> /// <param name="scale">Used for <see cref="GetClosestPoint"/>. A good value is ~20. A specified region will be searched every time to avoid local minimum.</param> /// <param name="humpPeaks">Found hump peaks.</param> /// <returns>Humps contour indexes.</returns> public static List<Range> GetHumps(this IList<Point> contour, List<int> peaks, List<int> valeys, int scale, out List<int> humpPeaks) { List<Range> humps = new List<Range>(); humpPeaks = new List<int>(); if (valeys.Count == 0) return humps; foreach (var peak in peaks) { var closestValey = valeys.MinBy(valey => System.Math.Abs(valey - peak)); var searchDirection = ((peak - closestValey) > 0) ? 1 : -1; int closestPtToValey = contour.GetClosestPoint(closestValey, peak, searchDirection, scale); if (closestPtToValey == closestValey) //skip "humps" with zero elements continue; Range hump; if (searchDirection < 0) hump = new Range(closestPtToValey, closestValey); else hump = new Range(closestValey, closestPtToValey); //check if a hump contain some other peaks and valey; classify it as a bad hump if (hump.IsInside(peaks).Count(x => x == true) > 1 ||/*discard the current peak*/ hump.IsInside(valeys).Count(x => x == true) > 1) { } else { humps.Add(hump); humpPeaks.Add(peak); } } return humps; }
public ForceDataPoint MomentMin() { List<ForceDataPoint> Moments = new List<ForceDataPoint>() { new ForceDataPoint(0.0,M1), MMid, new ForceDataPoint(FindZeroPointLocation(),0.0), new ForceDataPoint(L,M2) }; var MinMoment = Moments.MinBy(m => m.Value); AddMaxMomentEntry(MinMoment.Value, false, true); return MinMoment; }
public SessionSummaryDto CalculateWorkoutSummary(SessionDto session, List<DetectedInterval> detectedIntervals, int unit) { var sessionSummaryDtoList = new List<SessionSummaryDto>(); for (var w = 0; w < detectedIntervals.Count; w++) { var sessionDataSubsetDto = new SessionDataSubsetDto() { MinimumSecond = (double)detectedIntervals[w].StartTime, MaximumSecond = (double)detectedIntervals[w].FinishTime, SessionId = session.Id, Unit = unit }; var sessionSummaryDto = GetSessionDataSubset(sessionDataSubsetDto); sessionSummaryDtoList.Add(sessionSummaryDto); } var totalCount = sessionSummaryDtoList.Count(); // calculate speed var averageSpeed = Math.Round(sessionSummaryDtoList.Sum(x => x.AverageSpeed) / totalCount, 2, MidpointRounding.AwayFromZero); var maximumSpeed = sessionSummaryDtoList.MaxBy(s => s.MaximumSpeed).MaximumSpeed; // calculate distance var totalDistance = Math.Round(sessionSummaryDtoList.Sum(x => x.TotalDistance), 2, MidpointRounding.AwayFromZero); // calculate altitiude var averageAltitude = Math.Round(sessionSummaryDtoList.Sum(x => x.AverageAltitude) / totalCount, 2, MidpointRounding.AwayFromZero); var maximumAltitude = sessionSummaryDtoList.MaxBy(s => s.MaximumAltitude).MaximumAltitude; // calculate heart rate var averageHeartRate = Math.Round(sessionSummaryDtoList.Sum(x => x.AverageHeartRate / totalCount), 2, MidpointRounding.AwayFromZero); var minimumHeartRate = sessionSummaryDtoList.MinBy(s => s.MinimumHeartRate).MinimumHeartRate; var maximumHeartRate = sessionSummaryDtoList.MinBy(s => s.MaximumHeartRate).MaximumHeartRate; // calculate power var averagePower = Math.Round(sessionSummaryDtoList.Sum(x => x.AveragePower) / totalCount, 2, MidpointRounding.AwayFromZero); var maximumPower = sessionSummaryDtoList.MaxBy(s => s.MaximumPower).MaximumPower; // calculate cadence var averageCadence = Math.Round(sessionSummaryDtoList.Sum(x => x.AverageCadence) / totalCount, 2, MidpointRounding.AwayFromZero); var maximumCadence = sessionSummaryDtoList.MaxBy(s => s.MaximumCadence).MaximumCadence; var workoutSummary = new SessionSummaryDto() { AverageAltitude = averageAltitude, MaximumAltitude = maximumAltitude, AverageHeartRate = averageHeartRate, MinimumHeartRate = minimumHeartRate, MaximumHeartRate = maximumHeartRate, AveragePower = averagePower, MaximumPower = maximumPower, AverageCadence = averageCadence, MaximumCadence = maximumCadence, AverageSpeed = averageSpeed, MaximumSpeed = maximumSpeed, TotalDistance = totalDistance, Date = session.Date, SessionId = session.Id }; return workoutSummary; }
private static void Step() { //push input state Input.PushState(); //process all SDL.SDL_events SDL.SDL_Event e; while (SDL.SDL_PollEvent(out e) == 1) { switch (e.type) { //let Input handle input related events case SDL.SDL_EventType.SDL_MOUSEBUTTONDOWN: case SDL.SDL_EventType.SDL_MOUSEBUTTONUP: case SDL.SDL_EventType.SDL_MOUSEWHEEL: case SDL.SDL_EventType.SDL_MOUSEMOTION: case SDL.SDL_EventType.SDL_KEYDOWN: case SDL.SDL_EventType.SDL_KEYUP: case SDL.SDL_EventType.SDL_TEXTINPUT: case SDL.SDL_EventType.SDL_CONTROLLERDEVICEADDED: case SDL.SDL_EventType.SDL_CONTROLLERDEVICEREMOVED: case SDL.SDL_EventType.SDL_CONTROLLERBUTTONDOWN: case SDL.SDL_EventType.SDL_CONTROLLERBUTTONUP: case SDL.SDL_EventType.SDL_CONTROLLERAXISMOTION: Input.InputEvent(e); break; //let Window handle window related events case SDL.SDL_EventType.SDL_WINDOWEVENT: Window.WindowEvent(e); break; //global quit, not only the window's exit button case SDL.SDL_EventType.SDL_QUIT: Exit(); break; } } Input.UpdateMousePosition(); Input.ApplyButtonMaps(); foreach (GameObject obj in Resources.Objects) { if (!obj.Destroyed) obj.Step(); } //collision time! Profiler.Start("collision"); float minX = float.PositiveInfinity; float minY = float.PositiveInfinity; float maxX = float.NegativeInfinity; float maxY = float.NegativeInfinity; foreach(PhysicalObject obj in Resources.PhysicalObjects) { obj.UpdateCoverableArea(); if (obj.CoverableArea.Position.X < minX) minX = obj.CoverableArea.Position.X; if (obj.CoverableArea.Position2.X > maxX) maxX = obj.CoverableArea.Position2.X; if (obj.CoverableArea.Position.Y < minY) minY = obj.CoverableArea.Position.Y; if (obj.CoverableArea.Position2.Y > maxY) maxY = obj.CoverableArea.Position2.Y; //set before the actual collision check phase obj.SpeedLeft = 1f; obj.CollisionCandidates = null; } //create and fill quadtree for this step QuadTree = new QuadTree(new Rectangle(minX, minY, maxX - minX, maxY - minY)); //create list of objects to process and calculate all first collision speedfractions for those objects List<PhysicalObject> processingObjects = new List<PhysicalObject>(Resources.PhysicalObjects); foreach (PhysicalObject obj in Resources.PhysicalObjects) { if (obj.Speed == Point.Zero) continue; processingObjects.Add(obj); obj.CalculateClosestCollision(); } while (processingObjects.Count > 0) { //get closest collision, process it/the pair of objects PhysicalObject obj = processingObjects.MinBy(o => o.ClosestCollisionSpeedFraction + 1 - o.SpeedLeft); obj.PerformClosestCollision(); //remove/recalculate collisions if (obj.SpeedLeft == 0f) processingObjects.Remove(obj); else obj.CalculateClosestCollision(); //recalculate for all possibly influenced objects (if needed) if (obj.CollisionCandidates != null) { foreach (PhysicalObject influencedObj in obj.CollisionCandidates) influencedObj.CalculateClosestCollision(); } } Profiler.Stop(); Resources.ObjectAdditionAndRemoval(); Resources.CleanupFontTextures(); }
public ForceDataPoint MomentMin() { if (MomentsWereCalculated == false) { CalculateMomentsAtPointOfApplication(); } List<ForceDataPoint> Moments = new List<ForceDataPoint>() { new ForceDataPoint(0.0,0.0), new ForceDataPoint(a, MmaxRight), new ForceDataPoint(a,MmaxLeft), }; var MinMoment = Moments.MinBy(m => m.Value); AddGoverningMomentEntry(MinMoment.Value, false, true); return MinMoment; }
public ForceDataPoint MomentMin() { if (ReactionsWereCalculated == false) CalulateReactions(); if (MomentsWereCalculated == false) CalculateMoments(); List<ForceDataPoint> Moments = new List<ForceDataPoint> { M1,M2,Mmid }; ForceDataPoint Mminimum = Moments.MinBy(m => m.Value); this.AddMomentEntry(Mminimum, false, true); return Mminimum; }
public static GeoLocation GetNearestGeoLocation(List<GeoLocation> geoLocations, location location) { foreach (var district in geoLocations) { district.Distance = district.GeoCoordinate.GetDistanceTo(location?.point?.GetGeoCoordinate()); } var nearestGeoLocation = geoLocations.MinBy(o => o.Distance); return nearestGeoLocation; }
public ForceDataPoint MomentMin() { if (MomentsWereCalculated == false) CalculateMoments(); List<ForceDataPoint> Moments = new List<ForceDataPoint>() { M1, MPointLeft, MPointRight, M2 }; ForceDataPoint MinMoment = Moments.MinBy(m => m.Value); AddMomentEntry(MinMoment, false, true); return MinMoment; }
public ForceDataPoint MomentMin() { List<ForceDataPoint> Moments = new List<ForceDataPoint>() { new ForceDataPoint(0.0,M1), Mx, new ForceDataPoint(L,M2) }; var MinMoment = Moments.MinBy(m => m.Value); AddGoverningMomentEntry(MinMoment.Value, false, true); return MinMoment; }