public static void Run() { EventSink.Instance = new EventSink(); if (!ScriptCompiler.Compile(Environment.Debug)) { Console.WriteLine("Fatal: Compilation failed. Press any key to exit."); Console.ReadLine(); return; } ScriptCompiler.VerifyLibraries(); // This instance is shared among timer scheduler and timer executor, // and accessed from both core & timer threads. Queue <Timer> timerQueue = new Queue <Timer>(); // Timer scheduler must be set up before world load, since world load // could schedule timers on entity deserialization. var timerScheduler = TimerScheduler.Instance = new TimerScheduler(timerQueue); m_TimerThread = new TimerThread(timerScheduler); TimerExecutor timerExecutor = new TimerExecutor(timerQueue); PacketHandlers.Instance = new PacketHandlers(); try { ScriptCompiler.Configure(); TileData.Configure(); } catch (TargetInvocationException e) { Console.WriteLine("Fatal: Configure exception: {0}", e.InnerException); return; } Environment.SaveConfig(); Region.Load(); World.Instance.Load(); try { ScriptCompiler.Initialize(); } catch (TargetInvocationException e) { Logger.Error("Initialize exception: {0}", e.InnerException); return; } m_TimerThread.Start(); NetServer netServer = new NetServer(new Listener(Listener.Port)); netServer.Initialize(); GameServer.Instance = new GameServer(netServer, PacketHandlers.Instance); GameServer.Instance.Initialize(); EventSink.Instance.InvokeServerStarted(); PacketDispatcher.Initialize(); m_Now = DateTime.UtcNow; m_TotalProfile = new MainProfile(m_Now); m_CurrentProfile = new MainProfile(m_Now); try { while (!m_Closing) { m_Now = DateTime.UtcNow; Thread.Sleep(1); ClockProfile(MainProfile.TimerId.Idle); Mobile.ProcessDeltaQueue(); ClockProfile(MainProfile.TimerId.MobileDelta); Item.ProcessDeltaQueue(); ClockProfile(MainProfile.TimerId.ItemDelta); timerExecutor.Slice(); ClockProfile(MainProfile.TimerId.Timers); netServer.Slice(); ClockProfile(MainProfile.TimerId.Network); // Done with this iteration. m_TotalProfile.Next(); m_CurrentProfile.Next(); } } catch (Exception e) { HandleCrashed(e); } m_TimerThread.Stop(); }
private static List <Tuple <ConstructorInfo, string> > ReadTypes(BinaryReader tdbReader) { int count = tdbReader.ReadInt32(); List <Tuple <ConstructorInfo, string> > types = new List <Tuple <ConstructorInfo, string> >(count); for (int i = 0; i < count; ++i) { string typeName = tdbReader.ReadString(); Type t = ScriptCompiler.FindTypeByFullName(typeName); if (t == null) { Console.WriteLine("failed"); if (!Core.Service) { Console.WriteLine("Error: Type '{0}' was not found. Delete all of those types? (y/n)", typeName); if (Console.ReadKey(true).Key == ConsoleKey.Y) { types.Add(null); Utility.PushColor(ConsoleColor.Yellow); Console.Write("World: Loading..."); Utility.PopColor(); continue; } Console.WriteLine("Types will not be deleted. An exception will be thrown."); } else { Console.WriteLine("Error: Type '{0}' was not found.", typeName); } throw new Exception(String.Format("Missing type '{0}'", typeName)); } if (t.IsAbstract) { foreach (var at in ScriptCompiler.FindTypesByFullName(t.FullName)) { if (at != t && !at.IsAbstract) { t = at; typeName = at.FullName; break; } } if (t.IsAbstract) { Console.WriteLine("failed"); if (!Core.Service) { Console.WriteLine("Error: Type '{0}' is abstract. Delete all of those types? (y/n)", typeName); if (Console.ReadKey(true).Key == ConsoleKey.Y) { types.Add(null); Utility.PushColor(ConsoleColor.Yellow); Console.Write("World: Loading..."); Utility.PopColor(); continue; } Console.WriteLine("Types will not be deleted. An exception will be thrown."); } else { Console.WriteLine("Error: Type '{0}' is abstract.", typeName); } throw new Exception(String.Format("Abstract type '{0}'", typeName)); } } ConstructorInfo ctor = t.GetConstructor(m_SerialTypeArray); if (ctor != null) { types.Add(new Tuple <ConstructorInfo, string>(ctor, typeName)); } else { throw new Exception(string.Format("Type '{0}' does not have a serialization constructor", t)); } } return(types); }
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://max.kellermann.name/projects/sunuo/", 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.3 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; } } 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; } 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; } } 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); 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); } 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 = 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); 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.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 void LoadItems() { FileStream fs = null; try { fs = File.Open("items.xml", FileMode.Open, FileAccess.Read); } catch { Console.WriteLine("Could not open file"); } if (fs == null) { World.Broadcast(0x35, false, "Loading failed."); return; } DataSet ds = new DataSet("static"); try { ds.ReadXml(fs); } catch { World.Broadcast(0x35, false, "Error with xml"); return; } finally { fs.Close(); } if (ds.Tables != null && ds.Tables.Count > 0) { World.Broadcast(0x35, false, "Table successfully populated."); if (ds.Tables["item"] != null && ds.Tables["item"].Rows.Count > 0) { foreach (DataRow dr in ds.Tables["item"].Rows) { string temp = string.Empty; Type type = null; try { type = ScriptCompiler.FindTypeByFullName(dr["Type"].ToString(), false); } catch { Console.WriteLine("Type loading failed"); } if (type == null) { continue; } Item item; try { item = Activator.CreateInstance(type) as Item; } catch { Console.WriteLine("Type creation failed."); continue; } if (item == null) { continue; } try { item.ItemID = int.Parse(dr["ItemID"].ToString()); } catch { Console.WriteLine("ItemID loading failed"); } try { item.Amount = int.Parse(dr["Amount"].ToString()); } catch { Console.WriteLine("Amount loading failed"); item.Amount = 1; } try { temp = dr["Movable"].ToString(); switch (temp) { case "True": item.Movable = true; break; case "False": item.Movable = false; break; } } catch { Console.WriteLine("Movable loading failed"); item.Movable = false; } try { temp = dr["Direction"].ToString(); switch (temp) { case "North": item.Direction = Direction.North; break; case "Right": item.Direction = Direction.Right; break; case "East": item.Direction = Direction.East; break; case "Down": item.Direction = Direction.Down; break; case "South": item.Direction = Direction.South; break; case "Left": item.Direction = Direction.Left; break; case "West": item.Direction = Direction.West; break; case "Up": item.Direction = Direction.Up; break; } } catch { Console.WriteLine("Direction loading failed"); } try { item.Hue = int.Parse(dr["Hue"].ToString()); } catch { Console.WriteLine("Hue loading failed"); } try { temp = dr["Layer"].ToString(); switch (temp) { case "Invalid": item.Layer = Layer.Invalid; break; case "FirstValid": item.Layer = Layer.FirstValid; break; case "OneHanded": item.Layer = Layer.OneHanded; break; case "TwoHanded": item.Layer = Layer.TwoHanded; break; case "Shoes": item.Layer = Layer.Shoes; break; case "Pants": item.Layer = Layer.Pants; break; case "Shirt": item.Layer = Layer.Shirt; break; case "Helm": item.Layer = Layer.Helm; break; case "Gloves": item.Layer = Layer.Gloves; break; case "Ring": item.Layer = Layer.Ring; break; case "Talisman": item.Layer = Layer.Talisman; break; case "Neck": item.Layer = Layer.Neck; break; case "Hair": item.Layer = Layer.Hair; break; case "Waist": item.Layer = Layer.Waist; break; case "InnerTorso": item.Layer = Layer.InnerTorso; break; case "Bracelet": item.Layer = Layer.Bracelet; break; case "Unused_xF": item.Layer = Layer.Unused_xF; break; case "FacialHair": item.Layer = Layer.FacialHair; break; case "MiddleTorso": item.Layer = Layer.MiddleTorso; break; case "Earrings": item.Layer = Layer.Earrings; break; case "Arms": item.Layer = Layer.Arms; break; case "Cloak": item.Layer = Layer.Cloak; break; case "Backpack": item.Layer = Layer.Backpack; break; case "OuterTorso": item.Layer = Layer.OuterTorso; break; case "OuterLegs": item.Layer = Layer.OuterLegs; break; case "InnerLegs": item.Layer = Layer.InnerLegs; break; case "LastUserValid": item.Layer = Layer.LastUserValid; break; case "Mount": item.Layer = Layer.Mount; break; case "ShopBuy": item.Layer = Layer.ShopBuy; break; case "ShopResale": item.Layer = Layer.ShopResale; break; case "ShopSell": item.Layer = Layer.ShopSell; break; case "Bank": item.Layer = Layer.Bank; break; case "LastValid": item.Layer = Layer.LastValid; break; } } catch { Console.WriteLine("Layer loading failed"); } try { temp = dr["Light"].ToString(); switch (temp) { case "ArchedWindowEast": item.Light = LightType.ArchedWindowEast; break; case "Circle225": item.Light = LightType.Circle225; break; case "Circle150": item.Light = LightType.Circle150; break; case "DoorSouth": item.Light = LightType.DoorSouth; break; case "DoorEast": item.Light = LightType.DoorEast; break; case "NorthBig": item.Light = LightType.NorthBig; break; case "NorthEastBig": item.Light = LightType.NorthEastBig; break; case "EastBig": item.Light = LightType.EastBig; break; case "WestBig": item.Light = LightType.WestBig; break; case "SouthWestBig": item.Light = LightType.SouthWestBig; break; case "SouthBig": item.Light = LightType.SouthBig; break; case "NorthSmall": item.Light = LightType.NorthSmall; break; case "NorthEastSmall": item.Light = LightType.NorthEastSmall; break; case "EastSmall": item.Light = LightType.EastSmall; break; case "WestSmall": item.Light = LightType.WestSmall; break; case "SouthSmall": item.Light = LightType.SouthSmall; break; case "DecorationNorth": item.Light = LightType.DecorationNorth; break; case "DecorationNorthEast": item.Light = LightType.DecorationNorthEast; break; case "EastTiny": item.Light = LightType.EastTiny; break; case "DecorationWest": item.Light = LightType.DecorationWest; break; case "DecorationSouthWest": item.Light = LightType.DecorationSouthWest; break; case "SouthTiny": item.Light = LightType.SouthTiny; break; case "RectWindowSouthNoRay": item.Light = LightType.RectWindowSouthNoRay; break; case "RectWindowEastNoRay": item.Light = LightType.RectWindowEastNoRay; break; case "RectWindowSouth": item.Light = LightType.RectWindowSouth; break; case "RectWindowEast": item.Light = LightType.RectWindowEast; break; case "ArchedWindowSouthNoRay": item.Light = LightType.ArchedWindowSouthNoRay; break; case "ArchedWindowEastNoRay": item.Light = LightType.ArchedWindowEastNoRay; break; case "ArchedWindowSouth": item.Light = LightType.ArchedWindowSouth; break; case "Cirle300": item.Light = LightType.Circle300; break; case "NorthWestBig": item.Light = LightType.NorthWestBig; break; case "DarkSouthEast": item.Light = LightType.DarkSouthEast; break; case "DarkSouth": item.Light = LightType.DarkSouth; break; case "DarkNorthWest": item.Light = LightType.DarkNorthWest; break; case "DarkSouthEast2": item.Light = LightType.DarkSouthEast2; break; case "DarkEast": item.Light = LightType.DarkEast; break; case "DarkCircle300": item.Light = LightType.DarkCircle300; break; case "DoorOpenSouth": item.Light = LightType.DoorOpenSouth; break; case "DoorOpenEast": item.Light = LightType.DoorOpenEast; break; case "SquareWindowEast": item.Light = LightType.SquareWindowEast; break; case "SquareWindowEastNoRay": item.Light = LightType.SquareWindowEastNoRay; break; case "SquareWindowSouth": item.Light = LightType.SquareWindowSouth; break; case "SquareWindowSouthNoRay": item.Light = LightType.SquareWindowSouthNoRay; break; case "Empty": item.Light = LightType.Empty; break; case "SkinnyWindowSouthNoRay": item.Light = LightType.SkinnyWindowSouthNoRay; break; case "SkinnyWindowEast": item.Light = LightType.SkinnyWindowEast; break; case "SkinnyWindowEastNoRay": item.Light = LightType.SkinnyWindowEastNoRay; break; case "HoleSouth": item.Light = LightType.HoleSouth; break; case "HoleEast": item.Light = LightType.HoleEast; break; case "Moongate": item.Light = LightType.Moongate; break; case "Strips": item.Light = LightType.Strips; break; case "SmallHoleSouth": item.Light = LightType.SmallHoleSouth; break; case "SmallHoleEast": item.Light = LightType.SmallHoleEast; break; case "NorthBig2": item.Light = LightType.NorthBig2; break; case "WestBig2": item.Light = LightType.WestBig2; break; case "NorthWestBig2": item.Light = LightType.NorthWestBig2; break; } } catch { Console.WriteLine("Light loading failed"); } try { temp = dr["LootType"].ToString(); switch (temp) { case "Regular": item.LootType = LootType.Regular; break; case "Newbied": item.LootType = LootType.Newbied; break; case "Blessed": item.LootType = LootType.Blessed; break; case "Cursed": item.LootType = LootType.Cursed; break; } } catch { Console.WriteLine("LootType loading failed"); } try { item.Name = dr["Name"].ToString(); } catch { Console.WriteLine("Name loading failed"); } try { temp = dr["Stackable"].ToString(); switch (temp) { case "True": item.Stackable = true; break; case "False": item.Stackable = false; break; } } catch { Console.WriteLine("Stackable loading failed"); } try { item.Weight = double.Parse(dr["Weight"].ToString()); } catch { Console.WriteLine("Weight loading failed"); } try { temp = dr["Visible"].ToString(); switch (temp) { case "True": item.Visible = true; break; case "False": item.Visible = false; break; } } catch { Console.WriteLine("Visible loading failed"); } try { item.X = int.Parse(dr["X"].ToString()); } catch { Console.WriteLine("X loading failed"); } try { item.Y = int.Parse(dr["Y"].ToString()); } catch { Console.WriteLine("Y loading failed"); } try { item.Z = int.Parse(dr["Z"].ToString()); } catch { Console.WriteLine("Z loading failed"); } try { temp = dr["Map"].ToString(); switch (temp) { case "Felucca": item.Map = Map.Felucca; break; case "Trammel": item.Map = Map.Trammel; break; case "Ilshenar": item.Map = Map.Ilshenar; break; case "Malas": item.Map = Map.Malas; break; case "Tokuno": item.Map = Map.Tokuno; break; case "Internal": item.Map = Map.Internal; break; } } catch { Console.WriteLine("Map loading failed"); } } World.Broadcast(0x35, false, "Items should now populate the shard..."); } } }
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; } } 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 { } #if !MONO m_ConsoleEventHandler = new ConsoleEventHandler(OnConsoleEvent); SetConsoleCtrlHandler(m_ConsoleEventHandler, true); #endif 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); } int processorCount = Utility.ToInt32(Environment.GetEnvironmentVariable("NUMBER_OF_PROCESSORS")); if (processorCount > 1) { m_MultiProcessor = true; } if (processorCount > 1 || Is64Bit) { Console.WriteLine("Core: Optimizing for {0} {2}processor{1}", processorCount, processorCount == 1 ? "" : "s", Is64Bit ? "64-bit " : ""); } m_ProcessorCount = processorCount; while (!ScriptCompiler.Compile(m_Debug)) { 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; } } MessagePump ms = m_MessagePump = new MessagePump(new Listener(Listener.Port)); 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_Closing) { Thread.Sleep(m_MultiProcessor ? 0 : 1); 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)); } if (timerThread.IsAlive) { timerThread.Abort(); } }
public static Type FindTypeByFullName(string fullName) { return(ScriptCompiler.FindTypeByFullName(fullName, true)); }
public static Type FindTypeByName(string name) { return(ScriptCompiler.FindTypeByName(name, true)); }
public static bool Compile() { return(ScriptCompiler.Compile(false)); }
public static bool Compile(bool debug) { int num1; ArrayList list1; Type[] typeArray1; int num2; MethodInfo info1; int num3; Type[] typeArray2; int num4; MethodInfo info2; int num5; ScriptCompiler.EnsureDirectory("Scripts/"); ScriptCompiler.EnsureDirectory("Scripts/Output/"); ScriptCompiler.DeleteFiles("Scripts.CS*.dll"); ScriptCompiler.DeleteFiles("Scripts.VB*.dll"); ScriptCompiler.DeleteFiles("Scripts*.dll"); if (ScriptCompiler.m_AdditionalReferences.Count > 0) { ScriptCompiler.m_AdditionalReferences.Clear(); } CompilerResults results1 = null; CompilerResults results2 = null; results1 = ScriptCompiler.CompileCSScripts(debug); if ((results1 == null) || !results1.Errors.HasErrors) { results2 = ScriptCompiler.CompileVBScripts(debug); } if ((((results1 == null) || !results1.Errors.HasErrors) && ((results2 == null) || !results2.Errors.HasErrors)) && ((results2 != null) || (results1 != null))) { num1 = 0; if ((results1 == null) || (results2 == null)) { ScriptCompiler.m_Assemblies = new Assembly[1]; } else { ScriptCompiler.m_Assemblies = new Assembly[2]; } if (results1 != null) { ScriptCompiler.m_Assemblies[num1++] = results1.CompiledAssembly; } if (results2 != null) { ScriptCompiler.m_Assemblies[num1++] = results2.CompiledAssembly; } Console.Write("Scripts: Verifying..."); Core.VerifySerialization(); Console.WriteLine("done ({0} items, {1} mobiles)", Core.ScriptItems, Core.ScriptMobiles); list1 = new ArrayList(); num1 = 0; while ((num1 < ScriptCompiler.m_Assemblies.Length)) { typeArray1 = ScriptCompiler.m_Assemblies[num1].GetTypes(); for (num2 = 0; (num2 < typeArray1.Length); ++num2) { info1 = typeArray1[num2].GetMethod("Configure", (BindingFlags.Public | BindingFlags.Static)); if (info1 != null) { list1.Add(info1); } } ++num1; } list1.Sort(new CallPriorityComparer()); for (num3 = 0; (num3 < list1.Count); ++num3) { ((MethodInfo)list1[num3]).Invoke(null, null); } list1.Clear(); World.Load(); for (num1 = 0; (num1 < ScriptCompiler.m_Assemblies.Length); ++num1) { typeArray2 = ScriptCompiler.m_Assemblies[num1].GetTypes(); for (num4 = 0; (num4 < typeArray2.Length); ++num4) { info2 = typeArray2[num4].GetMethod("Initialize", (BindingFlags.Public | BindingFlags.Static)); if (info2 != null) { list1.Add(info2); } } } list1.Sort(new CallPriorityComparer()); for (num5 = 0; (num5 < list1.Count); ++num5) { ((MethodInfo)list1[num5]).Invoke(null, null); } return(true); } return(false); }
private static CompilerResults CompileVBScripts(bool debug) { int num1; int num2; object[] objArray1; VBCodeProvider provider1 = new VBCodeProvider(); ICodeCompiler compiler1 = provider1.CreateCompiler(); Console.Write("Scripts: Compiling VB.net scripts..."); string[] textArray1 = ScriptCompiler.GetScripts("*.vb"); if (textArray1.Length == 0) { Console.WriteLine("no files found."); return(null); } string text1 = ScriptCompiler.GetUnusedPath("Scripts.VB"); CompilerResults results1 = compiler1.CompileAssemblyFromFileBatch(new CompilerParameters(ScriptCompiler.GetReferenceAssemblies(), text1, true), textArray1); ScriptCompiler.m_AdditionalReferences.Add(text1); if (results1.Errors.Count > 0) { num1 = 0; num2 = 0; foreach (CompilerError error1 in results1.Errors) { if (error1.IsWarning) { ++num2; continue; } ++num1; } if (num1 > 0) { Console.WriteLine("failed ({0} errors, {1} warnings)", num1, num2); } else { Console.WriteLine("done ({0} errors, {1} warnings)", num1, num2); } foreach (CompilerError error2 in results1.Errors) { objArray1 = new object[6]; objArray1[0] = (error2.IsWarning ? "Warning" : "Error"); objArray1[1] = error2.FileName; objArray1[2] = error2.ErrorNumber; objArray1[3] = error2.Line; objArray1[4] = error2.Column; objArray1[5] = error2.ErrorText; Console.WriteLine(" - {0}: {1}: {2}: (line {3}, column {4}) {5}", objArray1); } return(results1); } Console.WriteLine("done (0 errors, 0 warnings)"); return(results1); }
private static CompilerResults CompileVBScripts() { return(ScriptCompiler.CompileVBScripts(false)); }
public static void Start(Config.Root _config, bool debug, bool _service, bool _profiling) { config = _config; m_Service = _service; Profiling = _profiling; m_Assembly = Assembly.GetEntryAssembly(); /* prepare SunUO */ AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit); /* redirect Console to file in service mode */ if (m_Service) { string filename = Path.Combine(LogDirectoryInfo.FullName, "console.log"); FileStream stream = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.Read); StreamWriter writer = new StreamWriter(stream); Console.SetOut(writer); Console.SetError(writer); } 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; } m_ItemCount = 0; m_MobileCount = 0; foreach (Library l in ScriptCompiler.Libraries) { int itemCount = 0, mobileCount = 0; l.Verify(ref itemCount, ref mobileCount); log.Info(String.Format("Library {0} verified: {1} items, {2} mobiles", l.Name, itemCount, mobileCount)); m_ItemCount += itemCount; m_MobileCount += mobileCount; } log.Info(String.Format("All libraries verified: {0} items, {1} mobiles)", m_ItemCount, m_MobileCount)); try { ScriptCompiler.Configure(); } catch (TargetInvocationException e) { log.Fatal("Configure exception: {0}", e.InnerException); return; } if (!config.Exists) { config.Save(); } World.Load(); try { ScriptCompiler.Initialize(); } catch (TargetInvocationException e) { log.Fatal("Initialize exception: {0}", e.InnerException); return; } Region.Load(); m_MessagePump = new MessagePump(new Listener(Listener.Port)); timerThread.Start(); NetState.Initialize(); Encryption.Initialize(); EventSink.InvokeServerStarted(); log.Info("SunUO initialized, entering main loop"); try { while (!m_Closing) { m_Signal.WaitOne(); m_Now = DateTime.Now; 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 += 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; // 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 - [https://www.servuo.com] Version {0}.{1}, Build {2}.{3}", ver.Major, ver.Minor, ver.Build, ver.Revision); 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 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 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; } 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 { } 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_30 dotnet = "3.0"; #endif #if NETFX_35 dotnet = "3.5"; #endif #if NETFX_40 dotnet = "4.0"; #endif #if NETFX_45 dotnet = "4.5"; #endif #if NETFX_451 dotnet = "4.5.1"; #endif #if NETFX_46 dotnet = "4.6.0"; #endif #if NETFX_461 dotnet = "4.6.1"; #endif #if NETFX_462 dotnet = "4.6.2"; #endif #if NETFX_47 dotnet = "4.7"; #endif #if NETFX_471 dotnet = "4.7.1"; #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 static void Main(string[] args) { int num1; string text1; int num2; TextWriter[] writerArray1; AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(Core.CurrentDomain_UnhandledException); AppDomain.CurrentDomain.ProcessExit += new EventHandler(Core.CurrentDomain_ProcessExit); bool flag1 = false; for (num1 = 0; (num1 < args.Length); ++num1) { if (Insensitive.Equals(args[num1], "-debug")) { flag1 = true; } else if (Insensitive.Equals(args[num1], "-service")) { Core.m_Service = true; } else if (Insensitive.Equals(args[num1], "-profile")) { Core.Profiling = true; } } try { if (Core.m_Service) { if (!Directory.Exists("Logs")) { Directory.CreateDirectory("Logs"); } writerArray1 = new TextWriter[2]; writerArray1[0] = Console.Out; writerArray1[1] = new FileLogger("Logs/Console.log"); Console.SetOut((Core.m_MultiConOut = new MultiTextWriter(writerArray1))); } else { writerArray1 = new TextWriter[1]; writerArray1[0] = Console.Out; Console.SetOut((Core.m_MultiConOut = new MultiTextWriter(writerArray1))); } } catch { } Core.m_Thread = Thread.CurrentThread; Core.m_Process = Process.GetCurrentProcess(); Core.m_Assembly = Assembly.GetEntryAssembly(); if (Core.m_Thread != null) { Core.m_Thread.Name = "Core Thread"; } if (Core.BaseDirectory.Length > 0) { Directory.SetCurrentDirectory(Core.BaseDirectory); } Server.Timer.TimerThread thread1 = new Server.Timer.TimerThread(); Core.timerThread = new Thread(new ThreadStart(thread1.TimerMain)); Core.timerThread.Name = "Timer Thread"; while (!ScriptCompiler.Compile(flag1)) { 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."); text1 = Console.ReadLine(); if ((text1 == null) || (text1.ToLower() != "r")) { return; } } Region.Load(); Core.m_MessagePump = new MessagePump(new Listener(Listener.Port)); Core.timerThread.Start(); for (num2 = 0; (num2 < Map.AllMaps.Count); ++num2) { ((Map)Map.AllMaps[num2]).Tiles.Force(); } NetState.Initialize(); EventSink.InvokeServerStarted(); try { while (!Core.m_Closing) { Thread.Sleep(1); Mobile.ProcessDeltaQueue(); Item.ProcessDeltaQueue(); Server.Timer.Slice(); Core.m_MessagePump.Slice(); NetState.ProcessDisposedQueue(); if (Core.Slice != null) { Core.Slice.Invoke(); } } } catch (Exception exception1) { Core.CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(exception1, true)); } if (Core.timerThread.IsAlive) { Core.timerThread.Abort(); } }
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]; Type[] ctorTypes = new Type[1] { typeof(Serial) }; 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); 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"); if (!Core.Service) { Console.WriteLine("Error: Type '{0}' was not found. Delete all of those types? (y/n)", typeName); if (Console.ReadKey(true).Key == ConsoleKey.Y) { types.Add(null); Console.Write("World: Loading..."); continue; } Console.WriteLine("Types will not be deleted. An exception will be thrown."); } else { Console.WriteLine("Error: Type '{0}' was not found.", typeName); } 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 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(); 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 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); 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"); if (!Core.Service) { Console.WriteLine("Error: Type '{0}' was not found. Delete all of those types? (y/n)", typeName); if (Console.ReadKey(true).Key == ConsoleKey.Y) { types.Add(null); Console.Write("World: Loading..."); continue; } Console.WriteLine("Types will not be deleted. An exception will be thrown."); } else { Console.WriteLine("Error: Type '{0}' was not found.", typeName); } 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 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(); 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 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; BaseGuild guild = EventSink.InvokeCreateGuild(createEventArgs); 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 Main(string[] args) { 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; } } 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 { } #if !MONO m_ConsoleEventHandler = new ConsoleEventHandler(OnConsoleEvent); SetConsoleCtrlHandler(m_ConsoleEventHandler, true); #endif 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}.{3}, Build {2}", ver.Major, ver.Minor, ver.Revision, ver.Build); while (!ScriptCompiler.Compile(debug)) { 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."); string line = Console.ReadLine(); if (line == null || line.ToLower() != "r") { return; } } Region.Load(); MessagePump ms = m_MessagePump = new MessagePump(new Listener(Listener.Port)); timerThread.Start(); for (int i = 0; i < Map.AllMaps.Count; ++i) { ((Map)Map.AllMaps[i]).Tiles.Force(); } 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 += CurrentDomain_UnhandledException; AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit; foreach (string arg in args) { if (Insensitive.Equals(arg, "-debug")) { m_Debug = true; } else if (Insensitive.Equals(arg, "-service")) { m_Service = true; } else if (Insensitive.Equals(arg, "-profile")) { Profiling = true; } else if (Insensitive.Equals(arg, "-nocache")) { m_Cache = false; } else if (Insensitive.Equals(arg, "-haltonwarning")) { m_HaltOnWarning = true; } else if (Insensitive.Equals(arg, "-vb")) { m_VBdotNET = true; } else if (Insensitive.Equals(arg, "-usehrt")) { m_UseHRT = 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); } var ttObj = new Timer.TimerThread(); timerThread = new Thread(ttObj.TimerMain) { Name = "Timer Thread" }; Version ver = m_Assembly.GetName().Version; String publishNumber = String.Empty; if (File.Exists("publish.txt")) { try { publishNumber = File.ReadAllText("publish.txt", Encoding.UTF8); } catch { } } // 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(@"----------------------------------------------------------------------------"); Utility.PopColor(); Utility.PushColor(ConsoleColor.Cyan); Console.WriteLine("JustUO - [http://www.playuo.org] Version {0}.{1}", ver.Major, ver.Minor); if (!String.IsNullOrWhiteSpace(publishNumber)) { Console.WriteLine("Publish {0}", publishNumber); } Utility.PopColor(); Console.WriteLine( "Core: .NET Framework Version {0}.{1}.{2}", Environment.Version.Major, Environment.Version.Minor, Environment.Version.Build); string s = Arguments; if (s.Length > 0) { Utility.PushColor(ConsoleColor.Yellow); Console.WriteLine("Core: Running with arguments: {0}", s); Utility.PopColor(); } m_ProcessorCount = Environment.ProcessorCount; if (m_ProcessorCount > 1) { m_MultiProcessor = true; } if (m_MultiProcessor || Is64Bit) { Utility.PushColor(ConsoleColor.Green); Console.WriteLine( "Core: Optimizing for {0} {2}processor{1}", m_ProcessorCount, m_ProcessorCount == 1 ? "" : "s", Is64Bit ? "64-bit " : ""); Utility.PopColor(); } var platform = (int)Environment.OSVersion.Platform; if (platform == 4 || platform == 128) { // MS 4, MONO 128 m_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 (m_UseHRT) { Console.WriteLine( "Core: Requested high resolution timing ({0})", UsingHighResolutionTiming ? "Supported" : "Unsupported"); } Console.WriteLine("RandomImpl: {0} ({1})", RandomImpl.Type.Name, RandomImpl.IsHardwareRNG ? "Hardware" : "Software"); _OpenUOSDK = new OpenUOSDK(); while (!ScriptCompiler.Compile(m_Debug, m_Cache)) { Utility.PushColor(ConsoleColor.Red); Console.WriteLine("Scripts: One or more scripts failed to compile or no script files were found."); Utility.PopColor(); 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(); 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 = (float)(1000 * sampleInterval); long sample = 0; while (!m_Closing) { m_Signal.WaitOne(); Mobile.ProcessDeltaQueue(); Item.ProcessDeltaQueue(); Timer.Slice(); messagePump.Slice(); NetState.FlushAll(); NetState.ProcessDisposedQueue(); if (Slice != null) { Slice(); } if ((++sample % sampleInterval) == 0) { now = TickCount; m_CyclesPerSecond[m_CycleIndex++ % m_CyclesPerSecond.Length] = ticksPerSecond / (now - last); last = now; } } } catch (Exception e) { CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(e, true)); } }
public static void Main(string[] args) { 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; } } 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(); 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("SunUO Version {0}.{1}.{2} http://max.kellermann.name/projects/sunuo/", ver.Major, ver.Minor, ver.Revision); while (!ScriptCompiler.Compile(debug)) { 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."); string line = Console.ReadLine(); if (line == null || line.ToLower() != "r") { 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; } config.Save(); World.Load(); try { ScriptCompiler.Initialize(); } catch (TargetInvocationException e) { Console.WriteLine("Initialize exception: {0}", e.InnerException); return; } Region.Load(); MessagePump ms = 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(); } }
private static BaseDoor DeserializeDoor(XmlElement node) { var t = node.GetAttribute("type"); var type = ScriptCompiler.FindTypeByName(t, true) ?? // ScriptCompiler.FindTypeByFullName(t, true) ?? // Type.GetType(t, false, true); BaseDoor door; try { door = (Activator.CreateInstance(type, _ImportArgs) ?? Activator.CreateInstance(type)) as BaseDoor; } catch { return null; } if (door == null) { return null; } var x = XmlConvert.ToInt32(node.GetAttribute("x")); var y = XmlConvert.ToInt32(node.GetAttribute("y")); var z = XmlConvert.ToInt32(node.GetAttribute("z")); door.Location = new Point3D(x, y, z); var ox = XmlConvert.ToInt32(node.GetAttribute("ox")); var oy = XmlConvert.ToInt32(node.GetAttribute("oy")); var oz = XmlConvert.ToInt32(node.GetAttribute("oz")); door.Offset = new Point3D(ox, oy, oz); door.OpenedID = XmlConvert.ToInt32(node.GetAttribute("oid")); door.ClosedID = XmlConvert.ToInt32(node.GetAttribute("cid")); door.Locked = XmlConvert.ToBoolean(node.GetAttribute("locked")); if (node.HasAttribute("keyval")) { door.KeyValue = XmlConvert.ToUInt32(node.GetAttribute("keyval")); } if (node.HasAttribute("osound")) { door.OpenedSound = XmlConvert.ToInt32(node.GetAttribute("osound")); } if (node.HasAttribute("csound")) { door.ClosedSound = XmlConvert.ToInt32(node.GetAttribute("csound")); } if (node.HasAttribute("hue")) { door.Hue = XmlConvert.ToInt32(node.GetAttribute("hue")); } if (door.Open) { door.ItemID = door.OpenedID; } else { door.ItemID = door.ClosedID; } return door; }
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)); } }