Beispiel #1
0
        void OnHashMatchResult(int tick, long hash, bool isMatched)
        {
            if (isMatched)
            {
                _hashCodes[tick] = null;
            }

            if (!isMatched)
            {
                Debug.Log($"!!!!!!!!!!!! Hash not match tick{tick} hash{hash} ");
            }
        }
Beispiel #2
0
        //net status
        public void OnReconnect(Player player)
        {
            player.localId = _playerId2LocalId[player.PlayerId];
            _localId2Player[player.localId] = player;
            if (_allPlayers.Contains(player))
            {
                Debug.LogError("Duplicate add players" + player.PlayerId);
                return;
            }

            _allPlayers.Add(player);
        }
Beispiel #3
0
        public static ColliderPrefab CreateColliderPrefab(GameObject fab, ColliderData data)
        {
            Debug.Trace("CreateColliderPrefab " + fab.name);

            if (data == null)
            {
                Debug.LogError(fab.name + " Miss ColliderDataMono ");
                return(null);
            }

            Debug.Trace($"{fab.name} !!!CreateCollider  deg: {data.deg} up:{data.size} radius:{data.radius}");
            return(CreateColliderPrefab(data));
        }
Beispiel #4
0
        public void OnMsg_X2S_BorderMasterInfo(Deserializer reader)
        {
            var msg = reader.Parse <Msg_BorderMasterInfo>();

            Debug.Log("OnMsg_X2S_BorderMasterInfo " + msg.ToString());
            if (msg.serverInfo.serverType == (byte)serverType)
            {
                Debug.Log("OnMsg_X2S_RepMasterInfo " + msg.ToString());
                InitClientMS(msg.serverInfo);
            }

            OnMasterServerInfo(msg.serverInfo);
        }
        public void SendInput(Msg_PlayerInput input)
        {
            _tick2SendTimestamp[input.Tick] = LTime.realtimeSinceStartupMS;
#if DEBUG_SHOW_INPUT
            var cmd         = input.Commands[0];
            var playerInput = new Deserializer(cmd.content).Parse <Lockstep.Game.PlayerInput>();
            if (playerInput.inputUV != LVector2.zero)
            {
                Debug.Log($"SendInput tick:{input.Tick} uv:{playerInput.inputUV}");
            }
#endif
            _networkService.SendInput(input);
        }
Beispiel #6
0
        public void RollbackTo(int tick, int maxContinueServerTick, bool isNeedClear = true)
        {
            if (tick < 0)
            {
                Debug.LogError("Target Tick invalid!" + tick);
                return;
            }

            Debug.Log($" Rollback diff:{Tick - tick} From{Tick}->{tick}  maxContinueServerTick:{maxContinueServerTick} {isNeedClear}");
            _timeMachineService.RollbackTo(tick);
            _commonStateService.SetTick(tick);
            Tick = tick;
        }
Beispiel #7
0
 private void InitClientMS(ServerIpInfo msg)
 {
     InitNetClient(ref _netClientMS, msg.ip, msg.port, () => {
         Debug.Log("Connect Master " + serverType);
         _netClientMS.Send(EMsgMS.S2M_RegisterServer, new Msg_RegisterServer()
         {
             serverInfo = new ServerIpInfo()
             {
                 serverType = (byte)serverType
             }
         });
     }
                   );
 }
Beispiel #8
0
        public void SetTime(LFloat timer)
        {
            if (config == null)
            {
                return;
            }
            var idx = GetTimeIdx(timer);

            _intiPos = transform.Pos3 - curAnimInfo[idx].pos;
            Debug.Trace(
                $"{baseEntity.EntityId} SetTime  idx:{idx} intiPos {baseEntity.transform.Pos3}",
                true);
            this._timer = timer;
        }
