public bool SendRawMap(Level oldLevel, Level level) { if (level.blocks == null) { return(false); } bool success = true; useCheckpointSpawn = false; lastCheckpointIndex = -1; try { int usedLength = 0; byte[] buffer = CompressRawMap(out usedLength); if (hasBlockDefs) { if (oldLevel != null && oldLevel != level) { RemoveOldLevelCustomBlocks(oldLevel); } BlockDefinition.SendLevelCustomBlocks(this); } SendRaw(Opcode.LevelInitialise); int totalRead = 0; while (totalRead < usedLength) { byte[] packet = new byte[1028]; // need each packet separate for Mono packet[0] = Opcode.LevelDataChunk; short length = (short)Math.Min(buffer.Length - totalRead, 1024); NetUtils.WriteI16(length, packet, 1); Buffer.BlockCopy(buffer, totalRead, packet, 3, length); packet[1027] = (byte)(100 * (float)totalRead / buffer.Length); SendRaw(packet); if (ip != "127.0.0.1") { Thread.Sleep(Server.updateTimer.Interval > 1000 ? 100 : 10); } totalRead += length; } buffer = new byte[7]; buffer[0] = Opcode.LevelFinalise; NetUtils.WriteI16((short)level.Width, buffer, 1); NetUtils.WriteI16((short)level.Height, buffer, 3); NetUtils.WriteI16((short)level.Length, buffer, 5); SendRaw(buffer); Loading = false; if (HasCpeExt(CpeExt.EnvWeatherType)) { SendSetMapWeather(level.weather); } if (HasCpeExt(CpeExt.EnvColors)) { SendCurrentEnvColors(); } if (HasCpeExt(CpeExt.EnvMapAppearance) || HasCpeExt(CpeExt.EnvMapAppearance, 2)) { SendCurrentMapAppearance(); } if (OnSendMap != null) { OnSendMap(this, buffer); } if (!level.guns) { aiming = false; } } catch (Exception ex) { success = false; Command.all.Find("goto").Use(this, Server.mainLevel.name); SendMessage("There was an error sending the map data, you have been sent to the main level."); Server.ErrorLog(ex); } finally { GC.Collect(); GC.WaitForPendingFinalizers(); } if (HasCpeExt(CpeExt.BlockPermissions)) { SendCurrentBlockPermissions(); } return(success); }
/// <summary> /// Load a plugin /// </summary> /// <param name="pluginname">The file path of the dll file</param> /// <param name="startup">Is this startup?</param> public static void Load(string pluginname, bool startup) { String creator = ""; try { object instance = null; Assembly lib = null; using (FileStream fs = File.Open(pluginname, FileMode.Open)) { using (MemoryStream ms = new MemoryStream()) { byte[] buffer = new byte[1024]; int read = 0; while ((read = fs.Read(buffer, 0, 1024)) > 0) { ms.Write(buffer, 0, read); } lib = Assembly.Load(ms.ToArray()); ms.Close(); ms.Dispose(); } fs.Close(); fs.Dispose(); } try { foreach (Type t in lib.GetTypes()) { if (t.BaseType == typeof(Plugin)) { instance = Activator.CreateInstance(t); break; } } } catch { } if (instance == null) { Server.s.Log("The plugin " + pluginname + " couldn't be loaded!"); return; } String plugin_version = ((Plugin)instance).MCGalaxy_Version; if (!String.IsNullOrEmpty(plugin_version) && new Version(plugin_version) > Server.Version) { Server.s.Log("This plugin (" + ((Plugin)instance).name + ") isn't compatible with this version of MCGalaxy!"); Thread.Sleep(1000); if (Server.unsafe_plugin) { Server.s.Log("Will attempt to load!"); goto here; } else { return; } } here: Plugin.all.Add((Plugin)instance); creator = ((Plugin)instance).creator; if (((Plugin)instance).LoadAtStartup) { ((Plugin)instance).Load(startup); Server.s.Log("Plugin: " + ((Plugin)instance).name + " loaded...build: " + ((Plugin)instance).build); } else { Server.s.Log("Plugin: " + ((Plugin)instance).name + " was not loaded, you can load it with /pload"); } Server.s.Log(((Plugin)instance).welcome); return; } catch (FileNotFoundException) { Plugin_Simple.Load(pluginname, startup); } catch (BadImageFormatException) { Plugin_Simple.Load(pluginname, startup); } catch (PathTooLongException) { } catch (FileLoadException) { Plugin_Simple.Load(pluginname, startup); } catch (Exception e) { try { Server.s.Log("Attempting a simple plugin!"); if (Plugin_Simple.Load(pluginname, startup)) { return; } } catch { } Server.ErrorLog(e); Server.s.Log("The plugin " + pluginname + " failed to load!"); if (creator != "") { Server.s.Log("You can go bug " + creator + " about it."); } Thread.Sleep(1000); } }
public static void Call(string cmd, string message) { events.ForEach( pl => { try { pl.method(cmd, message); } catch (Exception e) { Server.s.Log("Plugin " + pl.plugin.name + " errored when calling ConsoleCommand Event."); Server.ErrorLog(e); } }); }
//givenName is safe against SQL injections, it gets checked in CmdLoad.cs public static Level Load(string givenName, byte phys) { if (LevelLoad != null) { LevelLoad(givenName); } OnLevelLoadEvent.Call(givenName); if (cancelload) { cancelload = false; return(null); } CreateLeveldb(givenName); string path = LevelInfo.LevelPath(givenName); if (File.Exists(path)) { try { Level level = LvlFile.Load(givenName, path); level.setPhysics(phys); level.backedup = true; using (DataTable ZoneDB = Database.fillData("SELECT * FROM `Zone" + givenName + "`")) { Zone Zn; for (int i = 0; i < ZoneDB.Rows.Count; ++i) { DataRow row = ZoneDB.Rows[i]; Zn.smallX = ushort.Parse(row["SmallX"].ToString()); Zn.smallY = ushort.Parse(row["SmallY"].ToString()); Zn.smallZ = ushort.Parse(row["SmallZ"].ToString()); Zn.bigX = ushort.Parse(row["BigX"].ToString()); Zn.bigY = ushort.Parse(row["BigY"].ToString()); Zn.bigZ = ushort.Parse(row["BigZ"].ToString()); Zn.Owner = row["Owner"].ToString(); level.ZoneList.Add(Zn); } } level.jailx = (ushort)(level.spawnx * 32); level.jaily = (ushort)(level.spawny * 32); level.jailz = (ushort)(level.spawnz * 32); level.jailrotx = level.rotx; level.jailroty = level.roty; level.StartPhysics(); //level.physChecker.Elapsed += delegate //{ // if (!level.physicssate && level.physics > 0) // level.StartPhysics(); //}; //level.physChecker.Start(); try { DataTable foundDB = Database.fillData("SELECT * FROM `Portals" + givenName + "`"); for (int i = 0; i < foundDB.Rows.Count; ++i) { DataRow row = foundDB.Rows[i]; if ( !Block.portal(level.GetTile(ushort.Parse(row["EntryX"].ToString()), ushort.Parse(row["EntryY"].ToString()), ushort.Parse(row["EntryZ"].ToString())))) { Database.executeQuery("DELETE FROM `Portals" + givenName + "` WHERE EntryX=" + row["EntryX"] + " AND EntryY=" + row["EntryY"] + " AND EntryZ=" + row["EntryZ"]); } } foundDB = Database.fillData("SELECT * FROM `Messages" + givenName + "`"); for (int i = 0; i < foundDB.Rows.Count; ++i) { DataRow row = foundDB.Rows[i]; if ( !Block.mb(level.GetTile(ushort.Parse(row["X"].ToString()), ushort.Parse(row["Y"].ToString()), ushort.Parse(row["Z"].ToString())))) { //givenName is safe against SQL injections, it gets checked in CmdLoad.cs Database.executeQuery("DELETE FROM `Messages" + givenName + "` WHERE X=" + row["X"] + " AND Y=" + row["Y"] + " AND Z=" + row["Z"]); } } foundDB.Dispose(); } catch (Exception e) { Server.ErrorLog(e); } try { string propsPath = LevelInfo.GetPropertiesPath(level.name); if (propsPath != null) { LvlProperties.Load(level, propsPath); } else { Server.s.Log(".properties file for level " + level.name + " was not found."); } LvlProperties.LoadEnv(level, level.name); } catch (Exception e) { Server.ErrorLog(e); } BlockDefinition[] defs = BlockDefinition.Load(false, level); for (int i = 0; i < defs.Length; i++) { if (defs[i] == null) { continue; } level.CustomBlockDefs[i] = defs[i]; } Server.s.Log(string.Format("Level \"{0}\" loaded.", level.name)); if (LevelLoaded != null) { LevelLoaded(level); } OnLevelLoadedEvent.Call(level); return(level); } catch (Exception ex) { Server.ErrorLog(ex); return(null); } } Server.s.Log("ERROR loading level."); return(null); }
public static void Call(Player p, ushort x, ushort y, ushort z) { events.ForEach( pl => { try { pl.method(p, x, y, z); } catch (Exception e) { Server.s.Log("Plugin " + pl.plugin.name + " errored when calling PlayerMove Event."); Server.ErrorLog(e); } }); }
public static void Call() { events.ForEach( pl => { try { pl.method(); } catch (Exception e) { Server.s.Log("Plugin " + pl.plugin.name + " errored when calling GroupSave Event."); Server.ErrorLog(e); } }); }
bool SendRawMapCore(Level oldLevel, Level level) { if (level.blocks == null) { return(false); } bool success = true; useCheckpointSpawn = false; lastCheckpointIndex = -1; LevelAccess access = level.BuildAccess.Check(this); AllowBuild = access == LevelAccess.Whitelisted || access == LevelAccess.Allowed; try { if (hasBlockDefs) { if (oldLevel != null && oldLevel != level) { RemoveOldLevelCustomBlocks(oldLevel); } BlockDefinition.SendLevelCustomBlocks(this); } SendRaw(Opcode.LevelInitialise); using (LevelChunkStream s = new LevelChunkStream(this)) LevelChunkStream.CompressMap(this, s); byte[] buffer = new byte[7]; buffer[0] = Opcode.LevelFinalise; NetUtils.WriteI16((short)level.Width, buffer, 1); NetUtils.WriteI16((short)level.Height, buffer, 3); NetUtils.WriteI16((short)level.Length, buffer, 5); Send(buffer); AFKCooldown = DateTime.UtcNow.AddSeconds(2); Loading = false; if (HasCpeExt(CpeExt.EnvWeatherType)) { Send(Packet.EnvWeatherType((byte)level.Weather)); } if (HasCpeExt(CpeExt.EnvColors)) { SendCurrentEnvColors(); } SendCurrentMapAppearance(); if (HasCpeExt(CpeExt.BlockPermissions)) { SendCurrentBlockPermissions(); } if (OnSendMap != null) { OnSendMap(this, buffer); } if (!level.guns && aiming) { aiming = false; ClearBlockchange(); } } catch (Exception ex) { success = false; PlayerActions.ChangeMap(this, Server.mainLevel); SendMessage("There was an error sending the map data, you have been sent to the main level."); Server.ErrorLog(ex); } finally { GC.Collect(); GC.WaitForPendingFinalizers(); } return(success); }
public static void Call(Player p, ushort x, ushort y, ushort z, byte type, byte extType) { events.ForEach( pl => { try { pl.method(p, x, y, z, type, extType); } catch (Exception e) { Server.s.Log("Plugin " + pl.plugin.name + " errored calling BlockChange Event."); Server.ErrorLog(e); } }); }
/// <summary> Load a plugin </summary> /// <param name="name">The name of the plugin.</param> /// <param name="startup">Is this startup?</param> public static void Load(string name, bool startup) { string creator = ""; string path = "plugins/" + name + ".dll"; try { Plugin instance = null; byte[] data = File.ReadAllBytes(path); Assembly lib = Assembly.Load(data); try { foreach (Type t in lib.GetTypes()) { if (!t.IsSubclassOf(typeof(Plugin))) { continue; } instance = (Plugin)Activator.CreateInstance(t); break; } } catch { } if (instance == null) { Server.s.Log("The plugin " + name + " couldn't be loaded!"); return; } creator = instance.creator; string ver = instance.MCGalaxy_Version; if (!String.IsNullOrEmpty(ver) && new Version(ver) > Server.Version) { Server.s.Log("This plugin (" + instance.name + ") isn't compatible with this version of MCGalaxy!"); Thread.Sleep(1000); if (!Server.unsafe_plugin) { return; } Server.s.Log("Will attempt to load!"); } Plugin.all.Add(instance); if (instance.LoadAtStartup) { instance.Load(startup); Server.s.Log("Plugin: " + instance.name + " loaded...build: " + instance.build); } else { Server.s.Log("Plugin: " + instance.name + " was not loaded, you can load it with /pload"); } Server.s.Log(instance.welcome); } catch (Exception e) { Server.ErrorLog(e); Server.s.Log("The plugin " + name + " failed to load!"); if (creator != "") { Server.s.Log("You can go bug " + creator + " about it."); } Thread.Sleep(1000); } }
void DoLocationChecks() { while (true) { Thread.Sleep(3); Player[] players = PlayerInfo.Online.Items; for (int i = 0; i < players.Length; i++) { try { Player p = players[i]; if (p.frozen) { p.SendPos(0xFF, p.pos[0], p.pos[1], p.pos[2], p.rot[0], p.rot[1]); continue; } else if (p.following != "") { Player who = PlayerInfo.FindExact(p.following); if (who == null || who.level != p.level) { p.following = ""; if (!p.canBuild) { p.canBuild = true; } if (who != null && who.possess == p.name) { who.possess = ""; } continue; } if (p.canBuild) { p.SendPos(0xFF, who.pos[0], (ushort)(who.pos[1] - 16), who.pos[2], who.rot[0], who.rot[1]); } else { p.SendPos(0xFF, who.pos[0], who.pos[1], who.pos[2], who.rot[0], who.rot[1]); } } else if (p.possess != "") { Player who = PlayerInfo.Find(p.possess); if (who == null || who.level != p.level) { p.possess = ""; } } ushort x = (ushort)(p.pos[0] / 32); ushort y = (ushort)(p.pos[1] / 32); ushort z = (ushort)(p.pos[2] / 32); if (p.level.Death) { p.CheckSurvival(x, y, z); } p.CheckBlock(x, y, z); p.oldIndex = p.level.PosToInt(x, y, z); } catch (Exception e) { Server.ErrorLog(e); } } } }
public bool DoBlockchange(Player p, ushort x, ushort y, ushort z, byte block, byte extBlock = 0, bool drawn = false) { string errorLocation = "start"; retry: try { //if (x < 0 || y < 0 || z < 0) return; if (x >= Width || y >= Height || z >= Length) { return(false); } byte old = GetTile(x, y, z), extOld = 0; if (old == Block.custom_block) { extOld = GetExtTile(x, y, z); } errorLocation = "Permission checking"; if (!CheckAffectPermissions(p, x, y, z, old, block, extBlock)) { p.RevertBlock(x, y, z); return(false); } if (old == Block.sponge && physics > 0 && block != Block.sponge) { OtherPhysics.DoSpongeRemoved(this, PosToInt(x, y, z)); } if (old == Block.lava_sponge && physics > 0 && block != Block.lava_sponge) { OtherPhysics.DoSpongeRemoved(this, PosToInt(x, y, z), true); } errorLocation = "Undo buffer filling"; Player.UndoPos Pos; Pos.x = x; Pos.y = y; Pos.z = z; Pos.mapName = name; Pos.type = old; Pos.extType = extOld; Pos.newtype = block; Pos.newExtType = extBlock; Pos.timeDelta = (int)DateTime.UtcNow.Subtract(Server.StartTime).TotalSeconds; p.UndoBuffer.Add(this, Pos); errorLocation = "Setting tile"; p.IncrementBlockStats(block, drawn); SetTile(x, y, z, block); if (old == Block.custom_block && block != Block.custom_block) { RevertExtTileNoCheck(x, y, z); } if (block == Block.custom_block) { SetExtTileNoCheck(x, y, z, extBlock); } errorLocation = "Adding physics"; if (p.PlayingTntWars && block == Block.smalltnt) { AddTntCheck(PosToInt(x, y, z), p); } if (physics > 0 && ActivatesPhysics(block, extBlock)) { AddCheck(PosToInt(x, y, z)); } changed = true; backedup = false; bool diffBlock = old == Block.custom_block ? extOld != extBlock : Block.Convert(old) != Block.Convert(block); return(diffBlock); } catch (OutOfMemoryException) { Player.Message(p, "Undo buffer too big! Cleared!"); p.UndoBuffer.Clear(); p.RemoveInvalidUndos(); goto retry; } catch (Exception e) { Server.ErrorLog(e); Chat.MessageOps(p.name + " triggered a non-fatal error on " + ColoredName); Chat.MessageOps("Error location: " + errorLocation); Server.s.Log(p.name + " triggered a non-fatal error on " + ColoredName); Server.s.Log("Error location: " + errorLocation); return(false); } }
public static void Call(ushort x, ushort y, ushort z, PhysicsArgs extraInfo, Level l) { events.ForEach( pl => { try { pl.method(x, y, z, extraInfo, l); } catch (Exception e) { Server.s.Log("Plugin " + pl.plugin.name + " errored when calling PhysicsUpdate Event."); Server.ErrorLog(e); } }); }
void PhysicsLoop() { int wait = speedPhysics; while (true) { if (!PhysicsEnabled) { Thread.Sleep(500); continue; } try { if (wait > 0) { Thread.Sleep(wait); } if (physics == 0 || ListCheck.Count == 0) { lastCheck = 0; wait = speedPhysics; if (physics == 0) { break; } continue; } DateTime start = DateTime.UtcNow; if (physics > 0) { try { lock (physStepLock) CalcPhysics(); } catch (Exception ex) { Server.s.Log("Level physics error"); Server.ErrorLog(ex); } } TimeSpan delta = DateTime.UtcNow - start; wait = speedPhysics - (int)delta.TotalMilliseconds; if (wait < (int)(-overload * 0.75f)) { if (wait < -overload) { if (!Server.physicsRestart) { setPhysics(0); } ClearPhysics(); Chat.MessageAll("Physics shutdown on {0}", ColoredName); Server.s.Log("Physics shutdown on " + name); if (PhysicsStateChanged != null) { PhysicsStateChanged(this, PhysicsState.Stopped); } wait = speedPhysics; } else { Player[] online = PlayerInfo.Online.Items; foreach (Player p in online) { if (p.level != this) { continue; } Player.Message(p, "Physics warning!"); } Server.s.Log("Physics warning on " + name); if (PhysicsStateChanged != null) { PhysicsStateChanged(this, PhysicsState.Warning); } } } } catch { wait = speedPhysics; } } physThreadStarted = false; }
public void LeaveServer(string kickMsg, string discMsg, bool sync = false) { if (discMsg != null) { discMsg = Colors.EscapeColors(discMsg); } if (kickMsg != null) { kickMsg = Colors.EscapeColors(kickMsg); } OnPlayerDisconnectEvent.Call(this, discMsg ?? kickMsg); //Umm...fixed? if (name == "") { if (socket != null) { CloseSocket(); } connections.Remove(this); SaveUndo(this); disconnected = true; return; } Server.reviewlist.Remove(name); try { if (disconnected) { CloseSocket(); connections.Remove(this); return; } // FlyBuffer.Clear(); disconnected = true; SaveIgnores(); pingTimer.Stop(); pingTimer.Dispose(); afkTimer.Stop(); afkTimer.Dispose(); muteTimer.Stop(); muteTimer.Dispose(); timespent.Stop(); timespent.Dispose(); afkCount = 0; afkStart = DateTime.Now; Server.afkset.Remove(name); isFlying = false; aiming = false; SendKick(kickMsg, sync); if (!loggedIn) { connections.Remove(this); RemoveFromPending(); Server.s.Log(ip + " disconnected."); return; } Server.zombie.PlayerLeftServer(this); if (Game.team != null) { Game.team.RemoveMember(this); } Server.Countdown.PlayerLeftServer(this); TntWarsGame tntwarsgame = TntWarsGame.GetTntWarsGame(this); if (tntwarsgame != null) { tntwarsgame.Players.Remove(tntwarsgame.FindPlayer(this)); tntwarsgame.SendAllPlayersMessage("TNT Wars: " + color + name + Server.DefaultColor + " has left TNT Wars!"); } GlobalDespawn(this, false); if (discMsg != null) { if (!hidden) { string leavem = "&c- " + FullName + " %S" + discMsg; if ((Server.guestLeaveNotify && group.Permission <= LevelPermission.Guest) || group.Permission > LevelPermission.Guest) { Player[] players = PlayerInfo.Online.Items; foreach (Player pl in players) { Player.SendMessage(pl, leavem); } } } Server.s.Log(name + "disconnected (" + discMsg + ")."); } else { totalKicked++; SendChatFrom(this, "&c- " + color + prefix + DisplayName + " %Skicked (" + kickMsg + "%S).", false); Server.s.Log(name + " kicked (" + kickMsg + ")."); } try { save(); } catch (Exception e) { Server.ErrorLog(e); } PlayerInfo.Online.Remove(this); Server.s.PlayerListUpdate(); if (name != null) { left[name.ToLower()] = ip; } if (PlayerDisconnect != null) { PlayerDisconnect(this, discMsg ?? kickMsg); } if (Server.AutoLoad && level.unload && !level.IsMuseum && IsAloneOnCurrentLevel()) { level.Unload(true); } Dispose(); } catch (Exception e) { Server.ErrorLog(e); } finally { CloseSocket(); } }
public void CalcPhysics() { if (physics == 0) { return; } try { ushort x, y, z; lastCheck = ListCheck.Count; if (physics == 5) { for (int i = 0; i < ListCheck.Count; i++) { Check C = ListCheck.Items[i]; IntToPos(C.b, out x, out y, out z); try { if (PhysicsUpdate != null) { PhysicsUpdate(x, y, z, C.data, this); } if ((C.data.Raw & 0x3F) == 0 || ExtraInfoPhysics.DoDoorsOnly(this, ref C, null)) { Block.HandlePhysics handler = Block.physicsDoorsHandlers[blocks[C.b]]; if (handler != null) { handler(this, ref C); } else if ((C.data.Raw & 0x3F) == 0 || !C.data.HasWait) { C.data.Data = 255; } } ListCheck.Items[i] = C; } catch { listCheckExists.Set(x, y, z, false); ListCheck.RemoveAt(i); } } } else { for (int i = 0; i < ListCheck.Count; i++) { Check C = ListCheck.Items[i]; IntToPos(C.b, out x, out y, out z); try { if (PhysicsUpdate != null) { PhysicsUpdate(x, y, z, C.data, this); } if (OnPhysicsUpdateEvent.events.Count > 0) { OnPhysicsUpdateEvent.Call(x, y, z, C.data, this); } if ((C.data.Raw & 0x3F) == 0 || ExtraInfoPhysics.DoComplex(this, ref C)) { Block.HandlePhysics handler = Block.physicsHandlers[blocks[C.b]]; if (handler != null) { handler(this, ref C); } else if ((C.data.Raw & 0x3F) == 0 || !C.data.HasWait) { C.data.Data = 255; } } ListCheck.Items[i] = C; } catch { listCheckExists.Set(x, y, z, false); ListCheck.RemoveAt(i); } } } RemoveExpiredChecks(); lastUpdate = ListUpdate.Count; if (ListUpdate.Count > 0 && bulkSender == null) { bulkSender = new BufferedBlockSender(this); } for (int i = 0; i < ListUpdate.Count; i++) { Update C = ListUpdate.Items[i]; try { byte type = C.data.Data; C.data.Data = 0; if (DoPhysicsBlockchange(C.b, type, false, C.data, 0, true)) { bulkSender.Add(C.b, type, 0); } } catch { Server.s.Log("Phys update issue"); } bulkSender.CheckIfSend(false); } if (bulkSender != null) { bulkSender.CheckIfSend(true); } ListUpdate.Clear(); listUpdateExists.Clear(); } catch (Exception e) { Server.s.Log("Level physics error"); Server.ErrorLog(e); } }
public static void Call(Player p, string mysqlcommand) { events.ForEach( pl => { try { pl.method(p, mysqlcommand); } catch (Exception e) { Server.s.Log("Plugin " + pl.plugin.name + " errored when calling MySQLSave Event."); Server.ErrorLog(e); } }); }
void InitRest() { try { if (EnableHttpApi) { APIServer = new WebServer(SendResponse, "http://localhost:8080/api/"); APIServer.Run(); InfoServer = new WebServer(WhoIsResponse, "http://localhost:8080/whois/"); InfoServer.Run(); } } catch { Server.s.Log("Failed to start local API server"); } IRC = new ForgeBot(Server.ircChannel, Server.ircOpChannel, Server.ircNick, Server.ircServer); GlobalChat = new GlobalChatBot(GlobalChatNick()); if (Server.irc) { IRC.Connect(); } if (Server.UseGlobalChat) { GlobalChat.Connect(); } new AutoSaver(Server.backupInterval); blockThread = new Thread(DoBlockUpdates); blockThread.Name = "MCG_BlockUpdates"; blockThread.Start(); locationChecker = new Thread(DoLocationChecks); locationChecker.Name = "MCG_LocationCheck"; locationChecker.Start(); #if DEBUG UseTextures = true; #endif Log("Finished setting up server, finding classicube.net url.."); ServerSetupFinished = true; Checktimer.StartTimer(); Commands.CommandKeywords.SetKeyWords(); try { if (Server.lava.startOnStartup) { Server.lava.Start(); } if (ZombieGame.StartImmediately) { Server.zombie.Start(ZombieGameStatus.InfiniteRounds, 0); } //This doesnt use the main map if (Server.UseCTF) { ctf = new Auto_CTF(); } } catch (Exception e) { Server.ErrorLog(e); } BlockQueue.Start(); }
public static void Call(Player p, string message) { events.ForEach( pl => { try { pl.method(p, message); } catch (Exception e) { Server.s.Log("Plugin " + pl.plugin.name + " errored when calling PlayerChat Event."); Server.ErrorLog(e); } }); }
public static Level Load(string name, byte phys) { if (LevelLoad != null) { LevelLoad(name); } OnLevelLoadEvent.Call(name); if (cancelload) { cancelload = false; return(null); } string path = LevelInfo.LevelPath(name); if (!File.Exists(path)) { Server.s.Log("Attempted to load " + name + ", but the level file does not exist."); return(null); } try { Level level = IMapImporter.Formats[0].Read(path, name, true); level.setPhysics(phys); level.backedup = true; level.jailx = (ushort)(level.spawnx * 32); level.jaily = (ushort)(level.spawny * 32); level.jailz = (ushort)(level.spawnz * 32); level.jailrotx = level.rotx; level.jailroty = level.roty; level.StartPhysics(); try { string propsPath = LevelInfo.FindPropertiesFile(level.name); if (propsPath != null) { LvlProperties.Load(level, propsPath); } else { Server.s.Log(".properties file for level " + level.name + " was not found."); } // Backwards compatibility for older levels which had .env files. LvlProperties.LoadEnv(level); } catch (Exception e) { Server.ErrorLog(e); } level.BlockDB.Used = level.UseBlockDB; BlockDefinition[] defs = BlockDefinition.Load(false, level); for (int i = 0; i < defs.Length; i++) { if (defs[i] == null) { continue; } level.CustomBlockDefs[i] = defs[i]; level.CustomBlockProps[i] = new BlockProps((byte)i); } BlockProps.Load("lvl_" + level.name, level.CustomBlockProps); Bots.BotsFile.LoadBots(level); object locker = ThreadSafeCache.DBCache.Get(name); lock (locker) { LevelDB.LoadZones(level, name); LevelDB.LoadPortals(level, name); LevelDB.LoadMessages(level, name); } Server.s.Log(string.Format("Level \"{0}\" loaded.", level.name)); if (LevelLoaded != null) { LevelLoaded(level); } OnLevelLoadedEvent.Call(level); return(level); } catch (Exception ex) { Server.ErrorLog(ex); return(null); } }
public static void Call(Player p, byte[] rot) { events.ForEach( pl => { try { pl.method(p, rot); } catch (Exception e) { Server.s.Log("Plugin " + pl.plugin.name + " errored when calling PlayerRotate Event."); Server.ErrorLog(e); } }); }
public void Save(bool Override = false, bool clearPhysics = false) { if (blocks == null) { return; } string path = LevelInfo.LevelPath(name); if (LevelSave != null) { LevelSave(this); } OnLevelSaveEvent.Call(this); if (cancelsave1) { cancelsave1 = false; return; } if (cancelsave) { cancelsave = false; return; } try { if (!Directory.Exists("levels")) { Directory.CreateDirectory("levels"); } if (!Directory.Exists("levels/level properties")) { Directory.CreateDirectory("levels/level properties"); } if (changed || !File.Exists(path) || Override || (physicschanged && clearPhysics)) { if (clearPhysics) { ClearPhysics(); } if (File.Exists(path)) { if (File.Exists(path + ".prev")) { File.Delete(path + ".prev"); } File.Copy(path, path + ".prev"); File.Delete(path); } LvlFile.Save(this, path + ".backup"); File.Copy(path + ".backup", path); SaveSettings(this); Server.s.Log(string.Format("SAVED: Level \"{0}\". ({1}/{2}/{3})", name, players.Count, PlayerInfo.Online.Count, Server.players)); changed = false; } else { Server.s.Log("Skipping level save for " + name + "."); } } catch (OutOfMemoryException e) { Server.ErrorLog(e); if (Server.mono) { Process[] prs = Process.GetProcesses(); foreach (Process pr in prs) { if (pr.ProcessName == "MCGalaxy") { pr.Kill(); } } } else { Command.all.Find("restart").Use(null, ""); } } catch (Exception e) { Server.s.Log("FAILED TO SAVE :" + name); Player.GlobalMessage("FAILED TO SAVE :" + name); Server.ErrorLog(e); } GC.Collect(); GC.WaitForPendingFinalizers(); }
public static void Call(Player p, Group newRank) { events.ForEach( pl => { try { pl.method(p, newRank); } catch (Exception e) { Server.s.Log("Plugin " + pl.plugin.name + " errored when calling PlayerRankSet Event."); Server.ErrorLog(e); } }); }
internal bool DoBlockchange(Player p, ushort x, ushort y, ushort z, byte type, byte extType = 0) { string errorLocation = "start"; retry: try { //if (x < 0 || y < 0 || z < 0) return; if (x >= Width || y >= Height || z >= Length) { return(false); } byte b = GetTile(x, y, z), extB = 0; if (b == Block.custom_block) { extB = GetExtTile(x, y, z); } errorLocation = "Permission checking"; if (!CheckAffectPermissions(p, x, y, z, b, type, extType)) { p.RevertBlock(x, y, z); return(false); } if (b == Block.sponge && physics > 0 && type != Block.sponge) { OtherPhysics.DoSpongeRemoved(this, PosToInt(x, y, z)); } if (b == Block.lava_sponge && physics > 0 && type != Block.lava_sponge) { OtherPhysics.DoSpongeRemoved(this, PosToInt(x, y, z), true); } errorLocation = "Undo buffer filling"; Player.UndoPos Pos; Pos.x = x; Pos.y = y; Pos.z = z; Pos.mapName = name; Pos.type = b; Pos.extType = extB; Pos.newtype = type; Pos.newExtType = extType; Pos.timeDelta = (int)DateTime.UtcNow.Subtract(Server.StartTime).TotalSeconds; p.UndoBuffer.Add(this, Pos); errorLocation = "Setting tile"; p.loginBlocks++; p.overallBlocks++; SetTile(x, y, z, type); if (b == Block.custom_block && type != Block.custom_block) { RevertExtTileNoCheck(x, y, z); } if (type == Block.custom_block) { SetExtTileNoCheck(x, y, z, extType); } errorLocation = "Adding physics"; if (p.PlayingTntWars && type == Block.smalltnt) { AddTntCheck(PosToInt(x, y, z), p); } if (physics > 0 && Block.Physics(type)) { AddCheck(PosToInt(x, y, z)); } changed = true; backedup = false; bool diffBlock = b == Block.custom_block ? extB != extType : Block.Convert(b) != Block.Convert(type); return(diffBlock); } catch (OutOfMemoryException) { Player.SendMessage(p, "Undo buffer too big! Cleared!"); p.UndoBuffer.Clear(); p.RemoveInvalidUndos(); goto retry; } catch (Exception e) { Server.ErrorLog(e); Chat.GlobalMessageOps(p.name + " triggered a non-fatal error on " + name); Chat.GlobalMessageOps("Error location: " + errorLocation); Server.s.Log(p.name + " triggered a non-fatal error on " + name); Server.s.Log("Error location: " + errorLocation); return(false); } }