Exemple #1
0
    // Token: 0x06000B5F RID: 2911 RVA: 0x000520EC File Offset: 0x000502EC
    public void SavePlayerData(Player player)
    {
        ZPackage zpackage = new ZPackage();

        player.Save(zpackage);
        this.m_playerData = zpackage.GetArray();
    }
Exemple #2
0
    // Token: 0x06000C09 RID: 3081 RVA: 0x000558D4 File Offset: 0x00053AD4
    public void SaveWorldMetaData()
    {
        ZPackage zpackage = new ZPackage();

        zpackage.Write(global::Version.m_worldVersion);
        zpackage.Write(this.m_name);
        zpackage.Write(this.m_seedName);
        zpackage.Write(this.m_seed);
        zpackage.Write(this.m_uid);
        zpackage.Write(this.m_worldGenVersion);
        Directory.CreateDirectory(this.m_worldSavePath);
        string metaPath = this.GetMetaPath();
        string text     = metaPath + ".new";
        string text2    = metaPath + ".old";

        byte[]       array        = zpackage.GetArray();
        FileStream   fileStream   = File.Create(text);
        BinaryWriter binaryWriter = new BinaryWriter(fileStream);

        binaryWriter.Write(array.Length);
        binaryWriter.Write(array);
        binaryWriter.Flush();
        fileStream.Flush(true);
        fileStream.Close();
        fileStream.Dispose();
        if (File.Exists(metaPath))
        {
            if (File.Exists(text2))
            {
                File.Delete(text2);
            }
            File.Move(metaPath, text2);
        }
        File.Move(text, metaPath);
    }
Exemple #3
0
    public float riverWavelength          = 20f;   // 20

    public void WriteBiomeData(ref ZPackage package)
    {
        //mountain
        package.Write(minMountainHeight);

        // ashlands/deepnorth
        package.Write(minAshlandsDist);
        package.Write(minDeepNorthDist);

        // swamp
        package.Write(swampBiomeScaleX);
        package.Write(swampBiomeScaleY);
        package.Write(minSwampNoise);
        package.Write(minSwampDist);
        package.Write(maxSwampDist);
        package.Write(minSwampHeight);
        package.Write(maxSwampHeight);

        // mistlands
        package.Write(mistlandsBiomeScaleX);
        package.Write(mistlandsBiomeScaleY);
        package.Write(minMistlandsNoise);
        package.Write(minMistlandsDist);
        package.Write(maxMistlandsDist);

        // plains
        package.Write(plainsBiomeScaleX);
        package.Write(plainsBiomeScaleY);
        package.Write(minPlainsNoise);
        package.Write(minPlainsDist);
        package.Write(maxPlainsDist);

        // black forest
        package.Write(blackForestBiomeScaleX);
        package.Write(blackForestBiomeScaleY);
        package.Write(minBlackForestNoise);
        package.Write(minBlackForestDist);
        package.Write(maxBlackForestDist);

        // switches
        package.Write((int)meadowsSwitch);
        package.Write((int)blackForestSwitch);
        package.Write((int)swampSwitch);
        package.Write((int)mountainSwitch);
        package.Write((int)plainsSwitch);
        package.Write((int)mistlandsSwitch);
        package.Write((int)ashlandsSwitch);
        package.Write((int)deepNorthSwitch);

        // river
        package.Write(riverMultipleMaxDistance);
        package.Write(riverExtremeMaxDistance);
        package.Write(riverMaxHeight);
        package.Write(riverWidthMaxLowerRange);
        package.Write(riverWidthMaxUpperRange);
        package.Write(riverWidthMinLowerRange);
        package.Write(riverCurveWidth);
        package.Write(riverWavelength);
    }