Beispiel #9
0
        private void OnDestroy()
        {
            netClient?.Send(new Msg_QuitRoom());
            foreach (var mgr in managers)
            {
                mgr.DoDestroy();
            }

            if (!isReplay)
            {
                RecordHelper.Serialize(recordFilePath, this);
            }
            Debug.FlushTrace();
            DoDestroy();
        }
        protected void G2C_GameStartInfo(object reader)
        {
            var msg = reader as Msg_G2C_GameStartInfo;

            HasRecvGameDta = true;
            GameStartInfo  = msg;
            _handler.OnGameStartInfo(msg);
            //TODO temp code
            HasConnGameTcp   = true;
            HasConnGameUdp   = true;
            CurGameState     = EGameState.Loading;
            _curLoadProgress = 1;
            EventHelper.Trigger(EEvent.OnGameCreate, msg);
            Debug.Log("G2C_GameStartInfo");
        }
Beispiel #11
0
        public void SendTo(Player player, EMsgSC type, ISerializable body, bool isNeedDebugSize = false)
        {
            var writer = new Serializer();

            writer.PutByte((byte)type);
            body.Serialize(writer);
            var bytes = Compressor.Compress(writer);

            if (isNeedDebugSize)
            {
                Debug.Log($"msg :type {type} size{bytes.Length}");
            }

            player.SendRoom(bytes);
        }
Beispiel #12
0
        private bool RollbackTo(int tick, int maxContinueServerTick, bool isNeedClear = true)
        {
            _world.RollbackTo(tick, maxContinueServerTick, isNeedClear);
            var hash    = _commonStateService.Hash;
            var curHash = _hashHelper.CalcHash();

            if (hash != curHash)
            {
                Debug.LogError($"tick:{tick} Rollback error: Hash isDiff oldHash ={hash}  curHash{curHash}");
#if UNITY_EDITOR
                _dumpHelper.DumpToFile(true);
                return(false);
#endif
            }
            return(true);
        }
Beispiel #13
0
 private void InitClientXS()
 {
     Debug.Log("InitClientXS " + _allConfig.daemonPort);
     InitNetClient(ref _netClientXS, "127.0.0.1", _allConfig.daemonPort,
                   () => {
         Debug.Log("OnConnectedDaemon " + _allConfig.daemonPort);
         _netClientXS.Send(EMsgXS.S2X_ReqMasterInfo, new Msg_ReqMasterInfo()
         {
             serverInfo = new ServerIpInfo()
             {
                 isMaster   = _serverConfig.isMaster,
                 port       = _serverConfig.masterPort,
                 serverType = (byte)serverType
             }
         });
     });
 }
Beispiel #14
0
        protected void OnMsg_S2M_ReqOtherServerInfo(IServerProxy net, Deserializer reader)
        {
            var msg  = reader.Parse <Msg_ReqOtherServerInfo>();
            var type = (EServerType)msg.serverType;

            Debug.Log("OnMsg_S2M_ReqOtherServerInfo " + type);
            if (type == serverType)
            {
                //TODO
                var info = GetSlaveServeInfo();
                Debug.Log("GetSlaveServeInfo " + info);
                net.SendMsg(EMsgMS.M2S_RepOtherServerInfo, new Msg_RepOtherServerInfo()
                {
                    serverInfo = info
                });
            }
        }
Beispiel #15
0
        public static BaseEntity InstantiateEntity(int prefabId, LVector3 position)
        {
            var    prefab = ResourceManager.LoadPrefab(prefabId);
            object config = ResourceManager.Instance.GetEnemyConfig(prefabId);

            Debug.Trace("CreateEnemy");
            var entity = new Enemy();
            var obj    = EntityView.CreateEntity(entity, prefabId, position, prefab, config);

            entity.nav = obj.GetComponent <NavMeshAgentMono>();
            entity.nav.DoStart();
            entity.nav.enabled = false;
            entity.CBrain      = new CBrain();
            entity.CBrain.Init(entity, 0);
            obj.name = obj.name + enmeyID++;
            obj.name = obj.name + enmeyID++;
            return(entity);
        }
Beispiel #16
0
        T ParseData <T>(Deserializer reader) where T : BaseFormater, new()
        {
            T data = null;

            try {
                data = reader.Parse <T>();
                if (!reader.IsEnd)
                {
                    data = null;
                }
            }
            catch (Exception e) {
                Debug.LogError("Parse Msg Error:" + e);
                data = null;
            }

            return(data);
        }
