public void OnServerInbound(NetInboundPacket packet, NetConnectionSnapshotState state)
        {
            bool playerSentData = packet.ReadBool();

            if (!playerSentData)
            {
                return;
            }

            ushort entId = packet.ReadUInt16();

            ServerMPPlayer player;

            if (players.TryGetValue(entId, out player))
            {
                // Read packet to snapshot
                player.ClientSnapshot.Deserialize(packet);
                // Update player
                player.OnServerInbound();
            }
            else if (DashCMD.GetCVar <bool>("log_css"))
            {
                DashCMD.WriteError("[CSS] Received client snapshot for player with id {0}, which does not exist!", entId);
            }
        }
Ejemplo n.º 2
0
        void R_ThrowGrenade(NetConnection client, NetBuffer buffer, ushort numArgs)
        {
            float ox = buffer.ReadFloat();
            float oy = buffer.ReadFloat();
            float oz = buffer.ReadFloat();

            float dx = buffer.ReadFloat();
            float dy = buffer.ReadFloat();
            float dz = buffer.ReadFloat();

            float power = buffer.ReadFloat();

            ServerMPPlayer player;

            if (players.TryGetValue(client, out player))
            {
                if (player.NumGrenades > 0)
                {
                    ThrowGrenade(player, new Vector3(ox, oy, oz), new Vector3(dx, dy, dz), power);

                    if (!DashCMD.GetCVar <bool>("ch_infammo"))
                    {
                        player.NumGrenades--;
                    }
                }
            }
        }
Ejemplo n.º 3
0
        public override void Update(float deltaTime)
        {
            foreach (KeyValuePair <NetConnection, ServerMPPlayer> pair in players)
            {
                ServerMPPlayer player = pair.Value;
                if (player.Health <= 0)
                {
                    player.OnKilled();

                    if (OnPlayerKilled != null)
                    {
                        if (player.LastDamage != null)
                        {
                            OnPlayerKilled(player.LastDamage);
                        }
                        else
                        {
                            OnPlayerKilled(new PlayerDamage(player, 0, "Unknown"));
                        }
                    }
                }
            }

            float timeAutoShift = DashCMD.GetCVar <float>("time_autoshift");

            TimeOfDay += timeAutoShift * deltaTime;

            base.Update(deltaTime);
        }
 void WriteDebug(string message, params object[] args)
 {
     if (DashCMD.GetCVar <bool>("log_css"))
     {
         DashCMD.WriteLine(message, args);
     }
 }
Ejemplo n.º 5
0
        protected override void Update(float deltaTime)
        {
            if (!GlobalNetwork.IsConnected || (CreatableInfo != null && CreatableInfo.IsAppOwner))
            {
                if (lastHolderCooldown > 0)
                {
                    lastHolderCooldown -= deltaTime;
                }

                if (Holder != null)
                {
                    Transform.Position = Holder.Transform.Position;
                }

                if (Transform.Position.Y < -200)
                {
                    Drop();
                    resetPosition = true;
                }

                if (resetPosition)
                {
                    Transform.Position = startPosition;
                    resetPosition      = false;
                }
            }
            else if (GlobalNetwork.IsClient && GlobalNetwork.IsConnected && CreatableInfo != null)
            {
                positionAnim.Step(DashCMD.GetCVar <float>("cl_interp_rep") * deltaTime);
                Transform.Position = positionAnim.Value;
            }

            base.Update(deltaTime);
        }
 void WriteDebug(string msg, params object[] args)
 {
     if (DashCMD.GetCVar <bool>("log_snapshots"))
     {
         DashCMD.WriteStandard(msg, args);
     }
 }
Ejemplo n.º 7
0
 void ImpactAt(Vector3 origin)
 {
     if (DashCMD.GetCVar <bool>("sv_impacts"))
     {
         channel.FireEventForAllConnections("Client_ServerImpact", origin.X, origin.Y, origin.Z);
     }
 }