Exemple #4
0
            private static IEnumerator ReceivedSettings(ZNetPeer peer)
            {
                int finalHash = GetHashCode(SettingsReceiveBuffer);

                if (finalHash == SettingsReceiveHash)
                {
                    Log($"Settings transfer complete, unpacking them now");

                    var loadingTask = Task.Run(() => {
                        var settingsPkg = new ZPackage(SettingsReceiveBuffer);
                        var settings    = BetterContinentsSettings.Load(settingsPkg);
                        WorldCache.Add(settingsPkg);
                        return(settings);
                    });

                    try
                    {
                        UI.Add("ReceivedSettings", () => UI.DisplayMessage($"Better Continents: initializing from server config"));
                        yield return(new WaitUntil(() => loadingTask.IsCompleted));
                    }
                    finally
                    {
                        UI.Remove("ReceivedSettings");
                    }

                    if (loadingTask.IsFaulted)
                    {
                        LastConnectionError = $"Better Continents: cached world settings failed to load ({loadingTask.Exception.Message}), please reconnect to download them again!";
                        LogError(LastConnectionError);
                        m_connectionStatus.SetValue(null, ZNet.ConnectionStatus.ErrorConnectFailed);
                        ZNet.instance.Disconnect(peer);
                        yield break;
                    }

                    Settings = loadingTask.Result;
                    Settings.Dump();

                    // We only care about server/client version match when the server sends a world that actually uses the mod
                    if (Settings.EnabledForThisWorld && ServerVersion != ModInfo.Version)
                    {
                        LastConnectionError = $"Better Continents: world has Better Continents enabled, but server {ServerVersion} and client {ModInfo.Version} mod versions don't match";
                        LogError(LastConnectionError);
                        m_connectionStatus.SetValue(null, ZNet.ConnectionStatus.ErrorConnectFailed);
                        ZNet.instance.Disconnect(peer);
                    }
                    else if (!Settings.EnabledForThisWorld)
                    {
                        Log($"Server world does not have Better Continents enabled, skipping version check");
                    }

                    peer.m_rpc.Invoke("BetterContinentsReady", 0);
                }
                else
                {
                    LogError($"{LastConnectionError}: hash mismatch, got {finalHash}, expected {SettingsReceiveHash}");
                    m_connectionStatus.SetValue(null, ZNet.ConnectionStatus.ErrorConnectFailed);
                    ZNet.instance.Disconnect(peer);
                }
            }
Exemple #5
0
    public void ReadBiomeData(ref ZPackage package)
    {
        // mountain
        minMountainHeight = package.ReadSingle();

        // ashlands/deepnorth
        minAshlandsDist  = package.ReadSingle();
        minDeepNorthDist = package.ReadSingle();

        // swamp
        swampBiomeScaleX = package.ReadSingle();
        swampBiomeScaleY = package.ReadSingle();
        minSwampNoise    = package.ReadSingle();
        minSwampDist     = package.ReadSingle();
        maxSwampDist     = package.ReadSingle();
        minSwampHeight   = package.ReadSingle();
        maxSwampHeight   = package.ReadSingle();

        // mistlands
        mistlandsBiomeScaleX = package.ReadSingle();
        mistlandsBiomeScaleY = package.ReadSingle();
        minMistlandsNoise    = package.ReadSingle();
        minMistlandsDist     = package.ReadSingle();
        maxMistlandsDist     = package.ReadSingle();

        // plains
        plainsBiomeScaleX = package.ReadSingle();
        plainsBiomeScaleY = package.ReadSingle();
        minPlainsNoise    = package.ReadSingle();
        minPlainsDist     = package.ReadSingle();
        maxPlainsDist     = package.ReadSingle();

        // black forest
        blackForestBiomeScaleX = package.ReadSingle();
        blackForestBiomeScaleY = package.ReadSingle();
        minBlackForestNoise    = package.ReadSingle();
        minBlackForestDist     = package.ReadSingle();
        maxBlackForestDist     = package.ReadSingle();

        // switches
        meadowsSwitch     = (Heightmap.Biome)package.ReadInt();
        blackForestSwitch = (Heightmap.Biome)package.ReadInt();
        swampSwitch       = (Heightmap.Biome)package.ReadInt();
        mountainSwitch    = (Heightmap.Biome)package.ReadInt();
        plainsSwitch      = (Heightmap.Biome)package.ReadInt();
        mistlandsSwitch   = (Heightmap.Biome)package.ReadInt();
        ashlandsSwitch    = (Heightmap.Biome)package.ReadInt();
        deepNorthSwitch   = (Heightmap.Biome)package.ReadInt();

        // river
        riverMultipleMaxDistance = package.ReadSingle();
        riverExtremeMaxDistance  = package.ReadSingle();
        riverMaxHeight           = package.ReadSingle();
        riverWidthMaxLowerRange  = package.ReadSingle();
        riverWidthMaxUpperRange  = package.ReadSingle();
        riverWidthMinLowerRange  = package.ReadSingle();
        riverCurveWidth          = package.ReadSingle();
        riverWavelength          = package.ReadSingle();
    }