Beispiel #17
0
 public void OnPlayerLeave(Player player)
 {
     Debug.Log($"Player{player.PlayerId} Leave room {RoomId}");
     _allPlayers.Remove(player);
     _localId2Player.Remove(player.localId);
     netId2LocalId.Remove(player.netID);
     if (netId2LocalId.Count == 0)
     {
         Console.WriteLine("All players left, stopping current simulation...");
         IsRunning = false;
         State     = ERoomState.Idle;
         _lobby.RemoveRoom(this);
     }
     else
     {
         Console.WriteLine(CurPlayerCount + " players remaining.");
     }
 }
        void UpdateAttack(LFloat deltaTime)
        {
            timer += deltaTime;
            if (timer >= timeBetweenAttacks && playerInRange && currentHealth > 0)
            {
                timer = LFloat.zero;
                if (player.currentHealth > 0)
                {
                    Debug.Trace($"{EntityId}Atk{player.EntityId}");
                    player.TakeDamage(attackDamage, player.transform.Pos3);
                }
            }

            if (player.currentHealth <= 0)
            {
                eventHandler.OnPlayerDied();
            }
        }
Beispiel #19
0
        protected void OnMsg_X2S_RepMasterInfo(Deserializer reader)
        {
            if (_netClientMS != null)
            {
                return;
            }
            var msg = reader.Parse <Msg_RepMasterInfo>();

            foreach (var serverInfo in msg.serverInfos)
            {
                if (serverInfo.serverType == (byte)serverType)
                {
                    Debug.Log("OnMsg_X2S_RepMasterInfo " + msg.ToString());
                    InitClientMS(serverInfo);
                }

                OnMasterServerInfo(serverInfo);
            }
        }
        public void OnGameCreate(int targetFps, byte localActorId, byte actorCount, bool isNeedRender = true)
        {
            FrameBuffer.__debugMainActorID = localActorId;
            var allActors = new byte[actorCount];

            for (byte i = 0; i < actorCount; i++)
            {
                allActors[i] = i;
            }

            Debug.Log($"GameCreate " + LocalActorId);

            //Init game status
            //_localActorId = localActorId;
            _allActors = allActors;
            _constStateService.LocalActorId = LocalActorId;
            _world.StartSimulate(_serviceContainer, _mgrContainer);
            EventHelper.Trigger(EEvent.LevelLoadProgress, 1f);
        }