Ejemplo n.º 8
0
        void R_ShootMelon(NetConnection client, NetBuffer buffer, ushort numArgs)
        {
            float ox = buffer.ReadFloat();
            float oy = buffer.ReadFloat();
            float oz = buffer.ReadFloat();

            float dx = buffer.ReadFloat();
            float dy = buffer.ReadFloat();
            float dz = buffer.ReadFloat();

            ServerMPPlayer player;

            if (players.TryGetValue(client, out player))
            {
                if (player.NumMelons > 0)
                {
                    ShootMelon(player, new Vector3(ox, oy, oz), new Vector3(dx, dy, dz));

                    if (!DashCMD.GetCVar <bool>("ch_infammo"))
                    {
                        player.NumMelons--;
                    }
                }
            }
        }
Ejemplo n.º 9
0
 public virtual void OnNetworkInstantiated(NetCreatableInfo stateInfo)
 {
     StateInfo = stateInfo;
     if (DashCMD.GetCVar <bool>("log_mpplayer"))
     {
         DashCMD.WriteStandard("[MPPlayer - {1}] Instantiated with id {0}", stateInfo.Id,
                               stateInfo.IsAppOwner ? "Ours" : "Not Ours");
     }
 }
Ejemplo n.º 10
0
        public virtual void OnNetworkDestroy()
        {
            if (DashCMD.GetCVar <bool>("log_mpplayer"))
            {
                DashCMD.WriteStandard("[MPPlayer - {1}] Destroyed with id {0}", StateInfo.Id,
                                      StateInfo.IsAppOwner ? "Ours" : "Not Ours");
            }

            Dispose();
        }
        protected void EndGame(Team winner)
        {
            if (DashCMD.GetCVar <bool>("gm_neverend"))
            {
                return;
            }

            IsActive = false;
            DespawnAllPlayers();
            Screen.TeamWon(winner);
        }
Ejemplo n.º 12
0
        protected override void OnPrimaryFire()
        {
            if (!GlobalNetwork.IsConnected || GlobalNetwork.IsServer)
            {
                if (CurrentMag > 0)
                {
                    for (int i = 0; i < GunConfig.BulletsPerShot; i++)
                    {
                        Vector3 recoil = GetRecoilJiggle(GunConfig.BulletSpread, GunConfig.BulletSpread);
                        World.FireBullet(OwnerPlayer, Camera.Position, Camera.LookVector, recoil,
                                         GunConfig.BlockDamage, GunConfig.PlayerDamage);
                    }

                    muzzleFlash.Show();
                    World.GunFired(GunConfig.VerticalRecoil, GetHorizontalCameraRecoil(GunConfig.HorizontalRecoil), GunConfig.ModelKickback);

                    if (!GlobalNetwork.IsServer || !DashCMD.GetCVar <bool>("ch_infammo"))
                    {
                        CurrentMag--;
                    }

                    if (!GlobalNetwork.IsServer)
                    {
                        fireAudioSource?.Play();
                    }
                }
                else
                {
                    dryFireAudioSource?.Play();
                }
            }
            else if (GlobalNetwork.IsConnected && GlobalNetwork.IsClient)
            {
                if (ServerMag > 0)
                {
                    //for (int i = 0; i < GunConfig.BulletsPerShot; i++)
                    {
                        Vector3 recoil = GetRecoilJiggle(GunConfig.BulletSpread, GunConfig.BulletSpread);
                        World.FireBullet(OwnerPlayer, Camera.Position, Camera.LookVector, recoil,
                                         GunConfig.BlockDamage, GunConfig.PlayerDamage);
                    }

                    muzzleFlash.Show();
                    World.GunFired(GunConfig.VerticalRecoil, GetHorizontalCameraRecoil(GunConfig.HorizontalRecoil), GunConfig.ModelKickback);

                    fireAudioSource?.Play();
                }
                else
                {
                    dryFireAudioSource?.Play();
                }
            }
        }
Ejemplo n.º 13
0
        public void TeamWon(Team winner)
        {
            if (DashCMD.GetCVar <bool>("gm_neverend"))
            {
                return;
            }

            channel.FireEventForAllConnections("Client_TeamWon", (byte)winner);
            Chat("Game Over, restarting in " + GAMEMODE_RESTART_DELAY + " seconds...");
            restartTime    = GAMEMODE_RESTART_DELAY;
            gameRestarting = true;
        }
