public void ImageBinBuffTest() { BinBuffer <uint, byte[]> imageBuff = new BinBuffer <uint, byte[]>(); imageBuff.pushSave(1234, new byte[] { 1, 2, 3, 4 }); imageBuff.pushSave(5678, new byte[] { 5, 6, 7, 8 }); byte[] expectNull = imageBuff.popSave(0000); Assert.IsNull(expectNull); byte[] firstArr = imageBuff.popSave(1234); Assert.IsNotNull(firstArr); Assert.AreEqual(firstArr.Length, 4); Assert.AreEqual(firstArr[3], 4); byte[] firstAnother = imageBuff.popSave(1234); Assert.IsNull(firstAnother); imageBuff.pushSave(1234, new byte[] { 9 }); byte[] firstNew = imageBuff.popSave(1234); Assert.IsNotNull(firstArr); Assert.AreEqual(firstNew.Length, 1); Assert.AreEqual(firstNew[0], 9); byte[] expectNull2 = imageBuff.popSave(1234); Assert.IsNull(expectNull2); byte[] secArr = imageBuff.popSave(5678); Assert.IsNotNull(secArr); Assert.AreEqual(secArr.Length, 4); Assert.AreEqual(secArr[3], 8); byte[] expectNull3 = imageBuff.popSave(5678); Assert.IsNull(expectNull3); }
public void TestSerializable() { Player player = new Player(5); Game game = new Game(720, 1280, 2); BinBuffer dbuf = new BinBuffer(BinBuffer.Type.DYNAMIC); BinBuffer sbuf = new BinBuffer(BinBuffer.Type.STATIC, 1024); dbuf.Write(player, game); sbuf.Write(player, game); Player dnp, snp; Game dng, sng; dbuf.SetRead(); sbuf.SetRead(); dbuf.Read(out dnp); dbuf.Read(out dng); sbuf.Read(out snp); sbuf.Read(out sng); Assert.Equal(player, dnp); Assert.Equal(player, snp); Assert.Equal(game, dng); Assert.Equal(game, sng); }
public void TestSerializableArray() { Player[] players = { new Player(1), new Player(2) }; Game[] games = { new Game(1280, 720, 1), new Game(1280, 720, 2) }; BinBuffer dbuf = new BinBuffer(BinBuffer.Type.DYNAMIC); BinBuffer sbuf = new BinBuffer(BinBuffer.Type.STATIC, 1024); dbuf.Write(players, games); sbuf.Write(players, games); Player[] dnp = new Player[2], snp = new Player[2]; Game[] dng = new Game[2], sng = new Game[2]; dbuf.SetRead(); sbuf.SetRead(); dbuf.Read(dnp, 2); dbuf.Read(dng, 2); sbuf.Read(snp, 2); sbuf.Read(sng, 2); for (int i = 0; i < 2; i++) { Assert.Equal(players[i], dnp[i]); Assert.Equal(players[i], snp[i]); Assert.Equal(games[i], dng[i]); Assert.Equal(games[i], sng[i]); } }
static LoadError ReadFormat(ref WorldFile ret, BinBuffer bb) { positions = new int[bb.ReadShort()]; for (int i = 0; i < positions.Length; i++) positions[i] = bb.ReadInt(); importance = new bool[bb.ReadShort()]; byte b = 0, b2 = 128; for (int i = 0; i < importance.Length; i++) { if (b2 == 128) { b = bb.ReadByte(); b2 = 1; } else b2 <<= 1; if ((b & b2) == b2) importance[i] = true; } return LoadError.Success; }
///load back locked-slot state public override void Load(BinBuffer bb) { if (bb.IsEmpty) { return; } for (int i = 0; i < lockedSlots.Length; i++) { lockedSlots[i] = bb.ReadBool(); } if (bb.IsEmpty) { return; } int count = bb.ReadInt(); for (int i = 0; i < count; i++) { int aID = bb.ReadInt(); bool state = bb.ReadBool(); if (Enum.IsDefined(typeof(TIH), aID)) { LockedActions[(TIH)aID] = state; } } }
public error SendAsync(byte[] msg, Action <bool> callback = null) { int length = msg.Length; BinBuffer buf = new BinBuffer(length + TcpBuffer.PCK_MIN_SIZE); buf.PushInt(TcpBuffer.PCK_HEADER); buf.PushShort((short)length); buf.PushBytes(msg); this.tcpsocket.BeginSend(buf.Bytes(), 0, buf.Bytes().Length, 0, (ar) => { if (callback != null) { try { int n = this.tcpsocket.EndSend(ar); callback.Invoke(n > 0); } catch (Exception e) { this.OnError(errors.New(e.Message)); } } }, null); return(errors.nil); }
/// <summary> /// Writes binary data to a world save file. Called when the world is closed. /// </summary> /// <param name="bb">The buffer containing the binary data.</param> public override void Save(BinBuffer bb) { // kinda hacky: use this as an OnQuit hook if (Main.gameMenu) // if ingame, it's a backup save (while playing), not when quitting { Array.Resize(ref managers, 1); Array.Resize(ref accessories, 1); Array.Resize(ref tomes, 1); } base.Save(bb); bb.WriteX( AvalonMod.IsInSuperHardmode, UltraOblivionDowned, SpawnedBerserkerOre, scanned); bb.WriteX( CatarystDownedCount, HallowAltarsBroken, ArmageddonCount, EverIceCount, WraithsDowned); CorrectJunglePos(); CorrectOceanPos(); CorrectHellPos(); bb.WriteX(TropicsRect.X, TropicsRect.Y, TropicsRect.Width, TropicsRect.Height, jungleX, jungleY, lOceanY, rOceanY, hellY); }
public error Send(byte[] msg) { int length = msg.Length; BinBuffer buf = new BinBuffer(length + TcpBuffer.PCK_MIN_SIZE); buf.PushInt(TcpBuffer.PCK_HEADER); buf.PushShort((short)length); buf.PushBytes(msg); try { int n = this.tcpsocket.Send(buf.Bytes()); if (n <= 0) { return(errors.New("there's no datas have been sended!")); } return(errors.nil); } catch (Exception e) { error err = errors.New(e.Message); this.OnError(err); return(err); } }
private static void WriteShader(BBData data, ShaderInfo si, StringsChunkBuilder strings) { var se = new ShaderEntry { Name = strings.GetOffset(si.Name), Type = si.Type.Encode(), AttributeCount = (uint)si.Attributes.Length }; unsafe { se.GLSL_ES.VertexSource = strings.GetOffset(si.Code.GLSL_ES.VertexShader); se.GLSL_ES.FragmentSource = strings.GetOffset(si.Code.GLSL_ES.FragmentShader); se.GLSL.VertexSource = strings.GetOffset(si.Code.GLSL.VertexShader); se.GLSL.FragmentSource = strings.GetOffset(si.Code.GLSL.FragmentShader); se.HLSL9.VertexSource = strings.GetOffset(si.Code.HLSL9.VertexShader); se.HLSL9.FragmentSource = strings.GetOffset(si.Code.HLSL9.FragmentShader); } var tmp = new BinBuffer(); tmp.Write(se); data.Buffer.Write(tmp, 0, tmp.Size - 4, 0); // TODO foreach (var attr in si.Attributes) { data.Buffer.Write(strings.GetOffset(attr)); } data.Buffer.Write(2); // TODO: ShaderEntry2 for (int i = 0; i < 12; i++) { data.Buffer.Write(0); } }
/// <summary> /// When the mod receives data from a peer connection. /// </summary> /// <param name="bb">The content of the message.</param> /// <param name="msg">The message type.</param> /// <param name="buffer">The <see cref="MessageBuffer" /> that received the message.</param> public override void NetReceive(BinBuffer bb, int msg, MessageBuffer buffer) { base.NetReceive(bb, msg, buffer); // commonly used vars int id; switch ((NetMessages)msg) { case NetMessages.StartWraithInvasion: // todo break; case NetMessages.SetMusicBox: // todo break; case NetMessages.RequestTiles: NetMessage.SendTileSquare(bb.ReadInt(), bb.ReadInt(), bb.ReadInt(), bb.ReadInt()); break; case NetMessages.RequestCustomSlots: BinBuffer itemB = new BinBuffer(); itemB.Write(Main.myPlayer); itemB.WriteX(MWorld.localAccessories); itemB.Write(MWorld.localTome); itemB.Pos = 0; NetHelper.SendModData(AvalonMod.Instance, NetMessages.SendCustomSlots, bb.ReadInt(), -1, itemB.ReadBytes()); break; case NetMessages.SendCustomSlots: id = bb.ReadInt(); for (int i = 0; i < AvalonMod.ExtraSlots; i++) { MWorld.accessories[id][i] = bb.ReadItem(); } MWorld.tomes[id] = bb.ReadItem(); MWorld.managers[id] = SkillManager.FromItem(MWorld.tomes[id]); break; case NetMessages.ActivateSkill: id = bb.ReadInt(); if (MWorld.managers[id] == null) { MWorld.managers[id] = SkillManager.FromItem(MWorld.tomes[id]); } if (MWorld.managers[id] != null) { MWorld.managers[id].Activate(Main.player[id]); // id is both client id and player id. } break; } }
/// <summary> /// Loads data about the <see cref="Item" /> from a <see cref="BinBuffer" />. /// </summary> /// <param name="bb">The <see cref="BinBuffer" /> to read data from.</param> public override void Load(BinBuffer bb) { base.Load(bb); UseMode = (Mode)bb.ReadByte(); item.tooltip2 = "Mode: " + UseMode; }
public void Deserialize(BinBuffer binBuffer) { binBuffer.Read(out playerNum); binBuffer.Read(out isAlive); binBuffer.Read(out health); binBuffer.Read(out strength); }
public void Save(BinBuffer bb) { // populate data dictionary foreach (var act in save) { BinBuffer bb_ = new BinBuffer(); act(bb_); if (bb_.Position > 0) // i.e. has written anything { bb_.Position = 0; // reset for writing data[act.Method.DeclaringType.FullName] = bb_; } else { bb_.Dispose(); } } // write the dictionary to the buffer bb.Write(data.Count); foreach (var kvp in data) { bb.Write(kvp.Key); bb.Write(kvp.Value.Size); bb.Write(kvp.Value); } }
public static int WriteOffset(BinBuffer self, int offset) { var r = self.Position; self.Write(offset); return(r); }
public override void Load(BinBuffer bb) { ClearFlags(); int v = bb.ReadInt(); if (v >= 1) { SarcophogusBeaten = bb.ReadBool(); } }
public static void Decompile(string modFile) { CommonToolUtilities.RefreshHashes(); string modName = Path.GetFileNameWithoutExtension(modFile), decompPath = ModDecompiler.decompDir + "\\" + modName; // might be a good idea if (!Directory.Exists(decompPath)) Directory.CreateDirectory(decompPath); // where to store file data List<Tuple<string, byte[]>> files = new List<Tuple<string, byte[]>>(); List<Tuple<string, int>> reading = new List<Tuple<string, int>>(); // load data into buffer BinBuffer bb = new BinBuffer(new BinBufferByte(File.ReadAllBytes(modFile))); // first 4 bytes is the version uint versionAssembly = bb.ReadUInt(); // write tAPI version if (!File.Exists(decompPath + "\\tAPI r" + versionAssembly)) File.Create(decompPath + "\\tAPI r" + versionAssembly); // write modinfo File.WriteAllText(decompPath + "\\ModInfo.json", bb.ReadString()); // get file amount int filesNum = bb.ReadInt(); // read file name + length while (filesNum-- > 0) reading.Add(new Tuple<string, int>(bb.ReadString(), bb.ReadInt())); // read file data foreach (Tuple<string, int> read in reading) files.Add(new Tuple<string, byte[]>(read.Item1, bb.ReadBytes(read.Item2))); // write files foreach (Tuple<string, byte[]> pfile in files) { if (!Directory.Exists(Path.GetDirectoryName(decompPath + "\\" + pfile.Item1))) Directory.CreateDirectory(Path.GetDirectoryName(decompPath + "\\" + pfile.Item1)); File.WriteAllBytes(decompPath + "\\" + pfile.Item1, pfile.Item2); } // write assembly File.WriteAllBytes(decompPath + "\\" + modName + ".dll", bb.ReadBytes(bb.BytesLeft())); CommonToolUtilities.RefreshHashes(); }
internal unsafe static string ReadString(BinBuffer bb) { byte[] data = Read7BitContinuous(bb); int length; fixed (byte* ptr = &data[0]) { length = *(int*)ptr; } return Encoding.UTF8.GetString(bb.ReadBytes(length)); }
/// <summary> /// Loads data from the player file. /// </summary> /// <param name="bb">The buffer to load data from.</param> public override void Load(BinBuffer bb) { base.Load(bb); for (int i = 0; i < accessories.Length; i++) { accessories[i] = bb.ReadItem(); } MWorld.localTome = bb.ReadItem(); starterSet = bb.ReadByte(); }
/// <summary> /// Saves data to the player file. /// </summary> /// <param name="bb">The buffer to put data in.</param> public override void Save(BinBuffer bb) { base.Save(bb); for (int i = 0; i < accessories.Length; i++) { bb.Write(accessories[i]); } bb.Write(MWorld.localTome); bb.Write((byte)(starterSet == -1 ? 0 : starterSet)); }
public override void Load(BinBuffer bb) { Entity.toolTip = bb.ReadString(); Entity.toolTip2 = bb.ReadString(); if (ModData.modsFromInternalName.ContainsKey(Entity.toolTip)) { var mod = ModData.modsFromInternalName[Entity.toolTip]; if (mod.ItemDefs.ContainsKey(Entity.toolTip2)) Entity.SetDefaults(ItemDef.Defs[Entity.toolTip2, Entity.toolTip].Type); } }
internal static WorldFile ReadWorld(string path) { WorldFile ret = new WorldFile(); BinBuffer bb = new BinBuffer(new BinBufferByte(File.ReadAllBytes(path))); int ver = ret.version = bb.ReadInt(); LoadError err; if ((err = (ver <= 87 ? ReadV1(ref ret, bb) : ReadV2(ref ret, bb))) != LoadError.Success) throw new FormatException("An error occured when reading the world file: " + ToReadableString(err)); return ret; }
/// <summary> /// When the mod receives data from a peer connection. /// </summary> /// <param name="bb">The content of the message.</param> /// <param name="msg">The message type.</param> /// <param name="buffer">The <see cref="MessageBuffer" /> that received the message.</param> public override void NetReceive(BinBuffer bb, int msg, MessageBuffer buffer) { base.NetReceive(bb, msg, buffer); // commonly used vars int id; switch ((NetMessages)msg) { case NetMessages.StartWraithInvasion: // todo break; case NetMessages.SetMusicBox: // todo break; case NetMessages.RequestTiles: NetMessage.SendTileSquare(bb.ReadInt(), bb.ReadInt(), bb.ReadInt(), bb.ReadInt()); break; case NetMessages.RequestCustomSlots: BinBuffer itemB = new BinBuffer(); itemB.Write (Main.myPlayer); itemB.WriteX(MWorld.localAccessories); itemB.Write (MWorld.localTome); itemB.Pos = 0; NetHelper.SendModData(AvalonMod.Instance, NetMessages.SendCustomSlots, bb.ReadInt(), -1, itemB.ReadBytes()); break; case NetMessages.SendCustomSlots: id = bb.ReadInt(); for (int i = 0; i < AvalonMod.ExtraSlots; i++) MWorld.accessories[id][i] = bb.ReadItem(); MWorld.tomes[id] = bb.ReadItem(); MWorld.managers[id] = SkillManager.FromItem(MWorld.tomes[id]); break; case NetMessages.ActivateSkill: id = bb.ReadInt(); if (MWorld.managers[id] == null) MWorld.managers[id] = SkillManager.FromItem(MWorld.tomes[id]); if (MWorld.managers[id] != null) MWorld.managers[id].Activate(Main.player[id]); // id is both client id and player id. break; } }
public static void WriteCodeBlock(BBData data, AnyInstruction[] instructions, uint bytecodeVersion) { foreach (var inst in instructions) { var ins_ = inst; var instdata = new BinBuffer(); instdata.Write(inst); uint size; unsafe { size = DisasmExt.Size(&ins_, bytecodeVersion) * 4; } data.Buffer.Write(instdata, 0, (int)size, 0); } }
#pragma warning restore 1591 ModInfo GetModInfoFromTapiMod(byte[] data) { BinBuffer bb = new BinBuffer(new BinBufferByte(data)); uint ver = bb.ReadUInt(); ModInfo mi = new ModInfo(Compiler) { checkCircularRefs = false }; var err = mi.CreateAndValidate(new JsonFile(String.Empty, JsonMapper.ToObject(bb.ReadString()))); if (!Compiler.CreateOutput(err.ToList()).Succeeded) return null; return mi; }
public override void Load(BinBuffer bb) { Entity.toolTip = bb.ReadString(); Entity.toolTip2 = bb.ReadString(); if (ModData.modsFromInternalName.ContainsKey(Entity.toolTip)) { var mod = ModData.modsFromInternalName[Entity.toolTip]; if (mod.ItemDefs.ContainsKey(Entity.toolTip2)) { Entity.SetDefaults(ItemDef.Defs[Entity.toolTip2, Entity.toolTip].Type); } } }
public void OnConn() { Console.WriteLine("conn succeed!"); new Thread(new ThreadStart(() => { while (true) { BinBuffer buf = new BinBuffer(4096); buf.PushInt(666); buf.PushString("almighty brother gang!!"); netWorker.Send(buf.Bytes()); Thread.Sleep(10); } })).Start(); }
internal static void WriteItem(BinBuffer bb, Item toWrite) { if (toWrite.stack < 0 || toWrite.netID > Main.maxItemTypes || toWrite.netID < -48) toWrite.stack = 0; bb.Write(toWrite.stack); if (toWrite.stack <= 0) return; bb.Write((short)toWrite.netID); bb.Write((int)toWrite.prefix); bb.Write((byte)0); // mod data (none ofc) }
public static int[] WriteOptions(BBData data, OptionInfo opt, StringsChunkBuilder strings) { var ret = new SectionOptions(); var stringOffsetOffsets = new List <int>(); unsafe { for (int i = 0; i < 2; i++) { ret._pad0[i] = opt._pad0[i]; } for (int i = 0; i < 0xC; i++) { ret._pad1[i] = opt._pad1[i]; } } ret.GEN8FlagsDup = opt.InfoFlags; if (opt.Constants == null) { ret.ConstMap.Count = 0; } else { ret.ConstMap.Count = (uint)opt.Constants.Count; } var tmp = new BinBuffer(); tmp.Write(ret); data.Buffer.Write(tmp, 0, tmp.Size - 12, 8); if (opt.Constants != null) { foreach (var kvp in opt.Constants) { stringOffsetOffsets.Add(data.Buffer.Position + 8); data.Buffer.Write(strings.GetOffset(kvp.Key)); stringOffsetOffsets.Add(data.Buffer.Position + 8); data.Buffer.Write(strings.GetOffset(kvp.Value)); } } return(stringOffsetOffsets.ToArray()); }
private static void WritePath(BBData data, PathInfo pi, StringsChunkBuilder strings) { var tmp = new BinBuffer(); tmp.Write(new PathEntry { Name = strings.GetOffset(pi.Name), IsSmooth = pi.IsSmooth ? DwordBool.True : DwordBool.False, IsClosed = pi.IsClosed ? DwordBool.True : DwordBool.False, Precision = pi.Precision, PointCount = (uint)pi.Points.Length }); data.Buffer.Write(tmp, 0, tmp.Size - 12, 0); foreach (var pt in pi.Points) { data.Buffer.Write(pt); } }
/// <summary> /// Loads binary data from a world save file. Called when the world is loaded. /// </summary> /// <param name="bb">The buffer containing the binary data.</param> public override void Load(BinBuffer bb) { base.Load(bb); accessories = new Item[Main.netMode == 0 ? 1 : Main.numPlayers][]; for (int i = 0; i < accessories.Length; i++) { accessories[i] = new Item[AvalonMod.ExtraSlots]; for (int j = 0; j < AvalonMod.ExtraSlots; j++) { accessories[i][j] = new Item(); } } AvalonMod.IsInSuperHardmode = bb.ReadBool(); UltraOblivionDowned = bb.ReadBool(); SpawnedBerserkerOre = bb.ReadBool(); scanned = bb.ReadBool(); CatarystDownedCount = bb.ReadInt(); HallowAltarsBroken = bb.ReadInt(); ArmageddonCount = bb.ReadInt(); EverIceCount = bb.ReadInt(); WraithsDowned = bb.ReadInt(); TropicsRect = new Rectangle(bb.ReadInt(), bb.ReadInt(), bb.ReadInt(), bb.ReadInt()); jungleX = bb.ReadInt(); jungleY = bb.ReadInt(); lOceanY = bb.ReadInt(); rOceanY = bb.ReadInt(); hellY = bb.ReadInt(); CorrectJunglePos(); CorrectOceanPos(); CorrectHellPos(); }
public override void NetReceive(BinBuffer bb, int msg, MessageBuffer buffer) { base.NetReceive(bb, msg, buffer); switch ((InternalNetMessages)msg) { case InternalNetMessages.SyncRandom_Sync: SyncedRandom.GetCached(bb.ReadInt()).NextDouble(); break; case InternalNetMessages.SyncRandom_CTOR: { string group = bb.ReadString(); int seed = bb.ReadInt(); SyncedRandom.rands[group] = seed; SyncedRandom.refs[group]++; } break; case InternalNetMessages.SyncRandom_DTOR: { int seed = bb.ReadInt(); string group = null; foreach (var kvp in SyncedRandom.rands) if (kvp.Value == seed) group = kvp.Key; if (group == null) return; SyncedRandom.refs[group]--; if (SyncedRandom.refs[group] <= 0) { SyncedRandom.rands.Remove(group); SyncedRandom.refs.Remove(group); SyncedRandom.RemoveCached(seed); } } break; } }
public void Load(BinBuffer bb) { int count = bb.ReadInt32(); for (int i = 0; i < count; i++) { var k = bb.ReadString(); var l = bb.ReadInt32(); var v = new BinBuffer(bb.ReadBytes(l), false); // keeping the data in the dictionary will make sure data from IOBehaviours will not get lost when the mod is unloaded data[k] = v; var act = load.FirstOrDefault(a => a.Method.DeclaringType.FullName == k); if (act != null) { act(v); } } }
public void ReadDictionary(BinBuffer bb) { int modAmt = bb.ReadByte(); for (int i = 0; i < modAmt; i++) Mods.Add(bb.ReadString(), bb.ReadByte()); for (int i = 0; i < modAmt; i++) { ModID mid = bb.ReadByte(); var modObjs = new BiDictionary<ObjName, ObjID>(); short objAmt = bb.ReadInt16(); for (int j = 0; j < objAmt; j++) modObjs.Add(bb.ReadString(), bb.ReadInt16()); ModObjects.Add(mid, modObjs); } }
public override void NetReceive(int id, BinBuffer bb) { switch ((InternalNetMessages)id) { case InternalNetMessages.SyncRandom_Sync: { string group = bb.ReadString(); Random rand = (Random)NetHelper.ReadObject(typeof(Random), bb); int @ref = bb.ReadInt(); SyncedRandom.rands[group] = rand; SyncedRandom.refs[group] = @ref; } break; case InternalNetMessages.SyncRandom_CTOR: { string group = bb.ReadString(); int seed = bb.ReadInt(); SyncedRandom.rands[group] = new Random(seed); SyncedRandom.refs[group]++; } break; case InternalNetMessages.SyncRandom_DTOR: { string group = bb.ReadString(); SyncedRandom.refs[group]--; if (SyncedRandom.refs[group] <= 0) { SyncedRandom.rands.Remove(group); } } break; } base.NetReceive(id, bb); }
internal static byte[] Read7BitContinuous(BinBuffer bb) { BigInteger ret = 0; // temporary store data byte data = 0; do { // read 1 byte from the stream int r = bb.ReadByte(); if (r == -1) break; data = (byte)r; ret <<= 7; // push data 7 bits to the left ret |= (uint)(data & 0x7f); // set 7 rightmost bits (01111111, 0x7f, or 127) } while ((data & 0x80) == 0x80); // while the 8th bit is 1 (10000000, or 0x80) // obvious enough return ret.ToByteArray(); }
public override void Save(BinBuffer bb) { if (Main.gameMenu) { var lii = Constants.LangInterIndices; // reset original chest-button strings if we're quitting to main // menu, which should be indicated by checking: // if (Main.gameMenu == true) // as this is set during the SaveAndQuit() method of the worldgen // immediately before player save. So: Lang.inter[lii[TIH.LootAll]] = IHBase.OriginalButtonLabels[TIH.LootAll]; Lang.inter[lii[TIH.DepositAll]] = IHBase.OriginalButtonLabels[TIH.DepositAll]; Lang.inter[lii[TIH.QuickStack]] = IHBase.OriginalButtonLabels[TIH.QuickStack]; if (IHBase.ModOptions["UseReplacers"]) { Lang.inter[lii[TIH.Rename]] = IHBase.OriginalButtonLabels[TIH.Rename]; Lang.inter[lii[TIH.SaveName]] = IHBase.OriginalButtonLabels[TIH.SaveName]; Lang.inter[lii[TIH.CancelEdit]] = IHBase.OriginalButtonLabels[TIH.CancelEdit]; } // should take care of it and make sure the strings are set // correctly if the mod is unloaded/the replacer-button option // is disabled. } // if (!IHBase.oLockingEnabled) return; //maybe? // save locked-slot state with player foreach (var l in lockedSlots) { bb.Write(l); } bb.Write(LockedActions.Count); //KeyValuePair<TIH, bool> foreach (var kvp in LockedActions) { bb.Write((int)kvp.Key); bb.Write(kvp.Value); } }
public override void NetReceive(int id, BinBuffer bb) { switch ((InternalNetMessages)id) { case InternalNetMessages.SyncRandom_Sync: { string group = bb.ReadString(); Random rand = (Random)NetHelper.ReadObject(typeof(Random), bb); int @ref = bb.ReadInt(); SyncedRandom.rands[group] = rand; SyncedRandom.refs[group] = @ref; } break; case InternalNetMessages.SyncRandom_CTOR: { string group = bb.ReadString(); int seed = bb.ReadInt(); SyncedRandom.rands[group] = new Random(seed); SyncedRandom.refs[group]++; } break; case InternalNetMessages.SyncRandom_DTOR: { string group = bb.ReadString(); SyncedRandom.refs[group]--; if (SyncedRandom.refs[group] <= 0) SyncedRandom.rands.Remove(group); } break; } base.NetReceive(id, bb); }
/// <summary> /// Save <paramref name="slots" /> items from <paramref name="inventory" /> to the <paramref name="bb" />. /// </summary> /// <param name="bb">The writer for storing data</param> /// <param name="inventory">The array of items</param> /// <param name="slots">The amount of items in the inventory to save</param> /// <param name="stack">Whether or not the stack size should be saved</param> /// <param name="favourited">Whether or not the favourited state should be saved</param> static void SaveItemSlots(BinBuffer bb, Item[] inventory, int slots, bool stack, bool favourited) { for (int i = 0; i < slots; i++) { if (inventory[i].type < ItemID.Count) bb.Write(String.Empty); // write an empty string instead of 'Vanilla' else { // Save basic item data ItemDef item = Handler.ItemDef.DefsByType[inventory[i].type]; bb.Write(item.Mod.InternalName); bb.Write(item.InternalName); // why, vanilla writes these already? // only type + mod data is needed imo (and prefix type (+ data?) later on) if (stack) bb.Write(inventory[i].stack); bb.WriteByte(inventory[i].prefix); if (favourited) bb.Write(inventory[i].favorited); } // Save Mod Data if (inventory[i].P_BHandler != null) { ItemBHandler handler = (ItemBHandler)inventory[i].P_BHandler; handler.Save(bb); } else bb.Write(0); } }
public void WriteDictionary(BinBuffer bb) { unchecked { bb.WriteByte((ModID)Mods.Count); } foreach (var kvp in Mods) { bb.Write(kvp.Key ); bb.Write(kvp.Value); } foreach (var kvp in ModObjects) { bb.Write(kvp.Key); var mod = kvp.Value; bb.Write(unchecked((ObjID)mod.Count)); foreach (var kvp_ in mod) { bb.Write(kvp_.Key ); bb.Write(kvp_.Value); } } }
static void SaveNpcData(BinBuffer bb) { for (int i = 0; i < Main.npc.Length; i++) { var n = Main.npc[i]; if (n == null || !n.active || !n.townNPC || n.type == NPCID.TravellingMerchant) continue; bb.Write(true); if (n.P_BHandler == null) bb.Write(0); // as length for the IOBHandler else { var bh = n.P_BHandler as NpcBHandler; bh.Save(bb); } } //bb.Write(false); // don't write, loops can be unified in the Load method (only mod data is written) // blame red for the double loop. see Terraria.IO.WorldFile.SaveNPCs/LoadNPCs for (int i = 0; i < Main.npc.Length; i++) { var n = Main.npc[i]; if (n == null || !n.active || !NPCID.Sets.SavesAndLoads[n.type] || (n.townNPC && n.type != NPCID.TravellingMerchant)) continue; bb.Write(true); if (n.P_BHandler == null) bb.Write(0); // as length for the IOBHandler else { var bh = n.P_BHandler as NpcBHandler; bh.Save(bb); } } bb.Write(false); }
static void SavePrismData(BinBuffer bb) { bb.WriteByte(WORLD_VERSION); }
internal static void WriteSettings(Stream s) { BinBuffer bb = new BinBuffer(new BinBufferStream(s)); bb.Write(UpdateChecker.CheckForUpdates); }
static void SaveTileTypes(BinBuffer bb) { var map = new ModIdMap(TileID.Count, or => TileDef.Defs[or].Type, id => Handler.TileDef.DefsByType[id]); Write2DArray(bb, map, Main.maxTilesX, Main.maxTilesY, (x, y) => Main.tile[x, y] == null || Main.tile[x, y].type <= 0, // 0 -> dirt wall, but this works here, too (x, y) => Main.tile[x, y].type >= TileID.Count ? 0 : Main.tile[x, y].type, (x, y) => Main.tile[x, y].type < TileID.Count || !Handler.TileDef.DefsByType.ContainsKey(Main.tile[x, y].type) ? ObjectRef.Null : Handler.TileDef.DefsByType[Main.tile[x, y].type]); }
public void TestPrimitiveArray() { sbyte[] sb = { -3, -2, -1, 0 }; char[] c = { 'a', 'b', 'c', 'd' }; bool[] b = { true, true, false, true }; short[] s = { 1, 2, 3, 4 }; int[] i = { 2, 3, 4, 5 }; long[] l = { 3, 4, 5, 6 }; float[] f = { 3.1f, 3.2f, 3.3f, 3.4f }; double[] d = { 3.2, 3.3, 3.4, 3.5 }; BinBuffer dbuf = new BinBuffer(BinBuffer.Type.DYNAMIC); BinBuffer sbuf = new BinBuffer(BinBuffer.Type.STATIC, 256); dbuf.Write(sb, c, b, s, i, l, f, d); sbuf.Write(sb, c, b, s, i, l, f, d); dbuf.SetRead(); sbuf.SetRead(); sbyte[] dnsb = new sbyte[4], snsb = new sbyte[4]; char[] dnc = new char[4], snc = new char[4]; bool[] dnb = new bool[4], snb = new bool[4]; short[] dns = new short[4], sns = new short[4]; int[] dni = new int[4], sni = new int[4]; long[] dnl = new long[4], snl = new long[4]; float[] dnf = new float[4], snf = new float[4]; double[] dnd = new double[4], snd = new double[4]; dbuf.Read(dnsb, 4); sbuf.Read(snsb, 4); dbuf.Read(dnc, 4); sbuf.Read(snc, 4); dbuf.Read(dnb, 4); sbuf.Read(snb, 4); dbuf.Read(dns, 4); sbuf.Read(sns, 4); dbuf.Read(dni, 4); sbuf.Read(sni, 4); dbuf.Read(dnl, 4); sbuf.Read(snl, 4); dbuf.Read(dnf, 4); sbuf.Read(snf, 4); dbuf.Read(dnd, 4); sbuf.Read(snd, 4); for (int j = 0; j < 4; j++) { Assert.Equal(sb[j], dnsb[j]); Assert.Equal(sb[j], snsb[j]); Assert.Equal(c[j], dnc[j]); Assert.Equal(c[j], snc[j]); Assert.Equal(b[j], dnb[j]); Assert.Equal(b[j], snb[j]); Assert.Equal(s[j], dns[j]); Assert.Equal(s[j], sns[j]); Assert.Equal(i[j], dni[j]); Assert.Equal(i[j], sni[j]); Assert.Equal(l[j], dnl[j]); Assert.Equal(l[j], snl[j]); Assert.Equal(f[j], dnf[j]); Assert.Equal(f[j], snf[j]); Assert.Equal(d[j], dnd[j]); Assert.Equal(d[j], snd[j]); } }
static void SaveGlobalData(BinBuffer bb) { HookManager.GameBehaviour.Save(bb); }
static void WriteData(string modInfo, string outputPath, List<Tuple<string, byte[]>> files) { JsonData json = JsonMapper.ToObject(modInfo); BinBuffer bb = new BinBuffer(); bb.Write(API.versionAssembly); bb.Write(modInfo); bool generatePDB = File.Exists(outputPath + ".pdb"); bb.Write(files.Count + (generatePDB ? 1 : 0)); byte[] pdb = null; if (generatePDB) { pdb = File.ReadAllBytes(outputPath + ".pdb"); bb.Write("DebugInformation.pdb"); bb.Write(pdb.Length); } foreach (Tuple<string, byte[]> pfile in files) { bb.Write(pfile.Item1); bb.Write(pfile.Item2.Length); } if (generatePDB) bb.Write(pdb); foreach (Tuple<string, byte[]> pfile in files) bb.Write(pfile.Item2); bb.Write(File.ReadAllBytes(outputPath + ".dll")); bb.Pos = 0; //File.WriteAllBytes(outputPath + ".tapimod", bb.ReadBytes(bb.GetSize())); File.Delete(outputPath + ".tapi"); using (ZipFile zip = new ZipFile()) { string dir = Mods.pathDirModsUnsorted; if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); zip.AddEntry("Mod.tapimod", bb.ReadBytes(bb.GetSize())); zip.AddEntry("ModInfo.json", Encoding.UTF8.GetBytes(modInfo)); if (generatePDB) zip.AddEntry("DebugInformation.pdb", pdb); foreach (Tuple<string, byte[]> file in files) zip.AddEntry(file.Item1, file.Item2); zip.Save(outputPath + ".tapi"); } if (json == null || !json.Has("extractDLL") || !(bool)json["extractDLL"]) { File.Delete(outputPath + ".dll"); if (File.Exists(outputPath + ".pdb")) File.Delete(outputPath + ".pdb"); } }
/// <summary> /// Saves data about the <see cref="Item" /> to a <see cref="BinBuffer" />. /// </summary> /// <param name="bb">The <see cref="BinBuffer" /> to write data to.</param> public override void Save(BinBuffer bb) { base.Save(bb); bb.Write((byte)UseMode); }
/// <summary> /// Load player data from a .plr.prism file /// </summary> /// <param name="playerPath">The path to the vanilla .plr file</param> internal static void LoadPlayer(Player player, string playerPath) { playerPath += ".prism"; // If mod data doesn't exist, don't try to load it if (!File.Exists(playerPath)) return; try { using (FileStream fileStream = File.OpenRead(playerPath)) { byte version = (byte)fileStream.ReadByte(); // should be safe to cast here, very unlikely that the file is empty if (version > PLAYER_VERSION) throw new FileFormatException("Tried to load a player file from a future version of Prism."); if (version < MIN_PLAYER_SUPPORT_VER) throw new FileFormatException("This player is saved in a format that is too old and unsupported."); using (CryptoStream cryptoStream = new CryptoStream(fileStream, new RijndaelManaged() { Padding = PaddingMode.None }.CreateDecryptor(GenerateKey(player.name), ENCRYPTION_KEY), CryptoStreamMode.Read)) using (BinBuffer bb = new BinBuffer(cryptoStream)) { #region Player Data if (player.P_BHandler == null) { player.P_BHandler = new PlayerBHandler(); ((PlayerBHandler)player.P_BHandler).Create(); } ((PlayerBHandler)player.P_BHandler).Load(bb); #endregion Player Data #region Item Data LoadItemSlots(bb, player.armor, player.armor.Length, false, false); LoadItemSlots(bb, player.dye, player.dye.Length, false, false); LoadItemSlots(bb, player.inventory, Main.maxInventory, true, true); LoadItemSlots(bb, player.miscEquips, player.miscEquips.Length, false, false); LoadItemSlots(bb, player.bank.item, Chest.maxItems, true, false); LoadItemSlots(bb, player.bank2.item, Chest.maxItems, true, false); #endregion Item Data #region Buff Data for (int i = 0; i < Player.maxBuffs; i++) { var mod = bb.ReadString(); if (String.IsNullOrEmpty(mod) || !ModData.modsFromInternalName.ContainsKey(mod)) continue; var md = ModData.modsFromInternalName[mod]; var buff = bb.ReadString(); var t = bb.ReadInt32(); if (!md.BuffDefs.ContainsKey(buff)) continue; player.AddBuff(md.BuffDefs[buff].Type, t); if (player.P_BuffBHandler[i] == null) { player.P_BuffBHandler[i] = new BuffBHandler(); ((BuffBHandler)player.P_BuffBHandler[i]).Create(); } ((BuffBHandler)player.P_BuffBHandler[i]).Save(bb); } #endregion Buff Data } } } catch (Exception e) { // Character could not be properly loaded, report and prevent playing //TODO: report Logging.LogError("Could not load player " + player.name + ": " + e); Trace.WriteLine ("Could not load player " + player.name + ": " + e.Message); player.loadStatus = 1; } }
//TODO: make these faster (especially write) static void Write2DArray(BinBuffer bb, ModIdMap map, int xLen, int yLen, Func <int, int, bool> isEmpty , Func <int, int, int > getElemV, Func<int, int, ObjectRef> getElemM) { var ov = 0; var ot = ObjectRef.Null; bool isOV = true; int amt = 0; bool once = true; int dictOffsetPosition = bb.Position; bb.Write(0); // dictionary position for (int y = 0; y < yLen; y++) for (int x = 0; x < xLen; x++) { var e = isEmpty(x, y); var v = e ? 0 : getElemV(x, y); var t = ObjectRef.Null; var isV = e || v > 0; if (!e && v == 0) { t = getElemM(x, y); isV = false; } if (once) { if (isV) ov = v; else ot = t; isOV = isV; bb.Write((uint)(isV ? map.Register(v) : map.Register(t))); once = false; } else if (isV == isOV && (isV ? v == ov : t == ot) && amt < UInt16.MaxValue) amt++; else { bb.Write((ushort)amt); // write the amount of successing elements of the same type, // instead of the type over and over again, to save some space amt = 0; // amt == 0 -> one element if (isV) ov = v; else ot = t; isOV = isV; bb.Write((uint)(isV ? map.Register(v) : map.Register(t))); } } bb.Write((ushort)amt); // write final amt var afterData = bb.Position; bb.Position = dictOffsetPosition; bb.Write(afterData); // dictionary position bb.Position = afterData; map.WriteDictionary(bb); }
static void SaveWallTypes(BinBuffer bb) { var map = new ModIdMap(WallID.Count, or => WallDef.Defs[or].Type, id => Handler.WallDef.DefsByType[id]); Write2DArray(bb, map, Main.maxTilesX, Main.maxTilesY, (x, y) => Main.tile[x, y] == null || Main.tile[x, y].wall <= 0, (x, y) => Main.tile[x, y].wall >= WallID.Count ? 0 : Main.tile[x, y].wall, (x, y) => Main.tile[x, y].wall < WallID.Count || !Handler.WallDef.DefsByType.ContainsKey(Main.tile[x, y].wall) ? ObjectRef.Null : Handler.WallDef.DefsByType[Main.tile[x, y].wall]); }
public override void Save(BinBuffer bb) { Main.dayRate = 1; base.Save(bb); }
public virtual void Save(BinBuffer bb) { }
public void Serialize(BinBuffer binBuffer) { binBuffer.Write(playerNum, isAlive, health, strength); }
internal static void ReadSettings(Stream s) { BinBuffer bb = new BinBuffer(new BinBufferStream(s)); UpdateChecker.CheckForUpdates = bb.ReadBool(); }
public void TestPrimitive() { byte ub = 255; sbyte sb = -1; char c = 'a'; bool b = true; float f = 3.1f; double d = 3.2; decimal dc = 3.3m; short s = 1; int i = 2; long l = 3; ushort us = 1; uint ui = 2; ulong ul = 3; BinBuffer dbuf = new BinBuffer(BinBuffer.Type.DYNAMIC); BinBuffer sbuf = new BinBuffer(BinBuffer.Type.STATIC, 128); dbuf.Write(ub, sb, c, b, f, d, dc, s, i, l, us, ui, ul); sbuf.Write(ub, sb, c, b, f, d, dc, s, i, l, us, ui, ul); dbuf.SetRead(); sbuf.SetRead(); byte dnub, snub; sbyte dnsb, snsb; char dnc, snc; bool dnb, snb; short dns, sns; int dni, sni; long dnl, snl; float dnf, snf; double dnd, snd; decimal dndc, sndc; ushort dnus, snus; uint dnui, snui; ulong dnul, snul; dbuf.Read(out dnub); sbuf.Read(out snub); dbuf.Read(out dnsb); sbuf.Read(out snsb); dbuf.Read(out dnc); sbuf.Read(out snc); dbuf.Read(out dnb); sbuf.Read(out snb); dbuf.Read(out dnf); sbuf.Read(out snf); dbuf.Read(out dnd); sbuf.Read(out snd); dbuf.Read(out dndc); sbuf.Read(out sndc); dbuf.Read(out dns); sbuf.Read(out sns); dbuf.Read(out dni); sbuf.Read(out sni); dbuf.Read(out dnl); sbuf.Read(out snl); dbuf.Read(out dnus); sbuf.Read(out snus); dbuf.Read(out dnui); sbuf.Read(out snui); dbuf.Read(out dnul); sbuf.Read(out snul); Assert.Equal(ub, dnub); Assert.Equal(ub, snub); Assert.Equal(sb, dnsb); Assert.Equal(sb, snsb); Assert.Equal(c, dnc); Assert.Equal(c, snc); Assert.Equal(b, dnb); Assert.Equal(b, snb); Assert.Equal(f, dnf); Assert.Equal(f, snf); Assert.Equal(d, dnd); Assert.Equal(d, snd); Assert.Equal(dc, dndc); Assert.Equal(dc, sndc); Assert.Equal(s, dns); Assert.Equal(s, sns); Assert.Equal(i, dni); Assert.Equal(i, sni); Assert.Equal(l, dnl); Assert.Equal(l, snl); Assert.Equal(us, dnus); Assert.Equal(us, snus); Assert.Equal(ui, dnui); Assert.Equal(ui, snui); Assert.Equal(ul, dnul); Assert.Equal(ul, snul); }
static void SaveTileData(BinBuffer bb) { for (int y = 0; y < Main.maxTilesY; y++) for (int x = 0; x < Main.maxTilesX; x++) { var p = new Point16(x, y); var t = Main.tile[x, y].type; var fl = TileDataEntryFlags.Finished; if (TileHooks.TileSpecificHandlers.ContainsKey(p)) fl |= TileDataEntryFlags.Tile; if (TileHooks.TypeSpecificHandlers.ContainsKey(t)) fl |= TileDataEntryFlags.Type; if (fl == TileDataEntryFlags.Finished) continue; bb.Write((byte)fl); bb.Write(p.X); bb.Write(p.Y); if ((fl & TileDataEntryFlags.Tile) != 0) { var bh = TileHooks.TileSpecificHandlers[p]; bh.Save(bb); } if ((fl & TileDataEntryFlags.Type) != 0) { var bh = TileHooks.TypeSpecificHandlers[t]; foreach (var b in bh.behaviours) b.Position = p; bh.Save(bb); } } bb.Write(0); }
public virtual void Load(BinBuffer bb) { }
static void SaveChestItems(BinBuffer bb) { var chests = Main.chest.Where(c => c != null); bb.Write((short)chests.Count()); bb.WriteByte(Chest.maxItems); foreach (var c in chests) SaveItemSlots(bb, c.item, Chest.maxItems, true, false); }
public void TestCollections() { Player p1 = new Player(1), p2 = new Player(2); Game g1 = new Game(1280, 720, 1), g2 = new Game(1280, 720, 2); List <Player> list = new List <Player>(2) { p1, p2 }; Dictionary <int, Game> dict = new Dictionary <int, Game> { { 1, g1 }, { 2, g2 } }; HashSet <Player> hset = new HashSet <Player>(new PlayerEqualityComparator()) { p1, p2 }; SortedList <int, Game> slist = new SortedList <int, Game> { { 1, g1 }, { 2, g2 } }; SortedSet <Player> sset = new SortedSet <Player>(new PlayerComparator()) { p1, p2, }; SortedDictionary <int, Game> sdict = new SortedDictionary <int, Game>() { { 1, g1 }, { 2, g2 } }; Queue <Player> queue = new Queue <Player>(); queue.Enqueue(p1); queue.Enqueue(p2); Stack <Game> stack = new Stack <Game>(); stack.Push(g1); stack.Push(g2); BinBuffer buf = new BinBuffer(BinBuffer.Type.DYNAMIC); buf.Write(list, dict, hset, slist, sset, sdict, queue, stack); buf.SetRead(); List <Player> nl = new List <Player>(); Dictionary <int, Game> nd = new Dictionary <int, Game>(); HashSet <Player> nhs = new HashSet <Player>(new PlayerEqualityComparator()); SortedList <int, Game> nsl = new SortedList <int, Game>(); SortedSet <Player> nss = new SortedSet <Player>(new PlayerComparator()); SortedDictionary <int, Game> nsd = new SortedDictionary <int, Game>(); Queue <Player> nq = new Queue <Player>(); Stack <Game> ns = new Stack <Game>(); buf.Read(nl, 2); buf.Read(nd, 2); buf.Read(nhs, 2); buf.Read(nsl, 2); buf.Read(nss, 2); buf.Read(nsd, 2); buf.Read(nq, 2); buf.Read(ns, 2); for (int i = 0; i < 2; i++) { Assert.Equal(list[i], nl[i]); Assert.Equal(dict[i + 1], nd[i + 1]); Assert.Equal(slist[i + 1], nsl[i + 1]); Assert.Equal(sdict[i + 1], nsd[i + 1]); Assert.Equal(queue.Dequeue(), nq.Dequeue()); Assert.Equal(stack.Pop(), ns.Pop()); } Assert.True(nhs.Contains(p1) && nhs.Contains(p2)); Assert.True(nss.Contains(p1) && nss.Contains(p2)); }
static void Read2DArray(BinBuffer bb, ModIdMap map, int xLen, int yLen, Action<int, int, int > setElemV, Action<int, int, ObjectRef> setElemM) { var dictPos = bb.ReadInt32(); var dataStart = bb.Position; bb.Position = dictPos; map.ReadDictionary(bb); var endOfStream = bb.Position; bb.Position = dataStart; int amt = 0; bool isM = false; ObjectRef curM = ObjectRef.Null; int curV = 0; for (int y = 0; y < yLen; y++) for (int x = 0; x < xLen; x++) if (amt == 0) { map.GetRef(bb.ReadUInt32(), oid => { curV = oid; isM = false; setElemV(x, y, curV); // amt == 0 -> one element }, or => { curM = or; isM = true; setElemM(x, y, curM); // amt == 0 -> one element }); amt = bb.ReadUInt16(); } else { if (isM) setElemM(x, y, curM); else setElemV(x, y, curV); amt--; } bb.Position = endOfStream; }