Ejemplo n.º 1
0
 public static void RegisterMachineType(string machineType, MachineSettings callback)
 {
     PandaLogger.Log(machineType + " Registered as a Machine Type!");
     _machineCallbacks[machineType] = callback;
 }
Ejemplo n.º 2
0
        public static void SaveOffline(Colony colony)
        {
            if (colony.OwnerIsOnline())
            {
                return;
            }

            try
            {
                var folder = $"{GameLoader.GAMEDATA_FOLDER}/savegames/{ServerManager.WorldName}/NPCArchive/";

                if (!Directory.Exists(folder))
                {
                    Directory.CreateDirectory(folder);
                }

                var file = $"{folder}{colony.ColonyID}.json";

                if (!SettlersConfiguration.OfflineColonies)
                {
                    if (!JSON.Deserialize(file, out var followers, false))
                    {
                        followers = new JSONNode(NodeType.Array);
                    }

                    followers.ClearChildren();

                    PandaLogger.Log(ChatColor.cyan, $"All players from {colony.ColonyID} have disconnected. Clearing colony until reconnect.");

                    var copyOfFollowers = new List <NPCBase>();

                    foreach (var follower in colony.Followers)
                    {
                        JSONNode jobloc = null;

                        if (follower.IsValid)
                        {
                            var job = follower.Job;

                            if (job != null && job.GetJobLocation() != Vector3Int.invalidPos)
                            {
                                jobloc = (JSONNode)job.GetJobLocation();
                                follower.ClearJob();
                            }
                        }

                        if (follower.TryGetJSON(out var node))
                        {
                            if (jobloc != null)
                            {
                                node.SetAs("JobPoS", jobloc);
                            }

                            ModLoader.Callbacks.OnNPCSaved.Invoke(follower, node);
                            followers.AddToArray(node);
                            copyOfFollowers.Add(follower);
                        }
                    }

                    JSON.Serialize(file, followers);

                    foreach (var deadMan in copyOfFollowers)
                    {
                        deadMan.OnDeath();
                    }

                    colony.ForEachOwner(o => MonsterTracker.KillAllZombies(o));
                }
            }
            catch (Exception ex)
            {
                PandaLogger.LogError(ex);
            }
        }
Ejemplo n.º 3
0
        public static void OnNPCRecruited(NPCBase npc)
        {
            try
            {
                if (npc.CustomData == null)
                {
                    npc.CustomData = new JSONNode();
                }

                if (npc.CustomData.TryGetAs(ISSETTLER, out bool settler) && settler)
                {
                    return;
                }

                var ps = ColonyState.GetColonyState(npc.Colony);

                if (ps.SettlersEnabled)
                {
                    if (Configuration.GetorDefault("ColonistsRecruitment", true))
                    {
                        if (ps.SettlersEnabled && npc.Colony.FollowerCount > MAX_BUYABLE)
                        {
                            var cost = Configuration.GetorDefault("CompoundingFoodRecruitmentCost", 2) * ps.ColonistsBought;
                            var num  = 0f;

                            if (cost < 1)
                            {
                                cost = 1;
                            }

                            if (npc.Colony.Stockpile.TotalFood < cost ||
                                !npc.Colony.Stockpile.TryRemoveFood(ref num, cost))
                            {
                                PandaChat.Send(npc.Colony, $"Could not recruit a new colonist; not enough food in stockpile. {cost + ServerManager.ServerSettings.NPCs.RecruitmentCost} food required.", ChatColor.red);
                                npc.Colony.HappinessData.RecruitmentCostCalculator.GetCost(npc.Colony.HappinessData.CachedHappiness, npc.Colony, out float foodCost);

                                if (ItemTypes.TryGetType(ColonyBuiltIn.ItemTypes.BREAD.Name, out var bread))
                                {
                                    npc.Colony.Stockpile.Add(ColonyBuiltIn.ItemTypes.BREAD, (int)Math.Floor(foodCost / bread.FoodValue));
                                }

                                npc.health = 0;
                                npc.Update();
                                return;
                            }

                            ps.ColonistsBought++;
                            ps.NextColonistBuyTime = TimeCycle.TotalTime.Value.Hours + 24;
                        }

                        SettlerInventory.GetSettlerInventory(npc);
                        UpdateFoodUse(ps);
                    }
                    else
                    {
                        PandaChat.Send(npc.Colony, "The server administrator has disabled recruitment of colonists while settlers are enabled.");
                    }
                }
            }
            catch (Exception ex)
            {
                PandaLogger.LogError(ex);
            }
        }
