private IAnimationFrame[] LoadAnimation(BinaryFileReader reader, AnimationFrame.SittingTransformation sitting) { ushort[] palette = GetPalette(reader); // 0x100 * 2 = 0x0200 bytes int read_start = (int)reader.Position; // save file position after palette. int frameCount = reader.ReadInt(); // 0x04 bytes int[] lookups = new int[frameCount]; // frameCount * 0x04 bytes for (int i = 0; i < frameCount; ++i) { lookups[i] = reader.ReadInt(); } IAnimationFrame[] frames = new AnimationFrame[frameCount]; for (int i = 0; i < frameCount; ++i) { if (lookups[i] < lookups[0]) { frames[i] = AnimationFrame.Empty; // Fix for broken animations, per issue13 } else { reader.Seek(read_start + lookups[i], SeekOrigin.Begin); frames[i] = new AnimationFrame(m_Graphics, palette, reader, sitting); } } return frames; }
public static AnimationFrame[] GetAnimation(BinaryFileReader reader) { uint[] palette = getPalette(reader); // 0x100 * 2 = 0x0200 bytes int read_start = (int)reader.Position; // save file position after palette. int frameCount = reader.ReadInt(); // 0x04 bytes int[] lookups = new int[frameCount]; // frameCount * 0x04 bytes for (int i = 0; i < frameCount; ++i) { lookups[i] = reader.ReadInt(); } AnimationFrame[] frames = new AnimationFrame[frameCount]; for (int i = 0; i < frameCount; ++i) { if (lookups[i] < lookups[0]) { frames[i] = AnimationFrame.Empty; // Fix for broken animations, per issue13 } else { reader.Seek(read_start + lookups[i], SeekOrigin.Begin); frames[i] = new AnimationFrame(m_graphics, palette, reader); } } return(frames); }
AAnimationFrame[] LoadAnimation(BinaryFileReader reader, int uniqueAnimationIndex, AnimationFrame.SittingTransformation sitting) { var palette = GetPalette(reader); // 0x100 * 2 = 0x0200 bytes var read_start = (int)reader.Position; // save file position after palette. var frameCount = reader.ReadInt(); // 0x04 bytes var lookups = new int[frameCount]; // frameCount * 0x04 bytes for (var i = 0; i < frameCount; ++i) { lookups[i] = reader.ReadInt(); } var frames = new AnimationFrame[frameCount]; for (var i = 0; i < frameCount; ++i) { if (lookups[i] < lookups[0]) { frames[i] = AnimationFrame.NullFrame; // Fix for broken animations, per issue13 } else { reader.Seek(read_start + lookups[i], SeekOrigin.Begin); frames[i] = new AnimationFrame(uniqueAnimationIndex + (i & 0xff), _graphics, palette, reader, sitting); } } return(frames); }
public static bool TryGetSoundData(int soundID, out byte[] data, out string name) { // Sounds.mul is exclusively locked by the legacy client, so we need to make sure this file is available // before attempting to play any sounds. if (!m_filesPrepared) { setupFiles(); } data = null; name = null; if (!m_filesPrepared || soundID < 0) { return(false); } else { int length, extra; bool is_patched; BinaryFileReader reader = m_Index.Seek(soundID, out length, out extra, out is_patched); int streamStart = (int)reader.Position; int offset = (int)reader.Position; if ((offset < 0) || (length <= 0)) { if (!m_Translations.TryGetValue(soundID, out soundID)) { return(false); } reader = m_Index.Seek(soundID, out length, out extra, out is_patched); streamStart = (int)reader.Position; offset = (int)reader.Position; } if ((offset < 0) || (length <= 0)) { return(false); } byte[] stringBuffer = new byte[40]; data = new byte[length - 40]; reader.Seek((long)(offset), SeekOrigin.Begin); stringBuffer = reader.ReadBytes(40); data = reader.ReadBytes(length - 40); name = Encoding.ASCII.GetString(stringBuffer).Trim(); int end = name.IndexOf("\0"); name = name.Substring(0, end); Metrics.ReportDataRead((int)reader.Position - streamStart); return(true); } }
public static void Load() { Console.Write("DonatorAccountSettings: Loading..."); string idxPath = Path.Combine("Saves/Donation", "DonatorAccountSettings.idx"); string binPath = Path.Combine("Saves/Donation", "DonatorAccountSettings.bin"); if (File.Exists(idxPath) && File.Exists(binPath)) { // Declare and initialize reader objects. FileStream idx = new FileStream(idxPath, FileMode.Open, FileAccess.Read, FileShare.Read); FileStream bin = new FileStream(binPath, FileMode.Open, FileAccess.Read, FileShare.Read); BinaryReader idxReader = new BinaryReader(idx); BinaryFileReader binReader = new BinaryFileReader(new BinaryReader(bin)); // Start by reading the number of duels from an index file int orderCount = idxReader.ReadInt32(); for (int i = 0; i < orderCount; ++i) { DonatorAccountSettings das = new DonatorAccountSettings(); // Read start-position and length of current order from index file long startPos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); // Point the reading stream to the proper position binReader.Seek(startPos, SeekOrigin.Begin); try { das.Deserialize(binReader); if (binReader.Position != (startPos + length)) { throw new Exception(String.Format("***** Bad serialize on DonatorAccountSettings[{0}] *****", i)); } } catch { //handle } if (das != null && das.m_Account != null) { DonatorAccountSettingsTable.Add(das.m_Account, das); } } // Remember to close the streams idxReader.Close(); binReader.Close(); } Console.WriteLine("done"); }
public static void Load() { string basePath = Path.Combine("Saves", "CTFScore"); string idxPath = Path.Combine(basePath, "CTFLScore.idx"); string binPath = Path.Combine(basePath, "CTFLScore.bin"); if (File.Exists(idxPath) && File.Exists(binPath)) { // Declare and initialize reader objects. FileStream idx = new FileStream(idxPath, FileMode.Open, FileAccess.Read, FileShare.Read); FileStream bin = new FileStream(binPath, FileMode.Open, FileAccess.Read, FileShare.Read); BinaryReader idxReader = new BinaryReader(idx); BinaryFileReader binReader = new BinaryFileReader(new BinaryReader(bin)); // Start by reading the number of duels from an index file int playerCount = idxReader.ReadInt32(); for (int i = 0; i < playerCount; ++i) { CTFPlayer player = new CTFPlayer(); // Read start-position and length of current order from index file long startPos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); // Point the reading stream to the proper position binReader.Seek(startPos, SeekOrigin.Begin); try { player.Deserialize(binReader); if (binReader.Position != (startPos + length)) { throw new Exception(String.Format("***** Bad serialize on CTFScore[{0}] *****", i)); } } catch { //handle } if (player != null && player.Mobile != null) { Players.Add(player.Mobile, player); } } // Remember to close the streams idxReader.Close(); binReader.Close(); } }
public static void Load() { string idxPath = Path.Combine("Saves/FS Systems/FSBounty", "BountyTable.idx"); string binPath = Path.Combine("Saves/FS Systems/FSBounty", "BountyTable.bin"); if (File.Exists(idxPath) && File.Exists(binPath)) { FileStream idx = new FileStream(idxPath, FileMode.Open, FileAccess.Read, FileShare.Read); FileStream bin = new FileStream(binPath, FileMode.Open, FileAccess.Read, FileShare.Read); BinaryReader idxReader = new BinaryReader(idx); BinaryFileReader binReader = new BinaryFileReader(new BinaryReader(bin)); int orderCount = idxReader.ReadInt32(); for (int i = 0; i < orderCount; ++i) { Bounty ps = new Bounty(); long startPos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); binReader.Seek(startPos, SeekOrigin.Begin); try { ps.Deserialize(binReader); if (binReader.Position != (startPos + length)) { throw new Exception(String.Format("***** Bad serialize on Bounty[{0}] *****", i)); } } catch { } if (ps != null && ps.Wanted != null) { BountyTable.Add(ps.Wanted, ps); } } idxReader.Close(); binReader.Close(); } }
public void DeserializeEntities() { if (!File.Exists(m_Repository.DataPath)) { return; } using (var bin = new FileStream(m_Repository.DataPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { var reader = new BinaryFileReader(new BinaryReader(bin)); foreach (var entry in m_EntityEntries) { var obj = entry.Object; if (obj != null) { reader.Seek(entry.Position, SeekOrigin.Begin); try { obj.Deserialize(reader); if (reader.Position != (entry.Position + entry.Length)) { throw new Exception(String.Format("***** Bad serialize on {0} *****", obj.GetType())); } } catch (Exception e) { entry.Clear(); throw new RepositoryLoadException(this, e, obj.SerialIdentity, obj.GetType(), entry.TypeId); } } } reader.Close(); } m_EntityEntries = null; }
public static void Load() { string idxPath = Path.Combine( "Saves/FS Systems/FSBounty", "BountyTable.idx" ); string binPath = Path.Combine( "Saves/FS Systems/FSBounty", "BountyTable.bin" ); if ( File.Exists( idxPath ) && File.Exists( binPath ) ) { FileStream idx = new FileStream( idxPath, FileMode.Open, FileAccess.Read, FileShare.Read ); FileStream bin = new FileStream( binPath, FileMode.Open, FileAccess.Read, FileShare.Read) ; BinaryReader idxReader = new BinaryReader( idx ); BinaryFileReader binReader = new BinaryFileReader( new BinaryReader( bin ) ); int orderCount = idxReader.ReadInt32(); for ( int i = 0; i < orderCount; ++i ) { Bounty ps = new Bounty(); long startPos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); binReader.Seek( startPos, SeekOrigin.Begin ); try { ps.Deserialize(binReader); if (binReader.Position != ( startPos + length ) ) throw new Exception( String.Format( "***** Bad serialize on Bounty[{0}] *****", i ) ); } catch { } if ( ps != null && ps.Wanted != null ) BountyTable.Add( ps.Wanted, ps ); } idxReader.Close(); binReader.Close(); } }
public static List<Mobile> ReadMobiles() { var output = new List<Mobile>(); try { var mobiles = new List<MobileEntry>(); if (File.Exists(MobileIndexPath) && File.Exists(MobileTypesPath)) { using ( FileStream idx = new FileStream(MobileIndexPath, FileMode.Open, FileAccess.Read, FileShare.Read) ) { BinaryReader idxReader = new BinaryReader(idx); using ( FileStream tdb = new FileStream(MobileTypesPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader tdbReader = new BinaryReader(tdb); var types = ReadTypes(tdbReader); int mobileCount = idxReader.ReadInt32(); for (int i = 0; i < mobileCount; ++i) { int typeID = idxReader.ReadInt32(); int serial = idxReader.ReadInt32(); long pos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); var objs = types[typeID]; if (objs == null) { continue; } ConstructorInfo ctor = objs.Item1; string typeName = objs.Item2; try { Mobile value; Mobile m = null; if (World.Mobiles.TryGetValue(serial, out value)) { Mobile sameSerialMob = value; BaseCreature bc = sameSerialMob as BaseCreature; // Don't use the real serial number, get a new serial number for it serial = Serial.NewMobile; m = (Mobile) (ctor.Invoke(new object[] {(Serial) serial})); // this constructor gets a new, unused serial number if (m.GetType() != sameSerialMob.GetType()) { // the serial has already been reused by a different type of mob // which means the original stabled mob is gone. Therefore add the original mob output.Add(m); World.AddMobile(m); /*LoggingCustom.Log("PetReassignedSerials.txt", "serial was previously replaced by: " + sameSerialMob.Name + "\t" + sameSerialMob.Serial + "\tDeleted:" + sameSerialMob.Deleted + "\t|new serial assigned for pet:" + m.Serial);*/ } else // it's a very safe bet that it's the same mob (though we can't be absolutely sure)... { /*LoggingCustom.Log("PetStillExists.txt", "Now Existing: " + sameSerialMob.Name + "\t" + sameSerialMob.Serial + "\tDeleted:" + sameSerialMob.Deleted);*/ // don't add mob to output } } else { // construct mob with it's original serial number... this probably won't happen much m = (Mobile) (ctor.Invoke(new object[] {(Serial) serial})); // this constructor adds this mob into the World.Mobiles dictionary at this serial World.AddMobile(m); output.Add(m); //LoggingCustom.Log("PetSameSerialRestored.txt", m.Serial + ""); } // always add it to this list regardless mobiles.Add(new MobileEntry(m, typeID, typeName, pos, length)); } catch (Exception e) { Console.WriteLine("LostStabledPetRecorder error!: " + e.Message); Console.WriteLine(e.StackTrace); } } tdbReader.Close(); } idxReader.Close(); } } else { Console.WriteLine("Lost stable files not found! Should be at " + Path.GetFullPath(MobileIndexPath)); } Serial failedSerial = Serial.Zero; if (File.Exists(MobileDataPath)) { using ( FileStream bin = new FileStream(MobileDataPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(bin)); for (int i = 0; i < mobiles.Count; ++i) { MobileEntry entry = mobiles[i]; Mobile m = entry.Mobile; if (m != null) { reader.Seek(entry.Position, SeekOrigin.Begin); try { if (!output.Contains(m)) { // same mob already exist in the world, but // m has been assigned a new serial number so it's ok to delete it } else { m_LoadingType = entry.TypeName; m.Deserialize(reader); m.Map = Map.Internal; if (m is Beetle || m is HordeMinion || m is PackHorse || m is PackLlama) { // pack animals: make sure they have their pack Container pack = m.Backpack; if (pack == null) { pack = new StrongBackpack {Movable = false}; m.AddItem(pack); } } if (reader.Position != (entry.Position + entry.Length)) { throw new Exception(String.Format("***** Bad serialize on {0} *****", m.GetType())); } } } catch { mobiles.RemoveAt(i); Type failedType = m.GetType(); int failedTypeID = entry.TypeID; failedSerial = m.Serial; Console.WriteLine(failedType); Console.WriteLine(failedTypeID); Console.WriteLine(failedSerial); break; } } } reader.Close(); } } } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); } return output; }
public static void LoadFights() { if (File.Exists(fightIdxPath) && File.Exists(fightBinPath)) { // Declare and initialize reader objects. FileStream idx = new FileStream(fightIdxPath, FileMode.Open, FileAccess.Read, FileShare.Read); FileStream bin = new FileStream(fightBinPath, FileMode.Open, FileAccess.Read, FileShare.Read); BinaryReader idxReader = new BinaryReader(idx); BinaryFileReader binReader = new BinaryFileReader(new BinaryReader(bin)); // Start by reading the number of figts from an index file int fightCount = idxReader.ReadInt32(); //Console.WriteLine("Fight objects: {0}", fightCount); bool indexSet = false; for (int i = 0; i < fightCount; ++i) { Fight fight = new Fight(); // Read start-position and length of current fight from index file long startPos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); // Point the reading stream to the proper position binReader.Seek(startPos, SeekOrigin.Begin); try { fight.Deserialize(binReader); if (binReader.Position != (startPos + length)) throw new Exception(String.Format("***** Bad serialize on Fight[{0}] *****", i)); } catch (Exception e) { //handle } fights.Add(fight); // Read data into fast-access variables // This is done to optimize perfomance // Searching through long arrays repeatedly // Could slow down the server // Add mobile to the list of active players if (fight.Winner != null && !players.Contains(fight.Winner)) players.Add(fight.Winner); if (fight.Loser != null && !players.Contains(fight.Loser)) players.Add(fight.Loser); // Adjust Honor, win and loss variables if (fight.Winner != null) { ((PlayerMobile)fight.Winner).Wins++; ((PlayerMobile)fight.Winner).Honor += fight.Gain; } if (fight.Loser != null) { ((PlayerMobile)fight.Loser).Losses++; ((PlayerMobile)fight.Loser).Honor -= fight.Loss; } // Adjust HonorChange variable and set the index of the last fight in interval if ( fight.Start > DateTime.Now - interval) { if (fight.Winner != null) ((PlayerMobile)fight.Winner).HonorChange += fight.Gain; if (fight.Loser != null) ((PlayerMobile)fight.Loser).HonorChange -= fight.Loss; if(!indexSet) { indexSet = true; lastIntervalIndex = fights.IndexOf(fight); } } } // Only old fights were found, or there was no fights to load.... so we set the index to last fight if (!indexSet && fights.Count != 0) lastIntervalIndex = fights.Count - 1; players.Sort(); // Remember to close the streams idxReader.Close(); binReader.Close(); } }
private static short FactoryLoad() { m_DODInst = new ArrayList(); m_DODGroup = new ArrayList(); string filePath = Path.Combine("Saves/AngelIsland", "RareFactory.dat"); if (!File.Exists(filePath)) { Console.WriteLine("FactoryLoad() : RareFactory.dat does not exist, assuming new factory"); return 1; // Assume new factory } using (FileStream sr = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { if (!sr.CanRead) { Console.WriteLine("FactoryLoad() : {0} is not readable but exists!!", filePath); return 0; } // This is the stream reader we will read our binary DOD data with BinaryFileReader bfr = new BinaryFileReader(new BinaryReader(sr)); bfr.Seek(0, SeekOrigin.Begin); try { // Just in case we change the save format sometime! short version = ((GenericReader)bfr).ReadShort(); int numtoload = ((GenericReader)bfr).ReadShort(); Console.WriteLine("FactoryLoad() : Loading {0} Dynamic Object Definition{1}...", numtoload, (numtoload != 1 ? "s" : "")); // Instance the DODs with the bfr pointer (the object constructor handles in file input) for (int i = 0; i < numtoload; i++) m_DODInst.Add(new DODInstance(bfr)); numtoload = ((GenericReader)bfr).ReadShort(); Console.WriteLine("FactoryLoad() : Loading {0} DOD Group{1}...", numtoload, (numtoload != 1 ? "s" : "")); for (int i = 0; i < numtoload; i++) { DODGroup dg = new DODGroup(bfr); // Save this group list m_DODGroup.Add(dg); } } catch (Exception e) { Console.WriteLine("FactoryLoad() : Caught exception trying to load DODs : {0}", e); LogHelper.LogException(e); } bfr.Close(); } // 'using' closes sr Console.WriteLine("FactoryLoad() : Complete."); return 1; }
public static void onLoad() { //System.Console.WriteLine("Loading Jailings"); FileStream idxFileStream; FileStream binFileStream; //BinaryReader idxReader; BinaryFileReader idxReader; BinaryFileReader binReader; //GenericReader idxReader; long tPos; int tID; int tLength; JailSystem tJail; int JailCount = 0; int temp = 0; // Scriptiz : false pour annuler le if et pour qu'on charge toujours les paramètres par défaut ! if (false && (File.Exists(idxPath)) && (File.Exists(binPath))) { idxFileStream = new FileStream(idxPath, (FileMode)3, (FileAccess)1, (FileShare)1); binFileStream = new FileStream(binPath, (FileMode)3, (FileAccess)1, (FileShare)1); try { idxReader = new BinaryFileReader(new BinaryReader(idxFileStream)); binReader = new BinaryFileReader(new BinaryReader(binFileStream)); JailCount = idxReader.ReadInt(); if (JailCount > 0) { for (int i = 0; i < JailCount; i++) { temp = idxReader.ReadInt();//catch the version number which we wont use tID = idxReader.ReadInt(); tPos = idxReader.ReadLong(); tLength = idxReader.ReadInt(); tJail = new JailSystem(tID); binReader.Seek(tPos, 0); try { tJail.Deserialize((GenericReader)binReader); if (binReader.Position != ((long)tPos + tLength)) throw new Exception(String.Format("***** Bad serialize on {0} *****", tID)); } catch { } } } loadingameeditsettings((GenericReader)binReader); } finally { if (idxFileStream != null) idxFileStream.Close(); if (binFileStream != null) binFileStream.Close(); } } else { JailSystem.defaultSettings(); //System.Console.WriteLine("{0}: No prior Jailsystem save, using default settings", JailSystem.JSName); } //System.Console.WriteLine("{0} Jailings Loaded:{1}", JailCount, list.Count); }
public static List <Mobile> ReadMobiles() { var output = new List <Mobile>(); try { var mobiles = new List <MobileEntry>(); if (File.Exists(MobileIndexPath) && File.Exists(MobileTypesPath)) { using ( FileStream idx = new FileStream(MobileIndexPath, FileMode.Open, FileAccess.Read, FileShare.Read) ) { BinaryReader idxReader = new BinaryReader(idx); using ( FileStream tdb = new FileStream(MobileTypesPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader tdbReader = new BinaryReader(tdb); var types = ReadTypes(tdbReader); int mobileCount = idxReader.ReadInt32(); for (int i = 0; i < mobileCount; ++i) { int typeID = idxReader.ReadInt32(); int serial = idxReader.ReadInt32(); long pos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); var objs = types[typeID]; if (objs == null) { continue; } ConstructorInfo ctor = objs.Item1; string typeName = objs.Item2; try { Mobile value; Mobile m = null; if (World.Mobiles.TryGetValue(serial, out value)) { Mobile sameSerialMob = value; BaseCreature bc = sameSerialMob as BaseCreature; // Don't use the real serial number, get a new serial number for it serial = Serial.NewMobile; m = (Mobile)(ctor.Invoke(new object[] { (Serial)serial })); // this constructor gets a new, unused serial number if (m.GetType() != sameSerialMob.GetType()) { // the serial has already been reused by a different type of mob // which means the original stabled mob is gone. Therefore add the original mob output.Add(m); World.AddMobile(m); /*LoggingCustom.Log("PetReassignedSerials.txt", * "serial was previously replaced by: " + sameSerialMob.Name + "\t" + * sameSerialMob.Serial + "\tDeleted:" + * sameSerialMob.Deleted + "\t|new serial assigned for pet:" + m.Serial);*/ } else // it's a very safe bet that it's the same mob (though we can't be absolutely sure)... { /*LoggingCustom.Log("PetStillExists.txt", * "Now Existing: " + sameSerialMob.Name + "\t" + sameSerialMob.Serial + * "\tDeleted:" + sameSerialMob.Deleted);*/ // don't add mob to output } } else { // construct mob with it's original serial number... this probably won't happen much m = (Mobile)(ctor.Invoke(new object[] { (Serial)serial })); // this constructor adds this mob into the World.Mobiles dictionary at this serial World.AddMobile(m); output.Add(m); //LoggingCustom.Log("PetSameSerialRestored.txt", m.Serial + ""); } // always add it to this list regardless mobiles.Add(new MobileEntry(m, typeID, typeName, pos, length)); } catch (Exception e) { Console.WriteLine("LostStabledPetRecorder error!: " + e.Message); Console.WriteLine(e.StackTrace); } } tdbReader.Close(); } idxReader.Close(); } } else { Console.WriteLine("Lost stable files not found! Should be at " + Path.GetFullPath(MobileIndexPath)); } Serial failedSerial = Serial.Zero; if (File.Exists(MobileDataPath)) { using ( FileStream bin = new FileStream(MobileDataPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(bin)); for (int i = 0; i < mobiles.Count; ++i) { MobileEntry entry = mobiles[i]; Mobile m = entry.Mobile; if (m != null) { reader.Seek(entry.Position, SeekOrigin.Begin); try { if (!output.Contains(m)) { // same mob already exist in the world, but // m has been assigned a new serial number so it's ok to delete it } else { m_LoadingType = entry.TypeName; m.Deserialize(reader); m.Map = Map.Internal; if (m is Beetle || m is HordeMinion || m is PackHorse || m is PackLlama) { // pack animals: make sure they have their pack Container pack = m.Backpack; if (pack == null) { pack = new StrongBackpack { Movable = false }; m.AddItem(pack); } } if (reader.Position != (entry.Position + entry.Length)) { throw new Exception(String.Format("***** Bad serialize on {0} *****", m.GetType())); } } } catch { mobiles.RemoveAt(i); Type failedType = m.GetType(); int failedTypeID = entry.TypeID; failedSerial = m.Serial; Console.WriteLine(failedType); Console.WriteLine(failedTypeID); Console.WriteLine(failedSerial); break; } } } reader.Close(); } } } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); } return(output); }
public static void Load() { Console.Write("DonatorAccountSettings: Loading..."); string idxPath = Path.Combine( "Saves/Donation", "DonatorAccountSettings.idx" ); string binPath = Path.Combine( "Saves/Donation", "DonatorAccountSettings.bin" ); if (File.Exists(idxPath) && File.Exists(binPath)) { // Declare and initialize reader objects. FileStream idx = new FileStream(idxPath, FileMode.Open, FileAccess.Read, FileShare.Read); FileStream bin = new FileStream(binPath, FileMode.Open, FileAccess.Read, FileShare.Read); BinaryReader idxReader = new BinaryReader(idx); BinaryFileReader binReader = new BinaryFileReader(new BinaryReader(bin)); // Start by reading the number of duels from an index file int orderCount = idxReader.ReadInt32(); for (int i = 0; i < orderCount; ++i) { DonatorAccountSettings das = new DonatorAccountSettings(); // Read start-position and length of current order from index file long startPos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); // Point the reading stream to the proper position binReader.Seek(startPos, SeekOrigin.Begin); try { das.Deserialize(binReader); if (binReader.Position != (startPos + length)) throw new Exception(String.Format("***** Bad serialize on DonatorAccountSettings[{0}] *****", i)); } catch { //handle } if ( das != null && das.m_Account != null ) DonatorAccountSettingsTable.Add( das.m_Account, das ); } // Remember to close the streams idxReader.Close(); binReader.Close(); } Console.WriteLine("done"); }
private static short FactoryLoad() { m_DODInst = new ArrayList(); m_DODGroup = new ArrayList(); string filePath = Path.Combine("Saves/AngelIsland", "RareFactory.dat"); if (!File.Exists(filePath)) { Console.WriteLine("FactoryLoad() : RareFactory.dat does not exist, assuming new factory"); return(1); // Assume new factory } using (FileStream sr = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { if (!sr.CanRead) { Console.WriteLine("FactoryLoad() : {0} is not readable but exists!!", filePath); return(0); } // This is the stream reader we will read our binary DOD data with BinaryFileReader bfr = new BinaryFileReader(new BinaryReader(sr)); bfr.Seek(0, SeekOrigin.Begin); try { // Just in case we change the save format sometime! short version = ((GenericReader)bfr).ReadShort(); int numtoload = ((GenericReader)bfr).ReadShort(); Console.WriteLine("FactoryLoad() : Loading {0} Dynamic Object Definition{1}...", numtoload, (numtoload != 1 ? "s" : "")); // Instance the DODs with the bfr pointer (the object constructor handles in file input) for (int i = 0; i < numtoload; i++) { m_DODInst.Add(new DODInstance(bfr)); } numtoload = ((GenericReader)bfr).ReadShort(); Console.WriteLine("FactoryLoad() : Loading {0} DOD Group{1}...", numtoload, (numtoload != 1 ? "s" : "")); for (int i = 0; i < numtoload; i++) { DODGroup dg = new DODGroup(bfr); // Save this group list m_DODGroup.Add(dg); } } catch (Exception e) { Console.WriteLine("FactoryLoad() : Caught exception trying to load DODs : {0}", e); LogHelper.LogException(e); } bfr.Close(); } // 'using' closes sr Console.WriteLine("FactoryLoad() : Complete."); return(1); }
public override void Load( BinaryReader idx, BinaryReader tdb, BinaryFileReader reader ) { object[] ctorArgs = new object[1]; Type[] ctorTypes = new Type[1]{ typeof( Serial ) }; ArrayList modules = new ArrayList(); m_Modules = new Hashtable(); int count = tdb.ReadInt32(); ArrayList types = new ArrayList( count ); for( int i = 0; i < count; ++i ) { string typeName = tdb.ReadString(); Type t = ScriptCompiler.FindTypeByFullName( typeName ); if( t == null ) { Console.WriteLine( "Type not found: {0}, remove?", typeName ); if( Console.ReadLine() == "y" ) { types.Add( null ); continue; } throw new Exception( String.Format( "Bad type '{0}'", typeName ) ); } ConstructorInfo ctor = t.GetConstructor( ctorTypes ); if( ctor != null ) types.Add( new object[]{ ctor, null } ); else throw new Exception( String.Format( "Type '{0}' does not have a serialization constructor", t ) ); } int moduleCount = idx.ReadInt32(); for( int i = 0; i < moduleCount; ++i ) { int typeID = idx.ReadInt32(); int serial = idx.ReadInt32(); long pos = idx.ReadInt64(); int length = idx.ReadInt32(); object[] objs = (object[])types[typeID]; if( objs == null ) continue; Module m = null; ConstructorInfo ctor = (ConstructorInfo)objs[0]; string typeName = (string)objs[1]; try { ctorArgs[0] = (Serial)serial; m = (Module)(ctor.Invoke( ctorArgs )); } catch { } if( m != null ) { modules.Add( new ModuleEntry( m, typeID, typeName, pos, length ) ); AddModule( m ); } } bool failedModules = false; Type failedType = null; Exception failed = null; int failedTypeID = 0; for( int i = 0; i < modules.Count; ++i ) { ModuleEntry entry = (ModuleEntry)modules[i]; Module m = (Module)entry.Object; if( m != null ) { reader.Seek( entry.Position, SeekOrigin.Begin ); try { m.Deserialize( reader ); if( reader.Position != (entry.Position + entry.Length) ) throw new Exception( String.Format( "Bad serialize on {0}", m.GetType() ) ); } catch( Exception e ) { modules.RemoveAt( i ); failed = e; failedModules = true; failedType = m.GetType(); failedTypeID = entry.TypeID; break; } } } if( failedModules ) { Console.WriteLine( "An error was encountered while loading a Module of Type: {0}", failedType ); Console.WriteLine( "Remove this type of Module? (y/n)" ); if( Console.ReadLine() == "y" ) { for( int i = 0; i < modules.Count; ) { if( ((ModuleEntry)modules[i]).TypeID == failedTypeID ) modules.RemoveAt( i ); else ++i; } SaveIndex( modules ); } Console.WriteLine( "After pressing return an exception will be thrown and the server will terminate" ); Console.ReadLine(); throw new Exception( String.Format( "Load failed (type={0})", failedType ), failed ); } }
public static void Load() { string filePath = Path.Combine("Saves/Attachments", "Attachments.bin"); // the attachment serializations string imaPath = Path.Combine("Saves/Attachments", "Attachments.ima"); // the item/mob attachment tables string fpiPath = Path.Combine("Saves/Attachments", "Attachments.fpi"); // the file position indices if (!File.Exists(filePath)) { return; } FileStream fs = null; BinaryFileReader reader = null; FileStream imafs = null; BinaryFileReader imareader = null; FileStream fpifs = null; BinaryFileReader fpireader = null; try { fs = new FileStream(filePath, (FileMode)3, (FileAccess)1, (FileShare)1); reader = new BinaryFileReader(new BinaryReader(fs)); imafs = new FileStream(imaPath, (FileMode)3, (FileAccess)1, (FileShare)1); imareader = new BinaryFileReader(new BinaryReader(imafs)); fpifs = new FileStream(fpiPath, (FileMode)3, (FileAccess)1, (FileShare)1); fpireader = new BinaryFileReader(new BinaryReader(fpifs)); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } if (reader != null && imareader != null && fpireader != null) { // restore the current global attachment serial state try { ASerial.GlobalDeserialize(reader); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } ASerial.serialInitialized = true; // read in the serial attachment hash table information int count = 0; try { count = reader.ReadInt(); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } for (int i = 0; i < count; i++) { // read the serial ASerial serialno = null; try { serialno = new ASerial(reader.ReadInt()); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } // read the attachment type string valuetype = null; try { valuetype = reader.ReadString(); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } // read the position of the beginning of the next attachment deser within the .bin file long position = 0; try { position = fpireader.ReadLong(); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } bool skip = false; XmlAttachment o = null; try { o = (XmlAttachment)Activator.CreateInstance(Type.GetType(valuetype), new object[] {serialno}); } catch { skip = true; } if (skip) { if (!AlreadyReported(valuetype)) { Console.WriteLine("\nError deserializing attachments {0}.\nMissing a serial constructor?\n", valuetype); ReportDeserError(valuetype, "Missing a serial constructor?"); } // position the .ima file at the next deser point try { reader.Seek(position, SeekOrigin.Begin); } catch { ErrorReporter.GenerateErrorReport( "Error deserializing. Attachments save file corrupted. Attachment load aborted."); return; } continue; } try { o.Deserialize(reader); } catch { skip = true; } // confirm the read position if (reader.Position != position || skip) { if (!AlreadyReported(valuetype)) { Console.WriteLine("\nError deserializing attachments {0}\n", valuetype); ReportDeserError(valuetype, "save file corruption or incorrect Serialize/Deserialize methods?"); } // position the .ima file at the next deser point try { reader.Seek(position, SeekOrigin.Begin); } catch { ErrorReporter.GenerateErrorReport( "Error deserializing. Attachments save file corrupted. Attachment load aborted."); return; } continue; } // add it to the hash table try { AllAttachments.Add(serialno.Value, o); } catch { ErrorReporter.GenerateErrorReport( String.Format( "\nError deserializing {0} serialno {1}. Attachments save file corrupted. Attachment load aborted.\n", valuetype, serialno.Value)); return; } } // read in the mobile attachment hash table information try { count = imareader.ReadInt(); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } for (int i = 0; i < count; i++) { Mobile key = null; try { key = imareader.ReadMobile(); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } int nattach = 0; try { nattach = imareader.ReadInt(); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } for (int j = 0; j < nattach; j++) { // and serial ASerial serialno = null; try { serialno = new ASerial(imareader.ReadInt()); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } // read the attachment type string valuetype = null; try { valuetype = imareader.ReadString(); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } // read the position of the beginning of the next attachment deser within the .bin file long position = 0; try { position = fpireader.ReadLong(); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } XmlAttachment o = FindAttachmentBySerial(serialno.Value); if (o == null || imareader.Position != position) { if (!AlreadyReported(valuetype)) { Console.WriteLine("\nError deserializing attachments of type {0}.\n", valuetype); ReportDeserError(valuetype, "save file corruption or incorrect Serialize/Deserialize methods?"); } // position the .ima file at the next deser point try { imareader.Seek(position, SeekOrigin.Begin); } catch { ErrorReporter.GenerateErrorReport( "Error deserializing. Attachments save file corrupted. Attachment load aborted."); return; } continue; } // attachment successfully deserialized so attach it AttachTo(key, o, false); } } // read in the item attachment hash table information try { count = imareader.ReadInt(); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } for (int i = 0; i < count; i++) { Item key = null; try { key = imareader.ReadItem(); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } int nattach = 0; try { nattach = imareader.ReadInt(); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } for (int j = 0; j < nattach; j++) { // and serial ASerial serialno = null; try { serialno = new ASerial(imareader.ReadInt()); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } // read the attachment type string valuetype = null; try { valuetype = imareader.ReadString(); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } // read the position of the beginning of the next attachment deser within the .bin file long position = 0; try { position = fpireader.ReadLong(); } catch (Exception e) { ErrorReporter.GenerateErrorReport(e.ToString()); return; } XmlAttachment o = FindAttachmentBySerial(serialno.Value); if (o == null || imareader.Position != position) { if (!AlreadyReported(valuetype)) { Console.WriteLine("\nError deserializing attachments of type {0}.\n", valuetype); ReportDeserError(valuetype, "save file corruption or incorrect Serialize/Deserialize methods?"); } // position the .ima file at the next deser point try { imareader.Seek(position, SeekOrigin.Begin); } catch { ErrorReporter.GenerateErrorReport( "Error deserializing. Attachments save file corrupted. Attachment load aborted."); return; } continue; } // attachment successfully deserialized so attach it AttachTo(key, o, false); } } if (fs != null) { fs.Close(); } if (imafs != null) { imafs.Close(); } if (fpifs != null) { fpifs.Close(); } if (desererror != null) { ErrorReporter.GenerateErrorReport("Error deserializing particular attachments."); } } }
public static void Load() { string idxPath = Path.Combine( "Saves/FriendLists", "FriendLists.idx" ); string binPath = Path.Combine( "Saves/FriendLists", "FriendLists.bin" ); if (File.Exists(idxPath) && File.Exists(binPath)) { // Declare and initialize reader objects. FileStream idx = new FileStream(idxPath, FileMode.Open, FileAccess.Read, FileShare.Read); FileStream bin = new FileStream(binPath, FileMode.Open, FileAccess.Read, FileShare.Read); BinaryReader idxReader = new BinaryReader(idx); BinaryFileReader binReader = new BinaryFileReader(new BinaryReader(bin)); // Start by reading the number of duels from an index file int orderCount = idxReader.ReadInt32(); for (int i = 0; i < orderCount; ++i) { FriendList fl = new FriendList(); // Read start-position and length of current order from index file long startPos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); // Point the reading stream to the proper position binReader.Seek(startPos, SeekOrigin.Begin); try { fl.Deserialize(binReader); if (binReader.Position != (startPos + length)) throw new Exception(String.Format("***** Bad serialize on FriendList[{0}] *****", i)); } catch { //handle } if ( fl != null && fl.m_Mobile != null ) FriendLists.Add( fl.m_Mobile, fl ); } // Remember to close the streams idxReader.Close(); binReader.Close(); } }
static void Test() { BinaryFileReader reader = new BinaryFileReader(@"D:\PlayGround\SOD_Data\h3ab_bmp.lod"); reader.Skip(8); uint count = reader.ReadUInt32(); Console.WriteLine("Total count: " + count); List <FileInfo> fileList = new List <FileInfo>(); reader.Seek(92); for (int fileIndex = 0; fileIndex < count; fileIndex++) { byte[] buffer = new byte[16]; for (int i = 0; i < 16; i++) { buffer[i] = reader.ReadByte(); } string filename = System.Text.Encoding.ASCII.GetString(buffer); filename = filename.Substring(0, filename.IndexOf('\0')); uint offset = reader.ReadUInt32(); uint size = reader.ReadUInt32(); uint placeholder = reader.ReadUInt32(); uint csize = reader.ReadUInt32(); Console.WriteLine(string.Format("[{4}] filename:{0} offset:{1} size:{2} csize:{3}", filename, offset, size, csize, fileIndex)); FileInfo info = new FileInfo(); info.FileName = filename; info.Offset = offset; info.Size = size; info.CSize = csize; fileList.Add(info); } Directory.CreateDirectory(@".\output\"); Directory.CreateDirectory(@".\output\extracted\"); for (int fileIndex = 0; fileIndex < count; fileIndex++) { FileInfo info = fileList[fileIndex]; reader.Seek(info.Offset); byte[] content; string filename = @".\output\" + info.FileName; if (info.CSize > 0) { filename = filename + ".zip"; content = reader.ReadBytes((int)info.CSize); } else { content = reader.ReadBytes((int)info.Size); } using (var fs = new FileStream(filename, FileMode.Create, FileAccess.Write)) { fs.Write(content, 0, content.Length); } //// Thread.Sleep(500); Console.WriteLine("Finished writing file " + filename); if (filename.EndsWith(".h3c")) { /* * //ZipFile.ExtractToDirectory(filename, @"D:\Temp\ab.h3c"); * int length = 100000; * byte[] data = new byte[length]; * for (int i = 0; i < length; i++) * { * data[i] = System.Convert.ToByte(i % 100 + i % 50); * } * * byte[] o; * //serialization into memory stream * IFormatter formatter = new BinaryFormatter(); * * using (FileStream decompressedFileStream = File.Create(filename + ".origin")) * { * using (FileStream file = new FileStream(filename, FileMode.Open, FileAccess.Read)) * { * using (GZipStream decompressionStream = new GZipStream(file, CompressionMode.Decompress, true)) * { * int dstreamlength = 0; * while(decompressionStream.ReadByte() >= 0) * { * dstreamlength++; * } * * Console.WriteLine("GZip Decompressed length: " + dstreamlength); * * ///DecompressFile(@".\output\extracted\", decompressionStream); * // decompressionStream.CopyTo(decompressedFileStream);/// * * Console.WriteLine("Decompressed: {0}", filename); * } * * * file.Seek(0, SeekOrigin.Begin); * var oo = formatter.Deserialize(decompressedFileStream); * o = (byte[])oo; * * } * } */ } if (info.CSize > 0) { ////ZipFile.ExtractToDirectory(filename, @"D:\Temp"); //// ZipFile.ExtractToDirectory(filename, filename.Substring(0, 5)); using (FileStream decompressedFileStream = File.Create(filename + ".origin")) { using (FileStream file = new FileStream(filename, FileMode.Open, FileAccess.Read)) { using (DeflateStream decompressionStream = new DeflateStream(file, CompressionMode.Decompress, true)) { decompressionStream.CopyTo(decompressedFileStream); Console.WriteLine("Decompressed: {0}", filename); } /* * using (GZipStream decompressionStream = new GZipStream(file, CompressionMode.Decompress, false)) * { * decompressionStream.CopyTo(decompressedFileStream); * Console.WriteLine("Decompressed: {0}", filename); * } */ } } } } }
public static void On_RHFile(CommandEventArgs e) { if (e.Arguments.Length != 1) { e.Mobile.SendMessage("Usage: [LoadCont <filename>"); return; } try { int loaded = 0; int count; LogHelper log = new LogHelper(e.Arguments[0] + " LoadCont.log"); log.Log(LogType.Text, String.Format("Reload process initiated by {0}, with {1} as backup data.", e.Mobile, e.Arguments[0])); using (FileStream idxfs = new FileStream(e.Arguments[0] + ".idx", FileMode.Open, FileAccess.Read)) { using (FileStream binfs = new FileStream(e.Arguments[0] + ".bin", FileMode.Open, FileAccess.Read)) { GenericReader bin = new BinaryFileReader(new BinaryReader(binfs)); GenericReader idx = new BinaryFileReader(new BinaryReader(idxfs)); count = idx.ReadInt(); if (count == -1) { log.Log(LogType.Text, "No item data to reload."); // do nothing } else { ArrayList items = new ArrayList(count); log.Log(LogType.Text, String.Format("Attempting to reload {0} items.", count)); Type[] ctortypes = new Type[] { typeof(Serial) }; object[] ctorargs = new object[1]; for (int i = 0; i < count; i++) { string type = idx.ReadString(); Serial serial = (Serial)idx.ReadInt(); long position = idx.ReadLong(); int length = idx.ReadInt(); Type t = ScriptCompiler.FindTypeByFullName(type); if (t == null) { Console.WriteLine("Warning: Tried to load nonexistent type {0}. Ignoring item.", type); log.Log(String.Format("Warning: Tried to load nonexistent type {0}. Ignoring item.", type)); continue; } ConstructorInfo ctor = t.GetConstructor(ctortypes); if (ctor == null) { Console.WriteLine("Warning: Tried to load type {0} which has no serialization constructor. Ignoring item.", type); log.Log(String.Format("Warning: Tried to load type {0} which has no serialization constructor. Ignoring item.", type)); continue; } Item item = null; try { if (World.FindItem(serial) != null) { log.Log(LogType.Item, World.FindItem(serial), "Serial already in use!! Loading of saved item failed."); } else if (!World.IsReserved(serial)) { log.Log(String.Format("Serial {0} is not reserved!! Loading of saved item failed.", serial)); } else { ctorargs[0] = serial; item = (Item)(ctor.Invoke(ctorargs)); } } catch (Exception ex) { LogHelper.LogException(ex); Console.WriteLine("An exception occurred while trying to invoke {0}'s serialization constructor.", t.FullName); Console.WriteLine(ex.ToString()); log.Log(String.Format("An exception occurred while trying to invoke {0}'s serialization constructor.", t.FullName)); log.Log(ex.ToString()); } if (item != null) { World.FreeSerial(serial); World.AddItem(item); items.Add(new object[] { item, position, length }); log.Log(String.Format("Successfully created item {0}", item)); } } for (int i = 0; i < items.Count; i++) { object[] entry = (object[])items[i]; Item item = entry[0] as Item; long position = (long)entry[1]; int length = (int)entry[2]; if (item != null) { bin.Seek(position, SeekOrigin.Begin); try { item.Deserialize(bin); // take care of parent hierarchy object p = item.Parent; if (p is Item) { ((Item)p).RemoveItem(item); item.Parent = null; ((Item)p).AddItem(item); } else if (p is Mobile) { ((Mobile)p).RemoveItem(item); item.Parent = null; ((Mobile)p).AddItem(item); } else { item.Delta(ItemDelta.Update); } item.ClearProperties(); object rp = item.RootParent; if (rp is Item) { ((Item)rp).UpdateTotals(); } else if (rp is Mobile) { ((Mobile)rp).UpdateTotals(); } else { item.UpdateTotals(); } if (bin.Position != (position + length)) { throw new Exception(String.Format("Bad serialize on {0}", item)); } log.Log(LogType.Item, item, "Successfully loaded."); loaded++; } catch (Exception ex) { LogHelper.LogException(ex); Console.WriteLine("Caught exception while deserializing {0}:", item); Console.WriteLine(ex.ToString()); Console.WriteLine("Deleting item."); log.Log(String.Format("Caught exception while deserializing {0}:", item)); log.Log(ex.ToString()); log.Log("Deleting item."); item.Delete(); } } } } idx.Close(); bin.Close(); } } Console.WriteLine("Attempted to load {0} items: {1} loaded, {2} failed.", count, loaded, count - loaded); log.Log(String.Format("Attempted to load {0} items: {1} loaded, {2} failed.", count, loaded, count - loaded)); e.Mobile.SendMessage("Attempted to load {0} items: {1} loaded, {2} failed.", count, loaded, count - loaded); log.Finish(); } catch (Exception ex) { LogHelper.LogException(ex); Console.WriteLine(ex.ToString()); e.Mobile.SendMessage("Exception: {0}", ex.Message); } }
public static void Load() { string idxPath = Path.Combine("Saves/Lottery", "Lottery.idx"); string binPath = Path.Combine("Saves/Lottery", "Lottery.bin"); if (File.Exists(idxPath) && File.Exists(binPath)) { // Declare and initialize reader objects. FileStream idx = new FileStream(idxPath, FileMode.Open, FileAccess.Read, FileShare.Read); FileStream bin = new FileStream(binPath, FileMode.Open, FileAccess.Read, FileShare.Read); BinaryReader idxReader = new BinaryReader(idx); BinaryFileReader binReader = new BinaryFileReader(new BinaryReader(bin)); // Read start-position and length of current order from index file long startPos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); // Point the reading stream to the proper position binReader.Seek(startPos, SeekOrigin.Begin); try { Deserialize(binReader); if (binReader.Position != (startPos + length)) throw new Exception("***** Bad serialize on Lottery *****"); } catch { } idxReader.Close(); binReader.Close(); } }
public static void LoadSpawners_OnCommand(CommandEventArgs e) { int count = 0; int itemCount = 0; Hashtable m_Items; if (e.Arguments.Length == 1) { string FileName = e.Arguments[0].ToString(); string itemIdxPath = Path.Combine("Saves/Spawners/", FileName + ".idx"); string itemBinPath = Path.Combine("Saves/Spawners/", FileName + ".bin"); try { ArrayList items = new ArrayList(); if (File.Exists(itemIdxPath)) { using (FileStream idx = new FileStream(itemIdxPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader idxReader = new BinaryReader(idx); itemCount = idxReader.ReadInt32(); count = itemCount; m_Items = new Hashtable(itemCount); for (int i = 0; i < itemCount; ++i) { long pos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); Item item = null; try { item = new Spawner(); } catch (Exception ex) { EventSink.InvokeLogException(new LogExceptionEventArgs(ex)); } if (item != null) { items.Add(new ItemEntry(item, pos, length)); World.AddItem(item); } } idxReader.Close(); } } else { e.Mobile.SendMessage("File Not Found {0}.idx", FileName); } if (File.Exists(itemBinPath)) { using (FileStream bin = new FileStream(itemBinPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(bin)); for (int i = 0; i < items.Count; ++i) { ItemEntry entry = (ItemEntry)items[i]; Item item = (Item)entry.Object; if (item != null) { reader.Seek(entry.Position, SeekOrigin.Begin); try { item.Deserialize(reader); if (reader.Position != (entry.Position + entry.Length)) { throw new Exception(String.Format("***** Bad serialize on {0} *****", item.GetType())); } item.MoveToWorld(item.Location, item.Map); } catch (Exception ex) { EventSink.InvokeLogException(new LogExceptionEventArgs(ex)); } } } reader.Close(); } } else { e.Mobile.SendMessage("File Not Found {0}.bin", FileName); } } catch (Exception ex) { LogHelper.LogException(ex); System.Console.WriteLine("Exception Caught in LoadSpawner code: " + ex.Message); System.Console.WriteLine(ex.StackTrace); } e.Mobile.SendMessage("{0} Spawners Loaded.", count); } else { e.Mobile.SendMessage("[Usage <FileName>"); } }
public override void Load(BinaryReader idx, BinaryReader tdb, BinaryFileReader reader) { object[] ctorArgs = new object[1]; Type[] ctorTypes = new Type[1] { typeof(Serial) }; List <ModuleEntry> modules = new List <ModuleEntry>(); m_DictionaryOfModuleLists = new Dictionary <Serial, ModuleList>(); int version = reader.ReadInt(); int count = tdb.ReadInt32(); ArrayList types = new ArrayList(count); for (int i = 0; i < count; ++i) { string typeName = tdb.ReadString(); Type t = ScriptCompiler.FindTypeByFullName(typeName); if (t == null) { Console.WriteLine("Type not found: {0}, remove?", typeName); if (Console.ReadKey(true).Key == ConsoleKey.Y) { types.Add(null); continue; } throw new Exception(String.Format("Bad type '{0}'", typeName)); } ConstructorInfo ctor = t.GetConstructor(ctorTypes); if (ctor != null) { types.Add(new object[] { ctor, null }); } else { throw new Exception(String.Format("Type '{0}' does not have a serialization constructor", t)); } } int moduleCount = idx.ReadInt32(); for (int i = 0; i < moduleCount; ++i) { int typeID = idx.ReadInt32(); int serial = idx.ReadInt32(); long pos = idx.ReadInt64(); int length = idx.ReadInt32(); object[] objs = (object[])types[typeID]; if (objs == null) { continue; } Module m = null; ConstructorInfo ctor = (ConstructorInfo)objs[0]; string typeName = (string)objs[1]; try { ctorArgs[0] = (Serial)serial; m = (Module)(ctor.Invoke(ctorArgs)); } catch { } if (m != null) { modules.Add(new ModuleEntry(m, typeID, typeName, pos, length)); AddModule(m); } } bool failedModules = false; Type failedType = null; Exception failed = null; int failedTypeID = 0; for (int i = 0; i < modules.Count; ++i) { ModuleEntry entry = modules[i]; Module m = entry.Module; if (m != null) { reader.Seek(entry.Position, SeekOrigin.Begin); try { m.Deserialize(reader); if (reader.Position != (entry.Position + entry.Length)) { throw new Exception(String.Format("Bad serialize on {0}", m.GetType())); } } catch (Exception e) { modules.RemoveAt(i); failed = e; failedModules = true; failedType = m.GetType(); failedTypeID = entry.TypeID; break; } } } if (failedModules) { Console.WriteLine("An error was encountered while loading a Module of Type: {0}", failedType); Console.WriteLine("Remove this type of Module? (y/n)"); if (Console.ReadLine() == "y") { for (int i = 0; i < modules.Count;) { if (((ModuleEntry)modules[i]).TypeID == failedTypeID) { modules.RemoveAt(i); } else { ++i; } } SaveIndex <ModuleEntry>(modules); } Console.WriteLine("After pressing return an exception will be thrown and the server will terminate"); Console.ReadLine(); throw new Exception(String.Format("Load failed (type={0})", failedType), failed); } }
public static void LoadDuels() { if (File.Exists(duelIdxPath) && File.Exists(duelBinPath)) { // Declare and initialize reader objects. FileStream idx = new FileStream(duelIdxPath, FileMode.Open, FileAccess.Read, FileShare.Read); FileStream bin = new FileStream(duelBinPath, FileMode.Open, FileAccess.Read, FileShare.Read); BinaryReader idxReader = new BinaryReader(idx); BinaryFileReader binReader = new BinaryFileReader(new BinaryReader(bin)); // Start by reading the number of duels from an index file int duelCount = idxReader.ReadInt32(); for (int i = 0; i < duelCount; ++i) { DuelObject d = new DuelObject(); // Read start-position and length of current fight from index file long startPos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); // Point the reading stream to the proper position binReader.Seek(startPos, SeekOrigin.Begin); try { d.Deserialize(binReader); if (binReader.Position != (startPos + length)) throw new Exception(String.Format("***** Bad serialize on DuelObject[{0}] *****", i)); } catch (Exception e) { //handle } duels.Add(d); } // Remember to close the streams idxReader.Close(); binReader.Close(); } }