public static void Triangle(int2[] points, Image <Rgba32> image, Rgba32 color) { // bounding box var(min, max) = MathUtils.BoundingBox(points); min.x = Math.Clamp(min.x, 0, image.Width); min.y = Math.Clamp(min.y, 0, image.Height); min.x = Math.Clamp(min.x, 0, image.Width); min.x = Math.Clamp(min.x, 0, image.Width); for (int x = min.x; x < max.x; x++) { for (int y = min.y; y < max.y; y++) { var point = new int2(x, y); float3 bcScreen = Barycentric(points, point); if (bcScreen.x < 0 || bcScreen.y < 0 || bcScreen.z < 0) { continue; } image[x, y] = color; } } }
protected virtual bool LegacyRateLimit() { var accept = false; var max = Config["SvOldClientsPerInterval"].AsInt(); var interval = Config["SvOldClientsInterval"].AsInt(); var useRateLimit = max > 0 && interval > 0; if (useRateLimit) { var now = Time.Get(); if (LegacyRateLimitStart < 0 || LegacyRateLimitStart + interval * Time.Freq() <= now) { LegacyRateLimitStart = now; LegacyRateLimitNum = Math.Clamp(LegacyRateLimitNum - max, 0, max); } accept = LegacyRateLimitNum < max; } if (Config["SvOldClientsSkip"] > 0 && (!accept || !useRateLimit)) { accept = new Random().Next(0, int.MaxValue) <= int.MaxValue / Config["SvOldClientsSkip"]; } if (accept && useRateLimit) { LegacyRateLimitNum++; } return(!accept); }
public static Rectangle ToRectangle(this in RECT rect) { int left = Math.Clamp(rect.left, int.MinValue / 2, int.MaxValue / 2); int top = Math.Clamp(rect.top, int.MinValue / 2, int.MaxValue / 2); int right = Math.Clamp(rect.right, int.MinValue / 2, int.MaxValue / 2); int bottom = Math.Clamp(rect.bottom, int.MinValue / 2, int.MaxValue / 2); int minX = Math.Min(left, right); int minY = Math.Min(top, bottom); int maxX = Math.Max(left, right); int maxY = Math.Max(top, bottom); return(new(minX, minY, maxX - minX, maxY - minY)); }
public override bool Feed(ChunkConstruct packet, IPEndPoint endPoint) { if (Sequence >= PeerAck) { if (packet.Ack < PeerAck || packet.Ack > Sequence) { return(false); } } else { if (packet.Ack < PeerAck && packet.Ack > Sequence) { return(false); } } PeerAck = packet.Ack; if (packet.Token == TokenHelper.TokenNone || packet.Token != Token) { return(false); } if (packet.Flags.HasFlag(PacketFlags.Resend)) { Resend(); } if (packet.Flags.HasFlag(PacketFlags.Connless)) { return(true); } var now = Time.Get(); if (packet.Flags.HasFlag(PacketFlags.Control)) { var msg = (ConnectionMessages)packet.Data[0]; if (msg == ConnectionMessages.Close) { State = ConnectionState.Error; RemoteClosed = true; string reason = null; if (packet.DataSize > 1) { reason = Encoding.UTF8.GetString(packet.Data, 1, Math.Clamp(packet.DataSize - 1, 1, 128)); reason = reason.SanitizeStrong(); } Error = reason; Debug.Log("connection", $"closed reason='{reason}'"); } else if (msg == ConnectionMessages.Token) { PeerToken = packet.ResponseToken; if (State == ConnectionState.Token) { LastReceiveTime = now; State = ConnectionState.Connect; SendConnectionMsgWithToken(ConnectionMessages.Connect); Debug.Log("connection", $"got token, replying, token={PeerToken:X} mytoken={Token:X}"); } else { Debug.Log("connection", $"got token, token={PeerToken:X}"); } } else { if (State == ConnectionState.Offline) { if (msg == ConnectionMessages.Connect) { var token = Token; Reset(); State = ConnectionState.Pending; EndPoint = endPoint; Token = token; PeerToken = packet.ResponseToken; LastSendTime = now; LastReceiveTime = now; ConnectedAt = now; SendConnectionMsg(ConnectionMessages.ConnectAccept, null); Debug.Log("connection", "got connection, sending connect+accept"); } } else if (State == ConnectionState.Connect) { if (msg == ConnectionMessages.ConnectAccept) { LastReceiveTime = now; SendConnectionMsg(ConnectionMessages.Accept, null); State = ConnectionState.Online; Debug.Log("connection", "got connect+accept, sending accept. connection online"); } } } } else if (State == ConnectionState.Pending) { LastReceiveTime = now; State = ConnectionState.Online; Debug.Log("connection", "connecting online"); } if (State == ConnectionState.Online) { LastReceiveTime = now; AckChunks(packet.Ack); } return(true); }
public bool SolveTOIPositionConstraints(int toiIndexA, int toiIndexB) { float minSeparation = 0.0f; for (int i = 0; i < _count; ++i) { ContactPositionConstraint pc = _positionConstraints[i]; int indexA = pc.indexA; int indexB = pc.indexB; Vector2 localCenterA = pc.localCenterA; Vector2 localCenterB = pc.localCenterB; int pointCount = pc.pointCount; float mA = 0.0f; float iA = 0.0f; if (indexA == toiIndexA || indexA == toiIndexB) { mA = pc.invMassA; iA = pc.invIA; } float mB = 0.0f; float iB = 0.0f; if (indexB == toiIndexA || indexB == toiIndexB) { mB = pc.invMassB; iB = pc.invIB; } Vector2 cA = _positions[indexA].c; float aA = _positions[indexA].a; Vector2 cB = _positions[indexB].c; float aB = _positions[indexB].a; // Solve normal constraints for (int j = 0; j < pointCount; ++j) { Transform xfA = new Transform(); Transform xfB = new Transform(); xfA.q = Matrex.CreateRotation(aA); // Actually about twice as fast to use our own function xfB.q = Matrex.CreateRotation(aB); // Actually about twice as fast to use our own function xfA.p = cA - Vector2.Transform(localCenterA, xfA.q); // Common.Math.Mul(xfA.q, localCenterA); xfB.p = cB - Vector2.Transform(localCenterB, xfB.q); // Common.Math.Mul(xfB.q, localCenterB); PositionSolverManifold psm = new PositionSolverManifold(); psm.Initialize(pc, xfA, xfB, j); Vector2 normal = psm.normal; Vector2 point = psm.point; float separation = psm.separation; Vector2 rA = point - cA; Vector2 rB = point - cB; // Track max constraint error. minSeparation = MathF.Min(minSeparation, separation); // Prevent large corrections and allow slop. float C = Math.Clamp(Settings.TOIBaumgarte * (separation + Settings.LinearSlop), -Settings.MaxLinearCorrection, 0.0f); // Compute the effective mass. float rnA = Vectex.Cross(rA, normal); float rnB = Vectex.Cross(rB, normal); float K = mA + mB + iA * rnA * rnA + iB * rnB * rnB; // Compute normal impulse float impulse = K > 0.0f ? -C / K : 0.0f; Vector2 P = impulse * normal; cA -= mA * P; aA -= iA * Vectex.Cross(rA, P); cB += mB * P; aB += iB * Vectex.Cross(rB, P); } _positions[indexA].c = cA; _positions[indexA].a = aA; _positions[indexB].c = cB; _positions[indexB].a = aB; } // We can't expect minSpeparation >= -b2_linearSlop because we don't // push the separation above -b2_linearSlop. return(minSeparation >= -1.5f * Settings.LinearSlop); }
public void SolveVelocityConstraints() { for (int i = 0; i < _count; ++i) { ContactVelocityConstraint vc = _velocityConstraints[i]; int indexA = vc.indexA; int indexB = vc.indexB; float mA = vc.invMassA; float iA = vc.invIA; float mB = vc.invMassB; float iB = vc.invIB; int pointCount = vc.pointCount; Vector2 vA = _velocities[indexA].v; float wA = _velocities[indexA].w; Vector2 vB = _velocities[indexB].v; float wB = _velocities[indexB].w; Vector2 normal = vc.normal; Vector2 tangent = Vectex.Cross(normal, 1.0f); float friction = vc.friction; //Debug.Assert(pointCount == 1 || pointCount == 2); // Solve tangent constraints first because non-penetration is more important // than friction. for (int j = 0; j < pointCount; ++j) { VelocityConstraintPoint vcp = vc.points[j]; // Relative velocity at contact Vector2 dv = vB + Vectex.Cross(wB, vcp.rB) - vA - Vectex.Cross(wA, vcp.rA); // Compute tangent force float vt = Vector2.Dot(dv, tangent) - vc.tangentSpeed; float lambda = vcp.tangentMass * (-vt); // b2Clamp the accumulated force float maxFriction = friction * vcp.normalImpulse; float newImpulse = Math.Clamp(vcp.tangentImpulse + lambda, -maxFriction, maxFriction); lambda = newImpulse - vcp.tangentImpulse; vcp.tangentImpulse = newImpulse; // Apply contact impulse Vector2 P = lambda * tangent; vA -= mA * P; wA -= iA * Vectex.Cross(vcp.rA, P); vB += mB * P; wB += iB * Vectex.Cross(vcp.rB, P); } // Solve normal constraints if (pointCount == 1 || Settings.BlockSolve == false) { for (int j = 0; j < pointCount; ++j) { VelocityConstraintPoint vcp = vc.points[j]; // Relative velocity at contact Vector2 dv = vB + Vectex.Cross(wB, vcp.rB) - vA - Vectex.Cross(wA, vcp.rA); // Compute normal impulse float vn = Vector2.Dot(dv, normal); float lambda = -vcp.normalMass * (vn - vcp.velocityBias); // b2Clamp the accumulated impulse float newImpulse = MathF.Max(vcp.normalImpulse + lambda, 0.0f); lambda = newImpulse - vcp.normalImpulse; vcp.normalImpulse = newImpulse; // Apply contact impulse Vector2 P = lambda * normal; vA -= mA * P; wA -= iA * Vectex.Cross(vcp.rA, P); vB += mB * P; wB += iB * Vectex.Cross(vcp.rB, P); } } else { // Block solver developed in collaboration with Dirk Gregorius (back in 01/07 on Box2D_Lite). // Build the mini LCP for this contact patch // // vn = A * x + b, vn >= 0, x >= 0 and vn_i * x_i = 0 with i = 1..2 // // A = J * W * JT and J = ( -n, -r1 x n, n, r2 x n ) // b = vn0 - velocityBias // // The system is solved using the "Total enumeration method" (s. Murty). The complementary constraint vn_i * x_i // implies that we must have in any solution either vn_i = 0 or x_i = 0. So for the 2D contact problem the cases // vn1 = 0 and vn2 = 0, x1 = 0 and x2 = 0, x1 = 0 and vn2 = 0, x2 = 0 and vn1 = 0 need to be tested. The first valid // solution that satisfies the problem is chosen. // // In order to account of the accumulated impulse 'a' (because of the iterative nature of the solver which only requires // that the accumulated impulse is clamped and not the incremental impulse) we change the impulse variable (x_i). // // Substitute: // // x = a + d // // a := old total impulse // x := new total impulse // d := incremental impulse // // For the current iteration we extend the formula for the incremental impulse // to compute the new total impulse: // // vn = A * d + b // = A * (x - a) + b // = A * x + b - A * a // = A * x + b' // b' = b - A * a; VelocityConstraintPoint cp1 = vc.points[0]; VelocityConstraintPoint cp2 = vc.points[1]; Vector2 a = new Vector2(cp1.normalImpulse, cp2.normalImpulse); //Debug.Assert(a.X >= 0.0f && a.Y >= 0.0f); // Relative velocity at contact Vector2 dv1 = vB + Vectex.Cross(wB, cp1.rB) - vA - Vectex.Cross(wA, cp1.rA); Vector2 dv2 = vB + Vectex.Cross(wB, cp2.rB) - vA - Vectex.Cross(wA, cp2.rA); // Compute normal velocity float vn1 = Vector2.Dot(dv1, normal); float vn2 = Vector2.Dot(dv2, normal); Vector2 b = new Vector2((float)(vn1 - cp1.velocityBias), (float)(vn2 - cp2.velocityBias)); // Compute b' b -= Vector2.Transform(a, vc.K); // Common.Math.Mul(vc.K, a); //const float k_errorTol = 1e-3f; //B2_NOT_USED(k_errorTol); for (; ;) { // // Case 1: vn = 0 // // 0 = A * x + b' // // Solve for x: // // x = - inv(A) * b' // Vector2 x = -Vector2.Transform(b, vc.normalMass); //Common.Math.Mul(vc.normalMass, b); if (x.X >= 0.0f && x.Y >= 0.0f) { // Get the incremental impulse Vector2 d = x - a; // Apply incremental impulse Vector2 P1 = d.X * normal; Vector2 P2 = d.Y * normal; vA -= mA * (P1 + P2); wA -= iA * (Vectex.Cross(cp1.rA, P1) + Vectex.Cross(cp2.rA, P2)); vB += mB * (P1 + P2); wB += iB * (Vectex.Cross(cp1.rB, P1) + Vectex.Cross(cp2.rB, P2)); // Accumulate cp1.normalImpulse = x.X; cp2.normalImpulse = x.Y; break; } // // Case 2: vn1 = 0 and x2 = 0 // // 0 = a11 * x1 + a12 * 0 + b1' // vn2 = a21 * x1 + a22 * 0 + b2' // x.X = -cp1.normalMass * b.X; x.Y = 0.0f; vn1 = 0.0f; vn2 = vc.K.M22 * x.X + b.Y; if (x.X >= 0.0f && vn2 >= 0.0f) { // Get the incremental impulse Vector2 d = x - a; // Apply incremental impulse Vector2 P1 = d.X * normal; Vector2 P2 = d.Y * normal; vA -= mA * (P1 + P2); wA -= iA * (Vectex.Cross(cp1.rA, P1) + Vectex.Cross(cp2.rA, P2)); vB += mB * (P1 + P2); wB += iB * (Vectex.Cross(cp1.rB, P1) + Vectex.Cross(cp2.rB, P2)); // Accumulate cp1.normalImpulse = x.X; cp2.normalImpulse = x.Y; break; } // // Case 3: vn2 = 0 and x1 = 0 // // vn1 = a11 * 0 + a12 * x2 + b1' // 0 = a21 * 0 + a22 * x2 + b2' // x.X = 0.0f; x.Y = -cp2.normalMass * b.Y; vn1 = vc.K.M12 * x.Y + b.X; vn2 = 0.0f; if (x.Y >= 0.0f && vn1 >= 0.0f) { // Resubstitute for the incremental impulse Vector2 d = x - a; // Apply incremental impulse Vector2 P1 = d.X * normal; Vector2 P2 = d.Y * normal; vA -= mA * (P1 + P2); wA -= iA * (Vectex.Cross(cp1.rA, P1) + Vectex.Cross(cp2.rA, P2)); vB += mB * (P1 + P2); wB += iB * (Vectex.Cross(cp1.rB, P1) + Vectex.Cross(cp2.rB, P2)); // Accumulate cp1.normalImpulse = x.X; cp2.normalImpulse = x.Y; break; } // // Case 4: x1 = 0 and x2 = 0 // // vn1 = b1 // vn2 = b2; x.X = 0.0f; x.Y = 0.0f; vn1 = b.X; vn2 = b.Y; if (vn1 >= 0.0f && vn2 >= 0.0f) { // Resubstitute for the incremental impulse Vector2 d = x - a; // Apply incremental impulse Vector2 P1 = d.X * normal; Vector2 P2 = d.Y * normal; vA -= mA * (P1 + P2); wA -= iA * (Vectex.Cross(cp1.rA, P1) + Vectex.Cross(cp2.rA, P2)); vB += mB * (P1 + P2); wB += iB * (Vectex.Cross(cp1.rB, P1) + Vectex.Cross(cp2.rB, P2)); // Accumulate cp1.normalImpulse = x.X; cp2.normalImpulse = x.Y; break; } // No solution, give up. This is hit sometimes, but it doesn't seem to matter. break; } } _velocities[indexA].v = vA; _velocities[indexA].w = wA; _velocities[indexB].v = vB; _velocities[indexB].w = wB; } }
public override void Tick() { if (!Server.ClientInGame(ClientId)) { return; } if (Server.GetClientInfo(ClientId, out var info)) { Latency.Accumulate += info.Latency; Latency.AccumulateMax = Math.Max(Latency.AccumulateMax, info.Latency); Latency.AccumulateMin = Math.Min(Latency.AccumulateMin, info.Latency); } if (Server.Tick % Server.TickSpeed == 0) { Latency.Average = Latency.Accumulate / Server.TickSpeed; Latency.Max = Latency.AccumulateMax; Latency.Min = Latency.AccumulateMin; Latency.Accumulate = 0; Latency.AccumulateMax = 0; Latency.AccumulateMin = 1000; } if (GameContext.World.IsPaused) { RespawnTick++; LastActionTick++; TeamChangeTick++; DieTick++; } else { if (Character == null && Team == Team.SPECTATORS && SpectatorId == -1) { ViewPos -= new Vector2( Math.Clamp(ViewPos.x - LatestActivity.TargetX, -500f, 500f), Math.Clamp(ViewPos.y - LatestActivity.TargetY, -400f, 400f) ); } if (Character == null && DieTick + Server.TickSpeed * 3 <= Server.Tick) { Spawning = true; } if (Character != null) { if (Character.IsAlive) { ViewPos = Character.Position; } else { Character = null; } } else if (Spawning && RespawnTick <= Server.Tick) { TryRespawn(); } } }
public override void SetMaxClientsPerIp(int max) { var config = ServerConfig; config.MaxClientsPerIp = Math.Clamp(max, 1, config.MaxClients); }
protected override NetworkServerConfig CheckConfig(NetworkServerConfig config) { config.MaxClientsPerIp = Math.Clamp(config.MaxClientsPerIp, 1, config.MaxClients); return(config); }
public override bool Feed(NetworkChunkConstruct packet, IPEndPoint remote) { if (packet.Flags.HasFlag(PacketFlags.RESEND)) { Resend(); } if (UseToken) { if (!packet.Flags.HasFlag(PacketFlags.TOKEN)) { if (!packet.Flags.HasFlag(PacketFlags.CONTROL) || packet.DataSize < 1) { Debug.Log("connection", "dropping msg without token"); return(false); } if (packet.Data[0] == (int)ConnectionMessages.CONNECTACCEPT) { if (!Config["ClAllowOldServers"]) { Debug.Log("connection", "dropping connect+accept without token"); return(false); } } else { Debug.Log("connection", "dropping ctrl msg without token"); return(false); } } else { if (packet.Token != Token) { Debug.Log("connection", $"dropping msg with invalid token, wanted={Token} got={packet.Token}"); return(false); } } } if (Sequence >= PeerAck) { if (packet.Ack < PeerAck || packet.Ack > Sequence) { return(false); } } else { if (packet.Ack < PeerAck && packet.Ack > Sequence) { return(false); } } PeerAck = packet.Ack; if (packet.Flags.HasFlag(PacketFlags.RESEND)) { Resend(); } if (packet.Flags.HasFlag(PacketFlags.CONTROL)) { var msg = (ConnectionMessages)packet.Data[0]; if (msg == ConnectionMessages.CLOSE) { if (!NetworkCore.CompareEndPoints(EndPoint, remote, true)) { return(false); } State = ConnectionState.ERROR; RemoteClosed = true; var reason = ""; if (packet.DataSize > 1) { reason = Encoding.UTF8.GetString(packet.Data, 1, Math.Clamp(packet.DataSize - 1, 1, 128)); } Error = reason; Debug.Log("connection", $"closed reason='{reason}'"); return(false); } else { if (State == ConnectionState.CONNECT) { if (msg == ConnectionMessages.CONNECTACCEPT) { if (packet.Flags.HasFlag(PacketFlags.TOKEN)) { if (packet.DataSize < 1 + 4) { Debug.Log("connection", $"got short connect+accept, size={packet.DataSize}"); return(true); } Token = packet.Data.ToUInt32(1); } else { UseToken = false; } LastReceiveTime = Time.Get(); State = ConnectionState.ONLINE; Debug.Log("connection", "got connect+accept, sending accept. connection online"); } } } } if (State == ConnectionState.ONLINE) { LastReceiveTime = Time.Get(); AckChunks(packet.Ack); } return(true); }
static double INumber <double> .Clamp(double value, double min, double max) => Math.Clamp(value, min, max);
static sbyte INumber <sbyte> .Clamp(sbyte value, sbyte min, sbyte max) => Math.Clamp(value, min, max);
static uint INumber <uint> .Clamp(uint value, uint min, uint max) => Math.Clamp(value, min, max);
/// <inheritdoc cref="INumber{TSelf}.Clamp(TSelf, TSelf, TSelf)" /> public static uint Clamp(uint value, uint min, uint max) => Math.Clamp(value, min, max);
/// <inheritdoc cref="INumber{TSelf}.Clamp(TSelf, TSelf, TSelf)" /> public static ulong Clamp(ulong value, ulong min, ulong max) => Math.Clamp(value, min, max);