Ejemplo n.º 14
0
        protected override void Update(float deltaTime)
        {
            SwitchScreen();

            lastDeltaTime = deltaTime;

            StaticGui.Update(deltaTime);

            if (AOSClient.Instance != null)
            {
                AOSClient.Instance.Update(deltaTime);
            }

            if (activeScreen != null)
            {
                activeScreen.Update(deltaTime);
            }

            if (Input.GetControlDown("Hide UI"))
            {
                Renderer.Gui.Hide = !Renderer.Gui.Hide;
            }

            bool r_vsync = DashCMD.GetCVar <bool>("r_vsync");

            if (r_vsync != GetVSync())
            {
                SetVSync(r_vsync);
            }

            TargetFrameRate = DashCMD.GetCVar <float>("r_targfps");
            ShadowCamera.UseExperimental = DashCMD.GetCVar <bool>("r_exp_shadows");

            //if (Input.GetKey(Key.K)) source.Pitch += 0.01f;
            //if (Input.GetKey(Key.J)) source.Pitch -= 0.01f;

            if (Input.GetControlDown("1080p Screenshot"))
            {
                TakeScreenshot(1920, 1080);
            }
            if (Input.GetControlDown("1440p Screenshot"))
            {
                TakeScreenshot(2560, 1440);
            }
            //if (Input.GetKeyDown(Key.F12)) TakeScreenshot(8192, 4608);

            if (Input.GetKeyDown(Key.F6))
            {
                debugRenderBoundingBoxes = !debugRenderBoundingBoxes;
            }
            PhysicsEngine.RecordProcessedBoundingBoxes = debugRenderBoundingBoxes;
        }
Ejemplo n.º 15
0
        public override void FireBullet(Player player, Vector3 origin, Vector3 dir, Vector3 recoil,
                                        int blockDamage, float playerDamage, float maxDist = float.MaxValue)
        {
            Ray ray = new Ray(origin, dir + recoil);
            TerrainRaycastResult result = TerrainPhysics.Raycast(ray, true, maxDist);

            if (result.Intersects)
            {
                result.Chunk.DamageBlock(result.BlockIndex.Value, blockDamage);
                if (DashCMD.GetCVar <bool>("cl_impacts"))
                {
                    debugRenderer.AddBulletImpact(ray.Origin + ray.Direction * result.IntersectionDistance.Value, Color.Red);
                }
            }
        }
Ejemplo n.º 16
0
        void R_SetBlock(NetConnection client, NetBuffer buffer, ushort numArgs)
        {
            int cx = buffer.ReadInt16();
            int cy = buffer.ReadInt16();
            int cz = buffer.ReadInt16();

            int bx = buffer.ReadUInt16();
            int by = buffer.ReadUInt16();
            int bz = buffer.ReadUInt16();

            byte r = buffer.ReadByte();
            byte g = buffer.ReadByte();
            byte b = buffer.ReadByte();
            byte d = buffer.ReadByte();

            bool placement = buffer.ReadBool();

            ServerMPPlayer player;

            if (players.TryGetValue(client, out player))
            {
                IndexPosition chunkPos = new IndexPosition(cx, cy, cz);
                IndexPosition blockPos = new IndexPosition(bx, by, bz);

                Block block = new Block(new Nybble2(d), r, g, b);
                // Validate modification
                float distToBlock = (player.GetCamera().Position - Chunk.ChunkBlockToWorldCoords(chunkPos, blockPos)).Length;
                if (!placement /* && distToBlock <= Spade.MODIFY_RANGE*/)
                {
                    SetBlock(chunkPos, blockPos, block, placement);

                    if (block == Block.AIR)
                    {
                        player.NumBlocks++;
                    }
                }
                else if (placement && /*distToBlock <= BlockItem.PLACE_RANGE
                                       * &&*/player.NumBlocks > 0)
                {
                    SetBlock(chunkPos, blockPos, block, placement);

                    if (!DashCMD.GetCVar <bool>("ch_infammo"))
                    {
                        player.NumBlocks--;
                    }
                }
            }
        }
