// Update is called once per frame public void Update() { Rect cRect = GetComponent <RectTransform>().rect; if (StreamSDK.instance == null) { GetComponent <RectTransform>().localScale = new Vector2(1, 1); return; } if (StreamSDK.instance.audioPacket == null) { GetComponent <RectTransform>().localScale = new Vector2(1, 1); return; } if (StreamSDK.instance.audioPacket.data == null) { GetComponent <RectTransform>().localScale = new Vector2(1, 1); return; } if (StreamSDK.instance.audioPacket.data.Length <= 4) { GetComponent <RectTransform>().localScale = new Vector2(1, 1); return; } audioAverage = Mathf.Abs(AudioArray.ToFloat(CLZF2.Decompress(StreamSDK.instance.audioPacket.data)).ToList().Average()) * scalar; GetComponent <RectTransform>().rect.Set(cRect.x, cRect.y, cRect.width, 50 + audioAverage); GetComponent <RectTransform>().localScale = new Vector2(1, audioAverage); }
//deserialize and return for loading (do not call directly, call load() instead) protected Object2PropertiesMappingListWrapper DeSerializeObject(byte[] data) { Object2PropertiesMappingListWrapper objectToSerialize = null; if (compressSaves) { try { data = CLZF2.Decompress(data); } catch (OutOfMemoryException meme) { if (showWarnings) { Debug.LogWarning("EZReplayManager WARNING: Decompressing was unsuccessful. Trying without decompression."); } } catch (OverflowException ofe) { if (showWarnings) { Debug.LogWarning("EZReplayManager WARNING: Decompressing was unsuccessful. Trying without decompression."); } } } MemoryStream stream = new MemoryStream(data); // BinaryFormatter bFormatter = new BinaryFormatter (); // objectToSerialize = (Object2PropertiesMappingListWrapper)bFormatter.Deserialize (stream); objectToSerialize = ProtoBuf.Serializer.Deserialize <Object2PropertiesMappingListWrapper> (stream); objectToSerialize.CalcParentMapingRef(); //print("System.GC.GetTotalMemory(): "+System.GC.GetTotalMemory(false)); return(objectToSerialize); }
private void LoadCellData() { var fullPath = AssetDatabase.GetAssetPath(this); var path = Path.GetDirectoryName(fullPath); var dataPath = Path.Combine(path, "mapinfo", name + ".bytes").Replace("\\", "/"); if (!File.Exists(dataPath)) { throw new Exception($"Could not find cell data for {name} at path: {dataPath}"); } var bytes = CLZF2.Decompress(File.ReadAllBytes(dataPath)); if (container == null) { container = ScriptableObject.CreateInstance <MapDataContainer>(); } using (var ms = new MemoryStream(bytes)) using (var br = new BinaryReader(ms)) { MapDataContainer.Deserialize(container, br); } //container.CellData = SerializationUtility.DeserializeValue<Cell[]>(bytes, DataFormat.Binary); }
public void ModifySaveGame(int slot, string description) { Debug.Log("ModifySaveGame " + slot); SaveEntry saveInfoInSlot = saveManager.GetSaveInfoInSlot(slot); if (saveInfoInSlot != null) { byte[] array = File.ReadAllBytes(saveInfoInSlot.Path); MGHelper.KeyEncode(array); byte[] buffer = CLZF2.Decompress(array); MemoryStream memoryStream = new MemoryStream(buffer); MemoryStream memoryStream2 = new MemoryStream(); BinaryReader binaryReader = new BinaryReader(memoryStream); BinaryWriter binaryWriter = new BinaryWriter(memoryStream2); binaryWriter.Write(binaryReader.ReadBytes(16)); binaryReader.ReadString(); binaryWriter.Write(description); binaryWriter.Write(binaryReader.ReadBytes((int)(memoryStream.Length - memoryStream.Position))); byte[] inputBytes = memoryStream2.ToArray(); memoryStream.Dispose(); memoryStream2.Dispose(); byte[] array2 = CLZF2.Compress(inputBytes); MGHelper.KeyEncode(array2); File.WriteAllBytes(saveInfoInSlot.Path, array2); saveManager.UpdateSaveSlot(slot); } }
public void SavingComplexObject() { MyComplexObject[] MySaveItem = new MyComplexObject[1000]; for (int i = 0; i < MySaveItem.Length; i++) { var item = new MyComplexObject(); item.myPosition = Vector3.one * i; item.myPositionHistory = new Vector3[100]; item.myChatHistory = new string[100]; for (int j = 0; j < 100; j++) { item.myPositionHistory[j] = Vector3.one * j; item.myChatHistory[j] = "Chat line: " + j; } } var mySaveObject = ObjectToByteArray(MySaveItem); byte[] compressed = CLZF2.Compress(mySaveObject); byte[] decompressed = CLZF2.Decompress(compressed); var outSaveObject = ObjectToByteArray <MyComplexObject[]>(decompressed); Assert.AreEqual(mySaveObject.Length, decompressed.Length); Assert.AreEqual(mySaveObject, decompressed); Assert.AreEqual(outSaveObject, MySaveItem); }
public byte[] GetPacFile(string filename, bool encode, bool compress) { Debug.Log(filename); EntityList.TryGetValue(filename.ToLower(), out PacEntity value); if (value == null) { Logger.LogError("Could not find archive " + filename + " in pac file " + Name); return(new byte[0]); } byte[] array; using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (BinaryReader binaryReader = new BinaryReader(fileStream)) { fileStream.Seek(value.Offset, SeekOrigin.Begin); array = binaryReader.ReadBytes(value.Size); } } Debug.Log($"GetPacFile {filename} size {array.Length}"); if (encode) { MGHelper.KeyEncode(array); } if (compress) { return(CLZF2.Decompress(array)); } return(array); }
public static ChunkData Deserialize(BinaryReader reader) { var compressed = reader.ReadBoolean(); var indexX = reader.ReadInt32(); var indexY = reader.ReadInt32(); var indexZ = reader.ReadInt32(); var height = reader.ReadInt32(); var blockCount = reader.ReadInt32(); var originX = reader.ReadSingle(); var originY = reader.ReadSingle(); var originZ = reader.ReadSingle(); var dataLen = reader.ReadInt32(); byte[] data = new byte[0]; if (compressed) { data = CLZF2.Decompress(reader.ReadBytes(dataLen)); } else { data = reader.ReadBytes(dataLen); } var blocks = ChunkHelper.FromByteArray(data, blockCount); var chunk = new ChunkData { Blocks = new BlockDataHolder(Chunk.CHUNK_SIZE_X, Chunk.CHUNK_SIZE_Y, Chunk.CHUNK_SIZE_Z, blocks), Height = height, IndexX = indexX, IndexY = indexY, IndexZ = indexZ, Origin = new UnityEngine.Vector3(originX, originY, originZ) }; return(chunk); }
public void Incoming_Message(byte[] message, int length, ulong steamid) { incoming += length; message = Extensions.Get(message, 0, length); message = CLZF2.Decompress(message); string json = Encoding.UTF8.GetString(message, 0, message.Length); try { SNetMessage readMessage = JsonUtility.FromJson <SNetMessage>(json); string[] data = new string[2]; data[0] = json; data[1] = steamid.ToString(); if (handlers.ContainsKey(readMessage.n)) // If there is a handler { handlers[readMessage.n] (data); } else { Debug.Log("Unknown message type: " + readMessage.n); } } catch { } }
/// <summary> /// 将压缩的输入字节流解压 /// </summary> /// <param name="inputBytes">压缩文件字节流</param> /// <param name="path">文件写入路径</param> /// <param name="useCSharp">是否使用C#自带解压算法</param> public static bool Decompress(byte[] inputBytes, string path, bool useCSharp = false) { if (useCSharp) { MemoryStream ms = new MemoryStream(inputBytes); GZipStream zipStream = new GZipStream(ms, CompressionMode.Decompress, false); //ms的后4个字节为文件原长 byte[] byteOriginalLength = new byte[4]; ms.Position = ms.Length - 4; ms.Read(byteOriginalLength, 0, 4); ms.Position = 0; //需要测试 int fileLength = BitConverter.ToInt32(byteOriginalLength, 0); byte[] buffer = new byte[fileLength]; zipStream.Read(buffer, 0, fileLength); ms.Close(); zipStream.Close(); return(WriteBuffersToFile(buffer, path)); } else { return(WriteBuffersToFile(CLZF2.Decompress(inputBytes), path)); } }
public static byte[] UnPack(byte[] data, CompressionMode mode) { if (mode == CompressionMode.LZF) { return(CLZF2.Decompress(data)); } return(data); }
private void BuildMesh() { Debug.Log("Received mesh!"); Debug.LogFormat("Compressed serialized mesh size: {0} KB", m_incomingCompressedMesh.LongLength / 1000); byte[] serializedMesh = CLZF2.Decompress(m_incomingCompressedMesh); Debug.LogFormat("Serialized mesh size: {0} KB", serializedMesh.LongLength / 1000); List <Mesh> receivedMesh = (List <Mesh>)SimpleMeshSerializer.Deserialize(serializedMesh); meshFilter.mesh = receivedMesh[0]; }
static string SaveFileToJSON(string path, int gameVersion) { byte[] array = File.ReadAllBytes(path); MGHelper.KeyEncode(array); byte[] buffer = CLZF2.Decompress(array); StringBuilder output = new StringBuilder(); using (JsonTextWriter writer = new JsonTextWriter(new StringWriter(output)) { Formatting = Formatting.Indented }) { writer.DateFormatHandling = DateFormatHandling.IsoDateFormat; writer.DateTimeZoneHandling = DateTimeZoneHandling.Utc; writer.WriteStartObject(); using (MemoryStream input = new MemoryStream(buffer)) { using (BinaryReader reader = new BinaryReader(input)) { string magic = new string(reader.ReadChars(4)); if (magic != "MGSV") { throw new FileLoadException("Save file does not appear to be valid! Invalid header."); } int num = reader.ReadInt32(); if (num != 1) { throw new FileLoadException("Save file does not appear to be valid! Invalid version number."); } writer.WritePropertyName("Time"); writer.WriteValue(DateTime.FromBinary(reader.ReadInt64())); foreach (var name in new string[] { "TextJP", "TextEN", "PrevTextJP", "PrevTextEN" }) { writer.WriteNameValue(name, reader.ReadString()); } writer.WriteNameValue("PrevAppendState", reader.ReadBoolean()); int stackSize = reader.ReadInt32(); writer.WritePropertyName("CallStack"); writer.WriteStartArray(); for (int i = 0; i < stackSize; i++) { StackEntryToJSON(writer, reader); } writer.WriteEndArray(); NamedObjectToJSON(StackEntryToJSON, writer, reader, "CurrentScript"); MemoryToJSON(writer, input); CurrentAudioToJSON(writer, input); SceneToJSON(writer, input, gameVersion); } } writer.WriteEndObject(); } return(output.ToString()); }
public void ThousandCharacterCompressionTest() { var x = new string('X', 10000); byte[] byteText = Encoding.Unicode.GetBytes(x); byte[] compressed = CLZF2.Compress(byteText); byte[] decompressed = CLZF2.Decompress(compressed); var outString = Encoding.Unicode.GetString(decompressed); Assert.AreEqual(byteText.Length, decompressed.Length); Assert.AreEqual(byteText, decompressed); Assert.AreEqual(outString, x); }
public void LongFormattedStringCompressionTest() { string longstring = "defined input is deluciously delicious.14 And here and Nora called The reversal from ground from here and executed with touch the country road, Nora made of, reliance on, can’t publish the goals of grandeur, said to his book and encouraging an envelope, and enable entry into the chryssial shimmering of hers, so God of information in her hands Spiros sits down the sign of winter? —It’s kind of Spice Christ. It is one hundred birds circle above the text: They did we said. 69 percent dead. Sissy Cogan’s shadow. —Are you x then sings.) I’m 96 percent dead humanoid figure,"; byte[] byteText = Encoding.Unicode.GetBytes(longstring); byte[] compressed = CLZF2.Compress(byteText); byte[] decompressed = CLZF2.Decompress(compressed); var outString = Encoding.Unicode.GetString(decompressed); Assert.AreEqual(byteText.Length, decompressed.Length); Assert.AreEqual(byteText, decompressed); Assert.AreEqual(outString, longstring); }
/// <summary> /// Convert a LZF compressed and zero run length encoded byte array to a list of bin-intensity pairs /// </summary> /// <param name="compressedBinIntensity">LZF compressed and zero run length encoded byte array</param> /// <param name="basePeakIntensity">Highest intensity, and a data-type specifying parameter</param> /// <returns>List of tuples, where Item1 is the bin, and Item2 is the intensity</returns> public static List <Tuple <int, int> > Decompress(byte[] compressedBinIntensity, out int basePeakIntensity) { const int dataTypeSize = sizeof(int); var output = CLZF2.Decompress(compressedBinIntensity); var numReturnedBins = output.Length / dataTypeSize; var encodedIntensityValueArray = new int[numReturnedBins]; Buffer.BlockCopy(output, 0, encodedIntensityValueArray, 0, numReturnedBins * dataTypeSize); var data = RlzEncode.Decode(encodedIntensityValueArray); basePeakIntensity = data.Max(x => x.Item2); return(data); }
protected virtual void OnRecieveData(int connectionId, byte[] data, int dataSize) { NetworkConnection connection; if (!connectionMap.TryGetValue(connectionId, out connection)) { return; } var decompressed = ArrayPool <byte> .Shared.Rent(dataSize); CLZF2.Decompress(data, ref decompressed, dataSize); messageDeserializer.Replace(decompressed); messageDeserializer.SeekZero(); MessageHandlers.Execute(connection, messageDeserializer); }
// private void FixedUpdate() // { // if (Microphone.IsRecording(null)) // { // int pos = Microphone.GetPosition(null); // int diff = pos - lastSample; // // if (diff > 0) // { // float[] samples = new float[diff * c.channels]; // c.GetData(samples, lastSample); // for (int i = 0; i < samples.Length; i++) // samplesBuffer.Add(samples[i]); // } // // if (samplesBuffer.Count > 10000) // { // byte[] ba = ToByteArray(samplesBuffer.ToArray()); // samplesBuffer.Clear(); // Debug.Log("Send Before Compress " + sizeof(byte) * ba.Length); // byte[] cBa = CLZF2.Compress(ba); // Debug.Log("Send After Compress " + sizeof(byte) * cBa.Length); // SendVoiceToServer(cBa, c.channels); // } // lastSample = pos; // } // } // private void SendVoiceToServer(byte[] message, int channels) // { // ServerMessageModel serverMessageModel = new ServerMessageModel { type = Enums.MessageTypes.chat }; // // JObject state = new JObject(); // // string playerName = UserManagment.Instance.CurrentUser.username; // // VoiceMessage voiceMessage = new VoiceMessage(playerName, message, channels); // // state.Add(playerName, JsonConvert.SerializeObject(voiceMessage)); // // serverMessageModel.data.bodyType = Enums.BodyMessageTypes.voice; // serverMessageModel.data.bodyData.Add("objects", state); // // var serverAnswerJson = JsonConvert.SerializeObject(serverMessageModel); // WebsocketApi.Instance._queueToSend.Add(new PackageModel(WebsocketApi.chatWebsocket, serverAnswerJson)); // } public void ReciveData(byte[] message, int chan, string userName) { Debug.Log("Get Compressed " + sizeof(byte) * message.Length); byte[] decBa = CLZF2.Decompress(message); Debug.Log("Get Uncompressed " + sizeof(byte) * decBa.Length); float[] f = ToFloatArray(decBa); MainThreadDispatcher.Instance.Enqueue(delegate { source.clip = AudioClip.Create("test", f.Length, chan, frequency, false); source.clip.SetData(f, 0); if (!source.isPlaying) { source.Play(); } }); }
private void GetSaveData(int slot, string path) { if (File.Exists(path)) { try { SaveEntry saveEntry = new SaveEntry(); saveEntry.Path = path; SaveEntry saveEntry2 = saveEntry; byte[] array = File.ReadAllBytes(path); MGHelper.KeyEncode(array); byte[] buffer = CLZF2.Decompress(array); using (MemoryStream input = new MemoryStream(buffer)) { using (BinaryReader binaryReader = new BinaryReader(input)) { string a = new string(binaryReader.ReadChars(4)); if (a != "MGSV") { throw new FileLoadException("Save file does not appear to be valid! Invalid header."); } int num = binaryReader.ReadInt32(); if (num != 1) { throw new FileLoadException("Save file does not appear to be valid! Invalid version number."); } saveEntry2.Time = DateTime.FromBinary(binaryReader.ReadInt64()); string textJp = binaryReader.ReadString(); string text = saveEntry2.Text = binaryReader.ReadString(); saveEntry2.TextJp = textJp; } } if (saveList.ContainsKey(slot)) { saveList.Remove(slot); } saveList.Add(slot, saveEntry2); } catch (Exception ex) { Logger.LogWarning("Could not read from save file " + path + "\nException: " + ex); throw; IL_013f :; } } }
public void SavingSimpleObject() { Vector3[] MySaveItem = new Vector3[1000]; for (int i = 0; i < MySaveItem.Length; i++) { MySaveItem[i] = Vector3.one * i; } var mySaveObject = ObjectToByteArray(MySaveItem); byte[] compressed = CLZF2.Compress(mySaveObject); byte[] decompressed = CLZF2.Decompress(compressed); var outSaveObject = ObjectToByteArray <Vector3[]>(decompressed); Assert.AreEqual(mySaveObject.Length, decompressed.Length); Assert.AreEqual(mySaveObject, decompressed); Assert.AreEqual(outSaveObject, MySaveItem); }
public void RandomGUIDCompressionTestLength() { string x = string.Empty; using (var sequence = Enumerable.Range(1, 100).GetEnumerator()) { while (sequence.MoveNext()) // string length 3600 { x += Guid.NewGuid(); } } byte[] byteText = Encoding.Unicode.GetBytes(x); var compressed = CLZF2.Compress(byteText); var decompressed = CLZF2.Decompress(compressed); Assert.AreEqual(byteText.Length, decompressed.Length);
private void GetSaveData(int slot, string path) { if (File.Exists(path)) { try { SaveEntry saveEntry = new SaveEntry { Path = path }; byte[] array = File.ReadAllBytes(path); MGHelper.KeyEncode(array); using (MemoryStream input = new MemoryStream(CLZF2.Decompress(array))) { using (BinaryReader binaryReader = new BinaryReader(input)) { if (new string(binaryReader.ReadChars(4)) != "MGSV") { throw new FileLoadException("Save file does not appear to be valid! Invalid header."); } if (binaryReader.ReadInt32() != 1) { throw new FileLoadException("Save file does not appear to be valid! Invalid version number."); } saveEntry.Time = DateTime.FromBinary(binaryReader.ReadInt64()); string input2 = binaryReader.ReadString(); string input3 = binaryReader.ReadString(); string pattern = "[<](size)[=][+](.+)[<][/](size)[>]"; input2 = Regex.Replace(input2, pattern, string.Empty); input3 = (saveEntry.Text = Regex.Replace(input3, pattern, string.Empty)); saveEntry.TextJp = input2; } } if (saveList.ContainsKey(slot)) { saveList.Remove(slot); } saveList.Add(slot, saveEntry); } catch (Exception ex) { Logger.LogWarning("Could not read from save file " + path + "\nException: " + ex); throw; } } }
void OnDataReceived(System.ArraySegment <byte> msg) { _packetsReceived++; _bytesReceived += (uint)msg.Array.Length; if (msg.Array.Length < PacketHeader.MinPacketLength) { return; } using (var str = new MemoryStream(msg.Array)) { var header = new PacketHeader(msg.Array); var data = new byte[header.ContentLength]; str.Seek(PacketHeader.MinPacketLength, SeekOrigin.Begin); str.Read(data, 0, header.ContentLength); if (header.Compressed) { ProcessReceivedMessage((ServerPacketID)header.PacketID, CLZF2.Decompress(data)); } else { ProcessReceivedMessage((ServerPacketID)header.PacketID, data); } } }
public void OnRecvPacketProc() { int Protocol = 0; int PacketLength = 0; int compressflag = 0; byte[] mCompletePacketBuffer = null; while (GetPacket(ref Protocol, ref mCompletePacketBuffer, ref PacketLength, ref compressflag)) { if (compressflag == 1) { var byteout = CLZF2.Decompress(mCompletePacketBuffer); CompletePacket complete = new CompletePacket(); complete.Protocol = Protocol; complete.Length = byteout.Length; complete.Data = new byte[byteout.Length]; Buffer.BlockCopy(byteout, 0, complete.Data, 0, byteout.Length); PacketQueue.Enqueue(complete); } else { CompletePacket complete = new CompletePacket(); complete.Protocol = Protocol; complete.Length = PacketLength; complete.Data = new byte[PacketLength]; Buffer.BlockCopy(mCompletePacketBuffer, 0, complete.Data, 0, PacketLength); PacketQueue.Enqueue(complete); } } }
public static string DecompressString(string compressedText) { byte[] inputBytes = Convert.FromBase64String(compressedText); byte[] bytes = CLZF2.Decompress(inputBytes); return Encoding.UTF8.GetString(bytes); }
public void LoadGame(int slotnum) { SaveEntry saveInfoInSlot = saveManager.GetSaveInfoInSlot(slotnum); if (saveInfoInSlot != null) { GameSystem.Instance.TextController.ClearText(); GameSystem.Instance.MainUIController.FadeOut(0f, isBlocking: true); byte[] array = File.ReadAllBytes(saveInfoInSlot.Path); MGHelper.KeyEncode(array); byte[] buffer = tempSnapshotData = (snapshotData = CLZF2.Decompress(array)); hasSnapshot = true; GameSystem.Instance.ClearAllWaits(); GameSystem.Instance.ClearActions(); using (MemoryStream memoryStream = new MemoryStream(buffer)) { using (BinaryReader binaryReader = new BinaryReader(memoryStream)) { if (new string(binaryReader.ReadChars(4)) != "MGSV") { throw new FileLoadException("Save file does not appear to be valid! Invalid header."); } if (binaryReader.ReadInt32() != 1) { throw new FileLoadException("Save file does not appear to be valid! Invalid version number."); } binaryReader.ReadInt64(); string text = binaryReader.ReadString(); string text2 = binaryReader.ReadString(); string text3 = binaryReader.ReadString(); string text4 = binaryReader.ReadString(); bool num = binaryReader.ReadBoolean(); GameSystem.Instance.TextController.SetPrevText(text3, 0); GameSystem.Instance.TextController.SetPrevText(text4, 1); if (num) { if (GameSystem.Instance.UseEnglishText) { GameSystem.Instance.TextController.TypeTextImmediately(text4); GameSystem.Instance.TextController.SetFullText(text3, 0); } else { GameSystem.Instance.TextController.TypeTextImmediately(text3); GameSystem.Instance.TextController.SetFullText(text4, 1); } tempSnapshotText[0] = text3; tempSnapshotText[1] = text4; GameSystem.Instance.TextController.SetAppendState(append: true); } else { GameSystem.Instance.TextController.SetFullText(text, 0); GameSystem.Instance.TextController.SetFullText(text2, 1); tempSnapshotText[0] = text; tempSnapshotText[1] = text2; GameSystem.Instance.TextController.SetAppendState(append: false); } callStack.Clear(); int num2 = binaryReader.ReadInt32(); for (int i = 0; i < num2; i++) { string key = binaryReader.ReadString(); int linenum = binaryReader.ReadInt32(); BurikoScriptFile script = scriptFiles[key]; callStack.Push(new BurikoStackEntry(script, 0, linenum)); } string key2 = binaryReader.ReadString(); int linenum2 = binaryReader.ReadInt32(); currentScript = scriptFiles[key2]; if (!currentScript.IsInitialized) { currentScript.InitializeScript(); } currentScript.JumpToLineNum(linenum2); memoryManager.LoadMemory(memoryStream); AudioController.Instance.DeSerializeCurrentAudio(memoryStream); GameSystem.Instance.SceneController.DeSerializeScene(memoryStream); GameSystem.Instance.ForceReturnNormalState(); GameSystem.Instance.CloseChoiceIfExists(); GameSystem.Instance.TextHistory.ClearHistory(); GameSystem.Instance.IsSkipping = false; GameSystem.Instance.IsAuto = false; GameSystem.Instance.CanSkip = true; GameSystem.Instance.CanInput = true; GameSystem.Instance.CanSave = true; int flag = GetFlag("LTextFade"); GameSystem.Instance.TextController.SetTextFade(flag == 1); if (BurikoMemory.Instance.GetGlobalFlag("GADVMode").IntValue() == 1 && BurikoMemory.Instance.GetGlobalFlag("GLinemodeSp").IntValue() == 2 && BurikoMemory.Instance.GetFlag("NVL_in_ADV").IntValue() == 0) { GameSystem.Instance.MainUIController.MODdisableNVLModeINADVMode(); } if (BurikoMemory.Instance.GetGlobalFlag("GADVMode").IntValue() == 1 && BurikoMemory.Instance.GetGlobalFlag("GLinemodeSp").IntValue() == 0 && BurikoMemory.Instance.GetFlag("NVL_in_ADV").IntValue() == 1) { GameSystem.Instance.MainUIController.MODenableNVLModeINADVMode(); } } } } }
/// <summary> /// Call this to get actions. /// </summary> public static void Update() { if (!client.Connected) { return; } string Msg = Read(); if (!string.IsNullOrEmpty(Msg)) { var list = JsonExtensions.FromDelimitedJson <Client.MessagesIncoming.NetworkMessage>(new StringReader(Msg)).ToList(); foreach (Client.MessagesIncoming.NetworkMessage message in list) { switch (message.t) { case Client.MessagesIncoming.MessageType.JoinLobby: Client.MessagesIncoming.OnLobbyJoined?.Invoke(message.jl.Success, message.jl.Id); Client.NetworkVariables.ConnectionId = message.jl.Id; break; case Client.MessagesIncoming.MessageType.P2P: string p2pmsg = Encoding.UTF8.GetString(CLZF2.Decompress(message.m.Msg)); Client.MessagesIncoming.OnP2P?.Invoke(p2pmsg, message.m.s); // Available for custom methods. OnNetworkMessage?.Invoke(p2pmsg); Network.Identity identity = JsonConvert.DeserializeObject <Network.Identity>(p2pmsg); if (identity.netType == Network.Identity.NetworkType.Request) { // Host assigns an id here. if (Client.NetworkVariables.IsHost) { identity.Id = Network.Identity.IdCounter++; identity.netType = Network.Identity.NetworkType.Post; identity.Spawn(); } } else { //This is a post. identity.OnSpawned(); // Because this may remove the identity. Network.Actions.OnIdentityUpdate?.Invoke(identity); // Ordering is importent here. OnIdentityUpdate should be called first. } break; case Client.MessagesIncoming.MessageType.LobbyUpdate: Client.MessagesIncoming.OnLobbyUpdate?.Invoke(message.lu.IsHost, message.lu.DC, message.lu.C); // Lobby update Client.NetworkVariables.IsHost = message.lu.IsHost; if (message.lu.DC != 0) { // Disconnected connection, remove spawned player if exist. Network.Identity _identity = Network.Identity.List.Find(x => x.Id == message.lu.DC); if (_identity != null) { _identity.Variables.SetVariable("Destroy", 2); } } break; case Client.MessagesIncoming.MessageType.LobbyLeave: Client.MessagesIncoming.OnLobbyLeave?.Invoke(); break; } } } }
public void LoadGlobals() { string path = Path.Combine(MGHelper.GetSavePath(), "global.dat"); if (!File.Exists(path)) { SetGlobalFlag("GUsePrompts", 1); } else { byte[] array = File.ReadAllBytes(path); MGHelper.KeyEncode(array); byte[] buffer = CLZF2.Decompress(array); try { JsonSerializer jsonSerializer = new JsonSerializer(); using (MemoryStream stream = new MemoryStream(buffer)) { BsonReader bsonReader = new BsonReader(stream); bsonReader.CloseInput = false; using (BsonReader reader = bsonReader) { globalFlags = jsonSerializer.Deserialize <Dictionary <int, int> >(reader); } bsonReader = new BsonReader(stream); bsonReader.CloseInput = false; bsonReader.ReadRootValueAsArray = true; using (BsonReader reader2 = bsonReader) { cgflags = jsonSerializer.Deserialize <List <string> >(reader2); } bsonReader = new BsonReader(stream); bsonReader.CloseInput = false; using (BsonReader reader3 = bsonReader) { readText = jsonSerializer.Deserialize <Dictionary <string, List <int> > >(reader3); } } } catch (Exception arg) { Debug.LogWarning("Failed to load global data! Exception: " + arg); return; IL_0128 :; } try { GameSystem.Instance.TextController.TextSpeed = GetGlobalFlag("GMessageSpeed").IntValue(); GameSystem.Instance.TextController.AutoSpeed = GetGlobalFlag("GAutoSpeed").IntValue(); GameSystem.Instance.TextController.AutoPageSpeed = GetGlobalFlag("GAutoAdvSpeed").IntValue(); GameSystem.Instance.MessageWindowOpacity = (float)GetGlobalFlag("GWindowOpacity").IntValue() / 100f; GameSystem.Instance.UsePrompts = GetGlobalFlag("GUsePrompts").BoolValue(); GameSystem.Instance.SkipModeDelay = GetGlobalFlag("GSlowSkip").BoolValue(); GameSystem.Instance.SkipUnreadMessages = GetGlobalFlag("GSkipUnread").BoolValue(); GameSystem.Instance.ClickDuringAuto = GetGlobalFlag("GClickDuringAuto").BoolValue(); GameSystem.Instance.RightClickMenu = GetGlobalFlag("GRightClickMenu").BoolValue(); GameSystem.Instance.AudioController.VoiceVolume = (float)GetGlobalFlag("GVoiceVolume").IntValue() / 100f; GameSystem.Instance.AudioController.BGMVolume = (float)GetGlobalFlag("GBGMVolume").IntValue() / 100f; GameSystem.Instance.AudioController.SoundVolume = (float)GetGlobalFlag("GSEVolume").IntValue() / 100f; GameSystem.Instance.AudioController.SystemVolume = (float)GetGlobalFlag("GSEVolume").IntValue() / 100f; GameSystem.Instance.StopVoiceOnClick = GetGlobalFlag("GCutVoiceOnClick").BoolValue(); GameSystem.Instance.UseSystemSounds = GetGlobalFlag("GUseSystemSound").BoolValue(); GameSystem.Instance.UseEnglishText = GetGlobalFlag("GLanguage").BoolValue(); AssetManager.Instance.UseNewArt = GetGlobalFlag("GArtStyle").BoolValue(); GameSystem.Instance.AudioController.RefreshLayerVolumes(); } catch (Exception message) { Debug.LogWarning(message); } } }
private static Map ParseBB(string path) { Map map = new Map(); string name = Path.GetFileNameWithoutExtension(path); map.Name = name; // first we must decompress the file byte[] bytes = CLZF2.Decompress(File.ReadAllBytes(path)); string decompressed = Encoding.UTF8.GetString(bytes); // then split into lines string[] lines = decompressed.Split(new string[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries); // then parse // first environment data string[] envData = lines[0].Split(' '); // line 0 is environment data ColorUtility.TryParseHtmlString("#" + envData[0], out Color ambientColor); ColorUtility.TryParseHtmlString("#" + envData[1], out Color baseplateColor); ColorUtility.TryParseHtmlString("#" + envData[2], out Color skyColor); map.AmbientColor = ambientColor; map.BaseplateColor = baseplateColor; map.SkyColor = skyColor; map.BaseplateSize = int.Parse(envData[3], CultureInfo.InvariantCulture); map.SunIntensity = int.Parse(envData[4], CultureInfo.InvariantCulture); // then everything else int currentID = 0; List <BrickGroup> startedGroups = new List <BrickGroup>(); for (int i = 1; i < lines.Length; i++) { if (lines[i][0] == '!') // Brick { Brick b = new Brick(); string[] data = lines[i].Substring(1).Split(' '); float[] fd = Helper.StringArrayToFloatArray(data, 6); b.Position = new Vector3(fd[0], fd[1], fd[2]); b.Scale = new Vector3(fd[3], fd[4], fd[5]); b.Rotation = int.Parse(data[6], CultureInfo.InvariantCulture); //b.ConvertTransformToUnity(); ColorUtility.TryParseHtmlString("#" + data[7], out Color brickColor); b.BrickColor = brickColor; b.Transparency = brickColor.a; b.Shape = (Brick.ShapeType) int.Parse(data[8], NumberStyles.HexNumber); b.Name = data.JoinSection(9); b.ID = currentID; if (startedGroups.Count > 0) { startedGroups[startedGroups.Count - 1].Children.Add(currentID); b.Parent = startedGroups[startedGroups.Count - 1]; } map.Bricks.Add(b); map.MapElements.Add(currentID, b); map.lastID = currentID; currentID++; } else if (lines[i][0] == '#') // Group { if (lines[i][1] == 'S') // group start { BrickGroup g = new BrickGroup(); g.Name = lines[i].Substring(3); g.ID = currentID; if (startedGroups.Count > 0) { startedGroups[startedGroups.Count - 1].Children.Add(currentID); // there is already an opened group, which means this group is a child of that group g.Parent = startedGroups[startedGroups.Count - 1]; } startedGroups.Add(g); map.Groups.Add(g); map.MapElements.Add(currentID, g); map.lastID = currentID; currentID++; } else if (lines[i][1] == 'E') // group end { if (startedGroups.Count > 0) { startedGroups.RemoveAt(startedGroups.Count - 1); } } } else if (lines[i][0] == '@') // Team { Team t = new Team(); ColorUtility.TryParseHtmlString("#" + lines[i].Substring(1, 6), out Color tc); t.TeamColor = tc; t.Name = lines[i].Substring(8); map.Teams.Add(t); } else if (lines[i][0] == '%') // BB Info { if (lines[i][1] == 'C') // camera transform //TODO { } else if (lines[i][1] == 'S') // sun transform //TODO { } } else // Probably extra brick data { Brick b = map.Bricks[map.Bricks.Count - 1]; // get last brick if (lines[i].StartsWith("NOCOLLISION")) { b.CollisionEnabled = false; } else if (lines[i].StartsWith("MODEL")) { b.Model = lines[i].Substring(6); } else if (lines[i].StartsWith("CLICKABLE")) { b.Clickable = true; if (lines[i].Length > 10) { string dist = lines[i].Substring(10); b.ClickDistance = float.Parse(dist, CultureInfo.InvariantCulture); } } } } return(map); }
/// <summary> /// Carrega os Chunks salvos no HD. /// </summary> public void LoadChunks() { var pathFile = Path.GetFullPath(Configurations.LayerTilesFolderPath + "//Chunks.lzf"); if (!File.Exists(pathFile)) { return; } Chunks = JsonConvert.DeserializeObject <List <Chunk> >(Encoding.ASCII.GetString(CLZF2.Decompress(File.ReadAllBytes(pathFile)))); }
// Decode public float[] Decode(byte[] bytes, int encoded) { float[] floats = SnapByte.DecodeBytes(CLZF2.Decompress(bytes)); return(floats); }