Ejemplo n.º 4
0
        public void AddItemTypes(Dictionary <string, ItemTypesServer.ItemTypeRaw> itemTypes)
        {
            var i = 0;
            Dictionary <string, ICSType> loadedItems = new Dictionary <string, ICSType>();

            foreach (var item in LoadedAssembalies)
            {
                try
                {
                    if (Activator.CreateInstance(item) is ICSType itemType &&
                        !string.IsNullOrEmpty(itemType.name))
                    {
                        loadedItems[itemType.name] = itemType;

                        var permutations = ConnectedBlockCalculator.GetPermutations(itemType);

                        foreach (var permutation in permutations)
                        {
                            loadedItems[permutation.name] = permutation;
                        }
                    }
                }
                catch (Exception ex)
                {
                    PandaLogger.LogError(ex);
                }
            }

            var settings = GameLoader.GetJSONSettingPaths(GameLoader.NAMESPACE + ".CSItems");

            foreach (var modInfo in settings)
            {
                foreach (var path in modInfo.Value)
                {
                    try
                    {
                        var jsonFile = JSON.Deserialize(modInfo.Key + "/" + path);

                        if (jsonFile.NodeType == NodeType.Object && jsonFile.ChildCount > 0)
                        {
                            foreach (var item in jsonFile.LoopObject())
                            {
                                foreach (var property in _fixRelativePaths)
                                {
                                    if (item.Value.TryGetAs(property, out string propertyPath) && propertyPath.StartsWith("./"))
                                    {
                                        item.Value[property] = new JSONNode(modInfo.Key + "/" + propertyPath.Substring(2));
                                    }
                                }

                                if (item.Value.TryGetAs("Durability", out int durability))
                                {
                                    var ma = item.Value.JsonDeerialize <MagicArmor>();
                                    loadedItems[ma.name] = ma;
                                }
                                else if (item.Value.TryGetAs("WepDurability", out bool wepDurability))
                                {
                                    var mw = item.Value.JsonDeerialize <MagicWeapon>();
                                    loadedItems[mw.name] = mw;
                                }
                                else if (item.Value.TryGetAs("IsMagical", out bool isMagic))
                                {
                                    var mi = item.Value.JsonDeerialize <PlayerMagicItem>();
                                    loadedItems[mi.name] = mi;
                                }
                                else
                                {
                                    var newItem = item.Value.JsonDeerialize <CSType>();
                                    loadedItems[newItem.name] = newItem;
                                    var permutations = ConnectedBlockCalculator.GetPermutations(newItem);

                                    foreach (var permutation in permutations)
                                    {
                                        loadedItems[permutation.name] = permutation;
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        PandaLogger.LogError(ex);
                    }
                }
            }

            foreach (var itemType in loadedItems.Values)
            {
                ConnectedBlockSystem.AddConnectedBlock(itemType);

                var rawItem = new ItemTypesServer.ItemTypeRaw(itemType.name, itemType.JsonSerialize());

                if (itemTypes.ContainsKey(itemType.name))
                {
                    PandaLogger.Log(ChatColor.yellow, "Item {0} already loaded...Overriding item.", itemType.name);
                    itemTypes[itemType.name] = rawItem;
                }
                else
                {
                    itemTypes.Add(itemType.name, rawItem);
                }

                if (itemType.StaticItemSettings != null && !string.IsNullOrWhiteSpace(itemType.StaticItemSettings.Name))
                {
                    StaticItems.List.Add(itemType.StaticItemSettings);
                }

                if (itemType is IPlayerMagicItem pmi)
                {
                    MagicItemsCache.PlayerMagicItems[pmi.name] = pmi;
                }

                if (itemType.OpensMenuSettings != null && !string.IsNullOrEmpty(itemType.OpensMenuSettings.ItemName))
                {
                    Help.UIManager.OpenMenuItems.Add(itemType.OpensMenuSettings);
                }

                _sb.Append($"{itemType.name}, ");
                i++;

                if (i > 5)
                {
                    _sb.Append("</color>");
                    i = 0;
                    _sb.AppendLine();
                    _sb.Append("<color=lime>");
                }
            }
        }
Ejemplo n.º 5
0
        private static bool EvaluateBeds(Players.Player p)
        {
            var update = false;

            try
            {
                if (!TimeCycle.IsDay && Time.SecondsSinceStartDouble > _nextbedTime)
                {
                    if (p.IsConnected)
                    {
                        var colony        = Colony.Get(p);
                        var state         = PlayerState.GetPlayerState(p);
                        var remainingBeds = BedBlockTracker.GetCount(p) - colony.FollowerCount;
                        var left          = 0;

                        if (remainingBeds >= 0)
                        {
                            state.NeedsABed = 0;
                        }
                        else
                        {
                            if (state.NeedsABed == 0)
                            {
                                state.NeedsABed = Time.SecondsSinceStartDouble + LOABOROR_LEAVE_HOURS;
                                PandaChat.Send(p, SettlerReasoning.GetNeedBed(), ChatColor.grey);
                            }

                            if (state.NeedsABed != 0 && state.NeedsABed < TimeCycle.TotalTime)
                            {
                                foreach (var follower in colony.Followers)
                                {
                                    if (follower.GetFieldValue <BedBlock, NPCBase>("bed") == null)
                                    {
                                        left++;
                                        NPCLeaving(follower);
                                    }
                                }

                                state.NeedsABed = 0;
                            }

                            if (left > 0)
                            {
                                PandaChat.Send(p,
                                               string.Concat(SettlerReasoning.GetNoBed(),
                                                             string.Format(" {0} colonists have left your colony.",
                                                                           left)), ChatColor.red);

                                update = true;
                            }
                        }

                        colony.SendUpdate();
                    }

                    _nextbedTime = Time.SecondsSinceStartDouble + Random.Next(5, 8) * TimeCycle.SecondsPerHour;
                }
            }
            catch (Exception ex)
            {
                PandaLogger.LogError(ex, "EvaluateBeds");
            }

            return(update);
        }
Ejemplo n.º 6
0
        public static void ProcesssCallToArms(Players.Player player, Colony colony)
        {
            var state = ColonyState.GetColonyState(colony);

            state.CallToArmsEnabled = !state.CallToArmsEnabled;

            if (!_Jobs.ContainsKey(colony))
            {
                _Jobs.Add(colony, new Dictionary <NPCBase, IJob>());
            }

            try
            {
                if (state.CallToArmsEnabled)
                {
                    PandaChat.Send(player, "Call to arms activated!", ChatColor.red, ChatStyle.bold);


                    foreach (var follower in colony.Followers)
                    {
                        var job = follower.Job;

                        if (job != null && CantCallToArms(job))
                        {
                            continue;
                        }

                        try
                        {
                            if (job != null)
                            {
                                if (job.GetType() != typeof(CalltoArmsJob))
                                {
                                    _Jobs[colony][follower] = job;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            PandaLogger.LogError(ex);
                        }

                        var armsJob = new CalltoArmsJob();
                        follower.TakeJob(armsJob);
                    }
                }
                else
                {
                    PandaChat.Send(player, "Call to arms deactivated.", ChatColor.green, ChatStyle.bold);
                    var assignedWorkers = new List <NPCBase>();

                    foreach (var follower in colony.Followers)
                    {
                        var job = follower.Job;

                        if (job != null && job.GetType() == typeof(CalltoArmsJob))
                        {
                            follower.ClearJob();
                        }

                        if (_Jobs[colony].ContainsKey(follower) && _Jobs[colony][follower].NeedsNPC)
                        {
                            assignedWorkers.Add(follower);
                            follower.TakeJob(_Jobs[colony][follower]);
                        }
                    }

                    _Jobs[colony].Clear();
                }
            }
            catch (Exception ex)
            {
                PandaLogger.LogError(ex);
            }

            colony.SendCommonData();
        }
Ejemplo n.º 7
0
        public static void OnUpdate()
        {
            if (!World.Initialized || AIManager.IsBusy())
            {
                return;
            }

            var secondsSinceStartDouble = Time.SecondsSinceStartDouble;

            if (_nextUpdateTime < secondsSinceStartDouble)
            {
                IMonster m = null;

                foreach (var monster in GetAllMonsters())
                {
                    if (m == null || Vector3.Distance(monster.Value.Position, m.Position) > 15 && Random.NextBool())
                    {
                        m = monster.Value;
                        ServerManager.SendAudio(monster.Value.Position, GameLoader.NAMESPACE + ".ZombieAudio");
                    }
                }

                _nextUpdateTime = secondsSinceStartDouble + 5;
            }

            IPandaBoss bossType = null;

            if (World.Initialized &&
                !AIManager.IsBusy())
            {
                if (!BossActive &&
                    _nextBossUpdateTime <= secondsSinceStartDouble)
                {
                    BossActive = true;
                    bossType   = GetMonsterType();

                    if (Players.CountConnected != 0)
                    {
                        PandaLogger.Log(ChatColor.yellow, $"Boss Active! Boss is: {bossType.Name}");
                    }
                }

                if (BossActive)
                {
                    var turnOffBoss   = true;
                    var worldSettings = ServerManager.WorldSettings;

                    Dictionary <PlayerState, List <Banner> > banners = new Dictionary <PlayerState, List <Banner> >();
                    var spawnBanners = new List <Banner>();

                    for (var i = 0; i < BannerTracker.GetCount(); i++)
                    {
                        if (BannerTracker.TryGetAtIndex(i, out var newBanner))
                        {
                            var bps = PlayerState.GetPlayerState(newBanner.Owner);

                            if (!banners.ContainsKey(bps))
                            {
                                banners.Add(bps, new List <Banner>());
                            }

                            banners[bps].Add(newBanner);
                        }
                    }


                    foreach (var bkvp in banners)
                    {
                        if (bkvp.Value.Count > 1)
                        {
                            var next = Pipliz.Random.Next(bkvp.Value.Count);
                            spawnBanners.Add(bkvp.Value[next]);
                        }
                        else if (bkvp.Value.Count == 1)
                        {
                            spawnBanners.Add(bkvp.Value[0]);
                        }
                    }

                    foreach (var bannerGoal in spawnBanners)
                    {
                        var ps     = PlayerState.GetPlayerState(bannerGoal.Owner);
                        var colony = Colony.Get(ps.Player);

                        if (ps.BossesEnabled &&
                            ps.Player.IsConnected &&
                            colony.FollowerCount > Configuration.GetorDefault("MinColonistsCountForBosses", 15))
                        {
                            if (bossType != null &&
                                !_spawnedBosses.ContainsKey(ps))
                            {
                                Vector3Int positionFinal;
                                switch (MonsterSpawner.TryGetSpawnLocation(bannerGoal, 500f, out positionFinal))
                                {
                                case MonsterSpawner.ESpawnResult.Success:
                                    if (AIManager.ZombiePathFinder.TryFindPath(positionFinal, bannerGoal.KeyLocation, out var path, 2000000000) == EPathFindingResult.Success)
                                    {
                                        var pandaboss = bossType.GetNewBoss(path, ps.Player);
                                        _spawnedBosses.Add(ps, pandaboss);

                                        BossSpawned?.Invoke(MonsterTracker.MonsterSpawner,
                                                            new BossSpawnedEvent(ps, pandaboss));

                                        ModLoader.TriggerCallbacks <IMonster>(ModLoader.EModCallbackType.OnMonsterSpawned,
                                                                              pandaboss);

                                        MonsterTracker.Add(pandaboss);
                                        colony.OnZombieSpawn(true);
                                        ps.FaiedBossSpawns = 0;

                                        PandaChat.Send(ps.Player, $"[{pandaboss.Name}] {pandaboss.AnnouncementText}",
                                                       ChatColor.red);

                                        if (!string.IsNullOrEmpty(pandaboss.AnnouncementAudio))
                                        {
                                            ServerManager.SendAudio(ps.Player.Position, pandaboss.AnnouncementAudio);
                                        }
                                    }

                                    break;

                                case MonsterSpawner.ESpawnResult.NotLoaded:
                                case MonsterSpawner.ESpawnResult.Impossible:
                                    colony.OnZombieSpawn(true);
                                    break;

                                case MonsterSpawner.ESpawnResult.Fail:
                                    CantSpawnBoss(ps, colony);
                                    break;
                                }

                                if (_spawnedBosses.ContainsKey(ps) &&
                                    _spawnedBosses[ps].IsValid &&
                                    _spawnedBosses[ps].CurrentHealth > 0)
                                {
                                    if (ps.Player.GetTempValues(true).GetOrDefault("BossIndicator", 0) <
                                        Time.SecondsSinceStartInt)
                                    {
                                        Indicator.SendIconIndicatorNear(new Vector3Int(_spawnedBosses[ps].Position),
                                                                        _spawnedBosses[ps].ID,
                                                                        new IndicatorState(1, GameLoader.Poisoned_Icon,
                                                                                           false, false));

                                        ps.Player.GetTempValues(true)
                                        .Set("BossIndicator", Time.SecondsSinceStartInt + 1);
                                    }

                                    turnOffBoss = false;
                                }
                            }
                        }


                        if (turnOffBoss)
                        {
                            if (Players.CountConnected != 0 && _spawnedBosses.Count != 0)
                            {
                                PandaLogger.Log(ChatColor.yellow, $"All bosses cleared!");
                                var boss = _spawnedBosses.FirstOrDefault().Value;
                                PandaChat.SendToAll($"[{boss.Name}] {boss.DeathText}", ChatColor.red);
                            }

                            BossActive = false;
                            _spawnedBosses.Clear();
                            GetNextBossSpawnTime();
                        }
                    }
                }
            }
        }
Ejemplo n.º 8
0
        public static void SaveOffline(Players.Player p)
        {
            if (p.ID == null || p.ID.steamID == null)
            {
                return;
            }

            try
            {
                var folder = $"{GameLoader.GAMEDATA_FOLDER}/savegames/{ServerManager.WorldName}/players/NPCArchive/";

                if (!Directory.Exists(folder))
                {
                    Directory.CreateDirectory(folder);
                }

                var file = $"{folder}{p.ID.steamID.ToString()}.json";

                if (!Configuration.OfflineColonies)
                {
                    if (!JSON.Deserialize(file, out var followers, false))
                    {
                        followers = new JSONNode(NodeType.Array);
                    }

                    followers.ClearChildren();

                    PandaLogger.Log(ChatColor.cyan,
                                    $"Player {p.ID.steamID} is disconnected. Clearing colony until reconnect.");

                    var colony          = Colony.Get(p);
                    var copyOfFollowers = new List <NPCBase>();

                    foreach (var follower in colony.Followers)
                    {
                        JSONNode jobloc = null;

                        if (follower.IsValid)
                        {
                            var job = follower.Job;

                            if (job != null && job.KeyLocation != Vector3Int.invalidPos)
                            {
                                jobloc  = (JSONNode)job.KeyLocation;
                                job.NPC = null;
                                follower.ClearJob();
                            }
                        }

                        if (follower.TryGetJSON(out var node))
                        {
                            if (jobloc != null)
                            {
                                node.SetAs("JobPoS", jobloc);
                            }

                            ModLoader.TriggerCallbacks(ModLoader.EModCallbackType.OnNPCSaved, follower, node);
                            followers.AddToArray(node);
                            copyOfFollowers.Add(follower);
                        }
                    }

                    JSON.Serialize(file, followers);

                    foreach (var deadMan in copyOfFollowers)
                    {
                        deadMan.OnDeath();
                    }

                    MonsterTracker.KillAllZombies(p);
                }
            }
            catch (Exception ex)
            {
                PandaLogger.LogError(ex);
            }
        }
Ejemplo n.º 9
0
        public static bool OnTryChangeBlockUser(ModLoader.OnTryChangeBlockUserData d)
        {
            if (d.typeTillNow == PatrolFlag.ItemIndex)
            {
                Knight toRemove = default(Knight);

                var state     = PlayerState.GetPlayerState(d.requestedBy);
                var stockpile = Stockpile.GetStockPile(d.requestedBy);

                if (!Knight.Knights.ContainsKey(d.requestedBy))
                {
                    Knight.Knights.Add(d.requestedBy, new List <Knight>());
                }

                foreach (var knight in Knight.Knights[d.requestedBy])
                {
                    try
                    {
                        if (knight.PatrolPoints.Contains(d.voxelHit))
                        {
                            knight.OnRemove();

                            foreach (var flagPoint in knight.PatrolPoints)
                            {
                                if (flagPoint != d.voxelHit)
                                {
                                    if (World.TryGetTypeAt(flagPoint, out var objType) && objType == PatrolFlag.ItemIndex)
                                    {
                                        ServerManager.TryChangeBlock(flagPoint, BuiltinBlocks.Air);
                                        stockpile.Add(PatrolFlag.ItemIndex);
                                    }
                                }
                            }

                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        PandaLogger.LogError(ex);
                    }
                }

                if (toRemove != default(Knight))
                {
                    PandaChat.Send(d.requestedBy, $"Patrol with {toRemove.PatrolPoints.Count} patrol points no longer active.", ChatColor.orange);
                    Knight.Knights[d.requestedBy].Remove(toRemove);

                    if (((JobTracker.JobFinder)JobTracker.GetOrCreateJobFinder(d.requestedBy)).openJobs.Contains(toRemove))
                    {
                        ((JobTracker.JobFinder)JobTracker.GetOrCreateJobFinder(d.requestedBy)).openJobs.Remove(toRemove);
                    }

                    JobTracker.Update();
                }

                if (state.FlagsPlaced.Contains(d.voxelHit))
                {
                    state.FlagsPlaced.Remove(d.voxelHit);
                    ServerManager.TryChangeBlock(d.voxelHit, BuiltinBlocks.Air);
                }

                stockpile.Add(PatrolFlag.ItemIndex);
            }

            return(true);
        }
Ejemplo n.º 10
0
 public static void RegisterMachineType(IMachineSettings callback)
 {
     PandaLogger.Log(callback.Name + " Registered as a Machine!");
     MachineCallbacks[callback.Name] = callback;
 }
Ejemplo n.º 11
0
        public static void RewindPlayersBlocks(Players.Player player)
        {
            foreach (var colony in player.Colonies)
            {
                if (colony.Owners.Length == 1)
                {
                    RewindColonyBlocks(colony);
                }
            }

            Task.Run(() =>
            {
                var playerId = player.ID.ToString();

                try
                {
                    using (TrackedPositionContext db = new TrackedPositionContext())
                    {
                        foreach (var trackedPos in db.Positions.Where(p => p.PlayerId == playerId))
                        {
                            var oldest = db.Positions.Where(o => o.X == trackedPos.X && o.Y == trackedPos.Y && o.Z == trackedPos.Z && o.TimeTracked < trackedPos.TimeTracked).OrderBy(tp => tp.TimeTracked).FirstOrDefault();

                            if (oldest == default(TrackedPosition))
                            {
                                oldest = trackedPos;
                            }

                            if (!_queuedPositions.Any(pos => pos.Equals(oldest)))
                            {
                                lock (_queuedPositions)
                                    _queuedPositions.Add(oldest);

                                ChunkQueue.QueuePlayerRequest(oldest.GetVector().ToChunk(), player);
                            }
                        }

                        if (_queuedPositions.Count <= 0)
                        {
                            return;
                        }

                        System.Threading.Thread.Sleep(10000);

                        List <TrackedPosition> replaced = new List <TrackedPosition>();

                        foreach (var trackedPos in _queuedPositions)
                        {
                            if (ServerManager.TryChangeBlock(trackedPos.GetVector(), (ushort)trackedPos.BlockId) == EServerChangeBlockResult.Success)
                            {
                                replaced.Add(trackedPos);
                            }
                        }

                        lock (_queuedPositions)
                        {
                            db.Positions.RemoveRange(_queuedPositions);
                            foreach (var replace in replaced)
                            {
                                _queuedPositions.Remove(replace);
                            }
                        }

                        db.SaveChanges();
                    }
                }
                catch (DbEntityValidationException e)
                {
                    ProcessEntityException(e);
                }
                catch (Exception ex)
                {
                    PandaLogger.LogError(ex);
                }
            });
        }
Ejemplo n.º 12
0
        public static async void RewindColonyBlocks(Colony colony)
        {
            foreach (var npc in colony.Followers.ToList())
            {
                npc.health = 0;

                if (npc.Job is IAreaJob areaJob)
                {
                    AreaJobTracker.RemoveJob(areaJob);
                }

                npc.ClearJob();
                npc.OnDeath();
            }

            RoamingJobManager.Objectives.Remove(colony);

            ServerManager.ColonyTracker.ColoniesLock.EnterWriteLock();
            ServerManager.ColonyTracker.ColoniesByID.Remove(colony.ColonyID);
            Colony newcolony = new Colony(colony.ColonyID);

            newcolony.Stockpile.AddEnumerable(from unresolved in ServerManager.WorldSettingsReadOnly.InitialStockpile
                                              select new InventoryItem(unresolved.type, unresolved.amount));
            ServerManager.ColonyTracker.ColoniesByID.Add(newcolony.ColonyID, newcolony);
            ServerManager.ColonyTracker.ColoniesLock.ExitWriteLock();
            ServerManager.ColonyTracker.Save();

            await Task.Run(() =>
            {
                try
                {
                    var colonyName = colony.Name;

                    using (TrackedPositionContext db = new TrackedPositionContext())
                    {
                        foreach (var trackedPos in db.Positions.Where(p => p.ColonyId == colonyName))
                        {
                            var oldest = db.Positions.Where(o => o.X == trackedPos.X && o.Y == trackedPos.Y && o.Z == trackedPos.Z && o.TimeTracked < trackedPos.TimeTracked).OrderBy(tp => tp.TimeTracked).FirstOrDefault();

                            if (oldest == default(TrackedPosition))
                            {
                                oldest = trackedPos;
                            }

                            if (!_queuedPositions.Any(pos => pos.Equals(oldest)))
                            {
                                lock (_queuedPositions)
                                    _queuedPositions.Add(oldest);

                                ChunkQueue.QueuePlayerRequest(oldest.GetVector().ToChunk(), colony.Owners.FirstOrDefault());
                            }
                        }

                        if (_queuedPositions.Count <= 0)
                        {
                            return;
                        }

                        System.Threading.Thread.Sleep(10000);

                        List <TrackedPosition> replaced = new List <TrackedPosition>();

                        foreach (var trackedPos in _queuedPositions)
                        {
                            if (ServerManager.TryChangeBlock(trackedPos.GetVector(), (ushort)trackedPos.BlockId) == EServerChangeBlockResult.Success)
                            {
                                replaced.Add(trackedPos);
                            }
                        }

                        lock (_queuedPositions)
                        {
                            db.Positions.RemoveRange(_queuedPositions);
                            foreach (var replace in replaced)
                            {
                                _queuedPositions.Remove(replace);
                            }
                        }

                        db.SaveChanges();
                    }
                }
                catch (DbEntityValidationException e)
                {
                    ProcessEntityException(e);
                }
                catch (Exception ex)
                {
                    PandaLogger.LogError(ex);
                }
            });
        }
Ejemplo n.º 13
0
        public static bool EvaluateSettlers(ColonyState state)
        {
            var update = false;

            if (state.ColonyRef.OwnerIsOnline())
            {
                if (state.NextGenTime == 0)
                {
                    state.NextGenTime = Time.SecondsSinceStartDouble + Random.Next(8, 16) * IN_GAME_HOUR_IN_SECONDS;
                }

                if (Time.SecondsSinceStartDouble > state.NextGenTime && state.ColonyRef.FollowerCount >= MAX_BUYABLE)
                {
                    var chance =
                        state.ColonyRef.TemporaryData.GetAsOrDefault(PandaResearch.GetResearchKey(PandaResearch.SettlerChance), 0f) +
                        state.Difficulty.AdditionalChance;

                    chance += SettlerEvaluation.SpawnChance(state);

                    var rand = Random.NextFloat();

                    if (chance > rand)
                    {
                        var addCount = Math.Floor(state.MaxPerSpawn * chance);

                        // if we lost alot of colonists add extra to help build back up.
                        if (state.ColonyRef.FollowerCount < state.HighestColonistCount)
                        {
                            var diff = state.HighestColonistCount - state.ColonyRef.FollowerCount;
                            addCount += Math.Floor(diff * .25);
                        }

                        try
                        {
                            var skillChance = state.ColonyRef.TemporaryData.GetAsOrDefault(PandaResearch.GetResearchKey(PandaResearch.SkilledLaborer), 0f);
                            var numbSkilled = 0;
                            rand = Random.NextFloat();

                            try
                            {
                                if (skillChance > rand)
                                {
                                    numbSkilled = Pipliz.Random.Next(1,
                                                                     2 + Pipliz.Math.RoundToInt(state.ColonyRef.TemporaryData.GetAsOrDefault(PandaResearch.GetResearchKey(PandaResearch.NumberSkilledLaborer), 0f)));
                                }
                            }
                            catch (Exception ex)
                            {
                                PandaLogger.Log("NumberSkilledLaborer");
                                PandaLogger.LogError(ex);
                            }


                            if (addCount > 0)
                            {
                                if (addCount > 30)
                                {
                                    addCount = 30;
                                }

                                var reason = string.Format(SettlerReasoning.GetSettleReason(), addCount);

                                if (numbSkilled > 0)
                                {
                                    if (numbSkilled == 1)
                                    {
                                        reason += string.Format(" {0} of them is skilled!", numbSkilled);
                                    }
                                    else
                                    {
                                        reason += string.Format(" {0} of them are skilled!", numbSkilled);
                                    }
                                }

                                PandaChat.Send(state.ColonyRef, reason, ChatColor.magenta);

                                for (var i = 0; i < addCount; i++)
                                {
                                    var newGuy = new NPCBase(state.ColonyRef, state.ColonyRef.GetRandomBanner().Position);

                                    NPCTracker.Add(newGuy);
                                    state.ColonyRef.RegisterNPC(newGuy);
                                    SettlerInventory.GetSettlerInventory(newGuy);
                                    newGuy.CustomData.SetAs(ISSETTLER, true);

                                    if (i <= numbSkilled)
                                    {
                                        newGuy.CustomData.SetAs(GameLoader.ALL_SKILLS, Random.Next(1, 10) * 0.002f);
                                    }

                                    update = true;
                                    ModLoader.TriggerCallbacks(ModLoader.EModCallbackType.OnNPCRecruited, newGuy);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            PandaLogger.Log("SkilledLaborer");
                            PandaLogger.LogError(ex);
                        }

                        if (state.ColonyRef.FollowerCount > state.HighestColonistCount)
                        {
                            state.HighestColonistCount = state.ColonyRef.FollowerCount;
                        }
                    }


                    state.NextGenTime = Time.SecondsSinceStartDouble + Random.Next(8, 16) * IN_GAME_HOUR_IN_SECONDS;

                    state.ColonyRef.SendCommonData();
                }
            }

            return(update);
        }
Ejemplo n.º 14
0
        //Ref menu is added for change LocalStorage -> avoid client error
        public static bool LoadItem(JSONNode item, ref NetworkMenu menu, Players.Player player, out List <IItem> menuItem)
        {
            string itemType = item.GetAs <string>("type").Trim().ToLower();
            bool   found    = false;

            menuItem = null;

            switch (itemType)
            {
            case "label":
            {
                menuItem = new List <IItem>()
                {
                    new Label(GetLabelData(item)).ApplyPosition(item)
                };
                found = true;
            }
            break;

            case "space":
            {
                item.TryGetAsOrDefault <int>("height", out int height, 10);
                menuItem = new List <IItem>()
                {
                    new EmptySpace(height).ApplyPosition(item)
                };
                found = true;
            }
            break;

            case "line":
            {
                UnityEngine.Color color = UnityEngine.Color.black;

                if (item.HasChild("color"))
                {
                    color = GetColor(item.GetAs <string>("color"));
                }

                item.TryGetAsOrDefault <int>("height", out int height, 4);
                item.TryGetAsOrDefault <int>("width", out int width, -1);

                menuItem = new List <IItem>()
                {
                    new Line(color, height, width).ApplyPosition(item)
                };
                found = true;
            }
            break;

            case "icon":
            {
                item.TryGetAsOrDefault <string>("name", out string icon, "missingerror");
                menuItem = new List <IItem>()
                {
                    new ItemIcon(icon).ApplyPosition(item)
                };
                found = true;
            }
            break;

            case "jobrecipies":
            {
                if (item.TryGetAs("job", out string job))
                {
                    List <Recipes.Recipe> recipes = new List <Recipes.Recipe>();
                    menuItem = new List <IItem>();

                    if (ServerManager.RecipeStorage.RecipesPerLimitType.TryGetValue(job, out var recipesDefault))
                    {
                        recipes.AddRange(recipesDefault);
                    }

                    foreach (var recipe in recipes.OrderBy(r => r.Name))
                    {
                        menuItem.Add(RecipeLines(menu, player, recipe, item));
                    }

                    found = true;
                }
            }
            break;

            case "item":
            {
                if (!item.HasChild("name"))
                {
                    PandaLogger.Log("Item: Not name defined");
                    return(found);
                }

                item.TryGetAs <string>("name", out string name);

                if (!ItemTypes.IndexLookup.TryGetIndex(name, out ushort index))
                {
                    PandaLogger.Log("Item: Not item found with name: " + name);
                    return(found);
                }

                if (!Localization.TryGetSentence(player.LastKnownLocale, _localizationHelper.GetLocalizationKey("ItemDetails." + name), out var extendedDetail))
                {
                    extendedDetail = "";
                }
                else
                {
                    extendedDetail = Environment.NewLine + extendedDetail;
                }

                if (Localization.TryGetType(player.LastKnownLocale, index, out string localeName) && Localization.TryGetTypeUse(player.LastKnownLocale, index, out var description))
                {
                    menuItem = new List <IItem>()
                    {
                        new HorizontalSplit(new ItemIcon(index), new Label(new LabelData(localeName + Environment.NewLine + description + extendedDetail, UnityEngine.Color.black)), 30, .3f).ApplyPosition(item)
                    };
                    found = true;
                }
            }
            break;

            case "itemrecipe":
            {
                if (!item.HasChild("name"))
                {
                    PandaLogger.Log("ItemRecipe: Not name defined");
                    return(found);
                }

                item.TryGetAs <string>("name", out string name);

                if (!ItemTypes.IndexLookup.TryGetIndex(name, out ushort index))
                {
                    PandaLogger.Log("ItemRecipe: Not item found with name: " + name);
                    return(found);
                }

                if (!ItemRecipe.TryGetValue(index, out var recipe))
                {
                    PandaLogger.Log("ItemRecipe: Not recipe found for: " + name);
                    return(found);
                }

                menuItem = new List <IItem>();

                if (Localization.TryGetType(player.LastKnownLocale, index, out string localeName))
                {
                    menuItem.Add(new Label(localeName + ":").ApplyPosition(item));
                }
                else
                {
                    menuItem.Add(new Label(name + ":").ApplyPosition(item));
                }

                menuItem.Add(RecipeLines(menu, player, recipe, item));
                found = true;
            }
            break;

            case "dropdown":
            {
                string id;

                if (item.HasChild("id"))
                {
                    id = item.GetAs <string>("id");
                }
                else
                {
                    id = "dropdown";
                    PandaLogger.Log("Dropdown without ID defined, default: dropdown");
                }

                List <string> options = new List <string>();

                if (item.HasChild("options"))
                {
                    JSONNode optionsj = item.GetAs <JSONNode>("options");

                    foreach (var option in optionsj.LoopArray())
                    {
                        options.Add(option.GetAs <string>());
                    }
                }
                else
                {
                    options.Add("No options available");
                    PandaLogger.Log(string.Format("dropdown {0} without options", id));
                }

                item.TryGetAsOrDefault <int>("height", out int height, 30);
                item.TryGetAsOrDefault <int>("marginHorizontal", out int marginHorizontal, 4);
                item.TryGetAsOrDefault <int>("marginVertical", out int marginVertical, 2);

                // if label dropdown else dropdownNOLABEL
                if (item.TryGetChild("label", out JSONNode labelj))
                {
                    LabelData label = GetLabelData(labelj);
                    menuItem = new List <IItem>()
                    {
                        new DropDown(label.text, id, options).ApplyPosition(item)
                    };
                }
                else
                {
                    menuItem = new List <IItem>()
                    {
                        new DropDownNoLabel(id, options, height).ApplyPosition(item)
                    };
                }

                menu.LocalStorage.SetAs(id, 0);
                found = true;
            }
            break;

            case "toggle":
            {
                string id;

                if (item.HasChild("id"))
                {
                    id = item.GetAs <string>("id");
                }
                else
                {
                    id = "toggle";
                    PandaLogger.Log("Toggle without ID defined, default: toggle");
                }

                item.TryGetAsOrDefault <int>("height", out int height, 25);
                item.TryGetAsOrDefault <int>("toggleSize", out int toggleSize, 20);

                // if label toggle else togglenolabel
                if (item.TryGetChild("label", out JSONNode labelj))
                {
                    LabelData label = GetLabelData(labelj);
                    menuItem = new List <IItem>()
                    {
                        new Toggle(label, id, height, toggleSize).ApplyPosition(item)
                    };
                }
                else
                {
                    menuItem = new List <IItem>()
                    {
                        new ToggleNoLabel(id, toggleSize).ApplyPosition(item)
                    };
                }

                found = true;
                menu.LocalStorage.SetAs(id, false);
            }
            break;

            case "button":
            {
                string id;

                if (item.HasChild("id"))
                {
                    id = item.GetAs <string>("id");
                }
                else
                {
                    id = "button";
                    PandaLogger.Log("Button without ID defined, default: button");
                }

                item.TryGetAsOrDefault <int>("width", out int width, -1);
                item.TryGetAsOrDefault <int>("height", out int height, 25);

                if (item.TryGetChild("label", out JSONNode labelj))
                {
                    LabelData label = GetLabelData(labelj);
                    menuItem = new List <IItem>()
                    {
                        new ButtonCallback(id, label, width, height).ApplyPosition(item)
                    };
                }
                else
                {
                    PandaLogger.Log(string.Format("Button {0} without label", id));
                    menuItem = new List <IItem>()
                    {
                        new ButtonCallback(id, new LabelData("Key label not defined"), width, height).ApplyPosition(item)
                    };
                }

                found = true;
            }
            break;

            case "link":
            {
                string url;

                if (item.HasChild("url"))
                {
                    url = GameLoader.NAMESPACE + ".link_" + item.GetAs <string>("url");
                }
                else
                {
                    PandaLogger.Log("Link without URL defined");
                    return(found);
                }

                item.TryGetAsOrDefault <int>("width", out int width, -1);
                item.TryGetAsOrDefault <int>("height", out int height, 25);

                if (item.TryGetChild("label", out JSONNode labelj))
                {
                    LabelData label = GetLabelData(labelj);
                    menuItem = new List <IItem>()
                    {
                        new ButtonCallback(url, label, width, height).ApplyPosition(item)
                    };
                }
                else
                {
                    PandaLogger.Log(string.Format("Link {0} without label", url));
                    menuItem = new List <IItem>()
                    {
                        new ButtonCallback(url, new LabelData("Key label not defined"), width, height).ApplyPosition(item)
                    };
                }

                found = true;
            }
            break;

            case "table":
            {
                item.TryGetAsOrDefault <int>("row_height", out int height, 30);

                if (item.TryGetAs("rows", out JSONNode rows) && rows.ChildCount != 0)
                {
                    menuItem = new List <IItem>();
                    found    = true;

                    foreach (JSONNode row in rows.LoopArray())
                    {
                        List <ValueTuple <IItem, int> > items = new List <ValueTuple <IItem, int> >();
                        var width = menu.Width / row.ChildCount;

                        foreach (JSONNode col in row.LoopArray())
                        {
                            if (LoadItem(col, ref menu, player, out var newMenuItems))
                            {
                                foreach (var newItem in newMenuItems)
                                {
                                    if (col.TryGetAs("col_width", out int setWidth))
                                    {
                                        items.Add(ValueTuple.Create(newItem, setWidth));
                                    }
                                    else
                                    {
                                        items.Add(ValueTuple.Create(newItem, width));
                                    }
                                }
                            }
                        }

                        menuItem.Add(new HorizontalRow(items, height).ApplyPosition(item));
                    }
                }
            }
            break;


            default:
            {
                PandaLogger.Log(string.Format("It doesn't exist an item of type: {0}", itemType));
            }
            break;
            }

            return(found);
        }
Ejemplo n.º 15
0
        public override void OnNPCAtJob(ref NPCBase.NPCState state)
        {
            try
            {
                var currentposition = usedNPC.Position;
                _hadAmmo.Clear();

                if (_target == null || !_target.IsValid || !General.Physics.Physics.CanSee(usedNPC.Position.Vector, _target.Position))
                {
                    _target = MonsterTracker.Find(currentposition, _weapon.range, _weapon.shootDamage);
                }

                if (_target != null && General.Physics.Physics.CanSee(usedNPC.Position.Vector, _target.Position))
                {
                    foreach (var projectile in _weapon.shootItem)
                    {
                        _hadAmmo[projectile] = false;

                        if (usedNPC.Inventory.Contains(projectile))
                        {
                            _hadAmmo[projectile] = true;
                            continue;
                        }

                        if (_stock.Contains(projectile))
                        {
                            _hadAmmo[projectile] = true;
                        }
                    }

                    if (!_hadAmmo.Any(a => !a.Value))
                    {
                        state.SetIndicator(NPCIndicatorType.Crafted, _weapon.cooldownShot, _weapon.shootItem[0].Type);
                        foreach (var ammo in _hadAmmo)
                        {
                            if (usedNPC.Inventory.Contains(ammo.Key))
                            {
                                usedNPC.Inventory.TryRemove(ammo.Key);
                                continue;
                            }

                            if (_stock.Contains(ammo.Key))
                            {
                                _stock.TryRemove(ammo.Key);
                            }
                        }

                        usedNPC.LookAt(_target.Position);

                        if (_weapon.OnShootAudio != null)
                        {
                            ServerManager.SendAudio(position.Vector, _weapon.OnShootAudio);
                        }

                        if (_weapon.OnHitAudio != null)
                        {
                            ServerManager.SendAudio(_target.PositionToAimFor, _weapon.OnHitAudio);
                        }

                        if (_weapon.shootItem.Count > 0)
                        {
                            foreach (var proj in _weapon.shootItem)
                            {
                                string projName = ItemTypes.IndexLookup.GetName(proj.Type);

                                if (AnimationManager.AnimatedObjects.ContainsKey(projName))
                                {
                                    AnimationManager.AnimatedObjects[projName].SendMoveToInterpolatedOnce(position.Vector, _target.PositionToAimFor);
                                    break;
                                }
                            }
                        }

                        _target.OnHit(_weapon.shootDamage);
                        state.SetCooldown(_weapon.cooldownShot);
                        _waitingFor = 0;
                    }
                    else
                    {
                        state.SetIndicator(NPCIndicatorType.MissingItem, _weapon.cooldownMissingItem, _weapon.shootItem[0].Type);
                        state.SetCooldown(_weapon.cooldownMissingItem);
                    }
                }
                else
                {
                    state.SetIndicator(NPCIndicatorType.MissingItem, _weapon.cooldownSearchingTarget, GameLoader.MissingMonster_Icon);
                    state.SetCooldown(_weapon.cooldownMissingItem);
                    _target = null;
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                PandaLogger.LogError(ex);
#endif
                state.SetIndicator(NPCIndicatorType.MissingItem, _weapon.cooldownSearchingTarget, GameLoader.MissingMonster_Icon);
                state.SetCooldown(_weapon.cooldownMissingItem);
                _target = null;
            }
        }
Ejemplo n.º 16
0
        public static void EvaluateBanners()
        {
            if (!GameLoader.WorldLoaded)
            {
                return;
            }

            _bannerCounts.Clear();

            var banners = BannerTracker.GetCount();

            if (banners > 0)
            {
                for (var i = 0; i < banners; i++)
                {
                    if (BannerTracker.TryGetAtIndex(i, out var banner))
                    {
                        if (!_bannerCounts.ContainsKey(banner.Owner))
                        {
                            _bannerCounts.Add(banner.Owner, 1);
                        }
                        else
                        {
                            _bannerCounts[banner.Owner]++;
                        }
                    }
                }
            }

            foreach (var p in _bannerCounts)
            {
                var ps = PlayerState.GetPlayerState(p.Key);

                if (ps == null)
                {
                    continue;
                }

                var numberOfBanners = p.Key.GetTempValues(true)
                                      .GetOrDefault(PandaResearch.GetLevelKey(PandaResearch.Settlement), 0) + 1;

                var inv        = Inventory.GetInventory(p.Key);
                var sockBanner = Stockpile.GetStockPile(p.Key).AmountContained(BuiltinBlocks.Banner);

                var inventoryBanners = 0;

                if (inv != null)
                {
                    foreach (var item in inv.Items)
                    {
                        if (item.Type == BuiltinBlocks.Banner)
                        {
                            inventoryBanners = item.Amount;
                        }
                    }
                }

                var totalBanners = p.Value + sockBanner + inventoryBanners;

#if Debug
                PandaLogger.Log($"Number of research banners: {numberOfBanners}");
                PandaLogger.Log($"Number of banners: {p.Value}");
                PandaLogger.Log($"Number of stockpile banners: {sockBanner}");
                PandaLogger.Log($"Number of Inventory banners: {inventoryBanners}");
                PandaLogger.Log($"Total banners: {totalBanners}");
                PandaLogger.Log($"Add Banner: {totalBanners < numberOfBanners}");
#endif

                if (totalBanners < numberOfBanners)
                {
                    if (!Inventory.GetInventory(p.Key).TryAdd(BuiltinBlocks.Banner))
                    {
                        Stockpile.GetStockPile(p.Key).Add(BuiltinBlocks.Banner);
                    }
                }
            }
        }
Ejemplo n.º 17
0
        public bool TryDoCommand(Players.Player player, string chat)
        {
            if (player == null || player.ID == NetworkID.Server)
            {
                return(true);
            }

            string[]    array  = CommandManager.SplitCommand(chat);
            Colony      colony = Colony.Get(player);
            PlayerState state  = PlayerState.GetPlayerState(player);

            state.CallToArmsEnabled = !state.CallToArmsEnabled;

            if (state.CallToArmsEnabled)
            {
                PandaChat.Send(player, "Call to arms activated!", ChatColor.red, ChatStyle.bold);

                foreach (var follower in colony.Followers)
                {
                    var job = follower.Job;

                    if (!CanCallToArms(job))
                    {
                        continue;
                    }

                    try
                    {
                        if (job != null)
                        {
                            if (job.GetType() != typeof(CalltoArmsJob))
                            {
                                _Jobs[follower] = job;
                            }

                            job.OnRemovedNPC();
                            follower.ClearJob();
                        }
                    }
                    catch (Exception ex)
                    {
                        PandaLogger.LogError(ex);
                    }

                    var armsJob = new CalltoArmsJob();
                    _callToArmsJobs.Add(armsJob);
                    armsJob.OnAssignedNPC(follower);
                    follower.TakeJob(armsJob);
                }
            }
            else
            {
                PandaChat.Send(player, "Call to arms deactivated.", ChatColor.green, ChatStyle.bold);
                List <NPCBase> assignedWorkers = new List <NPCBase>();

                foreach (var follower in colony.Followers)
                {
                    var job = follower.Job;

                    if (job != null && job.GetType() == typeof(CalltoArmsJob))
                    {
                        follower.ClearJob();
                        job.OnRemovedNPC();
                        ((JobTracker.JobFinder)JobTracker.GetOrCreateJobFinder(player)).openJobs.Remove(job);
                    }

                    if (_Jobs.ContainsKey(follower) && _Jobs[follower].NeedsNPC)
                    {
                        assignedWorkers.Add(follower);
                        follower.TakeJob(_Jobs[follower]);
                        _Jobs[follower].OnAssignedNPC(follower);
                        JobTracker.Remove(player, _Jobs[follower].KeyLocation);
                    }
                }

                _Jobs.Clear();
            }

            foreach (var armsJob in _callToArmsJobs)
            {
                ((JobTracker.JobFinder)JobTracker.GetOrCreateJobFinder(player)).openJobs.Remove(armsJob);
            }

            _callToArmsJobs.Clear();
            JobTracker.Update();
            Colony.SendColonistCount(player);

            return(true);
        }
Ejemplo n.º 18
0
        public static bool EvaluateSettlers(Players.Player p)
        {
            var update = false;

            if (p.IsConnected)
            {
                var colony = Colony.Get(p);
                var state  = PlayerState.GetPlayerState(p);

                if (state.NextGenTime == 0)
                {
                    state.NextGenTime = Time.SecondsSinceStartDouble +
                                        Random.Next(8,
                                                    16 - Pipliz.Math.RoundToInt(p.GetTempValues(true)
                                                                                .GetOrDefault(PandaResearch.GetResearchKey(PandaResearch.TimeBetween),
                                                                                              0f))) * TimeCycle
                                        .SecondsPerHour;
                }

                if (Time.SecondsSinceStartDouble > state.NextGenTime && colony.FollowerCount >= MAX_BUYABLE)
                {
                    var chance =
                        p.GetTempValues(true)
                        .GetOrDefault(PandaResearch.GetResearchKey(PandaResearch.SettlerChance), 0f) +
                        state.Difficulty.AdditionalChance;

                    chance += SettlerEvaluation.SpawnChance(p, colony, state);

                    var rand = Random.NextFloat();

                    if (chance > rand)
                    {
                        var addCount = Math.Floor(state.MaxPerSpawn * chance);

                        // if we lost alot of colonists add extra to help build back up.
                        if (colony.FollowerCount < state.HighestColonistCount)
                        {
                            var diff = state.HighestColonistCount - colony.FollowerCount;
                            addCount += Math.Floor(diff * .25);
                        }

                        try
                        {
                            var skillChance = p.GetTempValues(true)
                                              .GetOrDefault(PandaResearch.GetResearchKey(PandaResearch.SkilledLaborer),
                                                            0f);

                            var numbSkilled = 0;

                            rand = Random.NextFloat();

                            try
                            {
                                if (skillChance > rand)
                                {
                                    numbSkilled =
                                        state.Rand.Next(1,
                                                        2 + Pipliz.Math.RoundToInt(p.GetTempValues(true)
                                                                                   .GetOrDefault(PandaResearch.GetResearchKey(PandaResearch.NumberSkilledLaborer),
                                                                                                 0f)));
                                }
                            }
                            catch (Exception ex)
                            {
                                PandaLogger.Log("NumberSkilledLaborer");
                                PandaLogger.LogError(ex);
                            }


                            if (addCount > 0)
                            {
                                if (addCount > 30)
                                {
                                    addCount = 30;
                                }

                                var reason = string.Format(SettlerReasoning.GetSettleReason(), addCount);

                                if (numbSkilled > 0)
                                {
                                    if (numbSkilled == 1)
                                    {
                                        reason += string.Format(" {0} of them is skilled!", numbSkilled);
                                    }
                                    else
                                    {
                                        reason += string.Format(" {0} of them are skilled!", numbSkilled);
                                    }
                                }

                                PandaChat.Send(p, reason, ChatColor.magenta);
                                var playerPos = new Vector3Int(p.Position);

                                for (var i = 0; i < addCount; i++)
                                {
                                    var newGuy = new NPCBase(NPCType.GetByKeyNameOrDefault("pipliz.laborer"),
                                                             BannerTracker.GetClosest(p, playerPos).KeyLocation.Vector,
                                                             colony);

                                    SettlerInventory.GetSettlerInventory(newGuy);
                                    newGuy.GetTempValues().Set(ISSETTLER, true);

                                    if (i <= numbSkilled)
                                    {
                                        var npcTemp = newGuy.GetTempValues(true);
                                        npcTemp.Set(GameLoader.ALL_SKILLS, state.Rand.Next(1, 10) * 0.002f);
                                    }

                                    update = true;
                                    ModLoader.TriggerCallbacks(ModLoader.EModCallbackType.OnNPCRecruited, newGuy);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            PandaLogger.Log("SkilledLaborer");
                            PandaLogger.LogError(ex);
                        }

                        if (colony.FollowerCount > state.HighestColonistCount)
                        {
                            state.HighestColonistCount = colony.FollowerCount;
                        }
                    }


                    state.NextGenTime = Time.SecondsSinceStartDouble +
                                        Random.Next(8,
                                                    16 - Pipliz.Math.RoundToInt(p.GetTempValues(true)
                                                                                .GetOrDefault(PandaResearch.GetResearchKey(PandaResearch.TimeBetween),
                                                                                              0f))) * TimeCycle
                                        .SecondsPerHour;

                    colony.SendUpdate();
                }
            }

            return(update);
        }
Ejemplo n.º 19
0
        public void AfterWorldLoad()
        {
            StringBuilder sb = new StringBuilder();

            PandaLogger.Log(ChatColor.lime, "-------------------Armor Loaded----------------------");
            var           i      = 0;
            List <IArmor> armors = new List <IArmor>();


            foreach (var item in LoadedAssembalies)
            {
                if (Activator.CreateInstance(item) is IArmor armor &&
                    !string.IsNullOrEmpty(armor.name))
                {
                    armors.Add(armor);
                }
            }

            var settings = GameLoader.GetJSONSettingPaths(GameLoader.NAMESPACE + ".CSItems");

            foreach (var modInfo in settings)
            {
                foreach (var path in modInfo.Value)
                {
                    try
                    {
                        var jsonFile = JSON.Deserialize(modInfo.Key + "/" + path);

                        if (jsonFile.NodeType == NodeType.Array && jsonFile.ChildCount > 0)
                        {
                            foreach (var item in jsonFile.LoopArray())
                            {
                                if (item.TryGetAs("Durability", out int durability))
                                {
                                    armors.Add(item.JsonDeerialize <MagicArmor>());
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        PandaLogger.LogError(ex);
                    }
                }
            }

            foreach (var armor in armors)
            {
                if (ItemTypes.IndexLookup.TryGetIndex(armor.name, out var index))
                {
                    ArmorFactory.ArmorLookup[index] = armor;
                    sb.Append($"{armor.name}, ");
                    i++;

                    if (i > 5)
                    {
                        sb.Append("</color>");
                        i = 0;
                        sb.AppendLine();
                        sb.Append("<color=lime>");
                    }
                }
            }

            PandaLogger.Log(ChatColor.lime, sb.ToString());
            PandaLogger.Log(ChatColor.lime, "---------------------------------------------------------");
        }
Ejemplo n.º 20
0
 private static void AfterWorldLoad()
 {
     Instance = new PandaMonsterSpawner();
     MonsterTracker.MonsterSpawner = Instance;
     PandaLogger.Log("PandaMonsterSpawner Initialized!");
 }
Ejemplo n.º 21
0
 public void AfterWorldLoad()
 {
     PandaLogger.Log(ChatColor.lime, "-------------------Items Loaded----------------------");
     PandaLogger.Log(ChatColor.lime, _sb.ToString());
     PandaLogger.Log(ChatColor.lime, "------------------------------------------------------");
 }
Ejemplo n.º 22
0
        public static void AddArmor(Dictionary <string, ItemTypesServer.ItemTypeRaw> items)
        {
            try
            {
                // ----------------------------------------
                // Copper
                // ----------------------------------------

                // Helm
                var copperHelmName = GameLoader.NAMESPACE + ".CopperHelm";
                var copperHelmNode = new JSONNode();
                copperHelmNode["icon"]        = new JSONNode(GameLoader.ICON_PATH + "CopperHelm.png");
                copperHelmNode["isPlaceable"] = new JSONNode(false);

                var categories = new JSONNode(NodeType.Array);
                categories.AddToArray(new JSONNode("armor"));
                copperHelmNode.SetAs("categories", categories);

                var copperHelm = new ItemTypesServer.ItemTypeRaw(copperHelmName, copperHelmNode);
                items.Add(copperHelmName, copperHelm);

                ArmorLookup.Add(copperHelm.ItemIndex,
                                new ArmorMetadata(0.05f, 15, copperHelmName, copperHelm, ArmorSlot.Helm));

                // Chest
                var copperChestName = GameLoader.NAMESPACE + ".CopperChest";
                var copperChestNode = new JSONNode();
                copperChestNode["icon"]        = new JSONNode(GameLoader.ICON_PATH + "CopperChest.png");
                copperChestNode["isPlaceable"] = new JSONNode(false);

                copperChestNode.SetAs("categories", categories);

                var copperChest = new ItemTypesServer.ItemTypeRaw(copperChestName, copperChestNode);
                items.Add(copperChestName, copperChest);

                ArmorLookup.Add(copperChest.ItemIndex,
                                new ArmorMetadata(.1f, 25, copperChestName, copperChest, ArmorSlot.Chest));

                // Gloves
                var copperGlovesName = GameLoader.NAMESPACE + ".CopperGloves";
                var copperGlovesNode = new JSONNode();
                copperGlovesNode["icon"]        = new JSONNode(GameLoader.ICON_PATH + "CopperGloves.png");
                copperGlovesNode["isPlaceable"] = new JSONNode(false);

                copperGlovesNode.SetAs("categories", categories);

                var copperGloves = new ItemTypesServer.ItemTypeRaw(copperGlovesName, copperGlovesNode);
                items.Add(copperGlovesName, copperGloves);

                ArmorLookup.Add(copperGloves.ItemIndex,
                                new ArmorMetadata(0.025f, 10, copperGlovesName, copperGloves, ArmorSlot.Gloves));

                // Legs
                var copperLegsName = GameLoader.NAMESPACE + ".CopperLegs";
                var copperLegsNode = new JSONNode();
                copperLegsNode["icon"]        = new JSONNode(GameLoader.ICON_PATH + "CopperLegs.png");
                copperLegsNode["isPlaceable"] = new JSONNode(false);

                copperLegsNode.SetAs("categories", categories);

                var copperLegs = new ItemTypesServer.ItemTypeRaw(copperLegsName, copperLegsNode);
                items.Add(copperLegsName, copperLegs);

                ArmorLookup.Add(copperLegs.ItemIndex,
                                new ArmorMetadata(0.07f, 20, copperLegsName, copperLegs, ArmorSlot.Legs));

                // Boots
                var copperBootsName = GameLoader.NAMESPACE + ".CopperBoots";
                var copperBootsNode = new JSONNode();
                copperBootsNode["icon"]        = new JSONNode(GameLoader.ICON_PATH + "CopperBoots.png");
                copperBootsNode["isPlaceable"] = new JSONNode(false);

                copperBootsNode.SetAs("categories", categories);

                var copperBoots = new ItemTypesServer.ItemTypeRaw(copperBootsName, copperBootsNode);
                items.Add(copperBootsName, copperBoots);

                ArmorLookup.Add(copperBoots.ItemIndex,
                                new ArmorMetadata(0.025f, 10, copperBootsName, copperBoots, ArmorSlot.Boots));

                // Shield
                var copperShieldName = GameLoader.NAMESPACE + ".CopperShield";
                var copperShieldNode = new JSONNode();
                copperShieldNode["icon"]        = new JSONNode(GameLoader.ICON_PATH + "CopperShield.png");
                copperShieldNode["isPlaceable"] = new JSONNode(false);

                copperShieldNode.SetAs("categories", categories);

                var copperShield = new ItemTypesServer.ItemTypeRaw(copperShieldName, copperShieldNode);
                items.Add(copperShieldName, copperShield);

                ArmorLookup.Add(copperShield.ItemIndex,
                                new ArmorMetadata(0.05f, 30, copperShieldName, copperShield, ArmorSlot.Shield));

                // ----------------------------------------
                // Bronze
                // ----------------------------------------

                // Helm
                var bronzeHelmName = GameLoader.NAMESPACE + ".BronzeHelm";
                var bronzeHelmNode = new JSONNode();
                bronzeHelmNode["icon"]        = new JSONNode(GameLoader.ICON_PATH + "BronzeHelm.png");
                bronzeHelmNode["isPlaceable"] = new JSONNode(false);

                bronzeHelmNode.SetAs("categories", categories);

                var bronzeHelm = new ItemTypesServer.ItemTypeRaw(bronzeHelmName, bronzeHelmNode);
                items.Add(bronzeHelmName, bronzeHelm);

                ArmorLookup.Add(bronzeHelm.ItemIndex,
                                new ArmorMetadata(0.07f, 20, bronzeHelmName, bronzeHelm, ArmorSlot.Helm));

                // Chest
                var bronzeChestName = GameLoader.NAMESPACE + ".BronzeChest";
                var bronzeChestNode = new JSONNode();
                bronzeChestNode["icon"]        = new JSONNode(GameLoader.ICON_PATH + "BronzeChest.png");
                bronzeChestNode["isPlaceable"] = new JSONNode(false);

                bronzeChestNode.SetAs("categories", categories);

                var bronzeChest = new ItemTypesServer.ItemTypeRaw(bronzeChestName, bronzeChestNode);
                items.Add(bronzeChestName, bronzeChest);

                ArmorLookup.Add(bronzeChest.ItemIndex,
                                new ArmorMetadata(.15f, 30, bronzeChestName, bronzeChest, ArmorSlot.Chest));

                // Gloves
                var bronzeGlovesName = GameLoader.NAMESPACE + ".BronzeGloves";
                var bronzeGlovesNode = new JSONNode();
                bronzeGlovesNode["icon"]        = new JSONNode(GameLoader.ICON_PATH + "BronzeGloves.png");
                bronzeGlovesNode["isPlaceable"] = new JSONNode(false);

                bronzeGlovesNode.SetAs("categories", categories);

                var bronzeGloves = new ItemTypesServer.ItemTypeRaw(bronzeGlovesName, bronzeGlovesNode);
                items.Add(bronzeGlovesName, bronzeGloves);

                ArmorLookup.Add(bronzeGloves.ItemIndex,
                                new ArmorMetadata(0.04f, 15, bronzeGlovesName, bronzeGloves, ArmorSlot.Gloves));

                // Legs
                var bronzeLegsName = GameLoader.NAMESPACE + ".BronzeLegs";
                var bronzeLegsNode = new JSONNode();
                bronzeLegsNode["icon"]        = new JSONNode(GameLoader.ICON_PATH + "BronzeLegs.png");
                bronzeLegsNode["isPlaceable"] = new JSONNode(false);

                bronzeLegsNode.SetAs("categories", categories);

                var bronzeLegs = new ItemTypesServer.ItemTypeRaw(bronzeLegsName, bronzeLegsNode);
                items.Add(bronzeLegsName, bronzeLegs);

                ArmorLookup.Add(bronzeLegs.ItemIndex,
                                new ArmorMetadata(0.09f, 25, bronzeLegsName, bronzeLegs, ArmorSlot.Legs));

                // Boots
                var bronzeBootsName = GameLoader.NAMESPACE + ".BronzeBoots";
                var bronzeBootsNode = new JSONNode();
                bronzeBootsNode["icon"]        = new JSONNode(GameLoader.ICON_PATH + "BronzeBoots.png");
                bronzeBootsNode["isPlaceable"] = new JSONNode(false);

                bronzeBootsNode.SetAs("categories", categories);

                var bronzeBoots = new ItemTypesServer.ItemTypeRaw(bronzeBootsName, bronzeBootsNode);
                items.Add(bronzeBootsName, bronzeBoots);

                ArmorLookup.Add(bronzeBoots.ItemIndex,
                                new ArmorMetadata(0.04f, 15, bronzeBootsName, bronzeBoots, ArmorSlot.Boots));

                // Shield
                var bronzeShieldName = GameLoader.NAMESPACE + ".BronzeShield";
                var bronzeShieldNode = new JSONNode();
                bronzeShieldNode["icon"]        = new JSONNode(GameLoader.ICON_PATH + "BronzeShield.png");
                bronzeShieldNode["isPlaceable"] = new JSONNode(false);

                bronzeShieldNode.SetAs("categories", categories);

                var bronzeShield = new ItemTypesServer.ItemTypeRaw(bronzeShieldName, bronzeShieldNode);
                items.Add(bronzeShieldName, bronzeShield);

                ArmorLookup.Add(bronzeShield.ItemIndex,
                                new ArmorMetadata(0.07f, 40, bronzeShieldName, bronzeShield, ArmorSlot.Shield));

                // ----------------------------------------
                // Iron
                // ----------------------------------------

                // Helm
                var ironHelmName = GameLoader.NAMESPACE + ".IronHelm";
                var ironHelmNode = new JSONNode();
                ironHelmNode["icon"]        = new JSONNode(GameLoader.ICON_PATH + "IronHelm.png");
                ironHelmNode["isPlaceable"] = new JSONNode(false);

                ironHelmNode.SetAs("categories", categories);

                var ironHelm = new ItemTypesServer.ItemTypeRaw(ironHelmName, ironHelmNode);
                items.Add(ironHelmName, ironHelm);

                ArmorLookup.Add(ironHelm.ItemIndex,
                                new ArmorMetadata(0.09f, 30, ironHelmName, ironHelm, ArmorSlot.Helm));

                // Chest
                var ironChestName = GameLoader.NAMESPACE + ".IronChest";
                var ironChestNode = new JSONNode();
                ironChestNode["icon"]        = new JSONNode(GameLoader.ICON_PATH + "IronChest.png");
                ironChestNode["isPlaceable"] = new JSONNode(false);

                ironChestNode.SetAs("categories", categories);

                var ironChest = new ItemTypesServer.ItemTypeRaw(ironChestName, ironChestNode);
                items.Add(ironChestName, ironChest);

                ArmorLookup.Add(ironChest.ItemIndex,
                                new ArmorMetadata(.2f, 40, ironChestName, ironChest, ArmorSlot.Chest));

                // Gloves
                var ironGlovesName = GameLoader.NAMESPACE + ".IronGloves";
                var ironGlovesNode = new JSONNode();
                ironGlovesNode["icon"]        = new JSONNode(GameLoader.ICON_PATH + "IronGloves.png");
                ironGlovesNode["isPlaceable"] = new JSONNode(false);

                ironGlovesNode.SetAs("categories", categories);

                var ironGloves = new ItemTypesServer.ItemTypeRaw(ironGlovesName, ironGlovesNode);
                items.Add(ironGlovesName, ironGloves);

                ArmorLookup.Add(ironGloves.ItemIndex,
                                new ArmorMetadata(0.055f, 25, ironGlovesName, ironGloves, ArmorSlot.Gloves));

                // Legs
                var ironLegsName = GameLoader.NAMESPACE + ".IronLegs";
                var ironLegsNode = new JSONNode();
                ironLegsNode["icon"]        = new JSONNode(GameLoader.ICON_PATH + "IronLegs.png");
                ironLegsNode["isPlaceable"] = new JSONNode(false);

                ironLegsNode.SetAs("categories", categories);

                var ironLegs = new ItemTypesServer.ItemTypeRaw(ironLegsName, ironLegsNode);
                items.Add(ironLegsName, ironLegs);

                ArmorLookup.Add(ironLegs.ItemIndex,
                                new ArmorMetadata(0.11f, 35, ironLegsName, ironLegs, ArmorSlot.Legs));

                // Boots
                var ironBootsName = GameLoader.NAMESPACE + ".IronBoots";
                var ironBootsNode = new JSONNode();
                ironBootsNode["icon"]        = new JSONNode(GameLoader.ICON_PATH + "IronBoots.png");
                ironBootsNode["isPlaceable"] = new JSONNode(false);

                ironBootsNode.SetAs("categories", categories);

                var ironBoots = new ItemTypesServer.ItemTypeRaw(ironBootsName, ironBootsNode);
                items.Add(ironBootsName, ironBoots);

                ArmorLookup.Add(ironBoots.ItemIndex,
                                new ArmorMetadata(0.055f, 25, ironBootsName, ironBoots, ArmorSlot.Boots));

                // Shield
                var ironShieldName = GameLoader.NAMESPACE + ".IronShield";
                var ironShieldNode = new JSONNode();
                ironShieldNode["icon"]        = new JSONNode(GameLoader.ICON_PATH + "IronShield.png");
                ironShieldNode["isPlaceable"] = new JSONNode(false);

                ironShieldNode.SetAs("categories", categories);

                var ironShield = new ItemTypesServer.ItemTypeRaw(ironShieldName, ironShieldNode);
                items.Add(ironShieldName, ironShield);

                ArmorLookup.Add(ironShield.ItemIndex,
                                new ArmorMetadata(0.1f, 50, ironShieldName, ironShield, ArmorSlot.Shield));

                // ----------------------------------------
                // Steel
                // ----------------------------------------

                // Helm
                var steelHelmName = GameLoader.NAMESPACE + ".SteelHelm";
                var steelHelmNode = new JSONNode();
                steelHelmNode["icon"]        = new JSONNode(GameLoader.ICON_PATH + "SteelHelm.png");
                steelHelmNode["isPlaceable"] = new JSONNode(false);

                steelHelmNode.SetAs("categories", categories);

                var steelHelm = new ItemTypesServer.ItemTypeRaw(steelHelmName, steelHelmNode);
                items.Add(steelHelmName, steelHelm);

                ArmorLookup.Add(steelHelm.ItemIndex,
                                new ArmorMetadata(0.11f, 40, steelHelmName, steelHelm, ArmorSlot.Helm));

                // Chest
                var steelChestName = GameLoader.NAMESPACE + ".SteelChest";
                var steelChestNode = new JSONNode();
                steelChestNode["icon"]        = new JSONNode(GameLoader.ICON_PATH + "SteelChest.png");
                steelChestNode["isPlaceable"] = new JSONNode(false);

                steelChestNode.SetAs("categories", categories);

                var steelChest = new ItemTypesServer.ItemTypeRaw(steelChestName, steelChestNode);
                items.Add(steelChestName, steelChest);

                ArmorLookup.Add(steelChest.ItemIndex,
                                new ArmorMetadata(.3f, 50, steelChestName, steelChest, ArmorSlot.Chest));

                // Gloves
                var steelGlovesName = GameLoader.NAMESPACE + ".SteelGloves";
                var steelGlovesNode = new JSONNode();
                steelGlovesNode["icon"]        = new JSONNode(GameLoader.ICON_PATH + "SteelGloves.png");
                steelGlovesNode["isPlaceable"] = new JSONNode(false);

                steelGlovesNode.SetAs("categories", categories);

                var steelGloves = new ItemTypesServer.ItemTypeRaw(steelGlovesName, steelGlovesNode);
                items.Add(steelGlovesName, steelGloves);

                ArmorLookup.Add(steelGloves.ItemIndex,
                                new ArmorMetadata(0.07f, 35, steelGlovesName, steelGloves, ArmorSlot.Gloves));

                // Legs
                var steelLegsName = GameLoader.NAMESPACE + ".SteelLegs";
                var steelLegsNode = new JSONNode();
                steelLegsNode["icon"]        = new JSONNode(GameLoader.ICON_PATH + "SteelLegs.png");
                steelLegsNode["isPlaceable"] = new JSONNode(false);

                steelLegsNode.SetAs("categories", categories);

                var steelLegs = new ItemTypesServer.ItemTypeRaw(steelLegsName, steelLegsNode);
                items.Add(steelLegsName, steelLegs);

                ArmorLookup.Add(steelLegs.ItemIndex,
                                new ArmorMetadata(0.13f, 40, steelLegsName, steelLegs, ArmorSlot.Legs));

                // Boots
                var steelBootsName = GameLoader.NAMESPACE + ".SteelBoots";
                var steelBootsNode = new JSONNode();
                steelBootsNode["icon"]        = new JSONNode(GameLoader.ICON_PATH + "SteelBoots.png");
                steelBootsNode["isPlaceable"] = new JSONNode(false);

                steelBootsNode.SetAs("categories", categories);

                var steelBoots = new ItemTypesServer.ItemTypeRaw(steelBootsName, steelBootsNode);
                items.Add(steelBootsName, steelBoots);

                ArmorLookup.Add(steelBoots.ItemIndex,
                                new ArmorMetadata(0.07f, 35, steelBootsName, steelBoots, ArmorSlot.Boots));

                // Shield
                var steelShieldName = GameLoader.NAMESPACE + ".SteelShield";
                var steelShieldNode = new JSONNode();
                steelShieldNode["icon"]        = new JSONNode(GameLoader.ICON_PATH + "SteelShield.png");
                steelShieldNode["isPlaceable"] = new JSONNode(false);

                steelShieldNode.SetAs("categories", categories);

                var steelShield = new ItemTypesServer.ItemTypeRaw(steelShieldName, steelShieldNode);
                items.Add(steelShieldName, steelShield);

                ArmorLookup.Add(steelShield.ItemIndex,
                                new ArmorMetadata(0.12f, 60, steelShieldName, steelShield, ArmorSlot.Shield));

                ArmorLookup = ArmorLookup.OrderBy(kvp => kvp.Value.name).ThenBy(kvp => kvp.Value.ArmorRating)
                              .ToDictionary(k => k.Key, v => v.Value);
            }
            catch (Exception ex)
            {
                PandaLogger.LogError(ex);
            }
        }
Ejemplo n.º 23
0
        public static NetworkMenu ToolbarMenu(ButtonPressCallbackData data, bool error = false, bool?selectAll = null)
        {
            NetworkMenu menu = new NetworkMenu();

            menu.LocalStorage.SetAs("header", _localizationHelper.LocalizeOrDefault("MoveItemsToBackpack", data.Player));
            menu.Width  = 1000;
            menu.Height = 600;

            try
            {
                if (error)
                {
                    menu.Items.Add(new Label(new LabelData(_localizationHelper.GetLocalizationKey("invalidNumber"), UnityEngine.Color.red)));
                }

                List <ValueTuple <IItem, int> > headerItems = new List <ValueTuple <IItem, int> >();
                headerItems.Add(ValueTuple.Create <IItem, int>(new Label(new LabelData(_localizationHelper.GetLocalizationKey("Numberofitems"), UnityEngine.Color.black)), 333));
                headerItems.Add(ValueTuple.Create <IItem, int>(new InputField("Backpack.NumberOfItems"), 333));
                headerItems.Add(ValueTuple.Create <IItem, int>(new ButtonCallback("Backpack.MoveItemsToBackpackFromToolbar", new LabelData(_localizationHelper.GetLocalizationKey("MoveItemsToBackpack"), UnityEngine.Color.black)), 333));
                menu.Items.Add(new HorizontalRow(headerItems));
                menu.Items.Add(new Line(UnityEngine.Color.black));

                List <ValueTuple <IItem, int> > items = new List <ValueTuple <IItem, int> >();
                items.Add(ValueTuple.Create <IItem, int>(new ButtonCallback("Backpack.MainMenu", new LabelData(_localizationHelper.GetLocalizationKey("Back"), UnityEngine.Color.black)), 250));
                items.Add(ValueTuple.Create <IItem, int>(new EmptySpace(), 250));
                items.Add(ValueTuple.Create <IItem, int>(new EmptySpace(), 250));

                bool selected = false;

                if (selectAll == true)
                {
                    selected = true;
                }
                else if (selectAll == false)
                {
                    selected = false;
                }

                if (selected)
                {
                    items.Add(ValueTuple.Create <IItem, int>(new ButtonCallback("Backpack.SelectNoneInBackpackToolbar", new LabelData(_localizationHelper.GetLocalizationKey("SelectNone"), UnityEngine.Color.black)), 250));
                }
                else
                {
                    items.Add(ValueTuple.Create <IItem, int>(new ButtonCallback("Backpack.SelectAllInBackpackToolbar", new LabelData(_localizationHelper.GetLocalizationKey("SelectAll"), UnityEngine.Color.black)), 250));
                }

                menu.Items.Add(new HorizontalRow(items));
                menu.Items.Add(new Line(UnityEngine.Color.black));
                var invRef     = data.Player.Inventory;
                var backpackID = ItemId.GetItemId(Backpack.NAME);

                foreach (var itemKvp in invRef.Items)
                {
                    if (itemKvp.Type != ColonyBuiltIn.ItemTypes.AIR.Id && itemKvp.Type != backpackID)
                    {
                        items = new List <ValueTuple <IItem, int> >();
                        items.Add(ValueTuple.Create <IItem, int>(new ItemIcon(itemKvp.Type), 250));
                        items.Add(ValueTuple.Create <IItem, int>(new Label(new LabelData(ItemId.GetItemId(itemKvp.Type), UnityEngine.Color.black, UnityEngine.TextAnchor.MiddleLeft, 18, LabelData.ELocalizationType.Type)), 250));
                        items.Add(ValueTuple.Create <IItem, int>(new Label(new LabelData(_localizationHelper.LocalizeOrDefault("Toolbar", data.Player) + ": " + itemKvp.Amount.ToString(), UnityEngine.Color.black)), 250));
                        items.Add(ValueTuple.Create <IItem, int>(new Toggle(new LabelData(_localizationHelper.LocalizeOrDefault("Select", data.Player), UnityEngine.Color.black), "Backpack." + itemKvp.Type + ".ItemSelected"), 250));

                        if (selectAll == null)
                        {
                            menu.LocalStorage.TryGetAs("Backpack." + itemKvp.Type + ".ItemSelected", out selected);
                        }

                        menu.LocalStorage.SetAs("Backpack." + itemKvp.Type + ".ItemSelected", selected);
                        menu.Items.Add(new HorizontalRow(items));
                    }
                }
            }
            catch (Exception ex)
            {
                PandaLogger.LogError(ex);
            }

            return(menu);
        }