Beispiel #21
0
        void OnNet_LoadingProgress(Player player, BaseFormater data)
        {
            if (State != ERoomState.PartLoading)
            {
                return;
            }
            var msg = data as Msg_LoadingProgress;

            if (playerLoadingProgress == null)
            {
                playerLoadingProgress = new byte[MaxPlayerCount];
            }

            playerLoadingProgress[player.localId] = msg.progress;

            Debug.Log($"palyer{player.localId} Load {msg.progress}");
            var isDone = true;

            foreach (var progress in playerLoadingProgress)
            {
                if (progress < 100)
                {
                    isDone = false;
                    break;
                }
            }

            var retmsg = new Msg_AllLoadingProgress();

            retmsg.isAllDone = isDone;
            retmsg.progress  = playerLoadingProgress;
            SendToAll(EMsgSC.G2C_LoadingProgress, retmsg);
            if (isDone)
            {
                for (int i = 0; i < playerLoadingProgress.Length; i++)
                {
                    playerLoadingProgress[i] = 0;
                }

                State = ERoomState.PartLoaded;
                Debug.Log("All Load done");
            }
        }
 public void CreatePlayer(byte actorId, int type){
     var bornPos = _gameConstStateService.playerBornPoss[actorId % _gameConstStateService.playerBornPoss.Count];
     var createPos = bornPos + base._gameConfigService.TankBornOffset;
     _gameEffectService.ShowBornEffect(createPos);
     _gameAudioService.PlayClipBorn();
     EDir dir = EDir.Up;
     DelayCall(base._gameConfigService.TankBornDelay, () => {
         var entity = CreateUnit(createPos, _gameConfigService.playerPrefabs, type, dir);
         var actor = _actorContext.GetEntityWithId(actorId);
         if (actor != null) {
             actor.ReplaceGameLocalId(entity.localId.value);
             entity.ReplaceActorId(actorId);
         }
         else {
             Debug.LogError(
                 $"can not find a actor after create a game player actorId:{actorId} localId{entity.localId.value}");
         }
     });
 }
            public void DoUpdate(float deltaTime)
            {
                _timer += deltaTime;
                if (_timer > _checkInterval)
                {
                    _timer = 0;
                    if (!hasMissTick)
                    {
                        var preSend = _cmdBuffer._maxPing * 1.0f / NetworkDefine.UPDATE_DELTATIME;
                        _targetPreSendTick = _targetPreSendTick * _oldPercent + preSend * (1 - _oldPercent);

                        var targetPreSendTick = LMath.Clamp((int)System.Math.Ceiling(_targetPreSendTick), 1, 60);
#if UNITY_EDITOR
                        //if (targetPreSendTick != _simulatorService.PreSendInputCount)
                        {
                            Debug.LogWarning(
                                $"Shrink preSend buffer old:{_simulatorService.PreSendInputCount} new:{_targetPreSendTick} " +
                                $"PING: min:{_cmdBuffer._minPing} max:{_cmdBuffer._maxPing} avg:{_cmdBuffer.PingVal}");
                        }
#endif
                        _simulatorService.PreSendInputCount = targetPreSendTick;
                    }

                    hasMissTick = false;
                }

                if (missTick != -1)
                {
                    var delayTick         = _simulatorService.TargetTick - missTick;
                    var targetPreSendTick =
                        _simulatorService.PreSendInputCount + (int)System.Math.Ceiling(delayTick * _incPercent);
                    targetPreSendTick = LMath.Clamp(targetPreSendTick, 1, 60);
#if UNITY_EDITOR
                    Debug.LogWarning(
                        $"Expend preSend buffer old:{_simulatorService.PreSendInputCount} new:{targetPreSendTick}");
#endif
                    _simulatorService.PreSendInputCount = targetPreSendTick;
                    nextCheckMissTick = _simulatorService.TargetTick;
                    missTick          = -1;
                    hasMissTick       = true;
                }
            }
Beispiel #24
0
        public void Initialize(IContext context)
        {
            _context.HasInit = true;
            var config   = _gameConfigService;
            int playerId = 0;
            var count    = _globalStateService.ActorCount;

            for (int i = 0; i < count; i++)
            {
                var obstacleInfo = config.PlayerInfos[i % config.PlayerInfos.Count];
                var entity       = _context.PostCmdCreatePlayerCube();
                entity->Transform.Position = obstacleInfo.Position;
                entity->Transform.Forward  = obstacleInfo.Forward;
                entity->Transform.Scale    = obstacleInfo.Scale;
                entity->Move           = obstacleInfo.MoveData;
                entity->Prefab.AssetId = obstacleInfo.AssetId;
                entity->Player.LocalId = playerId++; //
                Debug.Log("Create ObstacleInfos " + entity->Player.LocalId);
            }
        }
Beispiel #25
0
        public void OnPlayerEnter(Player player)
        {
            if (State == ERoomState.Idle)
            {
                State = ERoomState.WaitingToPlay;
            }
            if (State != ERoomState.WaitingToPlay)
            {
                return;
            }
            if (_allPlayers.Contains(player))
            {
                Debug.LogError("Player already exist" + player.PlayerId);
                return;
            }

            Debug.Log($"Player{player.PlayerId} Enter room {RoomId}");
            player.room = this;
            _allPlayers.Add(player);
        }
Beispiel #26
0
        public static void Gen(string[] args)
        {
            if (args == null || args.Length == 0)
            {
                args = new[] { "../Config/CodeGenerator/Config.json" };
            }

            if (args.Length > 0)
            {
                foreach (var path in args)
                {
                    Debug.Log(path);
                    CopyFilesByConfig(Path.Combine(Define.BaseDirectory, path));
                }
            }
            else
            {
                Debug.Log("Need config path");
            }
        }