Ejemplo n.º 17
0
        public override void FireBullet(Player player, Vector3 origin, Vector3 dir, Vector3 recoil,
                                        int damage, float playerDamage, float maxDist = float.MaxValue)
        {
            // Signal server that we fired a bullet at this time
            OurPlayer.ClientSnapshot.BulletSnapshot.EnqueueBullet(new NetworkBullet(origin, Camera.Active.Yaw, Camera.Active.Pitch));

            // Simulate bullet locally if enabled
            if (DashCMD.GetCVar <bool>("cl_impacts"))
            {
                Ray ray = new Ray(origin, dir + recoil);
                TerrainRaycastResult result = TerrainPhysics.Raycast(ray, true, maxDist);

                ClientPlayer hitPlayer   = null;
                float?       hitPlayerAt = null;
                foreach (ClientPlayer otherPlayer in players.Values)
                {
                    if (otherPlayer != player)
                    {
                        if (DashCMD.GetCVar <bool>("cl_impacts"))
                        {
                            debugRenderer.AddPlayerRollback(otherPlayer.Transform.Position, Color.Green);
                        }

                        Ray newRay = new Ray(origin - otherPlayer.Transform.Position, dir);

                        float?dist;
                        if (newRay.Intersects(otherPlayer.GetOrientatedBoundingBox(), out dist))
                        {
                            if (!hitPlayerAt.HasValue || dist.Value < hitPlayerAt.Value)
                            {
                                hitPlayer   = otherPlayer;
                                hitPlayerAt = dist.Value;
                            }
                        }
                    }
                }

                if (result.Intersects && (!hitPlayerAt.HasValue || (hitPlayerAt.Value > result.IntersectionDistance.Value)))
                {
                    debugRenderer.AddBulletImpact(ray.Origin + ray.Direction * result.IntersectionDistance.Value, Color.Red);
                }
                else if (hitPlayerAt.HasValue)
                {
                    debugRenderer.AddBulletImpact(ray.Origin + ray.Direction * hitPlayerAt.Value, Color.Red);
                }
            }
        }
Ejemplo n.º 18
0
        public override void Update(float deltaTime)
        {
            if (measuringRTT)
            {
                timeSinceSend += deltaTime;
            }

            bool svForceAwait = WorldSnapshot != null
                ? WorldSnapshot.ForceSnapshotAwait : true;
            bool gotServerSnapshot = gotPacket ||
                                     (!DashCMD.GetCVar <bool>("cl_await_sv_snap") && !svForceAwait);

            if (syncTime <= 0 && gotServerSnapshot || syncTime <= -1)
            {
                syncTime += tickrate;
                gotPacket = false;

                // Create and send client state snapshot
                NetOutboundPacket packet = new NetOutboundPacket(NetDeliveryMethod.Unreliable);
                packet.SendImmediately = true;
                int size = packet.Length;
                packet.Write((byte)CustomPacketType.Snapshot);
                packet.Write(pid++);

                lastOutboundPacketStats.PacketHeader = packet.Length - size; size = packet.Length;

                // Write snapshot delta data
                snapshotSystem.OnOutbound(packet, client.ServerConnection);
                lastOutboundPacketStats.Acks = packet.Length - size; size = packet.Length;

                // Write player data
                charSnapshotSystem.OnClientOutbound(packet);
                lastOutboundPacketStats.PlayerData = packet.Length - size; size = packet.Length;

                // Send packet
                client.SendPacket(packet);

                timeSinceSend = 0;
                measuringRTT  = true;
            }
            else
            {
                syncTime -= deltaTime;
            }

            base.Update(deltaTime);
        }
Ejemplo n.º 19
0
        protected override void Update(float deltaTime)
        {
            if (GlobalNetwork.IsClient && GlobalNetwork.IsConnected && CreatableInfo != null)
            {
                positionAnim.Step(DashCMD.GetCVar <float>("cl_interp_rep") * deltaTime);
                Transform.Position = positionAnim.Value;
            }
            else if (!GlobalNetwork.IsConnected || GlobalNetwork.IsServer)
            {
                if (Transform.Position.Y < -200)
                {
                    Transform.Position = startPosition;
                }
            }

            base.Update(deltaTime);
        }
Ejemplo n.º 20
0
        public void OnClientInbound(WorldSnapshot worldSnapshot)
        {
            // Update players
            foreach (SnapshotField field in worldSnapshot.Players)
            {
                PlayerSnapshot snapshot = (PlayerSnapshot)field.Value;

                ClientPlayer player;
                if (players.TryGetValue(snapshot.NetId, out player))
                {
                    player.OnClientInbound(snapshot);
                }
                else if (DashCMD.GetCVar <bool>("log_css"))
                {
                    DashCMD.WriteError("[CSS] Received player state for non-existant player! Id: {0}", snapshot.NetId);
                }
            }
        }