Exemple #6
0
        public static void ServerSendKnownRecipes(ZNetPeer peer)
        {
            var pkg = new ZPackage();

            WriteServerKnownRecipes(PlayerKnownRecipes, pkg);

            ZRoutedRpc.instance.InvokeRoutedRPC(peer.m_uid, Name_RPC_ServerKnownRecipes, pkg);
        }
Exemple #7
0
 public void Serialize(ZPackage pkg)
 {
     pkg.Write(NoiseLayers.Count);
     for (int i = 0; i < NoiseLayers.Count; i++)
     {
         NoiseLayers[i].Serialize(pkg);
     }
 }
    // Token: 0x060009B2 RID: 2482 RVA: 0x00046BB0 File Offset: 0x00044DB0
    private void QueuePackage(byte[] data)
    {
        ZPackage item = new ZPackage(data);

        this.m_pkgQueue.Enqueue(item);
        this.m_gotData    = true;
        this.m_totalRecv += data.Length;
    }
Exemple #9
0
        public bool Deserialize(ZPackage zpg)
        {
            Debug.LogWarning($"Deserialized config ({_sourceFile})");
            var configJson = zpg.ReadString();

            _config = EpicLoot.EpicLoot.JsonToObject <T>(configJson);
            return(_config != null);
        }
Exemple #10
0
    // Token: 0x06000917 RID: 2327 RVA: 0x00043750 File Offset: 0x00041950
    public static object[] Deserialize(ZRpc rpc, ParameterInfo[] paramInfo, ZPackage pkg)
    {
        List <object> list = new List <object>();

        list.Add(rpc);
        ZRpc.Deserialize(paramInfo, pkg, ref list);
        return(list.ToArray());
    }
Exemple #11
0
 private void writeFinger(ZPackage pkg, Transform finger)
 {
     pkg.Write(finger.localRotation);
     if (finger.childCount > 0)
     {
         writeFinger(pkg, finger.GetChild(0));
     }
 }
Exemple #12
0
        private static void ZNet_OnNewConnection(ZNet __instance, ZNetPeer peer)
        {
            // clear the previous connection, if existing
            LastServerVersion = null;

            // Register our RPC very early
            peer.m_rpc.Register <ZPackage>(nameof(RPC_Jotunn_ReceiveVersionData), RPC_Jotunn_ReceiveVersionData);
        }
        // Save all online players.
        public static void SaveAll()
        {
            ZPackage pkg = new ZPackage(); // Create ZPackage
            string   msg = "SaveAll";

            pkg.Write(msg);
            ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "SaveAll", new object[] { pkg });
        }
Exemple #14
0
    public static object[] Deserialize(long callerID, ParameterInfo[] paramInfo, ZPackage pkg)
    {
        List <object> parameters = new List <object>();

        parameters.Add((object)callerID);
        ZRpc.Deserialize(paramInfo, pkg, ref parameters);
        return(parameters.ToArray());
    }
