public static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit); for (int i = 0; i < args.Length; ++i) { if (Insensitive.Equals(args[i], "-debug")) { m_Debug = true; } else if (Insensitive.Equals(args[i], "-service")) { m_Service = true; } else if (Insensitive.Equals(args[i], "-profile")) { Profiling = true; } else if (Insensitive.Equals(args[i], "-nocache")) { m_Cache = false; } else if (Insensitive.Equals(args[i], "-haltonwarning")) { m_HaltOnWarning = true; } } try { if (m_Service) { if (!Directory.Exists("Logs")) { Directory.CreateDirectory("Logs"); } Console.SetOut(m_MultiConOut = new MultiTextWriter(Console.Out, new FileLogger("Logs/Console.log"))); } else { Console.SetOut(m_MultiConOut = new MultiTextWriter(Console.Out)); } } catch { } m_Thread = Thread.CurrentThread; m_Process = Process.GetCurrentProcess(); m_Assembly = Assembly.GetEntryAssembly(); if (m_Thread != null) { m_Thread.Name = "Core Thread"; } if (BaseDirectory.Length > 0) { Directory.SetCurrentDirectory(BaseDirectory); } Timer.TimerThread ttObj = new Timer.TimerThread(); timerThread = new Thread(new ThreadStart(ttObj.TimerMain)); timerThread.Name = "Timer Thread"; Version ver = m_Assembly.GetName().Version; // Added to help future code support on forums, as a 'check' people can ask for to it see if they recompiled core or not Console.WriteLine("RunUO - [www.runuo.com] Version {0}.{1}, Build {2}.{3}", ver.Major, ver.Minor, ver.Build, ver.Revision); Console.WriteLine("Core: Running on .NET Framework Version {0}.{1}.{2}", Environment.Version.Major, Environment.Version.Minor, Environment.Version.Build); string s = Arguments; if (s.Length > 0) { Console.WriteLine("Core: Running with arguments: {0}", s); } m_ProcessorCount = Environment.ProcessorCount; if (m_ProcessorCount > 1) { m_MultiProcessor = true; } if (m_MultiProcessor || Is64Bit) { Console.WriteLine("Core: Optimizing for {0} {2}processor{1}", m_ProcessorCount, m_ProcessorCount == 1 ? "" : "s", Is64Bit ? "64-bit " : ""); } int platform = (int)Environment.OSVersion.Platform; if ((platform == 4) || (platform == 128)) // MS 4, MONO 128 { m_Unix = true; Console.WriteLine("Core: Unix environment detected"); } else { m_ConsoleEventHandler = new ConsoleEventHandler(OnConsoleEvent); SetConsoleCtrlHandler(m_ConsoleEventHandler, true); } while (!ScriptCompiler.Compile(m_Debug, m_Cache)) { Console.WriteLine("Scripts: One or more scripts failed to compile or no script files were found."); Console.WriteLine(" - Press return to exit, or R to try again."); if (Console.ReadKey(true).Key != ConsoleKey.R) { return; } } SocketPool.Create(); MessagePump ms = m_MessagePump = new MessagePump(); timerThread.Start(); for (int i = 0; i < Map.AllMaps.Count; ++i) { Map.AllMaps[i].Tiles.Force(); } NetState.Initialize(); EventSink.InvokeServerStarted(); try { DateTime now, last = DateTime.Now; const int sampleInterval = 100; const float ticksPerSecond = (float)(TimeSpan.TicksPerSecond * sampleInterval); int sample = 0; while (m_Signal.WaitOne()) { Mobile.ProcessDeltaQueue(); Item.ProcessDeltaQueue(); Timer.Slice(); m_MessagePump.Slice(); NetState.FlushAll(); NetState.ProcessDisposedQueue(); if (Slice != null) { Slice(); } if ((++sample % sampleInterval) == 0) { now = DateTime.Now; m_CyclesPerSecond[m_CycleIndex++ % m_CyclesPerSecond.Length] = ticksPerSecond / (now.Ticks - last.Ticks); last = now; } } } catch (Exception e) { CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(e, true)); } }
public static void Load() { if (m_Loaded) { return; } m_Loaded = true; m_LoadingType = null; Console.Write("World: Loading..."); DateTime start = DateTime.Now; m_Loading = true; m_DeleteList = new ArrayList(); int mobileCount = 0, itemCount = 0, guildCount = 0, regionCount = 0; object[] ctorArgs = new object[1]; Type[] ctorTypes = new Type[1] { typeof(Serial) }; ArrayList items = new ArrayList(); ArrayList mobiles = new ArrayList(); ArrayList guilds = new ArrayList(); ArrayList regions = new ArrayList(); if (File.Exists(mobIdxPath) && File.Exists(mobTdbPath)) { using (FileStream idx = new FileStream(mobIdxPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader idxReader = new BinaryReader(idx); using (FileStream tdb = new FileStream(mobTdbPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader tdbReader = new BinaryReader(tdb); int count = tdbReader.ReadInt32(); ArrayList types = new ArrayList(count); for (int i = 0; i < count; ++i) { string typeName = tdbReader.ReadString(); Type t = ScriptCompiler.FindTypeByFullName(typeName); if (t == null) { Console.WriteLine("failed"); Console.WriteLine("Error: Type '{0}' was not found. Delete all of those types? (y/n)", typeName); if (Console.ReadLine() == "y") { types.Add(null); Console.Write("World: Loading..."); continue; } Console.WriteLine("Types will not be deleted. An exception will be thrown when you press return"); 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)); } } mobileCount = idxReader.ReadInt32(); m_Mobiles = new Hashtable(mobileCount); for (int i = 0; i < mobileCount; ++i) { int typeID = idxReader.ReadInt32(); int serial = idxReader.ReadInt32(); long pos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); object[] objs = (object[])types[typeID]; if (objs == null) { continue; } Mobile m = null; ConstructorInfo ctor = (ConstructorInfo)objs[0]; string typeName = (string)objs[1]; try { ctorArgs[0] = (Serial)serial; m = (Mobile)(ctor.Invoke(ctorArgs)); } catch { } if (m != null) { mobiles.Add(new MobileEntry(m, typeID, typeName, pos, length)); AddMobile(m); } } tdbReader.Close(); } idxReader.Close(); } } else { m_Mobiles = new Hashtable(); } if (File.Exists(itemIdxPath) && File.Exists(itemTdbPath)) { using (FileStream idx = new FileStream(itemIdxPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader idxReader = new BinaryReader(idx); using (FileStream tdb = new FileStream(itemTdbPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader tdbReader = new BinaryReader(tdb); int count = tdbReader.ReadInt32(); ArrayList types = new ArrayList(count); for (int i = 0; i < count; ++i) { string typeName = tdbReader.ReadString(); Type t = ScriptCompiler.FindTypeByFullName(typeName); if (t == null) { Console.WriteLine("failed"); Console.WriteLine("Error: Type '{0}' was not found. Delete all of those types? (y/n)", typeName); if (Console.ReadLine() == "y") { types.Add(null); Console.Write("World: Loading..."); continue; } Console.WriteLine("Types will not be deleted. An exception will be thrown when you press return"); throw new Exception(String.Format("Bad type '{0}'", typeName)); } ConstructorInfo ctor = t.GetConstructor(ctorTypes); if (ctor != null) { types.Add(new object[] { ctor, typeName }); } else { throw new Exception(String.Format("Type '{0}' does not have a serialization constructor", t)); } } itemCount = idxReader.ReadInt32(); m_Items = new Hashtable(itemCount); for (int i = 0; i < itemCount; ++i) { int typeID = idxReader.ReadInt32(); int serial = idxReader.ReadInt32(); long pos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); object[] objs = (object[])types[typeID]; if (objs == null) { continue; } Item item = null; ConstructorInfo ctor = (ConstructorInfo)objs[0]; string typeName = (string)objs[1]; try { ctorArgs[0] = (Serial)serial; item = (Item)(ctor.Invoke(ctorArgs)); } catch { } if (item != null) { items.Add(new ItemEntry(item, typeID, typeName, pos, length)); AddItem(item); } } tdbReader.Close(); } idxReader.Close(); } } else { m_Items = new Hashtable(); } if (File.Exists(guildIdxPath)) { using (FileStream idx = new FileStream(guildIdxPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader idxReader = new BinaryReader(idx); guildCount = idxReader.ReadInt32(); CreateGuildEventArgs createEventArgs = new CreateGuildEventArgs(-1); for (int i = 0; i < guildCount; ++i) { idxReader.ReadInt32(); //no typeid for guilds int id = idxReader.ReadInt32(); long pos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); createEventArgs.Id = id; BaseGuild guild = EventSink.InvokeCreateGuild(createEventArgs); //new Guild( id ); if (guild != null) { guilds.Add(new GuildEntry(guild, pos, length)); } } idxReader.Close(); } } if (File.Exists(regionIdxPath)) { using (FileStream idx = new FileStream(regionIdxPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader idxReader = new BinaryReader(idx); regionCount = idxReader.ReadInt32(); for (int i = 0; i < regionCount; ++i) { idxReader.ReadInt32(); /* typeID */ int serial = idxReader.ReadInt32(); long pos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); Region r = Region.FindByUId(serial); if (r != null) { regions.Add(new RegionEntry(r, pos, length)); Region.AddRegion(r); regionCount++; } } idxReader.Close(); } } bool failedMobiles = false, failedItems = false, failedGuilds = false, failedRegions = false; Type failedType = null; Serial failedSerial = Serial.Zero; Exception failed = null; int failedTypeID = 0; if (File.Exists(mobBinPath)) { using (FileStream bin = new FileStream(mobBinPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(bin)); for (int i = 0; i < mobiles.Count; ++i) { MobileEntry entry = (MobileEntry)mobiles[i]; Mobile m = (Mobile)entry.Object; if (m != null) { reader.Seek(entry.Position, SeekOrigin.Begin); try { m_LoadingType = entry.TypeName; m.Deserialize(reader); if (reader.Position != (entry.Position + entry.Length)) { throw new Exception(String.Format("***** Bad serialize on {0} *****", m.GetType())); } } catch (Exception e) { Console.WriteLine("failed to load mobile: {0}", e); mobiles.RemoveAt(i); failed = e; failedMobiles = true; failedType = m.GetType(); failedTypeID = entry.TypeID; failedSerial = m.Serial; break; } } } reader.Close(); } } if (!failedMobiles && 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 { m_LoadingType = entry.TypeName; item.Deserialize(reader); if (reader.Position != (entry.Position + entry.Length)) { throw new Exception(String.Format("***** Bad serialize on {0} *****", item.GetType())); } } catch (Exception e) { Console.WriteLine("failed to load item: {0}", e); items.RemoveAt(i); failed = e; failedItems = true; failedType = item.GetType(); failedTypeID = entry.TypeID; failedSerial = item.Serial; break; } } } reader.Close(); } } m_LoadingType = null; if (!failedMobiles && !failedItems && File.Exists(guildBinPath)) { using (FileStream bin = new FileStream(guildBinPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(bin)); for (int i = 0; i < guilds.Count; ++i) { GuildEntry entry = (GuildEntry)guilds[i]; BaseGuild g = (BaseGuild)entry.Object; if (g != null) { reader.Seek(entry.Position, SeekOrigin.Begin); try { g.Deserialize(reader); if (reader.Position != (entry.Position + entry.Length)) { throw new Exception(String.Format("***** Bad serialize on Guild {0} *****", g.Id)); } } catch (Exception e) { Console.WriteLine("failed to load guild: {0}", e); guilds.RemoveAt(i); failed = e; failedGuilds = true; failedType = typeof(BaseGuild); failedTypeID = g.Id; failedSerial = g.Id; break; } } } reader.Close(); } } if (!failedMobiles && !failedItems && File.Exists(regionBinPath)) { using (FileStream bin = new FileStream(regionBinPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(bin)); for (int i = 0; i < regions.Count; ++i) { RegionEntry entry = (RegionEntry)regions[i]; Region r = (Region)entry.Object; if (r != null) { reader.Seek(entry.Position, SeekOrigin.Begin); try { r.Deserialize(reader); if (reader.Position != (entry.Position + entry.Length)) { throw new Exception(String.Format("***** Bad serialize on {0} *****", r.GetType())); } } catch (Exception e) { Console.WriteLine("failed to load region: {0}", e); regions.RemoveAt(i); failed = e; failedRegions = true; failedType = r.GetType(); failedTypeID = entry.TypeID; failedSerial = r.UId; break; } } } reader.Close(); } } if (failedItems || failedMobiles || failedGuilds || failedRegions) { Console.WriteLine("An error was encountered while loading a saved object"); Console.WriteLine(" - Type: {0}", failedType); Console.WriteLine(" - Serial: {0}", failedSerial); Console.WriteLine("Delete the object? (y/n)"); if (Console.ReadLine() == "y") { if (failedType != typeof(BaseGuild) && !failedType.IsSubclassOf(typeof(Region))) { Console.WriteLine("Delete all objects of that type? (y/n)"); if (Console.ReadLine() == "y") { if (failedMobiles) { for (int i = 0; i < mobiles.Count;) { if (((MobileEntry)mobiles[i]).TypeID == failedTypeID) { mobiles.RemoveAt(i); } else { ++i; } } } else if (failedItems) { for (int i = 0; i < items.Count;) { if (((ItemEntry)items[i]).TypeID == failedTypeID) { items.RemoveAt(i); } else { ++i; } } } } } SaveIndex(mobiles, mobIdxPath); SaveIndex(items, itemIdxPath); SaveIndex(guilds, guildIdxPath); SaveIndex(regions, regionIdxPath); } Console.WriteLine("After pressing return an exception will be thrown and the server will terminate"); Console.ReadLine(); throw new Exception(String.Format("Load failed (items={0}, mobiles={1}, guilds={2}, regions={3}, type={4}, serial={5})", failedItems, failedMobiles, failedGuilds, failedRegions, failedType, failedSerial), failed); } EventSink.InvokeWorldLoad(); m_Loading = false; for (int i = 0; i < m_DeleteList.Count; ++i) { object o = m_DeleteList[i]; if (o is Item) { ((Item)o).Delete(); } else if (o is Mobile) { ((Mobile)o).Delete(); } } m_DeleteList.Clear(); foreach (Item item in m_Items.Values) { if (item.Parent == null) { item.UpdateTotals(); } item.ClearProperties(); } ArrayList list = new ArrayList(m_Mobiles.Values); foreach (Mobile m in list) { m.ForceRegionReEnter(true); m.UpdateTotals(); m.ClearProperties(); } Console.WriteLine("done ({1} items, {2} mobiles) ({0:F1} seconds)", (DateTime.Now - start).TotalSeconds, m_Items.Count, m_Mobiles.Count); }
public static bool Handle(Mobile from, string text, MessageType type = MessageType.Regular) { if (!text.StartsWith(Prefix) && type != MessageType.Command) { return(false); } if (type != MessageType.Command) { text = text.Substring(Prefix.Length); } int indexOf = text.IndexOf(' '); string command; string[] args; string argString; if (indexOf >= 0) { argString = text.Substring(indexOf + 1); command = text.Substring(0, indexOf); args = Split(argString); } else { argString = ""; command = text.ToLower(); args = new string[0]; } Entries.TryGetValue(command, out CommandEntry entry); if (entry != null) { if (from.AccessLevel >= entry.AccessLevel) { if (entry.Handler != null) { CommandEventArgs e = new CommandEventArgs(from, command, argString, args); entry.Handler(e); EventSink.InvokeCommand(e); } } else { if (from.AccessLevel <= BadCommandIgnoreLevel) { return(false); } from.SendMessage("You do not have access to that command."); } } else { if (from.AccessLevel <= BadCommandIgnoreLevel) { return(false); } from.SendMessage("That is not a valid command."); } return(true); }
public void Cancel() { if (!m_Valid) { return; } List <Item> list = new List <Item>(); try { for (int i = 0; i < m_From.Container.Items.Count; i++) { try { Item it = m_From.Container.Items[i] as Item; if (it != null) { list.Add(it); } } catch (Exception ex) { EventSink.InvokeLogException(new LogExceptionEventArgs(ex)); } } } catch (Exception ex) { EventSink.InvokeLogException(new LogExceptionEventArgs(ex)); } for (int i = list.Count - 1; i >= 0; --i) { if (i < list.Count) { Item item = list[i]; item.OnSecureTrade(m_From.Mobile, m_To.Mobile, m_From.Mobile, false); if (!item.Deleted) { m_From.Mobile.AddToBackpack(item); } } } //list = m_To.Container.Items; list = new List <Item>(); try { for (int i = 0; i < m_To.Container.Items.Count; i++) { try { Item it = m_To.Container.Items[i] as Item; if (it != null) { list.Add(it); } } catch (Exception ex) { EventSink.InvokeLogException(new LogExceptionEventArgs(ex)); } } } catch (Exception ex) { EventSink.InvokeLogException(new LogExceptionEventArgs(ex)); } for (int i = list.Count - 1; i >= 0; --i) { if (i < list.Count) { Item item = list[i]; item.OnSecureTrade(m_To.Mobile, m_From.Mobile, m_To.Mobile, false); if (!item.Deleted) { m_To.Mobile.AddToBackpack(item); } } } Close(); }
public static void Save(bool message) { if (m_Saving || AsyncWriter.ThreadCount > 0) { return; } NetState.FlushAll(); m_Saving = true; if (message) { Broadcast(0x35, true, "The world is saving, please wait."); } Console.Write("World: Saving..."); DateTime startTime = DateTime.Now; if (!Directory.Exists("Saves/Mobiles/")) { Directory.CreateDirectory("Saves/Mobiles/"); } if (!Directory.Exists("Saves/Items/")) { Directory.CreateDirectory("Saves/Items/"); } if (!Directory.Exists("Saves/Guilds/")) { Directory.CreateDirectory("Saves/Guilds/"); } if (!Directory.Exists("Saves/Regions/")) { Directory.CreateDirectory("Saves/Regions/"); } if (m_MultiProcessor) { Thread saveThread = new Thread(new ThreadStart(SaveItems)); saveThread.Name = "Item Save Subset"; saveThread.Start(); SaveMobiles(); SaveGuilds(); SaveRegions(); saveThread.Join(); } else { SaveMobiles(); SaveItems(); SaveGuilds(); SaveRegions(); } //Accounts.Save(); try { EventSink.InvokeWorldSave(new WorldSaveEventArgs(message)); } catch (Exception e) { throw new Exception("World Save event threw an exception. Save failed!", e); } //System.GC.Collect(); DateTime endTime = DateTime.Now; Console.WriteLine("done in {0:F1} seconds.", (endTime - startTime).TotalSeconds); if (message) { Broadcast(0x35, true, "World save complete. The entire process took {0:F1} seconds.", (endTime - startTime).TotalSeconds); } m_Saving = false; }
public static void Load() { if (m_Loaded) { return; } m_Loaded = true; m_LoadingType = null; Console.Write("World: Loading..."); Stopwatch watch = Stopwatch.StartNew(); m_Loading = true; _addQueue = new Queue <IEntity>(); _deleteQueue = new Queue <IEntity>(); int mobileCount = 0, itemCount = 0, guildCount = 0; object[] ctorArgs = new object[1]; List <ItemEntry> items = new List <ItemEntry>(); List <MobileEntry> mobiles = new List <MobileEntry>(); List <GuildEntry> guilds = new List <GuildEntry>(); 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); List <Tuple <ConstructorInfo, string> > types = ReadTypes(tdbReader); mobileCount = idxReader.ReadInt32(); m_Mobiles = new Dictionary <Serial, Mobile>(mobileCount); for (int i = 0; i < mobileCount; ++i) { int typeID = idxReader.ReadInt32(); int serial = idxReader.ReadInt32(); long pos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); Tuple <ConstructorInfo, string> objs = types[typeID]; if (objs == null) { continue; } Mobile m = null; ConstructorInfo ctor = objs.Item1; string typeName = objs.Item2; try { ctorArgs[0] = ( Serial )serial; m = ( Mobile )(ctor.Invoke(ctorArgs)); } catch { } if (m != null) { mobiles.Add(new MobileEntry(m, typeID, typeName, pos, length)); AddMobile(m); } } tdbReader.Close(); } idxReader.Close(); } } else { m_Mobiles = new Dictionary <Serial, Mobile>(); } if (File.Exists(ItemIndexPath) && File.Exists(ItemTypesPath)) { using (FileStream idx = new FileStream(ItemIndexPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader idxReader = new BinaryReader(idx); using (FileStream tdb = new FileStream(ItemTypesPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader tdbReader = new BinaryReader(tdb); List <Tuple <ConstructorInfo, string> > types = ReadTypes(tdbReader); itemCount = idxReader.ReadInt32(); m_Items = new Dictionary <Serial, Item>(itemCount); for (int i = 0; i < itemCount; ++i) { int typeID = idxReader.ReadInt32(); int serial = idxReader.ReadInt32(); long pos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); Tuple <ConstructorInfo, string> objs = types[typeID]; if (objs == null) { continue; } Item item = null; ConstructorInfo ctor = objs.Item1; string typeName = objs.Item2; try { ctorArgs[0] = ( Serial )serial; item = ( Item )(ctor.Invoke(ctorArgs)); } catch { } if (item != null) { items.Add(new ItemEntry(item, typeID, typeName, pos, length)); AddItem(item); } } tdbReader.Close(); } idxReader.Close(); } } else { m_Items = new Dictionary <Serial, Item>(); } if (File.Exists(GuildIndexPath)) { using (FileStream idx = new FileStream(GuildIndexPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader idxReader = new BinaryReader(idx); guildCount = idxReader.ReadInt32(); CreateGuildEventArgs createEventArgs = new CreateGuildEventArgs(-1); for (int i = 0; i < guildCount; ++i) { idxReader.ReadInt32(); //no typeid for guilds int id = idxReader.ReadInt32(); long pos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); createEventArgs.Id = id; EventSink.InvokeCreateGuild(createEventArgs); BaseGuild guild = createEventArgs.Guild; if (guild != null) { guilds.Add(new GuildEntry(guild, pos, length)); } } idxReader.Close(); } } bool failedMobiles = false, failedItems = false, failedGuilds = false; Type failedType = null; Serial failedSerial = Serial.Zero; Exception failed = null; int failedTypeID = 0; 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 { m_LoadingType = entry.TypeName; m.Deserialize(reader); if (reader.Position != (entry.Position + entry.Length)) { throw new Exception(String.Format("***** Bad serialize on {0} *****", m.GetType())); } } catch (Exception e) { mobiles.RemoveAt(i); failed = e; failedMobiles = true; failedType = m.GetType(); failedTypeID = entry.TypeID; failedSerial = m.Serial; break; } } } reader.Close(); } } if (!failedMobiles && File.Exists(ItemDataPath)) { using (FileStream bin = new FileStream(ItemDataPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(bin)); for (int i = 0; i < items.Count; ++i) { ItemEntry entry = items[i]; Item item = entry.Item; if (item != null) { reader.Seek(entry.Position, SeekOrigin.Begin); try { m_LoadingType = entry.TypeName; item.Deserialize(reader); if (reader.Position != (entry.Position + entry.Length)) { throw new Exception(String.Format("***** Bad serialize on {0} *****", item.GetType())); } } catch (Exception e) { items.RemoveAt(i); failed = e; failedItems = true; failedType = item.GetType(); failedTypeID = entry.TypeID; failedSerial = item.Serial; break; } } } reader.Close(); } } m_LoadingType = null; if (!failedMobiles && !failedItems && File.Exists(GuildDataPath)) { using (FileStream bin = new FileStream(GuildDataPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(bin)); for (int i = 0; i < guilds.Count; ++i) { GuildEntry entry = guilds[i]; BaseGuild g = entry.Guild; if (g != null) { reader.Seek(entry.Position, SeekOrigin.Begin); try { g.Deserialize(reader); if (reader.Position != (entry.Position + entry.Length)) { throw new Exception(String.Format("***** Bad serialize on Guild {0} *****", g.Id)); } } catch (Exception e) { guilds.RemoveAt(i); failed = e; failedGuilds = true; failedType = typeof(BaseGuild); failedTypeID = g.Id; failedSerial = g.Id; break; } } } reader.Close(); } } if (failedItems || failedMobiles || failedGuilds) { Console.WriteLine("An error was encountered while loading a saved object"); Console.WriteLine(" - Type: {0}", failedType); Console.WriteLine(" - Serial: {0}", failedSerial); if (!Core.Service) { Console.WriteLine("Delete the object? (y/n)"); if (Console.ReadKey(true).Key == ConsoleKey.Y) { if (failedType != typeof(BaseGuild)) { Console.WriteLine("Delete all objects of that type? (y/n)"); if (Console.ReadKey(true).Key == ConsoleKey.Y) { if (failedMobiles) { for (int i = 0; i < mobiles.Count;) { if (mobiles[i].TypeID == failedTypeID) { mobiles.RemoveAt(i); } else { ++i; } } } else if (failedItems) { for (int i = 0; i < items.Count;) { if (items[i].TypeID == failedTypeID) { items.RemoveAt(i); } else { ++i; } } } } } SaveIndex <MobileEntry>(mobiles, MobileIndexPath); SaveIndex <ItemEntry>(items, ItemIndexPath); SaveIndex <GuildEntry>(guilds, GuildIndexPath); } Console.WriteLine("After pressing return an exception will be thrown and the server will terminate."); Console.ReadLine(); } else { Console.WriteLine("An exception will be thrown and the server will terminate."); } throw new Exception(String.Format("Load failed (items={0}, mobiles={1}, guilds={2}, type={3}, serial={4})", failedItems, failedMobiles, failedGuilds, failedType, failedSerial), failed); } EventSink.InvokeWorldLoad(); m_Loading = false; ProcessSafetyQueues(); foreach (Item item in m_Items.Values) { if (item.Parent == null) { item.UpdateTotals(); } item.ClearProperties(); } foreach (Mobile m in m_Mobiles.Values) { m.UpdateRegion(); // Is this really needed? m.UpdateTotals(); m.ClearProperties(); } watch.Stop(); Console.WriteLine("done ({1} items, {2} mobiles) ({0:F2} seconds)", watch.Elapsed.TotalSeconds, m_Items.Count, m_Mobiles.Count); }
public static void Start(bool repair) { if (!ScriptCompiler.Compile(true)) { return; } m_ItemCount = 0; m_MobileCount = 0; foreach (Library l in ScriptCompiler.Libraries) { int itemCount = 0, mobileCount = 0; l.Verify(ref itemCount, ref mobileCount); log.InfoFormat("Library {0} verified: {1} items, {2} mobiles", l.Name, itemCount, mobileCount); m_ItemCount += itemCount; m_MobileCount += mobileCount; } log.InfoFormat("All libraries verified: {0} items, {1} mobiles)", m_ItemCount, m_MobileCount); try { TileData.Configure(); ScriptCompiler.Configure(); } catch (TargetInvocationException e) { log.Fatal("Configure exception: {0}", e.InnerException); return; } if (!config.Exists) { config.Save(); } World.Load(); if (World.LoadErrors > 0) { log.ErrorFormat("There were {0} errors during world load.", World.LoadErrors); if (repair) { log.Error("The world load errors are being ignored for now, and will not reappear once you save this world."); } else { log.Error("Try 'SunUO --repair' to repair this world save, or restore an older non-corrupt save."); return; } } try { ScriptCompiler.Initialize(); } catch (TargetInvocationException e) { log.Fatal("Initialize exception: {0}", e.InnerException); return; } Region.Load(); m_MessagePump = new MessagePump(); foreach (IPEndPoint ipep in Config.Network.Bind) { m_MessagePump.AddListener(new Listener(ipep)); } Timer.TimerThread ttObj = new Timer.TimerThread(); timerThread = new Thread(new ThreadStart(ttObj.TimerMain)); timerThread.Name = "Timer Thread"; timerThread.Start(); NetState.Initialize(); Encryption.Initialize(); EventSink.InvokeServerStarted(); log.Info("SunUO initialized, entering main loop"); try { Run(); } catch (Exception e) { CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(e, true)); } if (timerThread.IsAlive) { timerThread.Abort(); } }
public static void Save(bool message, bool permitBackgroundWrite) { if (Saving) { return; } ++m_Saves; NetState.FlushAll(); NetState.Pause(); WaitForWriteCompletion(); //Blocks Save until current disk flush is done. Saving = true; m_DiskWriteHandle.Reset(); if (message) { Broadcast(0x35, false, AccessLevel.Player, "The world is saving, please wait."); } SaveStrategy strategy = SaveStrategy.Acquire(); Console.WriteLine("Core: Using {0} save strategy", strategy.Name.ToLowerInvariant()); Console.WriteLine("World: Saving..."); Stopwatch watch = Stopwatch.StartNew(); if (!Directory.Exists("Saves/Mobiles/")) { Directory.CreateDirectory("Saves/Mobiles/"); } if (!Directory.Exists("Saves/Items/")) { Directory.CreateDirectory("Saves/Items/"); } if (!Directory.Exists("Saves/Guilds/")) { Directory.CreateDirectory("Saves/Guilds/"); } try { EventSink.InvokeBeforeWorldSave(new BeforeWorldSaveEventArgs()); } catch (Exception e) { throw new Exception("FATAL: Exception in EventSink.BeforeWorldSave", e); } if (m_Metrics) { using (SaveMetrics metrics = new SaveMetrics()) strategy.Save(metrics, permitBackgroundWrite); } else { strategy.Save(null, permitBackgroundWrite); } try { EventSink.InvokeWorldSave(new WorldSaveEventArgs(message)); } catch (Exception e) { throw new Exception("FATAL: Exception in EventSink.WorldSave", e); } watch.Stop(); Saving = false; if (!permitBackgroundWrite) { NotifyDiskWriteComplete(); //Sets the DiskWriteHandle. If we allow background writes, we leave this upto the individual save strategies. } ProcessSafetyQueues(); strategy.ProcessDecay(); Console.WriteLine("Save finished in {0:F2} seconds.", watch.Elapsed.TotalSeconds); if (message) { Broadcast(0x35, false, AccessLevel.Player, "World save done in {0:F1} seconds.", watch.Elapsed.TotalSeconds); } NetState.Resume(); try { EventSink.InvokeAfterWorldSave(new AfterWorldSaveEventArgs()); } catch (Exception e) { throw new Exception("FATAL: Exception in EventSink.AfterWorldSave", e); } }
public static void Save(bool message) { if (m_Saving || AsyncWriter.ThreadCount > 0) { return; } NetState.FlushAll(); NetState.Pause(); m_Saving = true; if (message) { Broadcast(0x35, true, "The world is saving, please wait."); } SaveStrategy strategy = SaveStrategy.Acquire(); Console.WriteLine("Core: Using {0} save strategy", strategy.Name.ToLowerInvariant()); Console.Write("World: Saving..."); Stopwatch watch = Stopwatch.StartNew(); if (!Directory.Exists("Saves/Mobiles/")) { Directory.CreateDirectory("Saves/Mobiles/"); } if (!Directory.Exists("Saves/Items/")) { Directory.CreateDirectory("Saves/Items/"); } if (!Directory.Exists("Saves/Guilds/")) { Directory.CreateDirectory("Saves/Guilds/"); } /*using ( SaveMetrics metrics = new SaveMetrics() ) {*/ strategy.Save(null); /*}*/ try { EventSink.InvokeWorldSave(new WorldSaveEventArgs(message)); } catch (Exception e) { throw new Exception("World Save event threw an exception. Save failed!", e); } watch.Stop(); m_Saving = false; ProcessSafetyQueues(); strategy.ProcessDecay(); Console.WriteLine("done in {0:F2} seconds.", watch.Elapsed.TotalSeconds); if (message) { Broadcast(0x35, true, "World save complete. The entire process took {0:F1} seconds.", watch.Elapsed.TotalSeconds); } NetState.Resume(); }
public static void Save(bool message, bool permitBackgroundWrite) { if (Saving) { return; } ++m_Saves; NetState.Pause(); WaitForWriteCompletion(); // Blocks Save until current disk flush is done. Saving = true; m_DiskWriteHandle.Reset(); if (message) { Broadcast(0x35, true, "The world is saving, please wait."); } var strategy = SaveStrategy.Acquire(); Console.WriteLine("Core: Using {0} save strategy", strategy.Name.ToLower()); Console.Write($"[{DateTime.UtcNow.ToLongTimeString()}] World: Saving..."); var watch = Stopwatch.StartNew(); if (!Directory.Exists("Saves/Mobiles/")) { Directory.CreateDirectory("Saves/Mobiles/"); } if (!Directory.Exists("Saves/Items/")) { Directory.CreateDirectory("Saves/Items/"); } if (!Directory.Exists("Saves/Guilds/")) { Directory.CreateDirectory("Saves/Guilds/"); } strategy.Save(permitBackgroundWrite); try { EventSink.InvokeWorldSave(message); } catch (Exception e) { throw new Exception("World Save event threw an exception. Save failed!", e); } watch.Stop(); Saving = false; if (!permitBackgroundWrite) { NotifyDiskWriteComplete(); // Sets the DiskWriteHandle. If we allow background writes, we leave this upto the individual save strategies. } ProcessSafetyQueues(); strategy.ProcessDecay(); Console.WriteLine("Save done in {0:F2} seconds.", watch.Elapsed.TotalSeconds); if (message) { Broadcast( 0x35, true, "World save complete. The entire process took {0:F1} seconds.", watch.Elapsed.TotalSeconds ); } NetState.Resume(); }
public static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.Gray; Console.Title = "UO Aberration : Core"; for (int i = 0; i < args.Length; ++i) { if (Insensitive.Equals(args[i], "-debug")) { m_Debug = true; } else if (Insensitive.Equals(args[i], "-service")) { m_Service = true; } else if (Insensitive.Equals(args[i], "-profile")) { Profiling = true; } else if (Insensitive.Equals(args[i], "-nocache")) { m_Cache = false; } else if (Insensitive.Equals(args[i], "-haltonwarning")) { m_HaltOnWarning = true; } } try { if (m_Service) { if (!Directory.Exists("Logs")) { Directory.CreateDirectory("Logs"); } Console.SetOut(m_MultiConOut = new MultiTextWriter(new FileLogger("Logs/Console.log"))); } else { Console.SetOut(m_MultiConOut = new MultiTextWriter(Console.Out)); } } catch { } m_Thread = Thread.CurrentThread; m_Process = Process.GetCurrentProcess(); m_Assembly = Assembly.GetEntryAssembly(); if (m_Thread != null) { m_Thread.Name = "Core Thread"; } if (BaseDirectory.Length > 0) { Directory.SetCurrentDirectory(BaseDirectory); } Timer.TimerThread ttObj = new Timer.TimerThread(); timerThread = new Thread(new ThreadStart(ttObj.TimerMain)); timerThread.Name = "Timer Thread"; Version ver = m_Assembly.GetName().Version; /* * ServUO's Original Code * if (File.Exists("publish.txt")) * { * try * { * FileStream fs = new FileStream("publish.txt", FileMode.Open, FileAccess.Read, FileShare.Read); * StreamReader sr = new StreamReader(fs); * * publishNumber = sr.ReadLine(); * * sr.Close(); * fs.Close(); * } * catch * { } * }*/ //Concept Expanded based upon ServUO's publish number. string header = ""; ConsoleColor desiredColor = ConsoleColor.White; if (File.Exists("header.txt")) { bool chopColor = false; try { FileStream file = new FileStream("header.txt", FileMode.Open, FileAccess.Read, FileShare.Read); StreamReader reader = new StreamReader(file); string determineTextColor = (string)(reader.ReadLine().Trim().ToLower()); if (Enum.TryParse <ConsoleColor>(determineTextColor, true, out desiredColor)) { chopColor = true; } else { Utility.PushColor(ConsoleColor.White); } if (chopColor) { header = (string)(reader.ReadToEnd()); } file.Close(); reader.Close(); file.Dispose(); reader.Dispose(); } catch { Utility.PushColor(ConsoleColor.Red); Console.Write("Error: "); Utility.PushColor(ConsoleColor.White); Console.WriteLine("Your are either missing header.txt or it is misconfigured."); } } else { Utility.PushColor(ConsoleColor.Red); Console.Write("Error: "); Utility.PushColor(ConsoleColor.White); Console.WriteLine("header.txt could not be located."); } Utility.PushColor(desiredColor); Console.WriteLine(header); Utility.PushColor(ConsoleColor.White); Console.WriteLine(); Console.WriteLine("Core ({3}): Running on .NET Framework Version {0}.{1}.{2}", Environment.Version.Major, Environment.Version.Minor, Environment.Version.Build, Environment.Is64BitProcess ? "x64" : "x86"); string s = Arguments; if (s.Length > 0) { Console.WriteLine("Core: Running with arguments: {0}", s); } m_ProcessorCount = Environment.ProcessorCount; if (m_ProcessorCount > 1) { m_MultiProcessor = true; } if (m_MultiProcessor || Is64Bit) { Console.WriteLine("Core: Optimizing for {0} {2}processor{1}", m_ProcessorCount, m_ProcessorCount == 1 ? "" : "s", Is64Bit ? "64-bit " : ""); } int platform = (int)Environment.OSVersion.Platform; if (platform == 4 || platform == 128) // MS 4, MONO 128 { m_Unix = true; Console.WriteLine("Core: Unix environment detected"); } else { m_ConsoleEventHandler = new ConsoleEventHandler(OnConsoleEvent); SetConsoleCtrlHandler(m_ConsoleEventHandler, true); } if (GCSettings.IsServerGC) { Console.WriteLine("Core: Server garbage collection mode enabled"); } while (!ScriptCompiler.Compile(m_Debug, m_Cache)) { Console.WriteLine("Scripts: One or more scripts failed to compile or no script files were found."); if (m_Service) { return; } Console.WriteLine(" - Press return to exit, or R to try again."); if (Console.ReadKey(true).Key != ConsoleKey.R) { return; } } ScriptCompiler.Invoke("Configure"); Region.Load(); World.Load(); ScriptCompiler.Invoke("Initialize"); MessagePump messagePump = m_MessagePump = new MessagePump(); timerThread.Start(); for (int i = 0; i < Map.AllMaps.Count; ++i) { Map.AllMaps[i].Tiles.Force(); } NetState.Initialize(); EventSink.InvokeServerStarted(); try { DateTime now, last = DateTime.UtcNow; const int sampleInterval = 100; const float ticksPerSecond = (float)(TimeSpan.TicksPerSecond * sampleInterval); long sample = 0; while (m_Signal.WaitOne()) { Mobile.ProcessDeltaQueue(); Item.ProcessDeltaQueue(); Timer.Slice(); messagePump.Slice(); NetState.FlushAll(); NetState.ProcessDisposedQueue(); if (Slice != null) { Slice(); } if ((++sample % sampleInterval) == 0) { now = DateTime.UtcNow; m_CyclesPerSecond[m_CycleIndex++ % m_CyclesPerSecond.Length] = ticksPerSecond / (now.Ticks - last.Ticks); last = now; } } } catch (Exception e) { CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(e, true)); } }
public static bool Handle(Mobile from, object target, string text) { if (text.StartsWith(m_CommandPrefix)) { text = text.Substring(m_CommandPrefix.Length); int indexOf = text.IndexOf(' '); string command; string[] args; string argString; if (indexOf >= 0) { argString = text.Substring(indexOf + 1); command = text.Substring(0, indexOf); args = Split(argString); } else { argString = ""; command = text.ToLower(); args = new string[0]; } CommandEntry entry = (CommandEntry)m_Entries[command]; if (entry != null) { if (from.AccessLevel >= entry.AccessLevel) { if (entry.Handler != null) { CommandEventArgs e = new CommandEventArgs(from, target, command, argString, args); entry.Handler(e); EventSink.InvokeCommand(e); } } else { if (from.AccessLevel <= m_BadCommandIngoreLevel) { return(false); } from.SendMessage("You do not have access to that command."); } } else { if (from.AccessLevel <= m_BadCommandIngoreLevel) { return(false); } from.SendMessage("That is not a valid command."); } return(true); } return(false); }
public static void Main(string[] args) { m_Assembly = Assembly.GetEntryAssembly(); /* print a banner */ Version ver = m_Assembly.GetName().Version; Console.WriteLine("SunLogin Version {0}.{1}.{2} http://www.sunuo.org/", ver.Major, ver.Minor, ver.Revision); Console.WriteLine(" on {0}, runtime {1}", Environment.OSVersion, Environment.Version); if ((int)Environment.OSVersion.Platform == 128) { Console.WriteLine("Please make sure you have Mono 1.1.7 or newer! (mono -V)"); } Console.WriteLine(); /* prepare SunUO */ AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit); if (args.Length > 0) { Console.WriteLine("SunLogin does not understand command line arguments"); return; } string baseDirectory = Path.GetDirectoryName(ExePath); string confDirectory = new DirectoryInfo(baseDirectory) .CreateSubdirectory("etc").FullName; config = new Config.Root(baseDirectory, Path.Combine(confDirectory, "sunuo.xml")); Directory.SetCurrentDirectory(config.BaseDirectory); m_Thread = Thread.CurrentThread; if (m_Thread != null) { m_Thread.Name = "Core Thread"; } if (config.BaseDirectory.Length > 0) { Directory.SetCurrentDirectory(config.BaseDirectory); } Timer.TimerThread ttObj = new Timer.TimerThread(); timerThread = new Thread(new ThreadStart(ttObj.TimerMain)); timerThread.Name = "Timer Thread"; if (!config.Exists) { config.Save(); } m_MessagePump = new MessagePump(); foreach (IPEndPoint ipep in Config.Network.Bind) { m_MessagePump.AddListener(new Listener(ipep)); } timerThread.Start(); NetState.Initialize(); Encryption.Initialize(); ServerList.Initialize(); ServerQueryTimer.Initialize(); Server.Accounting.AccountHandler.Initialize(); EventSink.InvokeServerStarted(); log.Info("SunLogin initialized, entering main loop"); try { while (!m_Closing) { m_Signal.WaitOne(); m_Now = DateTime.UtcNow; Timer.Slice(); m_MessagePump.Slice(); NetState.FlushAll(); NetState.ProcessDisposedQueue(); } } catch (Exception e) { CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(e, true)); } if (timerThread.IsAlive) { timerThread.Abort(); } }
public static void Main(string[] args) { m_Assembly = Assembly.GetEntryAssembly(); /* print a banner */ Version ver = m_Assembly.GetName().Version; Console.WriteLine("SunUO Version {0}.{1}.{2} http://www.sunuo.org/", ver.Major, ver.Minor, ver.Revision); Console.WriteLine(" on {0}, runtime {1}", Environment.OSVersion, Environment.Version); if ((int)Environment.OSVersion.Platform == 128) { Console.WriteLine("Please make sure you have Mono 1.1.7 or newer! (mono -V)"); } Console.WriteLine(); /* prepare SunUO */ AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit); bool debug = false; for (int i = 0; i < args.Length; ++i) { if (Insensitive.Equals(args[i], "-debug")) { debug = true; } else if (Insensitive.Equals(args[i], "-service")) { m_Service = true; } else if (Insensitive.Equals(args[i], "-profile")) { Profiling = true; } else if (args[i] == "--logfile") { string logfile = args[++i]; StreamWriter writer = new StreamWriter(new FileStream(logfile, FileMode.Append, FileAccess.Write)); writer.AutoFlush = true; Console.SetOut(writer); Console.SetError(writer); } } config = new Config(Path.Combine(BaseDirectoryInfo.CreateSubdirectory("etc").FullName, "sunuo.xml")); try { m_MultiConOut = new MultiTextWriter(Console.Out); Console.SetOut(m_MultiConOut); if (m_Service) { string filename = Path.Combine(LogDirectoryInfo.FullName, "console.log"); m_MultiConOut.Add(new FileLogger(filename)); } } catch { } m_Thread = Thread.CurrentThread; m_Process = Process.GetCurrentProcess(); if (m_Thread != null) { m_Thread.Name = "Core Thread"; } if (BaseDirectory.Length > 0) { Directory.SetCurrentDirectory(BaseDirectory); } Timer.TimerThread ttObj = new Timer.TimerThread(); timerThread = new Thread(new ThreadStart(ttObj.TimerMain)); timerThread.Name = "Timer Thread"; if (!ScriptCompiler.Compile(debug)) { return; } Console.Write("Verifying scripts:"); m_ItemCount = 0; m_MobileCount = 0; foreach (Library l in ScriptCompiler.Libraries) { int itemCount = 0, mobileCount = 0; Console.Write(" {0}[", l.Name); l.Verify(ref itemCount, ref mobileCount); Console.Write("{0} items, {1} mobiles]", itemCount, mobileCount); m_ItemCount += itemCount; m_MobileCount += mobileCount; } Console.WriteLine(" - done ({0} items, {1} mobiles)", m_ItemCount, m_MobileCount); try { ScriptCompiler.Configure(); } catch (TargetInvocationException e) { Console.WriteLine("Configure exception: {0}", e.InnerException); return; } if (!config.Exists) { config.Save(); } World.Load(); try { ScriptCompiler.Initialize(); } catch (TargetInvocationException e) { Console.WriteLine("Initialize exception: {0}", e.InnerException); return; } Region.Load(); m_MessagePump = new MessagePump(new Listener(Listener.Port)); timerThread.Start(); NetState.Initialize(); EventSink.InvokeServerStarted(); try { while (!m_Closing) { Thread.Sleep(1); Mobile.ProcessDeltaQueue(); Item.ProcessDeltaQueue(); Timer.Slice(); m_MessagePump.Slice(); NetState.FlushAll(); NetState.ProcessDisposedQueue(); if (Slice != null) { Slice(); } } } catch (Exception e) { CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(e, true)); } if (timerThread.IsAlive) { timerThread.Abort(); } }
public static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit); for (int i = 0; i < args.Length; ++i) { if (Insensitive.Equals(args[i], "-debug")) { m_Debug = true; } else if (Insensitive.Equals(args[i], "-service")) { m_Service = true; } else if (Insensitive.Equals(args[i], "-profile")) { Profiling = true; } else if (Insensitive.Equals(args[i], "-nocache")) { m_Cache = false; } else if (Insensitive.Equals(args[i], "-haltonwarning")) { m_HaltOnWarning = true; } else if (Insensitive.Equals(args[i], "-vb")) { m_VBdotNET = true; } else if (Insensitive.Equals(args[i], "-publish")) { m_Publish = true; } } try { if (m_Service) { if (!Directory.Exists("Logs")) { Directory.CreateDirectory("Logs"); } Console.SetOut(m_MultiConOut = new MultiTextWriter(new FileLogger("Logs/Console.log"))); } else { Console.SetOut(m_MultiConOut = new MultiTextWriter(Console.Out)); } } catch { } m_Thread = Thread.CurrentThread; m_Process = Process.GetCurrentProcess(); m_Assembly = Assembly.GetEntryAssembly(); if (m_Thread != null) { m_Thread.Name = "Core Thread"; } if (BaseDirectory.Length > 0) { Directory.SetCurrentDirectory(BaseDirectory); } Timer.TimerThread ttObj = new Timer.TimerThread(); timerThread = new Thread(new ThreadStart(ttObj.TimerMain)); timerThread.Name = "Timer Thread"; Version ver = m_Assembly.GetName().Version; // Added to help future code support on forums, as a 'check' people can ask for to it see if they recompiled core or not Console.WriteLine("RunUO - [www.runuo.com] Version {0}.{1}, Build {2}.{3}", ver.Major, ver.Minor, ver.Build, ver.Revision); #if Mono string version = "MONO"; #else string version = Environment.Version.ToString(); #endif Console.WriteLine("Core: Running on .NET Framework Version {0}", version); string s = Arguments; if (s.Length > 0) { Console.WriteLine("Core: Running with arguments: {0}", s); } m_ProcessorCount = Environment.ProcessorCount; if (m_ProcessorCount > 1) { m_MultiProcessor = true; } if (m_MultiProcessor || Is64Bit) { Console.WriteLine("Core: Optimizing for {0} {2}processor{1}", m_ProcessorCount, m_ProcessorCount == 1 ? "" : "s", Is64Bit ? "64-bit " : ""); } int platform = (int)Environment.OSVersion.Platform; if (platform == 4 || platform == 128) // MS 4, MONO 128 { m_Unix = true; Console.WriteLine("Core: Unix environment detected"); } else { m_ConsoleEventHandler = new ConsoleEventHandler(OnConsoleEvent); SetConsoleCtrlHandler(m_ConsoleEventHandler, true); } if (GCSettings.IsServerGC) { Console.WriteLine("Core: Server garbage collection mode enabled"); } if (File.Exists("Data/Culture.cfg")) { using (StreamReader ip = new StreamReader("Data/Culture.cfg")) { string line = ip.ReadLine(); if (!String.IsNullOrEmpty(line)) { m_Thread.CurrentCulture = new CultureInfo(line); Console.WriteLine("Core: Culture modified to {0}", m_Thread.CurrentCulture.NativeName); } } } while (!ScriptCompiler.Compile(m_Debug, m_Cache, m_Publish)) { Console.WriteLine("Scripts: One or more scripts failed to compile or no script files were found."); if (m_Publish || m_Service) { return; } Console.WriteLine(" - Press return to exit, or R to try again."); if (Console.ReadKey(true).Key != ConsoleKey.R) { return; } } ScriptCompiler.Invoke("Configure"); Console.Write("Core: Initializing localization strings..."); ClilocHandler.AddCliloc("ENU"); //English - No Argument sets the default ClilocHandler.AddCliloc("CHS"); //Chinese ClilocHandler.AddCliloc("CHT"); //Chinese ClilocHandler.AddCliloc("DEU"); //German ClilocHandler.AddCliloc("ESP"); //Spanish ClilocHandler.AddCliloc("FRA"); //French ClilocHandler.AddCliloc("JPN"); //Japan ClilocHandler.AddCliloc("KOR"); //Korean Console.WriteLine("done ({0} languages)", StringList.StringLists.Count); Region.Load(); World.Load(); ScriptCompiler.Invoke("Initialize"); MessagePump messagePump = new MessagePump(); timerThread.Start(); for (int i = 0; i < Map.AllMaps.Count; ++i) { Map.AllMaps[i].Tiles.Force(); } NetState.Initialize(); EventSink.InvokeServerStarted(); try { DateTime now, last = DateTime.UtcNow; const int sampleInterval = 100; const float ticksPerSecond = (float)(TimeSpan.TicksPerSecond * sampleInterval); long sample = 0; while (m_Signal.WaitOne()) { Mobile.ProcessDeltaQueue(); Item.ProcessDeltaQueue(); Timer.Slice(); messagePump.Slice(); NetState.FlushAll(); NetState.ProcessDisposedQueue(); if (Slice != null) { Slice(); } if ((++sample % sampleInterval) == 0) { now = DateTime.UtcNow; m_CyclesPerSecond[m_CycleIndex++ % m_CyclesPerSecond.Length] = ticksPerSecond / (now.Ticks - last.Ticks); last = now; } } } catch (Exception e) { CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(e, true)); } }
public static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit; foreach (string a in args) { if (Insensitive.Equals(a, "-debug")) { Debug = true; } else if (Insensitive.Equals(a, "-service")) { Service = true; } else if (Insensitive.Equals(a, "-profile")) { Profiling = true; } else if (Insensitive.Equals(a, "-nocache")) { _Cache = false; } else if (Insensitive.Equals(a, "-haltonwarning")) { HaltOnWarning = true; } else if (Insensitive.Equals(a, "-vb")) { VBdotNet = true; } else if (Insensitive.Equals(a, "-usehrt")) { _UseHRT = true; } } try { if (Service) { if (!Directory.Exists("Logs")) { Directory.CreateDirectory("Logs"); } Console.SetOut(MultiConsoleOut = new MultiTextWriter(new FileLogger("Logs/Console.log"))); } else { Console.SetOut(MultiConsoleOut = new MultiTextWriter(Console.Out)); } } catch { } Thread = Thread.CurrentThread; Process = Process.GetCurrentProcess(); Assembly = Assembly.GetEntryAssembly(); if (Thread != null) { Thread.Name = "Core Thread"; } if (BaseDirectory.Length > 0) { Directory.SetCurrentDirectory(BaseDirectory); } Timer.TimerThread ttObj = new Timer.TimerThread(); _TimerThread = new Thread(ttObj.TimerMain) { Name = "Timer Thread" }; Version ver = Assembly.GetName().Version; String publishNumber = ""; if (File.Exists("Publish.txt")) { publishNumber = File.ReadAllText("Publish.txt"); } // Added to help future code support on forums, as a 'check' people can ask for to it see if they recompiled core or not Utility.PushColor(ConsoleColor.DarkGreen); Console.WriteLine(new String('-', Console.BufferWidth)); Utility.PopColor(); Utility.PushColor(ConsoleColor.Cyan); Console.WriteLine( "ServUO - [http://www.servuo.com] Version {0}.{1}, Build {2}.{3}", ver.Major, ver.Minor, ver.Build, ver.Revision); Console.WriteLine("Publish {0}", publishNumber); Utility.PopColor(); string s = Arguments; if (s.Length > 0) { Utility.PushColor(ConsoleColor.Yellow); Console.WriteLine("Core: Running with arguments: {0}", s); Utility.PopColor(); } ProcessorCount = Environment.ProcessorCount; if (ProcessorCount > 1) { MultiProcessor = true; } if (MultiProcessor || Is64Bit) { Utility.PushColor(ConsoleColor.Green); Console.WriteLine( "Core: Optimizing for {0} {2}processor{1}", ProcessorCount, ProcessorCount == 1 ? "" : "s", Is64Bit ? "64-bit " : ""); Utility.PopColor(); } int platform = (int)Environment.OSVersion.Platform; if (platform == 4 || platform == 128) { // MS 4, MONO 128 Unix = true; Utility.PushColor(ConsoleColor.Yellow); Console.WriteLine("Core: Unix environment detected"); Utility.PopColor(); } else { m_ConsoleEventHandler = OnConsoleEvent; UnsafeNativeMethods.SetConsoleCtrlHandler(m_ConsoleEventHandler, true); } if (GCSettings.IsServerGC) { Utility.PushColor(ConsoleColor.DarkYellow); Console.WriteLine("Core: Server garbage collection mode enabled"); Utility.PopColor(); } if (_UseHRT) { Utility.PushColor(ConsoleColor.DarkYellow); Console.WriteLine( "Core: Requested high resolution timing ({0})", UsingHighResolutionTiming ? "Supported" : "Unsupported"); Utility.PopColor(); } Utility.PushColor(ConsoleColor.DarkYellow); Console.WriteLine("RandomImpl: {0} ({1})", RandomImpl.Type.Name, RandomImpl.IsHardwareRNG ? "Hardware" : "Software"); Utility.PopColor(); Utility.PushColor(ConsoleColor.DarkYellow); Console.WriteLine("Core: Loading config..."); Config.Load(); Utility.PopColor(); while (!ScriptCompiler.Compile(Debug, _Cache)) { Utility.PushColor(ConsoleColor.Red); Console.WriteLine("Scripts: One or more scripts failed to compile or no script files were found."); Utility.PopColor(); if (Service) { return; } Console.WriteLine(" - Press return to exit, or R to try again."); if (Console.ReadKey(true).Key != ConsoleKey.R) { return; } } ScriptCompiler.Invoke("Configure"); Region.Load(); World.Load(); ScriptCompiler.Invoke("Initialize"); MessagePump messagePump = MessagePump = new MessagePump(); _TimerThread.Start(); foreach (Map m in Map.AllMaps) { m.Tiles.Force(); } NetState.Initialize(); EventSink.InvokeServerStarted(); try { long now, last = TickCount; const int sampleInterval = 100; const float ticksPerSecond = 1000.0f * sampleInterval; long sample = 0; while (!Closing) { _Signal.WaitOne(); Mobile.ProcessDeltaQueue(); Item.ProcessDeltaQueue(); Timer.Slice(); messagePump.Slice(); NetState.FlushAll(); NetState.ProcessDisposedQueue(); if (Slice != null) { Slice(); } if (sample++ % sampleInterval != 0) { continue; } now = TickCount; _CyclesPerSecond[_CycleIndex++ % _CyclesPerSecond.Length] = ticksPerSecond / (now - last); last = now; } } catch (Exception e) { CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(e, true)); } }
public static void Main(string[] args) { #if DEBUG Debug = true; #endif AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit; foreach (string a in args) { if (Insensitive.Equals(a, "-debug")) { Debug = true; } else if (Insensitive.Equals(a, "-service")) { Service = true; } else if (Insensitive.Equals(a, "-profile")) { Profiling = true; } else if (Insensitive.Equals(a, "-nocache")) { _Cache = false; } else if (Insensitive.Equals(a, "-haltonwarning")) { HaltOnWarning = true; } else if (Insensitive.Equals(a, "-vb")) { VBdotNet = true; } else if (Insensitive.Equals(a, "-usehrt")) { _UseHRT = true; } else if (Insensitive.Equals(a, "-noconsole")) { NoConsole = true; } else if (Insensitive.Equals(a, "-h") || Insensitive.Equals(a, "-help")) { Console.WriteLine("An Ultima Online server emulator written in C# - Visit https://www.servuo.com for more information.\n\n"); Console.WriteLine(System.AppDomain.CurrentDomain.FriendlyName + " [Parameter]\n\n"); Console.WriteLine(" -debug Starting ServUO in Debug Mode. Debug Mode is being used in Core and Scripts to give extended inforamtion during runtime."); Console.WriteLine(" -haltonwarning ServUO halts if any warning is raised during compilation of scripts."); Console.WriteLine(" -h or -help Displays this help text."); Console.WriteLine(" -nocache No known effect."); Console.WriteLine(" -noconsole No user interaction during startup and runtime."); Console.WriteLine(" -profile Enables profiling allowing to get performance diagnostic information of packets, timers etc. in AdminGump -> Maintenance. Use with caution. This increases server load."); Console.WriteLine(" -service This parameter should be set if you're running ServUO as a Windows Service. No user interaction. *Windows only*"); Console.WriteLine(" -usehrt Enables High Resolution Timing if requirements are met. Increasing the resolution of the timer. *Windows only*"); Console.WriteLine(" -vb Enables compilation of VB.NET Scripts. Without this option VB.NET Scripts are skipped."); System.Environment.Exit(0); } } if (!Environment.UserInteractive || Service) { NoConsole = true; } try { if (Service) { if (!Directory.Exists("Logs")) { Directory.CreateDirectory("Logs"); } Console.SetOut(MultiConsoleOut = new MultiTextWriter(new FileLogger("Logs/Console.log"))); } else { Console.SetOut(MultiConsoleOut = new MultiTextWriter(Console.Out)); } } catch (Exception e) { Server.Diagnostics.ExceptionLogging.LogException(e); } Thread = Thread.CurrentThread; Process = Process.GetCurrentProcess(); Assembly = Assembly.GetEntryAssembly(); if (Thread != null) { Thread.Name = "Core Thread"; } if (BaseDirectory.Length > 0) { Directory.SetCurrentDirectory(BaseDirectory); } Timer.TimerThread ttObj = new Timer.TimerThread(); _TimerThread = new Thread(ttObj.TimerMain) { Name = "Timer Thread" }; Version ver = Assembly.GetName().Version; DateTime buildDate = new DateTime(2000, 1, 1).AddDays(ver.Build).AddSeconds(ver.Revision * 2); Utility.PushColor(ConsoleColor.Cyan); #if DEBUG Console.WriteLine( "ServUO - [https://www.servuo.com] Version {0}.{1}, Build {2}.{3} - Build on {4} UTC - Debug", ver.Major, ver.Minor, ver.Build, ver.Revision, buildDate); #else Console.WriteLine( "ServUO - [https://www.servuo.com] Version {0}.{1}, Build {2}.{3} - Build on {4} UTC - Release", ver.Major, ver.Minor, ver.Build, ver.Revision, buildDate); #endif Utility.PopColor(); string s = Arguments; if (s.Length > 0) { Utility.PushColor(ConsoleColor.Yellow); Console.WriteLine("Core: Running with arguments: {0}", s); Utility.PopColor(); } ProcessorCount = Environment.ProcessorCount; if (ProcessorCount > 1) { MultiProcessor = true; } if (MultiProcessor || Is64Bit) { Utility.PushColor(ConsoleColor.Green); Console.WriteLine( "Core: Optimizing for {0} {2}processor{1}", ProcessorCount, ProcessorCount == 1 ? "" : "s", Is64Bit ? "64-bit " : ""); Utility.PopColor(); } string dotnet = null; if (Type.GetType("Mono.Runtime") != null) { MethodInfo displayName = Type.GetType("Mono.Runtime").GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static); if (displayName != null) { dotnet = displayName.Invoke(null, null).ToString(); Utility.PushColor(ConsoleColor.Yellow); Console.WriteLine("Core: Unix environment detected"); Utility.PopColor(); Unix = true; } } else { m_ConsoleEventHandler = OnConsoleEvent; UnsafeNativeMethods.SetConsoleCtrlHandler(m_ConsoleEventHandler, true); } #if NETFX_472 dotnet = "4.7.2"; #endif #if NETFX_48 dotnet = "4.8"; #endif if (String.IsNullOrEmpty(dotnet)) { dotnet = "MONO/CSC/Unknown"; } Utility.PushColor(ConsoleColor.Green); Console.WriteLine("Core: Compiled for " + (Unix ? "MONO and running on {0}" : ".NET {0}"), dotnet); Utility.PopColor(); if (GCSettings.IsServerGC) { Utility.PushColor(ConsoleColor.Green); Console.WriteLine("Core: Server garbage collection mode enabled"); Utility.PopColor(); } if (_UseHRT) { Utility.PushColor(ConsoleColor.DarkYellow); Console.WriteLine( "Core: Requested high resolution timing ({0})", UsingHighResolutionTiming ? "Supported" : "Unsupported"); Utility.PopColor(); } Utility.PushColor(ConsoleColor.DarkYellow); Console.WriteLine("RandomImpl: {0} ({1})", RandomImpl.Type.Name, RandomImpl.IsHardwareRNG ? "Hardware" : "Software"); Utility.PopColor(); Utility.PushColor(ConsoleColor.Green); Console.WriteLine("Core: Loading config..."); Config.Load(); Utility.PopColor(); while (!ScriptCompiler.Compile(Debug, _Cache)) { Utility.PushColor(ConsoleColor.Red); Console.WriteLine("Scripts: One or more scripts failed to compile or no script files were found."); Utility.PopColor(); if (Service) { return; } Console.WriteLine(" - Press return to exit, or R to try again."); if (Console.ReadKey(true).Key != ConsoleKey.R) { return; } } ScriptCompiler.Invoke("Configure"); Region.Load(); World.Load(); ScriptCompiler.Invoke("Initialize"); MessagePump messagePump = MessagePump = new MessagePump(); _TimerThread.Start(); foreach (Map m in Map.AllMaps) { m.Tiles.Force(); } NetState.Initialize(); EventSink.InvokeServerStarted(); try { long now, last = TickCount; const int sampleInterval = 100; const float ticksPerSecond = 1000.0f * sampleInterval; long sample = 0; while (!Closing) { _Signal.WaitOne(); Mobile.ProcessDeltaQueue(); Item.ProcessDeltaQueue(); Timer.Slice(); messagePump.Slice(); NetState.FlushAll(); NetState.ProcessDisposedQueue(); if (Slice != null) { Slice(); } if (sample++ % sampleInterval != 0) { continue; } now = TickCount; _CyclesPerSecond[_CycleIndex++ % _CyclesPerSecond.Length] = ticksPerSecond / (now - last); last = now; } } catch (Exception e) { CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(e, true)); } }
public void Update() { if (!m_Valid) { return; } if (m_From.Accepted && m_To.Accepted) { //List<Item> list = m_From.Container.Items; List <Item> list = new List <Item>(); try { for (int i = 0; i < m_From.Container.Items.Count; i++) { try { Item it = m_From.Container.Items[i] as Item; if (it != null) { list.Add(it); } } catch (Exception ex) { EventSink.InvokeLogException(new LogExceptionEventArgs(ex)); } } } catch (Exception ex) { EventSink.InvokeLogException(new LogExceptionEventArgs(ex)); } bool allowed = true; for (int i = list.Count - 1; allowed && i >= 0; --i) { if (i < list.Count) { Item item = list[i]; if (!item.AllowSecureTrade(m_From.Mobile, m_To.Mobile, m_To.Mobile, true)) { allowed = false; } } } //list = m_To.Container.Items; list = new List <Item>(); try { for (int i = 0; i < m_To.Container.Items.Count; i++) { try { Item it = m_To.Container.Items[i] as Item; if (it != null) { list.Add(it); } } catch (Exception ex) { EventSink.InvokeLogException(new LogExceptionEventArgs(ex)); } } } catch (Exception ex) { EventSink.InvokeLogException(new LogExceptionEventArgs(ex)); } for (int i = list.Count - 1; allowed && i >= 0; --i) { if (i < list.Count) { Item item = list[i]; if (!item.AllowSecureTrade(m_To.Mobile, m_From.Mobile, m_From.Mobile, true)) { allowed = false; } } } if (!allowed) { m_From.Accepted = false; m_To.Accepted = false; m_From.Mobile.Send(new UpdateSecureTrade(m_From.Container, m_From.Accepted, m_To.Accepted)); m_To.Mobile.Send(new UpdateSecureTrade(m_To.Container, m_To.Accepted, m_From.Accepted)); return; } //list = m_From.Container.Items; list = new List <Item>(); try { for (int i = 0; i < m_From.Container.Items.Count; i++) { try { Item it = m_From.Container.Items[i] as Item; if (it != null) { list.Add(it); } } catch (Exception ex) { EventSink.InvokeLogException(new LogExceptionEventArgs(ex)); } } } catch (Exception ex) { EventSink.InvokeLogException(new LogExceptionEventArgs(ex)); } for (int i = list.Count - 1; i >= 0; --i) { if (i < list.Count) { Item item = list[i]; item.OnSecureTrade(m_From.Mobile, m_To.Mobile, m_To.Mobile, true); if (!item.Deleted) { m_To.Mobile.AddToBackpack(item); } } } //list = m_To.Container.Items; list = new List <Item>(); try { for (int i = 0; i < m_To.Container.Items.Count; i++) { try { Item it = m_To.Container.Items[i] as Item; if (it != null) { list.Add(it); } } catch (Exception ex) { EventSink.InvokeLogException(new LogExceptionEventArgs(ex)); } } } catch (Exception ex) { EventSink.InvokeLogException(new LogExceptionEventArgs(ex)); } for (int i = list.Count - 1; i >= 0; --i) { if (i < list.Count) { Item item = list[i]; item.OnSecureTrade(m_To.Mobile, m_From.Mobile, m_From.Mobile, true); if (!item.Deleted) { m_From.Mobile.AddToBackpack(item); } } } Close(); } else { m_From.Mobile.Send(new UpdateSecureTrade(m_From.Container, m_From.Accepted, m_To.Accepted)); m_To.Mobile.Send(new UpdateSecureTrade(m_To.Container, m_To.Accepted, m_From.Accepted)); } }
public static void Save(bool message, bool permitBackgroundWrite) { if (m_Saving) { return; } ++m_Saves; NetState.FlushAll(); NetState.Pause(); World.WaitForWriteCompletion(); //Blocks Save until current disk flush is done. m_Saving = true; m_DiskWriteHandle.Reset(); if (message) { Broadcast(0x35, true, "The world is saving, please wait."); } SaveStrategy strategy = SaveStrategy.Acquire(); Console.WriteLine("Core: Using {0} save strategy", strategy.Name.ToLowerInvariant()); Console.Write("World: Saving..."); Stopwatch watch = Stopwatch.StartNew(); Directories.AppendPath(Directories.saves, "Mobiles"); Directories.AppendPath(Directories.saves, "Items"); Directories.AppendPath(Directories.saves, "Guilds"); Directories.AppendPath(Directories.saves, "Misc"); /*using ( SaveMetrics metrics = new SaveMetrics() ) {*/ strategy.Save(null, permitBackgroundWrite); /*}*/ try { EventSink.InvokeWorldSave(new WorldSaveEventArgs(message)); } catch (Exception e) { throw new Exception("World Save event threw an exception. Save failed!", e); } watch.Stop(); m_Saving = false; if (!permitBackgroundWrite) { World.NotifyDiskWriteComplete(); //Sets the DiskWriteHandle. If we allow background writes, we leave this upto the individual save strategies. } ProcessSafetyQueues(); strategy.ProcessDecay(); Console.WriteLine("Save done in {0:F2} seconds.", watch.Elapsed.TotalSeconds); if (message) { Broadcast(0x35, true, "World save complete. The entire process took {0:F1} seconds.", watch.Elapsed.TotalSeconds); } NetState.Resume(); }
public static void Main(string[] args) { m_Assembly = Assembly.GetEntryAssembly(); /* print a banner */ Version ver = m_Assembly.GetName().Version; Console.WriteLine("SunLogin Version {0}.{1}.{2} http://www.sunuo.org/", ver.Major, ver.Minor, ver.Revision); Console.WriteLine(" on {0}, runtime {1}", Environment.OSVersion, Environment.Version); if ((int)Environment.OSVersion.Platform == 128) { Console.WriteLine("Please make sure you have Mono 1.1.7 or newer! (mono -V)"); } Console.WriteLine(); /* prepare SunUO */ AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit); for (int i = 0; i < args.Length; ++i) { if (Insensitive.Equals(args[i], "-service")) { m_Service = true; } else if (Insensitive.Equals(args[i], "-profile")) { Profiling = true; } else if (args[i] == "--logfile") { string logfile = args[++i]; StreamWriter writer = new StreamWriter(new FileStream(logfile, FileMode.Append, FileAccess.Write)); writer.AutoFlush = true; Console.SetOut(writer); Console.SetError(writer); } } config = new Config(Path.Combine(BaseDirectoryInfo.CreateSubdirectory("etc").FullName, "sunuo.xml")); try { m_MultiConOut = new MultiTextWriter(Console.Out); Console.SetOut(m_MultiConOut); if (m_Service) { string filename = Path.Combine(LogDirectoryInfo.FullName, "console.log"); m_MultiConOut.Add(new FileLogger(filename)); } } catch { } m_Thread = Thread.CurrentThread; if (m_Thread != null) { m_Thread.Name = "Core Thread"; } if (BaseDirectory.Length > 0) { Directory.SetCurrentDirectory(BaseDirectory); } Timer.TimerThread ttObj = new Timer.TimerThread(); timerThread = new Thread(new ThreadStart(ttObj.TimerMain)); timerThread.Name = "Timer Thread"; if (!config.Exists) { config.Save(); } m_MessagePump = new MessagePump(new Listener(Listener.Port)); timerThread.Start(); NetState.Initialize(); Encryption.Initialize(); ServerList.Initialize(); Server.Accounting.AccountHandler.Initialize(); EventSink.InvokeServerStarted(); try { while (!m_Closing) { Thread.Sleep(1); Timer.Slice(); m_MessagePump.Slice(); NetState.FlushAll(); NetState.ProcessDisposedQueue(); if (Slice != null) { Slice(); } } } catch (Exception e) { CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(e, true)); } if (timerThread.IsAlive) { timerThread.Abort(); } }