コード例 #1
0
ファイル: Server.cs プロジェクト: CrusaderV/MCForge-Vanilla
        public void Start()
        {
            shuttingDown = false;
            Log("Starting Server");

            if (!Directory.Exists("properties")) Directory.CreateDirectory("properties");
            if (!Directory.Exists("bots")) Directory.CreateDirectory("bots");
            if (!Directory.Exists("text")) Directory.CreateDirectory("text");

            if (!Directory.Exists("extra")) Directory.CreateDirectory("extra");
            if (!Directory.Exists("extra/undo")) Directory.CreateDirectory("extra/undo");
            if (!Directory.Exists("extra/undoPrevious")) Directory.CreateDirectory("extra/undoPrevious");
            if (!Directory.Exists("extra/copy/")) { Directory.CreateDirectory("extra/copy/"); }
            if (!Directory.Exists("extra/copyBackup/")) { Directory.CreateDirectory("extra/copyBackup/"); }

            try
            {
                if (File.Exists("server.properties")) File.Move("server.properties", "properties/server.properties");
                if (File.Exists("rules.txt")) File.Move("rules.txt", "text/rules.txt");
                if (File.Exists("welcome.txt")) File.Move("welcome.txt", "text/welcome.txt");
                if (File.Exists("messages.txt")) File.Move("messages.txt", "text/messages.txt");
                if (File.Exists("externalurl.txt")) File.Move("externalurl.txt", "text/externalurl.txt");
                if (File.Exists("autoload.txt")) File.Move("autoload.txt", "text/autoload.txt");
                if (File.Exists("IRC_Controllers.txt")) File.Move("IRC_Controllers.txt", "ranks/IRC_Controllers.txt");
                if (Server.useWhitelist) if (File.Exists("whitelist.txt")) File.Move("whitelist.txt", "ranks/whitelist.txt");
            }
            catch { }

            if (File.Exists("text/custom$s.txt"))
            {
                using (StreamReader r = new StreamReader("text/custom$s.txt"))
                {
                    string line;
                    while ((line = r.ReadLine()) != null)
                    {
                        if (!line.StartsWith("//"))
                        {
                            var split = line.Split(new char[] { ':' }, 2);
                            if (split.Length == 2 && !String.IsNullOrEmpty(split[0]))
                            {
                                customdollars.Add(split[0], split[1]);
                            }
                        }
                    }
                }
            }
            else
            {
                Log("custom$s.txt does not exist, creating");
                using (StreamWriter SW = File.CreateText("text/custom$s.txt"))
                {
                    SW.WriteLine("// This is used to create custom $s");
                    SW.WriteLine("// If you start the line with a // it wont be used");
                    SW.WriteLine("// It should be formatted like this:");
                    SW.WriteLine("// $website:mcforge.net");
                    SW.WriteLine("// That would replace '$website' in any message to 'mcforge.net'");
                    SW.WriteLine("// It must not start with a // and it must not have a space between the 2 sides and the colon (:)");
                    SW.Close();
                }
            }

            Properties.Load("properties/server.properties");
            Updater.Load("properties/update.properties");

            Group.InitAll();
            Command.InitAll();
            GrpCommands.fillRanks();
            Block.SetBlocks();
            Awards.Load();

            if (File.Exists("text/emotelist.txt"))
            {
                foreach (string s in File.ReadAllLines("text/emotelist.txt"))
                {
                    Player.emoteList.Add(s);
                }
            }
            else
            {
                File.Create("text/emotelist.txt");
            }

            ProfanityFilter.Init();

            timeOnline = DateTime.Now;

            try
            {
                MySQL.executeQuery("CREATE DATABASE if not exists `" + MySQLDatabaseName + "`", true);
            }
            catch (Exception e)
            {
                Server.s.Log("MySQL settings have not been set! Please reference the MySQL_Setup.txt file on setting up MySQL!");
                Server.ErrorLog(e);
                //process.Kill();
                return;
            }

            MySQL.executeQuery("CREATE TABLE if not exists Players (ID MEDIUMINT not null auto_increment, Name VARCHAR(20), IP CHAR(15), FirstLogin DATETIME, LastLogin DATETIME, totalLogin MEDIUMINT, Title CHAR(20), TotalDeaths SMALLINT, Money MEDIUMINT UNSIGNED, totalBlocks BIGINT, totalKicked MEDIUMINT, color VARCHAR(6), title_color VARCHAR(6), PRIMARY KEY (ID));");

            // Check if the color column exists.
            DataTable colorExists = MySQL.fillData("SHOW COLUMNS FROM Players WHERE `Field`='color'");

            if (colorExists.Rows.Count == 0)
            {
                MySQL.executeQuery("ALTER TABLE Players ADD COLUMN color VARCHAR(6) AFTER totalKicked");
            }
            colorExists.Dispose();

            // Check if the title color column exists.
            DataTable tcolorExists = MySQL.fillData("SHOW COLUMNS FROM Players WHERE `Field`='title_color'");

            if (tcolorExists.Rows.Count == 0)
            {
                MySQL.executeQuery("ALTER TABLE Players ADD COLUMN title_color VARCHAR(6) AFTER color");
            }
            tcolorExists.Dispose();

            if (levels != null)
                foreach (Level l in levels) { l.Unload(); }
            ml.Queue(delegate
            {
                try
                {
                    levels = new List<Level>(Server.maps);
                    MapGen = new MapGenerator();

                    Random random = new Random();

                    if (File.Exists("levels/" + Server.level + ".lvl"))
                    {
                        mainLevel = Level.Load(Server.level);
                        mainLevel.unload = false;
                        if (mainLevel == null)
                        {
                            if (File.Exists("levels/" + Server.level + ".lvl.backup"))
                            {
                                Log("Attempting to load backup.");
                                File.Copy("levels/" + Server.level + ".lvl.backup", "levels/" + Server.level + ".lvl", true);
                                mainLevel = Level.Load(Server.level);
                                if (mainLevel == null)
                                {
                                    Log("BACKUP FAILED!");
                                    Console.ReadLine(); return;
                                }
                            }
                            else
                            {
                                Log("mainlevel not found");
                                mainLevel = new Level(Server.level, 128, 64, 128, "flat");

                                mainLevel.permissionvisit = LevelPermission.Guest;
                                mainLevel.permissionbuild = LevelPermission.Guest;
                                mainLevel.Save();
                            }
                        }
                    }
                    else
                    {
                        Log("mainlevel not found");
                        mainLevel = new Level(Server.level, 128, 64, 128, "flat");

                        mainLevel.permissionvisit = LevelPermission.Guest;
                        mainLevel.permissionbuild = LevelPermission.Guest;
                        mainLevel.Save();
                    }

                    addLevel(mainLevel);

                    // fenderrock - Make sure the level does have a physics thread
                    if (mainLevel.physThread == null)
                        mainLevel.physThread = new Thread(new ThreadStart(mainLevel.Physics));

                    mainLevel.physThread.Start();
                }
                catch (Exception e) { Server.ErrorLog(e); }
            });

            ml.Queue(delegate
            {
                bannedIP = PlayerList.Load("banned-ip.txt", null);
                ircControllers = PlayerList.Load("IRC_Controllers.txt", null);
                muted = PlayerList.Load("muted.txt", null);

                foreach (Group grp in Group.GroupList)
                    grp.playerList = PlayerList.Load(grp.fileName, grp);
                if (Server.useWhitelist)
                    whiteList = PlayerList.Load("whitelist.txt", null);
            });

            ml.Queue(delegate
            {
                if (File.Exists("text/autoload.txt"))
                {
                    try
                    {
                        string[] lines = File.ReadAllLines("text/autoload.txt");
                        foreach (string line in lines)
                        {
                            //int temp = 0;
                            string _line = line.Trim();
                            try
                            {
                                if (_line == "") { continue; }
                                if (_line[0] == '#') { continue; }
                                int index = _line.IndexOf("=");

                                string key = _line.Split('=')[0].Trim();
                                string value;
                                try
                                {
                                    value = _line.Split('=')[1].Trim();
                                }
                                catch
                                {
                                    value = "0";
                                }

                                if (!key.Equals(mainLevel.name))
                                {
                                    Command.all.Find("load").Use(null, key + " " + value);
                                    Level l = Level.FindExact(key);
                                }
                                else
                                {
                                    try
                                    {
                                        int temp = int.Parse(value);
                                        if (temp >= 0 && temp <= 3)
                                        {
                                            mainLevel.setPhysics(temp);
                                        }
                                    }
                                    catch
                                    {
                                        Server.s.Log("Physics variable invalid");
                                    }
                                }

                            }
                            catch
                            {
                                Server.s.Log(_line + " failed.");
                            }
                        }
                    }
                    catch
                    {
                        Server.s.Log("autoload.txt error");
                    }
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                }
                else
                {
                    Log("autoload.txt does not exist");
                }
            });

            ml.Queue(delegate
            {
                Log("Creating listening socket on port " + Server.port + "... ");
                if (Setup())
                {
                    s.Log("Done.");
                }
                else
                {
                    s.Log("Could not create socket connection.  Shutting down.");
                    return;
                }
            });

            ml.Queue(delegate
            {
                updateTimer.Elapsed += delegate
                {
                    Player.GlobalUpdate();
                    PlayerBot.GlobalUpdatePosition();
                };

                updateTimer.Start();
            });

            // Heartbeat code here:

            ml.Queue(delegate
            {
                try
                {
                    Heart.Init();
                }
                catch (Exception e)
                {
                    Server.ErrorLog(e);
                }
            });

            // END Heartbeat code

            /*
            Thread processThread = new Thread(new ThreadStart(delegate
            {
                try
                {
                    PCCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
                    ProcessCounter = new PerformanceCounter("Process", "% Processor Time", Process.GetCurrentProcess().ProcessName);
                    PCCounter.BeginInit();
                    ProcessCounter.BeginInit();
                    PCCounter.NextValue();
                    ProcessCounter.NextValue();
                }
                catch { }
            }));
            processThread.Start();
            */

            ml.Queue(delegate
            {
                messageTimer.Elapsed += delegate
                {
                    RandomMessage();
                };
                messageTimer.Start();

                process = System.Diagnostics.Process.GetCurrentProcess();

                if (File.Exists("text/messages.txt"))
                {
                    StreamReader r = File.OpenText("text/messages.txt");
                    while (!r.EndOfStream)
                        messages.Add(r.ReadLine());
                    r.Dispose();
                }
                else File.Create("text/messages.txt").Close();

                if (Server.irc)
                {
                    new IRCBot();
                }

                //      string CheckName = "FROSTEDBUTTS";

                //       if (Server.name.IndexOf(CheckName.ToLower())!= -1){ Server.s.Log("FROSTEDBUTTS DETECTED");}
                new AutoSaver(Server.backupInterval);     //2 and a half mins

                blockThread = new Thread(new ThreadStart(delegate
                {
                    while (true)
                    {
                        Thread.Sleep(blockInterval * 1000);
                        foreach (Level l in levels)
                        {
                            try
                            {
                                l.saveChanges();
                            }
                            catch (Exception e)
                            {
                                Server.ErrorLog(e);
                            }
                        }
                    }
                }));
                blockThread.Start();

                locationChecker = new Thread(new ThreadStart(delegate
                {
                    while (true)
                    {
                        Thread.Sleep(3);
                        for (int i = 0; i < Player.players.Count; i++)
                        {
                            try
                            {
                                Player p = Player.players[i];

                                if (p.frozen)
                                {
                                    unchecked { p.SendPos((byte)-1, p.pos[0], p.pos[1], p.pos[2], p.rot[0], p.rot[1]); } continue;
                                }
                                else if (p.following != "")
                                {
                                    Player who = Player.Find(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)
                                    {
                                        unchecked { p.SendPos((byte)-1, who.pos[0], (ushort)(who.pos[1] - 16), who.pos[2], who.rot[0], who.rot[1]); }
                                    }
                                    else
                                    {
                                        unchecked { p.SendPos((byte)-1, who.pos[0], who.pos[1], who.pos[2], who.rot[0], who.rot[1]); }
                                    }
                                }
                                else if (p.possess != "")
                                {
                                    Player who = Player.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.RealDeath(x, y, z);
                                p.CheckBlock(x, y, z);

                                p.oldBlock = (ushort)(x + y + z);
                            }
                            catch (Exception e) { Server.ErrorLog(e); }
                        }
                    }
                }));

                locationChecker.Start();
                Log("Finished setting up server");
            });
        }
コード例 #2
0
ファイル: CmdNewLvl.cs プロジェクト: Nerketur/MCForge-Vanilla
        public override void Use(Player p, string message)
        {
            if (message == "") { Help(p); return; }

            string[] parameters = message.Split(' '); // Grab the parameters from the player's message
            if (parameters.Length >= 5 && parameters.Length <= 6) // make sure there are 5 or 6 params
            {
                switch (parameters[4])
                {
                    case "flat":
                    case "pixel":
                    case "island":
                    case "mountains":
                    case "ocean":
                    case "forest":
                    case "desert":
                    case "space":
                    case "rainbow":
                    case "hell":
                    case "nether":
                        break;

                    default:
                        Player.SendMessage(p, "Valid types: island, mountains, forest, ocean, flat, pixel, desert, space, rainbow, and hell/nether"); return;
                }

                string name = parameters[0].ToLower();
                ushort x = 1, y = 1, z = 1;
                int seed = 0;
                bool useSeed = false;
                try
                {
                    x = Convert.ToUInt16(parameters[1]);
                    y = Convert.ToUInt16(parameters[2]);
                    z = Convert.ToUInt16(parameters[3]);
                }
                catch { Player.SendMessage(p, "Invalid dimensions."); return; }
                if (parameters.Length == 6)
                {
                    try { seed = Convert.ToInt32(parameters[5]); }
                    catch { seed = parameters[5].GetHashCode(); }
                    useSeed = true;
                }
                if (!isGood(x)) { Player.SendMessage(p, x + " is not a good dimension! Use a power of 2 next time."); }
                if (!isGood(y)) { Player.SendMessage(p, y + " is not a good dimension! Use a power of 2 next time."); }
                if (!isGood(z)) { Player.SendMessage(p, z + " is not a good dimension! Use a power of 2 next time."); }

                if (!Player.ValidName(name)) { Player.SendMessage(p, "Invalid name!"); return; }
                if (System.IO.File.Exists("levels/" + name + ".lvl")) { Player.SendMessage(p, "Level \"" + name + "\" already exists!"); return; }

                /*try
                {
                    if (p != null)
                    if (p.group.Permission < LevelPermission.Admin)
                    {
                        if (x * y * z > 30000000) { Player.SendMessage(p, "Cannot create a map with over 30million blocks"); return; }
                    }
                    else
                    {
                        if (x * y * z > 225000000) { Player.SendMessage(p, "You cannot make a map with over 225million blocks"); return; }
                    }
                }
                catch
                {
                    Player.SendMessage(p, "An error occured");
                }*/

                // create a new level...
                try
                {
                    using (Level lvl = new Level(name, x, y, z, parameters[4], seed, useSeed))
                    {
                        lvl.Save(true); //... and save it.
                        lvl.Dispose(); // Then take out the garbage.
                    }
                }
                finally
                {
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                }
                Player.GlobalMessage("Level \"" + name + "\" created" + (useSeed ? " with seed \"" + parameters[5] + "\"" : "")); // The player needs some form of confirmation.

            }
            else
                Help(p);
        }
コード例 #3
0
ファイル: CmdNewLvl.cs プロジェクト: Cazzar/MCaznowl-Build
        public override void Use(Player p, string message)
        {
            //if (message == "") { Help(p); return; }

            string[] parameters = { p.name, "64", "64", "64", "flat" }; // message.Split(' '); // Grab the parameters from the player's message
            if (p != null)
            {
                if (p.group.Permission <= LevelPermission.Operator)
                {
                    //some advanced coding for more custom params defaults will be player.name 64 64 64 flat user can specify the own params
                    string[] parameters2 = message.Split(' ');

                    switch (message.Split(' ').Length)
                    {
                        case 0:
                            //attempted workaround for "invalid dimensions"
                            parameters[1] = "64";
                            parameters[2] = "64";
                            parameters[3] = "64";
                            parameters[4] = "flat";
                            break;
                        case 1:
                            //set width to be first param
                            parameters[1] = parameters2[0];
                            break;
                        case 2:
                            //set width to be first param
                            parameters[1] = parameters2[0];
                            //set height to be 2nd param
                            parameters[2] = parameters2[1];
                            break;
                        case 3:
                            //set width to be first param
                            parameters[1] = parameters2[0];
                            //set height to be 2nd param
                            parameters[2] = parameters2[1];
                            //set depth to be 3rd param
                            parameters[3] = parameters2[2];
                            break;
                        case 4:
                            //set width to be first param
                            parameters[1] = parameters2[0];
                            //set height to be 2nd param
                            parameters[2] = parameters2[1];
                            //set depth to be 3rd param
                            parameters[3] = parameters2[2];
                            //set level type to be 4th param
                            parameters[4] = parameters2[3];
                            break;
                        case 5:
                            //set width to be first param
                            parameters[1] = parameters2[0];
                            //set height to be 2nd param
                            parameters[2] = parameters2[1];
                            //set depth to be 3rd param
                            parameters[3] = parameters2[2];
                            //set level type to be 4th param
                            parameters[4] = parameters2[3];
                            //set level seed to be last param
                            parameters[5] = parameters2[4];
                            break;
                        default:
                            Player.SendMessage(p, "Too many parameters");
                            Help(p);
                            return;
                    }
                }
                else { parameters = message.Split(' '); }
            }
            else { parameters = message.Split(' '); }
            if (parameters.Length >= 5 && parameters.Length <= 6) // make sure there are 5 or 6 params
            {
                switch (parameters[4])
                {
                    case "flat":
                    case "pixel":
                    case "island":
                    case "mountains":
                    case "ocean":
                    case "forest":
                    case "desert":
                    case "space":
                    case "rainbow":
                    case "hell":
                        break;

                    default:
                        Player.SendMessage(p, "Valid types: island, mountains, forest, ocean, flat, pixel, desert, space, rainbow, and hell"); return;
                }

                string name = parameters[0].ToLower();
                int mapnumber = 0;
                ushort x = 1, y = 1, z = 1;
                int seed = 0;
                bool useSeed = false;
                try
                {
                    x = Convert.ToUInt16(parameters[1]);
                    y = Convert.ToUInt16(parameters[2]);
                    z = Convert.ToUInt16(parameters[3]);
                }
                catch { Player.SendMessage(p, "Invalid dimensions."); return; }
                if (parameters.Length == 6)
                {
                    try { seed = Convert.ToInt32(parameters[5]); }
                    catch { seed = parameters[5].GetHashCode(); }
                    useSeed = true;
                }
                if (!isGood(x)) { Player.SendMessage(p, x + " is not a good dimension! Use a power of 2 next time."); }
                if (!isGood(y)) { Player.SendMessage(p, y + " is not a good dimension! Use a power of 2 next time."); }
                if (!isGood(z)) { Player.SendMessage(p, z + " is not a good dimension! Use a power of 2 next time."); }

                if (!Player.ValidName(name)) { Player.SendMessage(p, "Invalid name!"); return; }
                //if (System.IO.File.Exists("levels/" + name + ".lvl")) { Player.SendMessage(p, "Level \"" + name + "\" already exists!"); return; }

                StringBuilder dir = new StringBuilder("levels/" + name);
                dir.Append(mapnumber != 0 ? "." + mapnumber.ToString() : "");
                dir.Append(".lvl");

                while (System.IO.File.Exists(dir.ToString()))
                {
                    if (p != null)
                    {
                        if (mapnumber < p.GetMaxMaps())
                        {
                            Server.s.Log(mapnumber.ToString());
                            Server.s.Log(dir.ToString());
                            Server.s.Log(p.GetMaxMaps().ToString());
                            mapnumber++;
                            dir = null;
                            dir = new StringBuilder("levels/" + name);
                            dir.Append(mapnumber != 0 ? "." + mapnumber.ToString() : "");
                            dir.Append(".lvl");
                        }
                        else { Player.SendMessage(p, "You have used up your maps!"); return; }
                    }
                    else { Player.SendMessage(p, "Level \"" + name + "\" already exists!"); return; }
                }

                name = name + "." + mapnumber.ToString();

                /*retry:
                StringBuilder dir = new StringBuilder("levels/" + name);
                dir.Append(mapnumber != 0 ? "." + mapnumber.ToString() : "");
                dir.Append(".lvl");
                if (System.IO.File.Exists(dir.ToString()))
                {
                    if (p != null)
                    {
                        if (mapnumber <= p.GetMaxMaps())
                        {
                            mapnumber++;
                            goto retry;
                        }
                        else { Player.SendMessage(p, "You have used up your maps!"); return; }
                    }
                    else { Player.SendMessage(p, "Level \"" + name + "\" already exists!"); return; }
                }*/

                /*try
                {
                    if (p != null)
                    if (p.group.Permission < LevelPermission.Admin)
                    {
                        if (x * y * z > 30000000) { Player.SendMessage(p, "Cannot create a map with over 30million blocks"); return; }
                    }
                    else
                    {
                        if (x * y * z > 225000000) { Player.SendMessage(p, "You cannot make a map with over 225million blocks"); return; }
                    }
                }
                catch
                {
                    Player.SendMessage(p, "An error occured");
                }*/

                // create a new level...
                try
                {
                    using (Level lvl = new Level(name, x, y, z, parameters[4], seed, useSeed))
                    {
                        lvl.Save(true); //... and save it.
                        lvl.Dispose(); // Then take out the garbage.
                    }
                }
                finally
                {
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                }
                Player.GlobalMessage("Level \"" + name + "\" created" + (useSeed ? " with seed \"" + parameters[5] + "\"" : "")); // The player needs some form of confirmation.

            }
            else
                Help(p);
        }
コード例 #4
0
        public override void Use(Player p, string message)
        {
            if (message == "") { Help(p); return; }

            string[] parameters = message.Split(' '); // Grab the parameters from the player's message
            if (parameters.Length == 5) // make sure there are 5 params
            {
                switch (parameters[4])
                {
                    case "flat":
                    case "pixel":
                    case "island":
                    case "mountains":
                    case "ocean":
                    case "forest":
                    case "desert":
                    case "space":
                        break;

                    default:
                        Player.SendMessage(p, "Valid types: island, mountains, forest, ocean, flat, pixel, desert, space"); return;
                }

                string name = parameters[0].ToLower();
                ushort x = 1, y = 1, z = 1;
                try
                {
                    x = Convert.ToUInt16(parameters[1]);
                    y = Convert.ToUInt16(parameters[2]);
                    z = Convert.ToUInt16(parameters[3]);
                }
                catch { Player.SendMessage(p, "Invalid dimensions."); return; }
                if (!isGood(x)) { Player.SendMessage(p, x + " is not a good dimension! Use a power of 2 next time."); }
                if (!isGood(y)) { Player.SendMessage(p, y + " is not a good dimension! Use a power of 2 next time."); }
                if (!isGood(z)) { Player.SendMessage(p, z + " is not a good dimension! Use a power of 2 next time."); }

                if (!Player.ValidName(name)) { Player.SendMessage(p, "Invalid name!"); return; }

                try
                {
                    if (p != null)
                    if (p.group.Permission < LevelPermission.Admin)
                    {
                        if (x * y * z > 30000000) { Player.SendMessage(p, "Cannot create a map with over 30million blocks"); return; }
                    }
                    else
                    {
                        if (x * y * z > 225000000) { Player.SendMessage(p, "You cannot make a map with over 225million blocks"); return; }
                    }
                }
                catch
                {
                    Player.SendMessage(p, "An error occured");
                }

                // create a new level...
                try
                {
                    using(Level lvl = new Level(name, x, y, z, parameters[4]))
                        lvl.Save(true); //... and save it.
                }
                finally
                {
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                }
                Player.GlobalMessage("Level " + name + " created"); // The player needs some form of confirmation.
            }
            else
                Help(p);
        }
コード例 #5
0
        public static Level Load(Stream lvlStream, string fileName)
        {
            byte[] temp = new byte[8];
            using (Level lvl = new Level(fileName, 0, 0, 0, "empty"))
            {
                byte[] data;
                int length;
                try
                {
                    lvlStream.Seek(-4, SeekOrigin.End);
                    lvlStream.Read(temp, 0, sizeof(int));
                    lvlStream.Seek(0, SeekOrigin.Begin);
                    length = BitConverter.ToInt32(temp, 0);
                    data = new byte[length];
                    using (GZipStream reader = new GZipStream(lvlStream, CompressionMode.Decompress, true))
                    {
                        reader.Read(data, 0, length);
                    }

                    for (int i = 0; i < length - 1; i++)
                    {
                        if (data[i] == 0xAC && data[i + 1] == 0xED)
                        {

                            // bypassing the header crap
                            int pointer = i + 6;
                            Array.Copy(data, pointer, temp, 0, sizeof(short));
                            pointer += IPAddress.HostToNetworkOrder(BitConverter.ToInt16(temp, 0));
                            pointer += 13;

                            int headerEnd = 0;
                            // find the end of serialization listing
                            for (headerEnd = pointer; headerEnd < data.Length - 1; headerEnd++)
                            {
                                if (data[headerEnd] == 0x78 && data[headerEnd + 1] == 0x70)
                                {
                                    headerEnd += 2;
                                    break;
                                }
                            }

                            // start parsing serialization listing
                            int offset = 0;
                            while (pointer < headerEnd)
                            {
                                if (data[pointer] == 'Z') offset++;
                                else if (data[pointer] == 'I' || data[pointer] == 'F') offset += 4;
                                else if (data[pointer] == 'J') offset += 8;

                                pointer += 1;
                                Array.Copy(data, pointer, temp, 0, sizeof(short));
                                short skip = IPAddress.HostToNetworkOrder(BitConverter.ToInt16(temp, 0));
                                pointer += 2;

                                // look for relevant variables
                                Array.Copy(data, headerEnd + offset - 4, temp, 0, sizeof(int));
                                if (MemCmp(data, pointer, "width"))
                                {
                                    lvl.width = (ushort)IPAddress.HostToNetworkOrder(BitConverter.ToInt32(temp, 0));
                                }
                                else if (MemCmp(data, pointer, "depth"))
                                {
                                    lvl.depth = (ushort)IPAddress.HostToNetworkOrder(BitConverter.ToInt32(temp, 0));
                                }
                                else if (MemCmp(data, pointer, "height"))
                                {
                                    lvl.height = (ushort)IPAddress.HostToNetworkOrder(BitConverter.ToInt32(temp, 0));
                                }

                                pointer += skip;
                            }

                            lvl.spawnx = (ushort)(lvl.width / 1.3);
                            lvl.spawny = (ushort)(lvl.depth / 1.3);
                            lvl.spawnz = (ushort)(lvl.height / 1.3);

                            // find the start of the block array
                            bool foundBlockArray = false;
                            offset = Array.IndexOf<byte>(data, 0x00, headerEnd);
                            while (offset != -1 && offset < data.Length - 2)
                            {
                                if (data[offset] == 0x00 && data[offset + 1] == 0x78 && data[offset + 2] == 0x70)
                                {
                                    foundBlockArray = true;
                                    pointer = offset + 7;
                                }
                                offset = Array.IndexOf<byte>(data, 0x00, offset + 1);
                            }

                            // copy the block array... or fail
                            if (foundBlockArray)
                            {
                                lvl.CopyBlocks(data, pointer);
                                lvl.Save(true);
                            }
                            else
                            {
                                throw new Exception("Could not locate block array.");
                            }
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Server.s.Log("Conversion failed");
                    Server.ErrorLog(ex);
                    return null;
                }

                return lvl;
            }
        }
コード例 #6
0
ファイル: CmdNewLvl.cs プロジェクト: WanX/MCaznowl-Build
        public override void Use(Player p, string message)
        {
            if (Server.LevelExists(p.name)) { Player.SendMessage(p, "Your level already exists! use /deletelvl confirm to delete your level"); return; }
            ushort x = 1, y = 1, z = 1;
            bool usePixel = false;
            int num = message.Split(' ').Length;
            if (num >= 1)
            {
                string[] strings = message.Split(' ');

                for (int i = 0; i < num; i++)
                {
                    strings[i] = strings[i].ToLower();
                }

                if (strings[0].Equals(""))
                {
                    try
                    {
                        x = Convert.ToUInt16(64);
                        y = Convert.ToUInt16(64);
                        z = Convert.ToUInt16(64);
                    }
                    catch { }
                }
                else
                {
                    string Str = strings[0];

                    double Num;

                    bool isNum = double.TryParse(Str, out Num);

                    if (isNum)
                    {
                        if (Str == "1")
                        {
                            try
                            {
                                x = Convert.ToUInt16(128);
                                y = Convert.ToUInt16(64);
                                z = Convert.ToUInt16(128);
                            }
                            catch { }
                            if (num >= 2)
                            {
                                usePixel = true;
                            }
                        }
                        else if (Str == "2")
                        {
                            try
                            {
                                x = Convert.ToUInt16(128);
                                y = Convert.ToUInt16(128);
                                z = Convert.ToUInt16(128);
                            }
                            catch { }
                            if (num >= 2)
                            {
                                usePixel = true;
                            }
                        }
                        else
                        {
                            try
                            {
                                x = Convert.ToUInt16(64);
                                y = Convert.ToUInt16(64);
                                z = Convert.ToUInt16(64);
                            }
                            catch { }
                            if (num >= 2)
                            {
                                usePixel = true;
                            }
                        }
                    }
                    else if (strings[0] == "pixel")
                    {
                        try
                        {
                            x = Convert.ToUInt16(64);
                            y = Convert.ToUInt16(64);
                            z = Convert.ToUInt16(64);
                        }
                        catch { }
                        usePixel = true;
                    }
                    else
                    {
                        Help(p);
                        return;
                    }
                }
            }
            else
            {
                try
                {
                    x = Convert.ToUInt16(64);
                    y = Convert.ToUInt16(64);
                    z = Convert.ToUInt16(64);
                }
                catch { }
            }
            string name = p.name.ToLower();

            // create a new level...
            try
            {
                if (usePixel)
                {
                    using (Level lvl = new Level(name, x, y, z, "pixel"))
                    {
                        lvl.permissionbuild = LevelPermission.Guest;
                        lvl.Save(true); //... and save it.
                    }
                }
                else
                {
                    using (Level lvl = new Level(name, x, y, z, "flat"))
                    {
                        lvl.permissionbuild = LevelPermission.Guest;
                        lvl.Save(true); //... and save it.
                    }
                }

            }
            finally
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            Player.GlobalMessage(p.group.color + p.name + Server.DefaultColor + " created a new level!");
            Command.all.Find("load").Use(p, p.name);
            Command.all.Find("goto").Use(p, p.name);
        }