Exemple #15
0
    // Token: 0x06000C0A RID: 3082 RVA: 0x000559B8 File Offset: 0x00053BB8
    public static World LoadWorld(string name)
    {
        FileStream fileStream = null;

        try
        {
            fileStream = File.OpenRead(World.GetMetaPath(name));
        }
        catch
        {
            if (fileStream != null)
            {
                fileStream.Dispose();
            }
            ZLog.Log("  failed to load " + name);
            return(new World(name, true, false));
        }
        World result;

        try
        {
            BinaryReader binaryReader = new BinaryReader(fileStream);
            int          count        = binaryReader.ReadInt32();
            ZPackage     zpackage     = new ZPackage(binaryReader.ReadBytes(count));
            int          num          = zpackage.ReadInt();
            if (!global::Version.IsWorldVersionCompatible(num))
            {
                ZLog.Log("incompatible world version " + num);
                result = new World(name, false, true);
            }
            else
            {
                World world = new World();
                world.m_name     = zpackage.ReadString();
                world.m_seedName = zpackage.ReadString();
                world.m_seed     = zpackage.ReadInt();
                world.m_uid      = zpackage.ReadLong();
                if (num >= 26)
                {
                    world.m_worldGenVersion = zpackage.ReadInt();
                }
                result = world;
            }
        }
        catch
        {
            ZLog.LogWarning("  error loading world " + name);
            result = new World(name, true, false);
        }
        finally
        {
            if (fileStream != null)
            {
                fileStream.Dispose();
            }
        }
        return(result);
    }
        // Request that the server shuts itself down
        public static void ShutdownServer()
        {
            ZPackage pkg = new ZPackage(); // Create ZPackage
            string   msg = "ShutdownServer";

            pkg.Write(msg);
            Debug.Log($"{ModInfo.Title}: C->S ShutdownServer");
            ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "ShutdownServer", new object[] { pkg });
        }
Exemple #17
0
 // Token: 0x06001161 RID: 4449 RVA: 0x00078784 File Offset: 0x00076984
 public void Deserialize(ZPackage pkg)
 {
     this.m_msgID        = pkg.ReadLong();
     this.m_senderPeerID = pkg.ReadLong();
     this.m_targetPeerID = pkg.ReadLong();
     this.m_targetZDO    = pkg.ReadZDOID();
     this.m_methodHash   = pkg.ReadInt();
     this.m_parameters   = pkg.ReadPackage();
 }
Exemple #18
0
 // Token: 0x06001160 RID: 4448 RVA: 0x0007872C File Offset: 0x0007692C
 public void Serialize(ZPackage pkg)
 {
     pkg.Write(this.m_msgID);
     pkg.Write(this.m_senderPeerID);
     pkg.Write(this.m_targetPeerID);
     pkg.Write(this.m_targetZDO);
     pkg.Write(this.m_methodHash);
     pkg.Write(this.m_parameters);
 }
        public static WorldPlayer Load(ZPackage pkg)
        {
            var worldPlayer = new WorldPlayer();

            int num = pkg.ReadInt();

            if (!ValheimVersion.IsPlayerVersionCompatible(num))
            {
                return(null);
            }
            if (num >= 28)
            {
                worldPlayer.PlayerStats_kills  = pkg.ReadInt();
                worldPlayer.PlayerStats_deaths = pkg.ReadInt();
                worldPlayer.PlayerStats_crafts = pkg.ReadInt();
                worldPlayer.PlayerStats_builds = pkg.ReadInt();
            }
            worldPlayer.WorldPlayerData.Clear();
            int num2 = pkg.ReadInt();

            for (int i = 0; i < num2; i++)
            {
                long key             = pkg.ReadLong();
                var  worldPlayerData = new WorldPlayerData();
                worldPlayerData.m_haveCustomSpawnPoint = pkg.ReadBool();
                worldPlayerData.m_spawnPoint           = pkg.ReadVector3();
                worldPlayerData.m_haveLogoutPoint      = pkg.ReadBool();
                worldPlayerData.m_logoutPoint          = pkg.ReadVector3();
                if (num >= 30)
                {
                    worldPlayerData.m_haveDeathPoint = pkg.ReadBool();
                    worldPlayerData.m_deathPoint     = pkg.ReadVector3();
                }
                worldPlayerData.m_homePoint = pkg.ReadVector3();
                if (num >= 29 && pkg.ReadBool())
                {
                    worldPlayerData.m_mapData = pkg.ReadByteArray();
                }
                worldPlayer.WorldPlayerData.Add(key, worldPlayerData);
            }
            worldPlayer.PlayerName = pkg.ReadString();
            worldPlayer.PlayerId   = pkg.ReadLong();
            worldPlayer.StartSeed  = pkg.ReadString();
            if (pkg.ReadBool())
            {
                var byteArray = pkg.ReadByteArray();

                var playerPkg = new ZPackage(byteArray);

                worldPlayer.Player = PlayerReaderWriter.Load(playerPkg);
            }
            else
            {
                worldPlayer.Player = null;
            }
            return(worldPlayer);
        }
