public void AddWitchCheckedTestFail(int a, int b, int notExpected) { var testValue = new MathExtension().AddWitchChecked(a, b); Output($"new MathExtension().AddWitchChecked({a}, {b})={testValue},notExpected is {notExpected}"); Assert.AreNotEqual(notExpected, testValue, $"new MathExtension().AddWitchChecked({a}, {b})={testValue} 和预期值{notExpected} 相等"); }
// I/F public float GetHumidity(int x, int z) { float xf = x * inverseSizeX; float zf = z * inverseSizeZ; return(MathExtension.Saturate(HumidityNoise.Sample(xf, 0, zf))); }
private int GetCommonPrefix(String str1, String str2) { if (str1 == null || str2 == null) { return(this.prefixLength); } int commonPrefix = 0; int length = MathExtension.Min(str1.Length, str2.Length, this.prefixLength); // check for prefix similarity of length n for (int i = 0; i < length; i++) { // check the prefix is the same so far if (str1[i] == str2[i]) { // count up commonPrefix++; } } return(commonPrefix); }
private void GetValue(IEnumerable <LineSegment2D> lines, PointF endPoint, LineSegment2D[] previousLines, LineSegment2D?targetLine, ref LineSegment2D?nextLine) { const double minDistanceThreshold = 20; double minDistanceToEnd = double.MaxValue; nextLine = null; //targetPoint = null; foreach (var line in lines) { if (previousLines.Contains(line)) { continue; } if (line.P1 == targetLine.Value.P1 && line.P2 == targetLine.Value.P2) { continue; } double dist1 = MathExtension.FindDistanceBetweenSegments(targetLine.Value.P1, targetLine.Value.P2, line.P1, line.P2); double minDistToEnd = MathExtension.FindDistanceToSegment(endPoint, line.P1, line.P2); //.FindDistanceBetweenSegments(line.P1, line.P2, endLine.P1, endLine.P2); double currentDistToEnd = MathExtension.FindDistanceToSegment(endPoint, targetLine.Value.P1, targetLine.Value.P2); //.FindDistanceBetweenSegments(targetLine.Value.P1, targetLine.Value.P2, endLine.P1, endLine.P2); if (dist1 < minDistanceThreshold && minDistToEnd < currentDistToEnd && minDistToEnd < minDistanceToEnd) { minDistanceToEnd = minDistToEnd; nextLine = line; } } }
public override void RenderObjects() { base.RenderObjects(); // Inner bounds CreateModel.CreateWall(-5f, 2f, .25f, 18f); CreateModel.CreateWall(2f, -2f, .25f, 16f); // Laser start/stop laserWrappers.Add(CreateModel.CreateLaserStart(-10f, -1f, 2, -45)); Model model = CreateModel.CreateLaserStop(10, 7); model.Rotate(-90); // Moveables for (int i = 0; i < 7; i++) { int x = MathExtension.RandomInt(-3, 9); int y = MathExtension.RandomInt(-3, 8); model = CreateModel.CreateMovableBox(x, y); RandomRotate(model); } CreateModel.CreateMovableTriangle(-1f, 1f, 1f, 1f); // Unmoveables CreateModel.CreateTriangle(2f, 7f, 1f, 1f); }
private void UpdateSuperCharging(float elapsed) { foreach (var player in Game.GetPlayers()) { if (player == Player) { continue; } var position = player.GetWorldPosition(); var angles = new float[] { MathExtension.ToRadians(25), MathExtension.ToRadians(65) }; if (Player.FacingDirection < 0) { angles = ScriptHelper.Flip(angles, FlipDirection.Horizontal); } if (ScriptHelper.IntersectCircle(player.GetAABB(), Position, ChargeHitRange) && !chargedPlayers.Contains(player.UniqueID)) { Game.PlayEffect(EffectName.Electric, position); Game.PlaySound("ElectricSparks", position); var direction = RandomHelper.Direction(angles[0], angles[1], true); player.SetLinearVelocity(direction * 15f); ScriptHelper.ExecuteSingleCommand(player, PlayerCommandType.Fall); chargedPlayers.Add(player.UniqueID); } } var area = Player.GetAABB(); area.Grow(4); foreach (var obj in Game.GetObjectsByArea(area)) { if (obj.UniqueID == Player.UniqueID || chargedObjects.Contains(obj.UniqueID) || ScriptHelper.IsPlayer(obj)) { continue; } if (ScriptHelper.IsDynamicObject(obj) || RayCastHelper.ObjectsBulletCanDestroy.Contains(obj.Name)) { if (ScriptHelper.IntersectCircle(obj.GetWorldPosition(), Position, ChargeHitRange)) { var v = obj.GetLinearVelocity(); obj.SetLinearVelocity(v + Vector2.UnitX * Player.FacingDirection * 25); ScriptHelper.DealDamage(obj, 3); chargedObjects.Add(obj.UniqueID); } } } Game.PlayEffect(EffectName.FireNodeTrailAir, Position + new Vector2(-4, -4)); Game.PlayEffect(EffectName.FireNodeTrailAir, Position + new Vector2(4, -4)); m_chargeTimer += elapsed; if (m_chargeTimer >= 1500) { StopSuperCharge(); m_chargeTimer = 0f; } }
public void DecomposeNumberTest() { var result = MathExtension.DecomposeInteger(48); Assert.That(result.ToList().TrueForAll(MathExtension.IsPrime)); Assert.That(result.Aggregate(1, (p, next) => p * next) == 48); }
/// <summary> /// The camera is updated once per frame automatically by the renderer. /// </summary> public override void Update() { // Check if no target. if (Target == null) { return; } // Check if target last position is set. It isn't on the first frame. if (_targetLastPosition == Vector2.Zero) { _targetLastPosition = Target.Center; } // Get mouse location. Vector2 mouseLocation = ScreenToWorld(Engine.InputManager.GetMousePosition()); // Smooth between the mouse location and the target. float lx = MathExtension.Lerp(Target.Center.X, mouseLocation.X, MathExtension.Clamp(Speed * Engine.FrameTime, 0, CameraMaxDistance)); float ly = MathExtension.Lerp(Target.Center.Y, mouseLocation.Y, MathExtension.Clamp(Speed * Engine.FrameTime, 0, CameraMaxDistance)); Center = new Vector2(lx, ly); // Record position. _targetLastPosition = Target.Center; }
public void AddWitchUncheckedTestSuccess(int a, int b, int expected) { var testValue = new MathExtension().AddWitchUnchecked(a, b); Output($"new MathExtension().AddWitchUnchecked({a}, {b})={testValue},expected is {testValue}"); Assert.True(expected == testValue, $"new MathExtension().AddWitchUnchecked({a}, {b})={testValue} 和预期值{expected} 不相等"); }
private void DrawWithPainterAlgorithm() { foreach (Logic.Polygon p in Cam.Polygons) { for (int i = 0; i < p.Points.Count; i++) { p.Points[i] = MathExtension.MatrixMultiply(Cam.model, p.Points[i]); } p.UpdatePolygonDepth(); } Cam.Polygons.Sort(); foreach (Logic.Polygon p in Cam.Polygons) { PointCollection myPointCollection = new PointCollection(); foreach (Vector4 v in p.Points) { Vector3 tmp = CastPoint(v); myPointCollection.Add(new Point(tmp.X + Cam.FovX, canvas.Height - (tmp.Y + Cam.FovY))); } System.Windows.Shapes.Polygon wpfPolygon = new System.Windows.Shapes.Polygon { Stroke = Brushes.White, Fill = new SolidColorBrush(Color.FromArgb(255, (byte)p.RGB[0], (byte)p.RGB[1], (byte)p.RGB[2])), Points = myPointCollection }; canvas.Children.Add(wpfPolygon); } }
/** * Calculates the path of travel of the laser and sets the laser to such a * path * * @param laser * @param models */ public static object[] Reflect(LaserModel laser) { FindIntersects(laser, GameInstance.objectManager.GetModels()); // If there exists at least one valid intersection if (intersects.Count != 0) { closest = GetClosestIntersection(); // Find the closest one // Pythagorean theorem to find length of vector float length = (float)MathExtension.Hypotenuse((float)closest[1] - coords[0], (float)closest[2] - coords[1]); laser.SetLength(length); // Modify the laser to the correct length // Calculates reflected vector using the laser's vector and a new vector representing the side of the Model Vector2d resultantV = ReflectionVector(laser.vect, new Vector2d(10d, 10d * (float)closest[3])); ReflectionCallback((Model)closest[0], laser); return(new Object[] { CreateModel.CreateReflectedLaser((float)closest[1], (float)closest[2], resultantV), closest[0] }); } return(null); }
public IEnumerable <IPlayer> GetThrowTargets(int thrownPlayerID = 0) { var throwAngleLimits = new float[] { MathExtension.ToRadians(0), MathExtension.ToRadians(75) }; if (Player.FacingDirection < 0) { throwAngleLimits = ScriptHelper.Flip(throwAngleLimits, FlipDirection.Horizontal); } var i = 0; return(Game.GetPlayers() .Where(p => { var result = p.UniqueID != thrownPlayerID && p.UniqueID != Player.UniqueID && !p.IsDead && !ScriptHelper.SameTeam(p, Player) && ScriptHelper.IntersectCircle(p.GetAABB(), Position, ThrowRadius, throwAngleLimits[0], throwAngleLimits[1]); if (false && Game.IsEditorTest && result && i++ == 0) { ScriptHelper.RunIn(() => { Game.DrawArea(p.GetAABB(), Color.Red); Game.DrawCircle(Position, ThrowRadius, Color.Cyan); Game.DrawLine(Position, Position + ScriptHelper.GetDirection(throwAngleLimits[0]) * ThrowRadius); Game.DrawLine(Position, Position + ScriptHelper.GetDirection(throwAngleLimits[1]) * ThrowRadius); }, 2000); } return result; })); }
public void SubtractWitchCheckedTestFail(int minuend, int subtrahend, int notExpected) { var testValue = new MathExtension().SubtractWitchChecked(minuend, subtrahend); Output($"new MathExtension().SubtractWitchChecked({minuend}, {subtrahend})={testValue},notExpected is {notExpected}"); Assert.AreNotEqual(notExpected, testValue, $"new MathExtension().SubtractWitchChecked({minuend}, {subtrahend})={testValue} 和预期值{notExpected} 相等"); }
public void SubtractWitchCheckedTestSuccess(int minuend, int subtrahend, int expected) { var testValue = new MathExtension().SubtractWitchChecked(minuend, subtrahend); Output($"new MathExtension().SubtractWitchChecked({minuend}, {subtrahend})={testValue},expected is {testValue}"); Assert.AreEqual(expected, testValue, $"new MathExtension().SubtractWitchChecked({minuend}, {subtrahend})={testValue} 和预期值{expected} 不相等"); }
public float BuildSmithWaterman(string str1, string str2) { float[,] matrix = new float[str1.Length + 1, str2.Length + 1]; matrix[0, 0] = 0; // fill first row and column with 0 for (int i = 1; i <= str1.Length; i++) { matrix[i, 0] = 0; } for (int j = 1; j <= str2.Length; j++) { matrix[0, j] = 0; } for (int i = 1; i <= str1.Length; i++) { for (int j = 1; j <= str2.Length; j++) { float matchCost = this.CostFunction.GetCost(str1, i - 1, str2, j - 1); float scoreDiag = matrix[i - 1, j - 1]; // match/mismatch float scoreUp = matrix[i - 1, j]; // deletion float scoreLeft = matrix[i, j - 1]; // insertion matrix[i, j] = MathExtension.Max(0, scoreDiag + matchCost, scoreLeft - this.gapCost, scoreUp - this.gapCost); } } return(matrix[str1.Length, str2.Length]); }
public void AddTestFail(int a, int b, int notExpected) { var testValue = new MathExtension().Add(a, b); Output($"new MathExtension().Add({a}, {b})={testValue},notExpected is {notExpected}"); Assert.False(notExpected == testValue, $"new MathExtension().Add({a}, {b})={testValue} 和预期值{notExpected} 相等"); }
public override float Evaluate(HexCell cell) { if (cell.HasWater) { return(0f); } var score = 0f; score += MathExtension.GaussianProbability(cell.Temperature, 17, 15) * 60; score += MathExtension.GaussianProbability(cell.Elevation, 1, 2) * 10; var numberOfCoastalTiles = NumberOfCoastalNeighbours(cell); if (numberOfCoastalTiles == 6) { score -= 20; } else { score += numberOfCoastalTiles * 5f; } score += NumberOfSameHeightNeighbours(cell) * 5f; return(Mathf.Clamp(score / 100f, 0f, 1f)); }
public void SubtractTestSuccess(int minuend, int subtrahend, int expected) { var testValue = new MathExtension().Subtract(minuend, subtrahend); Output($"new MathExtension().Subtract({minuend}, {subtrahend})={testValue},expected is {testValue}"); Assert.True(expected == testValue, $"new MathExtension().Subtract({minuend}, {subtrahend})={testValue} 和预期值{expected} 不相等"); }
public override float Evaluate(HexCell cell) { if (cell.HasWater) { return(0f); } if (cell.transform.childCount > 0) { var child = cell.transform.GetChild(0); if (child.GetComponent <Tree>() == null) { return(0f); } } var score = 0f; score += MathExtension.GaussianProbability(cell.Temperature, 17, 20) * 35; score += MathExtension.GaussianProbability(cell.Elevation, 3, 2) * 35; score += MathExtension.GaussianProbability(NumberOfSameHeightNeighbours(cell), 5, 2) * 30; return(Mathf.Clamp01(score / 100f)); }
public void SubtractTestFail(int minuend, int subtrahend, int notExpected) { var testValue = new MathExtension().Subtract(minuend, subtrahend); Output($"new MathExtension().Subtract({minuend}, {subtrahend})={testValue},notExpected is {notExpected}"); Assert.False(notExpected == testValue, $"new MathExtension().Subtract({minuend}, {subtrahend})={testValue} 和预期值{notExpected} 相等"); }
public void ValidateRange() { int min; int max; min = (int)MathExtension.GetMinValue(yvalues); max = (int)MathExtension.GetMaxValue(yvalues); int range = max - min; yMinValue = MathExtension.Round(min, range); yMaxValue = MathExtension.Round(max, range); if (yMinValue > min) { yMinValue = yMinValue / 2; } if (yMaxValue < max) { yMaxValue = yMaxValue * 2; } if (yMaxValue <= yMinValue || yMaxValue < max) { yMaxValue = max; } }
public void SetBufferValue(int x, int y, float value, OutOfBoundsSetMode mode) { if (IsOutOfBounds(x, y)) { switch (mode) { case OutOfBoundsSetMode.Extend: x = MathExtension.Clamp(x, 0, width); y = MathExtension.Clamp(y, 0, height); break; case OutOfBoundsSetMode.Wrap: x = MathExtension.Wrap(x, 0, width); y = MathExtension.Wrap(y, 0, height); break; case OutOfBoundsSetMode.Ignore: return; default: throw new IndexOutOfRangeException(); } } buffer[x, y] = value; }
private double GetRandomAmount(int max = 3) { var result = rand.NextDouble() * max; result = MathExtension.ToCeiling(result, 0.05); return(result); }
private void ElectrocuteRange(Vector2 position) { foreach (var bot in BotManager.GetBots()) { var player = bot.Player; if (ScriptHelper.IntersectCircle(player.GetAABB(), position, EMPBlastRadius)) { StunBot(bot); } } for (var i = 0; i < 360; i += 72) // Play electric effect 5 times in circle (360 / 5 = 72) { var direction = ScriptHelper.GetDirection(MathExtension.ToRadians(i)); Game.PlayEffect(EffectName.Electric, position + direction * EMPBlastRadius); Game.PlaySound("ElectricSparks", position); } if (Game.IsEditorTest) { Events.UpdateCallback.Start((e) => Game.DrawCircle(position, EMPBlastRadius, Color.Cyan), 0, 60 * 2); } }
// I/F public float GetTemperature(int x, int z) { float xf = x * inverseSizeX; float zf = z * inverseSizeZ; return(MathExtension.Saturate(TemperatureNoise.Sample(xf, 0, zf))); }
/// <summary> /// Updates the current animation if there is one. /// </summary> private void UpdateAnimation() { if (this.endStatus != null) { this.progress += Time.deltaTime * this.endStatus.Speed; #if UNITY_EDITOR if (this.endStatus.Rotations.Length != this.startStatus.Rotations.Length) { Debug.LogWarning("The Amount of Sprites and Rotations does not match up."); } #endif // Move Body this.spriteManager.bodyTransform.localPosition = MathExtension.SmootherStep(this.startStatus.Position, this.endStatus.Position, this.progress); // Rotate Absolutely Everything Else int length = Mathf.Min(this.endStatus.Rotations.Length, this.startStatus.Rotations.Length); Vector3 localEulerAngles; for (int i = 0; i < length; i++) { localEulerAngles = this.spriteManager.animatedTransforms[i].localEulerAngles; this.spriteManager.animatedTransforms[i].localEulerAngles = new Vector3( localEulerAngles.x, localEulerAngles.y, MathExtension.SmootherStep(this.startStatus.Rotations[i], this.endStatus.Rotations[i], this.progress)); } } }
private void CheckBounceBounds() { if (BounceBounds == null || !BounceBounds.HasValue) { return; } if (X < BounceBounds.Value.X || X > BounceBounds.Value.X + BounceBounds.Value.Width || Y < BounceBounds.Value.Y || Y > BounceBounds.Value.Y + BounceBounds.Value.Height) { if (!_outOfBounceBounds) { var currentDirection = MathExtension.AngleToDirection(MathHelper.WrapAngle(Direction)); var normal = MathExtension.GetNormalFromPositionAndRectangle(Position(), BounceBounds.Value); Direction = MathHelper.WrapAngle(Vector2.Reflect( currentDirection, normal ).ToAngle() + MathHelper.PiOver2); } _outOfBounceBounds = true; } else { _outOfBounceBounds = false; } }
/// <summary> /// 将要素转换成Mesh对象 /// </summary> private void FeaturesToMesh() { //读取shapefile的内容 string path = ""; var rader = new NetTopologySuite.IO.ShapeFile.Extended.ShapeDataReader(path); var result = rader.ReadByMBRFilter(rader.ShapefileBounds); //读取其中的点信息,转换成mesh对象 var mesh = new PongGlobe.Core.Mesh <Vector3>(); mesh.PrimitiveType = PrimitiveType.TriangleStrip; //在转换成 List <Vector3> positions = new List <Vector3>(); //记录其indices List <ushort> indics = new List <ushort>(); //填充顶点跟索引 //详细流程,如果是投影坐标,将其转换成wgs84的经纬度坐标,再使用参考系计算出其真实的地理坐标 foreach (var item in result) { var geo = item.Geometry.Coordinates; //暂未考虑multipolygon的情况,也即是Hole polygon. foreach (var coord in geo) { //将其转换成弧度制 positions.Add(_shape.ToVector3(new Geodetic3D(MathExtension.ToRadius(coord.X), MathExtension.ToRadius(coord.Y)))); } } //简化几何,如去除重复点,重置indices等操作 }
public override void RenderObjects() { base.RenderObjects(); // Inner bounds CreateModel.CreateWall(0f, -5f, 8f, .25f); CreateModel.CreateWall(5f, -9f, .25f, 1.5f); CreateModel.CreateWall(7f, -8.5f, .25f, 2.5f); CreateModel.CreateWall(0f, 7f, 8f, .25f); CreateModel.CreateWall(4f, 4f, 5f, .25f); CreateModel.CreateWall(-4f, 4f, 5f, .25f); CreateModel.CreateWall(5.8f, 0f, 8f, .25f); CreateModel.CreateWall(-5.8f, -2f, 8f, .25f); // Laser start/stop LaserStart laserStart = CreateModel.CreateLaserStart(6f, 9f, 3); laserStart.Rotate(-35); laserWrappers.Add(laserStart); LaserStop laserStop = CreateModel.CreateLaserStop(6f, -9.5f); laserStop.Rotate(180.1f); // Moveables CreateModel.CreateMovableBox(4.05f, -5.925f); CreateModel.CreateMovableTrapezoid(-4f, 5f, 1.5f, 1f, 1f); CreateModel.CreateMovableTriangle(4f, 5f, 1f, 1f); CreateModel.CreateMovableTriangle(0f, 5f, 1f, 1f); Model model; for (int i = 0; i < 3; i++) { int x = MathExtension.RandomInt(-3, 9); int y = MathExtension.RandomInt(-3, 8); model = CreateModel.CreateMovableBox(x, y); RandomRotate(model); } // Moving Models movingBox = new MovingBox(-5f, 3f, 180, 0.5f, -0.5f); // Stationary Models Model triangle = CreateModel.CreateTriangle(3.9f, -9f, 1.5f, 2f); triangle.Rotate(-90); triangle = CreateModel.CreateTriangle(8.1f, -9f, 2f, 1.5f); triangle.Rotate(180); triangle = CreateModel.CreateTriangle(9.25f, -9.25f, 1f, 1f); triangle.Rotate(-90); isRendered = true; }
public override void RenderObjects() { base.RenderObjects(); // Inner bounds CreateModel.CreateWall(-4f, 2f, 12f, .25f); CreateModel.CreateWall(2f, -1.37f, .25f, 7f); CreateModel.CreateWall(-7.7f, 6f, 5f, .25f); // Unmoveables CreateModel.CreateBox(-4f, 5f, 1f); laserWrappers.Add(CreateModel.CreateLaserStart(-10f, -1f, 2, (float)MathExtension.ToRadians(-45))); Model laserStop = CreateModel.CreateLaserStop(-9.7f, 7f); laserStop.Rotate((float)MathExtension.ToRadians(90)); movingBox = new MovingBox(2.85f, 2.6f, 123, 0f, 1f); Model model; for (int i = 0; i < 7; i++) { int x = MathExtension.RandomInt(1, 9); int y = MathExtension.RandomInt(2, 8); model = CreateModel.CreateMovableBox(x, y); RandomRotate(model); } isRendered = true; }