Beispiel #27
0
        public void RollbackTo(int tick, int missFrameTick, bool isNeedClear = true)
        {
            if (tick < 0)
            {
                Debug.LogError("Target Tick invalid!" + tick);
                return;
            }

            Debug.Log($" curTick {Tick} RevertTo {tick} {missFrameTick} {isNeedClear}");
            _timeMachineService.RollbackTo(tick);
            _commonStateService.SetTick(tick);
            Tick = tick;
            var hash    = _commonStateService.Hash;
            var curHash = GetHash();

            if (hash != curHash)
            {
                Debug.LogError($"Rollback error: Hash isDiff oldHash ={hash}  curHash{curHash}");
            }
        }
        public override void OnEntityCreated(Context f, Lockstep.UnsafeECS.Entity *pEntity)
        {
            if (pEntity == null)
            {
                int i = 0;
                Debug.LogError("OnEntityCreated null");
                return;
            }

            if (pEntity->TypeId != EntityIds.Boid)
            {
                //Debug.LogError("OnEntityCreated not a Enemy" + pEntity->EnumType());
                return;
            }

            var pBoid = (Boid *)pEntity;

            if (_entityPrefabs == null)
            {
                //TODO read config to setup Entity Prefabs
                var _spawners = GameObject.FindObjectsOfType <SSSamples.Boids.Authoring.SpawnRandomInSphere>();
                _entityManager = Unity.Entities.World.Active.EntityManager;
                _entityPrefabs = new Unity.Entities.Entity[_spawners.Length];
                for (int i = 0; i < _spawners.Length; i++)
                {
                    _entityPrefabs[i] = _spawners[i].PrefabEntity;
                }
            }

            var uEntity = _entityManager.Instantiate(_entityPrefabs[pBoid->AssetData.AssetId]);

            _id2GameObject[pEntity->LocalId] = uEntity;
            _entityManager.SetComponentData(uEntity, new Unity.Transforms.LocalToWorld {
                Value = float4x4.TRS(
                    pBoid->LocalToWorld.Position.ToVector3(),
                    //quaternion.identity,
                    quaternion.LookRotationSafe(pBoid->LocalToWorld.Forward.ToVector3(), Unity.Mathematics.math.up()),
                    new float3(1.0f, 1.0f, 1.0f))
            });
            _entityManager.AddComponentData(uEntity, pEntity->_ref);
        }
        public override void DoStart()
        {
            if (_instance != this)
            {
                Debug.LogError("Duplicate CollisionSystemAdapt!");
                return;
            }

            var collisionSystem = new CollisionSystem()
            {
                worldSize    = worldSize,
                pos          = pos,
                minNodeSize  = minNodeSize,
                loosenessval = loosenessval
            };

            Debug.Trace($"worldSize:{worldSize} pos:{pos} minNodeSize:{minNodeSize} loosenessval:{loosenessval}");
            this.collisionSystem = collisionSystem;
            collisionSystem.DoStart(collisionMatrix, allTypes);
            collisionSystem.funcGlobalOnTriggerEvent += GlobalOnTriggerEvent;
        }
        public void Upgrade(IEntity iEntity){
            var entity = iEntity as GameEntity;
            var playerCount = _gameConfigService.playerPrefabs.Count;
            var targetType = entity.unit.detailType + 1;
            if (targetType >= playerCount) {
                Debug.Log($"hehe already max level can not upgrade");
                return;
            }

            var ecsPrefab = _gameConfigService.playerPrefabs[targetType] as ConfigUnit;
            var rawPos = entity.pos.value;
            var rawDir = entity.dir.value;
            ecsPrefab.SetComponentsTo(entity);
            entity.pos.value = rawPos;
            entity.dir.value = rawDir;
            if (!_constStateService.IsVideoLoading) {
                _viewService.DeleteView(entity.localId.value);
                _viewService.BindView(entity, (ushort) ecsPrefab.asset.assetId, rawPos,
                    DirUtil.GetDirDeg(rawDir));
            }
        }