Exemple #20
0
        /*public void RPC_SpawnBounties(long sender, ZPackage pkg)
         * {
         *  var bounty = BountyInfo.FromPackage(pkg);
         *  Debug.LogWarning($"RPC_SpawnBounties: {bounty.ID}");
         * }*/

        private void RPC_Client_SlayBountyTargetFromServer(long sender, ZPackage pkg, string monsterID, bool isAdd)
        {
            if (Common.Utils.IsServer())
            {
                return;
            }

            RPC_SlayBountyTarget(sender, pkg, monsterID, isAdd);
        }
        // Ask the server to reload all available zones **ADMIN ONLY**
        public static void ReloadZones()
        {
            ZPackage pkg = new ZPackage(); // Create ZPackage
            string   msg = "reloadzones";

            pkg.Write(msg);
            ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "ReloadZones", new object[] { pkg });
            return;
        }
Exemple #22
0
        private static void RPC_DropThatReceiveDataTest(ZRpc rpc, ZPackage pkg)
        {
            int packageSize = pkg.Size();

            ReceivedCount++;
            ReceivedBytes += packageSize;

            Log.LogInfo($"Received package {ReceivedCount} with size {packageSize}. Total received: {ReceivedBytes}");
        }
Exemple #23
0
        /// <summary>
        ///     Receive and handle an incoming package
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="package"></param>
        internal void ReceivePackage(long sender, ZPackage package)
        {
            if (package == null || package.Size() <= 0)
            {
                return;
            }

            Logger.LogDebug($"[{ID}] Received package");
            try
            {
                CacheExpirations.RemoveAll(kv =>
                {
                    if (kv.Key < DateTimeOffset.Now.Ticks)
                    {
                        PackageCache.Remove(kv.Value);
                        return(true);
                    }

                    return(false);
                });

                byte packageFlags = package.ReadByte();

                if ((packageFlags & FRAGMENTED_PACKAGE) != 0)
                {
                    long   uniqueIdentifier = package.ReadLong();
                    string cacheKey         = sender.ToString() + uniqueIdentifier;
                    int    fragment         = package.ReadInt();
                    int    fragments        = package.ReadInt();

                    if (!PackageCache.TryGetValue(cacheKey, out SortedDictionary <int, byte[]> dataFragments))
                    {
                        dataFragments          = new SortedDictionary <int, byte[]>();
                        PackageCache[cacheKey] = dataFragments;
                        CacheExpirations.Add(new KeyValuePair <long, string>(DateTimeOffset.Now.AddSeconds(60).Ticks, cacheKey));
                    }

                    dataFragments.Add(fragment, package.ReadByteArray());

                    if (dataFragments.Count < fragments)
                    {
                        return;
                    }

                    PackageCache.Remove(cacheKey);

                    package      = new ZPackage(dataFragments.Values.SelectMany(a => a).ToArray());
                    packageFlags = package.ReadByte();
                }

                ZNet.instance.StartCoroutine(HandlePackageRoutine(sender, package, packageFlags));
            }
            catch (Exception e)
            {
                Logger.LogWarning($"[{ID}] Error caught while applying package: {e}");
            }
        }
        public static void OnReceiveMapDataInitial(ZRpc client, ZPackage mapData)
        {
            if (!Store.IsSharingMap())
            {
                return;
            }

            mapData.SetPos(0);

            var chunk = mapData.ReadInt();
            //Utility.Log("Client received initial map data by server chunk " + (chunk+1) + "/" + CHUNKS);

            var explored   = ExplorationDatabase.UnpackBoolArray(mapData, ExplorationDatabase.MapSizeSquared / CHUNKS);
            var startIndex = chunk * (ExplorationDatabase.MapSizeSquared / CHUNKS);

            for (var index = 0; index < explored.Length; index++)
            {
                if (explored[index])
                {
                    _Minimap.Explore(_Minimap._instance, (startIndex + index) % ExplorationDatabase.MapSize, (startIndex + index) / ExplorationDatabase.MapSize);
                }
            }

            var fogTexture = Traverse.Create((_Minimap._instance)).Field("m_fogTexture").GetValue() as Texture2D;

            fogTexture.Apply();


            _ZNet._instance.StartCoroutine(SendChunkToServer(client, chunk));


            // var explored = ExplorationDatabase.UnpackBoolArray(mapData);
            //
            // for (var index = 0; index < explored.Length; index++)
            // {
            //     if (explored[index])
            //     {
            //         _Minimap.Explore(_Minimap._instance, index % ExplorationDatabase.MapSize, index / ExplorationDatabase.MapSize);
            //     }
            // }
            //
            // var fogTexture =  Traverse.Create((_Minimap._instance)).Field("m_fogTexture").GetValue() as Texture2D;
            // fogTexture.Apply();
            //
            // explored = Traverse.Create(_Minimap._instance).Field("m_explored").GetValue() as bool[];
            // var z = ExplorationDatabase.PackBoolArray(explored);
            // if (_ZNet.IsServer(_ZNet._instance))
            // {
            //     OnClientInitialData(null, z);
            // }
            // else
            // {
            //     var znet =  Traverse.Create(typeof(ZNet)).Field("m_instance").GetValue() as ZNet;
            //     ZRpc server = _ZNet.GetServerRPC(znet);
            //     server.Invoke("OnClientInitialData", (object) z);
            // }
        }