Ejemplo n.º 21
0
        public PlayerTransform RollbackTransform(int timeFrame, bool suppressLog = false)
        {
            PlayerTransform pt1 = null, pt2 = null;

            for (int i = 0; i < playerTransforms.Count; i++)
            {
                PlayerTransform pt      = playerTransforms[i];
                int             tickOff = Math.Abs(pt.Ticks - timeFrame);

                // Don't process anything more than a second off
                if (tickOff > 1000)
                {
                    continue;
                }

                if (pt1 == null || tickOff < Math.Abs(pt1.Ticks - timeFrame))
                {
                    pt1 = pt;
                }
            }

            for (int i = 0; i < playerTransforms.Count; i++)
            {
                PlayerTransform pt = playerTransforms[i];
                if (pt == pt1)
                {
                    continue;
                }

                int tickOff = Math.Abs(pt.Ticks - timeFrame);

                // Don't process anything more than a second off
                if (tickOff > 1000)
                {
                    continue;
                }

                if (pt2 == null || tickOff < Math.Abs(pt2.Ticks - timeFrame))
                {
                    pt2 = pt;
                }
            }

            if (pt1 != null && pt2 != null)
            {
                if (pt2.Ticks > pt1.Ticks)
                {
                    PlayerTransform temp = pt2;
                    pt2 = pt1;
                    pt1 = temp;
                }

                // Interpolate
                float timeI = pt1.Ticks == pt2.Ticks ? 0f : (float)(timeFrame - pt2.Ticks) / (pt1.Ticks - pt2.Ticks);
                //timeI = MathHelper.Clamp(timeI, 0f, 1f);

                if (DashCMD.GetCVar <bool>("sv_hitboxes") && !suppressLog)
                {
                    DashCMD.WriteImportant("[RB] Rolling back transform by {0}%. [timeFrame: {3}, pt2: {1}, pt1: {2}]",
                                           timeI * 100, pt2.Ticks, pt1.Ticks, timeFrame);
                }

                Vector3 position = Interpolation.Lerp(pt2.Position, pt1.Position, timeI);
                float   camPitch = Interpolation.LerpDegrees(pt2.CameraPitch, pt1.CameraPitch, timeI);
                float   camYaw   = Interpolation.LerpDegrees(pt2.CameraYaw, pt1.CameraYaw, timeI);

                return(new PlayerTransform(position, camYaw, camPitch, timeFrame));
            }
            else if (pt1 != null && pt2 == null)
            {
                // Take pt1
                return(pt1);
            }
            else
            {
                // Take current
                return(new PlayerTransform(Transform.Position, camera.Yaw, camera.Pitch, Environment.TickCount));
            }
        }
Ejemplo n.º 22
0
        public override void FireBullet(Player _player, Vector3 origin, Vector3 dir, Vector3 recoil,
                                        int blockDamage, float playerDamage, float maxDist = float.MaxValue)
        {
            ServerMPPlayer player = (ServerMPPlayer)_player;

            bool sv_impacts  = DashCMD.GetCVar <bool>("sv_impacts");
            bool sv_hitboxes = DashCMD.GetCVar <bool>("sv_hitboxes");

            int shooterPing    = player.StateInfo.Owner.Stats.Ping;
            int rollbackOffset = DashCMD.GetCVar <int>("rp_rollback_offset");
            int bulletDelta    = player.LastBulletDeltaTime;

            if (sv_hitboxes)
            {
                DashCMD.WriteLine("[RB] Starting bullet {0}ms delta with {1}ms offset",
                                  ConsoleColor.Green, bulletDelta, rollbackOffset);
            }

            // Raycast
            BeginRollback(shooterPing + bulletDelta + rollbackOffset);
            Ray ray = new Ray(origin, dir + recoil);
            WorldRaycastResult result = Raycast(ray, true, maxDist, player);

            EndRollback();

            // Handle intersection
            if (result.Intersects)
            {
                if (result.HitTerrain)
                {
                    // Damage terrain
                    TerrainRaycastResult tResult = result.TerrainResult;

                    if (blockDamage > 0)
                    {
                        tResult.Chunk.DamageBlock(tResult.BlockIndex.Value, blockDamage);
                    }
                }
                else if (result.HitPlayer)
                {
                    // Damage player
                    PlayerRaycastResult pResult = result.PlayerResult;

                    bool ff   = DashCMD.GetCVar <bool>("mp_friendlyfire");
                    bool infh = DashCMD.GetCVar <bool>("ch_infhealth");

                    if (!infh && (ff || player.Team != pResult.Player.Team))
                    {
                        DamagePlayer(player, player.ItemManager.SelectedItem.GetType().Name, (ServerMPPlayer)pResult.Player,
                                     playerDamage, origin);

                        if (sv_impacts)
                        {
                            DashCMD.WriteLine("[IMP] Hit player for {0} damage. Health After: {1}", playerDamage, pResult.Player.Health);
                        }
                    }
                }

                ImpactAt(result.IntersectionPosition.Value);
            }
        }