Exemple #25
0
    // Token: 0x060008E9 RID: 2281 RVA: 0x00042BC4 File Offset: 0x00040DC4
    public void ReadPackage(ref ZPackage pkg)
    {
        int count = this.m_reader.ReadInt32();

        byte[] array = this.m_reader.ReadBytes(count);
        pkg.Clear();
        pkg.m_stream.Write(array, 0, array.Length);
        pkg.m_stream.Position = 0L;
    }
Exemple #26
0
        public static SerializableVector3 FromPackage(ZPackage pkg)
        {
            var result = new SerializableVector3();

            result.x = pkg.ReadSingle();
            result.y = pkg.ReadSingle();
            result.z = pkg.ReadSingle();
            return(result);
        }
        public static BountyTargetInfo FromPackage(ZPackage pkg)
        {
            var result = new BountyTargetInfo();

            result.MonsterID = pkg.ReadString();
            result.Count     = pkg.ReadInt();
            result.Level     = pkg.ReadInt();
            return(result);
        }
 public static void SaveExplorationData(ZNet instance)
 {
     // Save exploration data only on the server
     if (ZNet.instance.IsServerInstance() && Configuration.Current.MapServer.IsEnabled && Configuration.Current.MapServer.shareMapProgression)
     {
         var mapData = new ZPackage(CreateExplorationData().ToArray());
         mapData.WriteToFile(Path.Combine(Configuration.ConfigIniPath, ZNet.instance.GetWorldUID().ToString(), "Explorationdata.bin"));
     }
 }
Exemple #29
0
 private bool LoadPlayerFromDisk()
 {
     try
     {
         ZPackage zpackage = this.LoadPlayerDataFromDisk();
         if (zpackage == null)
         {
             ZLog.LogWarning((object)"No player data");
             return(false);
         }
         int version = zpackage.ReadInt();
         if (!Version.IsPlayerVersionCompatible(version))
         {
             ZLog.Log((object)"Player data is not compatible, ignoring");
             return(false);
         }
         if (version >= 28)
         {
             this.m_playerStats.m_kills  = zpackage.ReadInt();
             this.m_playerStats.m_deaths = zpackage.ReadInt();
             this.m_playerStats.m_crafts = zpackage.ReadInt();
             this.m_playerStats.m_builds = zpackage.ReadInt();
         }
         this.m_worldData.Clear();
         int num = zpackage.ReadInt();
         for (int index = 0; index < num; ++index)
         {
             long key = zpackage.ReadLong();
             PlayerProfile.WorldPlayerData worldPlayerData = new PlayerProfile.WorldPlayerData();
             worldPlayerData.m_haveCustomSpawnPoint = zpackage.ReadBool();
             worldPlayerData.m_spawnPoint           = zpackage.ReadVector3();
             worldPlayerData.m_haveLogoutPoint      = zpackage.ReadBool();
             worldPlayerData.m_logoutPoint          = zpackage.ReadVector3();
             if (version >= 30)
             {
                 worldPlayerData.m_haveDeathPoint = zpackage.ReadBool();
                 worldPlayerData.m_deathPoint     = zpackage.ReadVector3();
             }
             worldPlayerData.m_homePoint = zpackage.ReadVector3();
             if (version >= 29 && zpackage.ReadBool())
             {
                 worldPlayerData.m_mapData = zpackage.ReadByteArray();
             }
             this.m_worldData.Add(key, worldPlayerData);
         }
         this.m_playerName = zpackage.ReadString();
         this.m_playerID   = zpackage.ReadLong();
         this.m_startSeed  = zpackage.ReadString();
         this.m_playerData = !zpackage.ReadBool() ? (byte[])null : zpackage.ReadByteArray();
     }
     catch (Exception ex)
     {
         ZLog.LogWarning((object)("Exception while loading player profile:" + this.m_filename + " , " + ex.ToString()));
     }
     return(true);
 }
Exemple #30
0
        /// <summary>
        ///     Coroutine to send a package to a list of peers. Compresses and fragments the package if necessary.
        /// </summary>
        /// <param name="peers"></param>
        /// <param name="package"></param>
        /// <returns></returns>
        public IEnumerator SendPackageRoutine(List <ZNetPeer> peers, ZPackage package)
        {
            if (!ZNet.instance)
            {
                yield break;
            }

            if (peers.Count == 0)
            {
                yield break;
            }

            try
            {
                ++SendCount;

                byte[]   originalData  = package.GetArray();
                ZPackage jotunnpackage = new ZPackage();
                jotunnpackage.Write(JOTUNN_PACKAGE);
                jotunnpackage.Write(originalData);
                package = jotunnpackage;

                const int compressMinSize = 10000;

                if (package.Size() > compressMinSize)
                {
                    byte[] rawData = package.GetArray();
                    Logger.LogDebug($"[{ID}] Compressing package with length {rawData.Length}");

                    ZPackage compressedPackage = new ZPackage();
                    compressedPackage.Write(COMPRESSED_PACKAGE);
                    MemoryStream output = new MemoryStream();
                    using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal))
                    {
                        deflateStream.Write(rawData, 0, rawData.Length);
                    }

                    compressedPackage.Write(output.ToArray());
                    package = compressedPackage;
                }

                List <IEnumerator <bool> > writers =
                    peers.Where(peer => peer.IsReady()).Select(p => SendToPeer(p, package)).ToList();
                writers.RemoveAll(writer => !writer.MoveNext());
                while (writers.Count > 0)
                {
                    yield return(null);

                    writers.RemoveAll(writer => !writer.MoveNext());
                }
            }
            finally
            {
                --SendCount;
            }
        }