Ejemplo n.º 23
0
        public override void Explode(Explosion explosion)
        {
            // Destroy terrain
            Vector3 origin = explosion.Origin;
            float   radius = explosion.BlockRadius;

            IndexPosition cpos     = FixedTerrain.WorldToChunkCoords(origin);
            IndexPosition blockPos = Chunk.WorldToBlockCoords(origin);

            blockPos -= cpos * Chunk.SIZE;

            Chunk chunk;

            if (Terrain.Chunks.TryGetValue(cpos, out chunk))
            {
                int blockRadius = (int)(radius / Block.CUBE_SIZE);
                for (int x = -blockRadius; x <= blockRadius; x++)
                {
                    for (int y = -blockRadius; y <= blockRadius; y++)
                    {
                        for (int z = -blockRadius; z <= blockRadius; z++)
                        {
                            int nx = x + blockPos.X;
                            int ny = y + blockPos.Y;
                            int nz = z + blockPos.Z;

                            IndexPosition ncpos = chunk.WrapBlockCoords(ref nx, ref ny, ref nz);

                            if (!chunk.IsBlockCoordInRange(nx, ny, nz))
                            {
                                continue;
                            }

                            Vector3 apos = Chunk.ChunkBlockToWorldCoords(ncpos, new IndexPosition(nx, ny, nz))
                                           - Block.HALF_CUBE_3D_SIZE;

                            float dist = Maths.Distance(apos, origin);
                            if (dist > radius)
                            {
                                continue;
                            }

                            int damage = (int)(14 * (1f - (dist / radius)));

                            if (ncpos != cpos)
                            {
                                Chunk otherChunk;
                                if (Terrain.Chunks.TryGetValue(ncpos, out otherChunk))
                                {
                                    otherChunk.DamageBlock(new IndexPosition(nx, ny, nz), damage);
                                }
                            }
                            else
                            {
                                chunk.DamageBlock(new IndexPosition(nx, ny, nz), damage);
                            }
                        }
                    }
                }
            }

            // Apply grenade damage
            bool ff = DashCMD.GetCVar <bool>("mp_friendlyfire");

            if (!DashCMD.GetCVar <bool>("ch_infhealth"))
            {
                foreach (ServerMPPlayer player in players.Values)
                {
                    if (player.Health <= 0 || !ff && explosion.Owner.Team == player.Team && explosion.Owner != player)
                    {
                        continue;
                    }

                    PlayerRaycastResult eResult = RaycastPlayer(explosion.Origin, player, explosion.PlayerRadius);
                    if (eResult.Intersects)
                    {
                        /*
                         *  Curve:
                         *  max(min((fa/max(x,0)) - (fa/d), a), 0)
                         *  where f = falloff rate, a = max damage, d = max distance,
                         *      x = distance
                         */

                        //float damage = MathHelper.Clamp(
                        //    explosion.Damage / (eResult.IntersectionDistance.Value * explosion.DamageFalloff),
                        //    0, explosion.Damage);

                        float damage = explosion.Damage * (float)Math.Cos(eResult.IntersectionDistance.Value / ((2 * explosion.PlayerRadius) / Math.PI));

                        //float fa = explosion.DamageFalloff * explosion.Damage;
                        // float damage = MathHelper.Clamp((fa / eResult.IntersectionDistance.Value) - (fa / 200f), 0, explosion.Damage);

                        DamagePlayer((ServerMPPlayer)explosion.Owner, explosion.EntityName, player, damage, origin);
                    }
                }
            }

            // Fling other grenades
            radius = explosion.PlayerRadius;

            for (int i = 0; i < grenades.Count; i++)
            {
                GrenadeEntity grenade = grenades[i];

                Vector3 dirTo = grenade.Transform.Position - origin;
                float   dist  = dirTo.Length;
                if (dist > radius)
                {
                    continue;
                }

                dirTo += new Vector3(0, 1, 0);
                dirTo  = dirTo.Normalize();

                float kickBack = 60 * (1f - (dist / radius));
                grenade.PhysicsBody.Velocity += dirTo * kickBack;
                grenade.Transform.Position.Y += 0.01f;
            }
        }
        protected override void Update(float deltaTime)
        {
            if (StateInfo != null)
            {
                // Update viewbob
                Viewbob.UpdateReplicated(deltaTime);

                // Step each value animation
                float interpStep = DashCMD.GetCVar <float>("cl_interp_rep") * deltaTime;
                interpPos.Step(interpStep);
                yawAnim.Step(interpStep);
                pitchAnim.Step(interpStep);

                // Update each property affected by interpolation
                Transform.Position = interpPos.Value;

                camera.Yaw   = yawAnim.Value;
                camera.Pitch = pitchAnim.Value;

                // Update our "fake" camera
                camera.Position = Transform.Position + new Vector3(0, Size.Y / 2f - 1.1f, 0);
                camera.Update(deltaTime);

                // Update flashlight
                flashlight.Position  = camera.Position;
                flashlight.Direction = -camera.LookVector;

                // Update the item manager
                ItemManager.UpdateReplicated(deltaTime);

                // Handle jump
                if (jumpAudioSource != null)
                {
                    jumpAudioSource.Position = Transform.Position;
                }

                if (jump)
                {
                    jump = false;
                    jumpAudioSource?.Play();
                }

                // Handle landing
                if (landAudioSource != null)
                {
                    landAudioSource.Position = Transform.Position;
                }

                if (land)
                {
                    land = false;
                    landAudioSource?.Play();
                }

                // Handle walking/running
                walkingAudioSource.IsPlaying       = isGrounded && isMoving && !IsSprinting;
                walkingAudioSource.IterationLength = (1f / GetFootstepIterationSpeed()) * 2f;
                walkingAudioSource.Update(deltaTime, Transform.Position);

                runningAudioSource.IsPlaying       = isGrounded && isMoving && IsSprinting;
                runningAudioSource.IterationLength = (1f / GetFootstepIterationSpeed()) * 2f;
                runningAudioSource.Update(deltaTime, Transform.Position);

                // Handle reload
                if (reload)
                {
                    reload = false;

                    if (ItemManager.SelectedItem is Gun gun)
                    {
                        gun.OnReplicatedReload();
                    }
                }
            }

            base.Update(deltaTime);
        }
        void SendSnapshotTo(NetConnection conn, NetConnectionSnapshotState connState, float deltaTime)
        {
            WorldSnapshot worldSnapshot = connState.WorldSnapshot;

            ushort epid = connState.OutboundSnapshotId;

            connState.OutboundSnapshotId++;

            //connState.TimeSinceLastSend -= deltaTime;
            //connState.GotPacket = false;

            connState.WorldSnapshot.MaxClientTickrate  = DashCMD.GetCVar <ushort>("ag_max_cl_tickrate");
            connState.WorldSnapshot.ForceSnapshotAwait = DashCMD.GetCVar <bool>("ag_cl_force_await_snap");

            NetOutboundPacket packet = new NetOutboundPacket(NetDeliveryMethod.Unreliable);

            packet.SendImmediately = true;
            int size = packet.Length;

            packet.Write((byte)CustomPacketType.Snapshot);
            packet.Write(epid);
            int _packetheader = packet.Length - size; size = packet.Length;

            // Write snapshot system data
            snapshotSystem.OnOutbound(packet, conn);
            int _acks = packet.Length - size; size = packet.Length;

            // Write players
            charSnapshotSystem.OnServerOutbound(packet, connState);

            // Invoke event
            if (OnWorldSnapshotOutbound != null)
            {
                OnWorldSnapshotOutbound(this, worldSnapshot);
            }

            // Serialize snapshot
            NetBuffer buffer = new NetBuffer();

            worldSnapshot.Serialize(buffer);

            packet.Write((ushort)buffer.Length);
            packet.WriteBytes(buffer.Data, 0, buffer.Length);


            int _playerdata  = packet.Length - size; size = packet.Length;
            int _terraindata = connState.WorldSnapshot.TerrainSnapshot.LastByteSize;

            _playerdata -= _terraindata;

            // Send packet
            conn.SendPacket(packet);

            if (connState != null)
            {
                SnapshotStats stats = connState.Stats;
                stats.PacketHeader = _packetheader;
                stats.Acks         = _acks;
                stats.PlayerData   = _playerdata;
                stats.TerrainData  = _terraindata;
            }
        }
Ejemplo n.º 26
0
        public override PlayerRaycastResult RaycastPlayers(Ray ray, float maxDist = float.MaxValue, params Player[] ignore)
        {
            bool sv_impacts  = DashCMD.GetCVar <bool>("sv_impacts");
            bool sv_hitboxes = DashCMD.GetCVar <bool>("sv_hitboxes");

            ServerMPPlayer hitPlayer   = null;
            float?         hitPlayerAt = null;

            foreach (ServerMPPlayer otherPlayer in players.Values)
            {
                // Make sure we aren't ignoring this player
                if (ignore.Length == 0 || !Array.Exists(ignore, (x => x == otherPlayer)))
                {
                    Vector3 otherPlayerPosition;
                    float   otherPlayerCamYaw;
                    if (rollbackTime.HasValue)
                    {
                        // We are applying rollback, so find the players old transform
                        int otherPlayerPing = DashCMD.GetCVar <bool>("rp_usetargetping") ? otherPlayer.StateInfo.Owner.Stats.Ping : 0;
                        int rollbackFrame   = MathHelper.Clamp(otherPlayerPing + rollbackTime.Value, 0, 1000);

                        if (sv_hitboxes)
                        {
                            DashCMD.WriteLine("[RB] Rolling back bullet-player transform by {0}ms [target ping: {1}ms]",
                                              ConsoleColor.Green, rollbackTime, otherPlayerPing);
                        }

                        PlayerTransform otherPlayerTransform = otherPlayer.RollbackTransform(Environment.TickCount - rollbackFrame);
                        otherPlayerPosition = otherPlayerTransform.Position;
                        otherPlayerCamYaw   = otherPlayerTransform.CameraYaw;
                    }
                    else
                    {
                        // No rollback currently, use current transform
                        otherPlayerPosition = otherPlayer.Transform.Position;
                        otherPlayerCamYaw   = otherPlayer.GetCamera().Yaw;
                    }

                    if (sv_hitboxes)
                    {
                        channel.FireEventForAllConnections("Client_RolledBackServerPlayer",
                                                           otherPlayerPosition.X, otherPlayerPosition.Y,
                                                           otherPlayerPosition.Z, (byte)otherPlayer.Team);
                    }

                    Ray newRay = new Ray(ray.Origin - otherPlayerPosition, ray.Direction);

                    float?dist;
                    // Check for intersection
                    if (newRay.Intersects(otherPlayer.GetOrientatedBoundingBox(otherPlayerCamYaw), out dist))
                    {
                        // If the distance is out of bounds, ignore
                        if (dist.Value > maxDist)
                        {
                            continue;
                        }

                        // Only update the intersected player if it was closer than the last
                        if (!hitPlayerAt.HasValue || dist.Value < hitPlayerAt.Value)
                        {
                            hitPlayer   = otherPlayer;
                            hitPlayerAt = dist.Value;
                        }
                    }
                }
            }

            if (hitPlayer != null)
            {
                return(new PlayerRaycastResult(ray, true, ray.Origin + ray.Direction * hitPlayerAt.Value, hitPlayerAt, hitPlayer));
            }
            else
            {
                return(new PlayerRaycastResult(ray));
            }
        }