예제 #1
0
 public override void Execute(CommandEntry entry)
 {
     if (entry.Arguments.Count < 1)
     {
         ShowUsage(entry);
     }
     else
     {
         string modechoice = entry.GetArgument(0);
         switch (modechoice.ToLower())
         {
             case "full":
                 entry.Queue.Debug = DebugMode.FULL;
                 entry.Good("Queue debug mode set to <{color.emphasis}>full<{color.base}>.");
                 break;
             case "minimal":
                 entry.Queue.Debug = DebugMode.MINIMAL;
                 entry.Good("Queue debug mode set to <{color.emphasis}>minimal<{color.base}>.");
                 break;
             case "none":
                 entry.Queue.Debug = DebugMode.NONE;
                 entry.Good("Queue debug mode set to <{color.emphasis}>none<{color.base}>.");
                 break;
             default:
                 entry.Bad("Unknown debug mode '<{color.emphasis}>" + modechoice + "<{color.base}>'.");
                 break;
         }
     }
 }
예제 #2
0
 public override void Execute(CommandQueue queue, CommandEntry entry)
 {
     PlayerTag player = PlayerTag.For(entry.GetArgument(queue, 0));
     if (player == null)
     {
         queue.HandleError(entry, "Invalid player!");
         return;
     }
     ItemAssetTag item = ItemAssetTag.For(entry.GetArgument(queue, 1));
     if (item == null)
     {
         queue.HandleError(entry, "Invalid item!");
         return;
     }
     byte amount = 1;
     if (entry.Arguments.Count > 2)
     {
         amount = (byte)Utilities.StringToUInt(entry.GetArgument(queue, 2));
     }
     if (ItemTool.tryForceGiveItem(player.Internal.player, item.Internal.id, amount))
     {
         if (entry.ShouldShowGood(queue))
         {
             entry.Good(queue, "Successfully gave a " + TagParser.Escape(item.Internal.name) + "!");
         }
     }
     else
     {
         queue.HandleError(entry, "Failed to give item (is the inventory full?)!");
     }
 }
 public override void Execute(CommandQueue queue, CommandEntry entry)
 {
     TemplateObject tcolor = entry.GetArgumentObject(queue, 0);
     ColorTag color = ColorTag.For(tcolor);
     if (color == null)
     {
         queue.HandleError(entry, "Invalid color: " + TagParser.Escape(tcolor.ToString()));
         return;
     }
     string message = entry.GetArgument(queue, 1);
     EChatMode chatMode = EChatMode.SAY;
     if (entry.Arguments.Count > 2)
     {
         string mode = entry.GetArgument(queue, 2);
         try
         {
             chatMode = (EChatMode)Enum.Parse(typeof(EChatMode), mode.ToUpper());
         } catch (ArgumentException)
         {
             queue.HandleError(entry, "Invalid chat mode: " + mode);
             return;
         }
     }
     ChatManager.manager.channel.send("tellChat", ESteamCall.OTHERS, ESteamPacket.UPDATE_UNRELIABLE_BUFFER, new object[]
     {
         CSteamID.Nil,
         (byte)chatMode,
         color.Internal,
         message
     });
 }
예제 #4
0
 public override void Execute(CommandQueue queue, CommandEntry entry)
 {
     bool enable = BooleanTag.TryFor(entry.GetArgumentObject(queue, 1)).Internal;
     EntityTag entity = EntityTag.For(entry.GetArgumentObject(queue, 0));
     if (entity == null)
     {
         queue.HandleError(entry, "Invalid entity!");
         return;
     }
     ZombieTag zombie;
     if (entity.TryGetZombie(out zombie))
     {
         zombie.Internal.UFM_AIDisabled = !enable;
         if (entry.ShouldShowGood(queue))
         {
             entry.Good(queue, "AI for a zombie " + (enable ? "enabled!" : "disabled!"));
         }
         return;
     }
     AnimalTag animal;
     if (entity.TryGetAnimal(out animal))
     {
         animal.Internal.UFM_AIDisabled = !enable;
         if (entry.ShouldShowGood(queue))
         {
             entry.Good(queue, "AI for an animal " + (enable ? "enabled!" : "disabled!"));
         }
         return;
     }
     queue.HandleError(entry, "That entity doesn't have AI!");
 }
예제 #5
0
 public override void Execute(CommandQueue queue, CommandEntry entry)
 {
     ListTag players = ListTag.For(entry.GetArgument(queue, 0));
     TemplateObject tcolor = entry.GetArgumentObject(queue, 1);
     ColorTag color = ColorTag.For(tcolor);
     if (color == null)
     {
         queue.HandleError(entry, "Invalid color: " + TagParser.Escape(tcolor.ToString()));
         return;
     }
     string tchatter = entry.GetArgument(queue, 2);
     PlayerTag chatter = PlayerTag.For(tchatter);
     if (chatter == null)
     {
         queue.HandleError(entry, "Invalid chatting player: " + TagParser.Escape(tchatter));
         return;
     }
     string message = entry.GetArgument(queue, 3);
     foreach (TemplateObject tplayer in players.ListEntries)
     {
         PlayerTag player = PlayerTag.For(tplayer.ToString());
         if (player == null)
         {
             queue.HandleError(entry, "Invalid player: " + TagParser.Escape(tplayer.ToString()));
             continue;
         }
         ChatManager.manager.channel.send("tellChat", player.Internal.playerID.steamID, ESteamPacket.UPDATE_UNRELIABLE_BUFFER,
             chatter.Internal.playerID.steamID, (byte)0 /* TODO: Configurable mode? */, color.Internal, message);
         if (entry.ShouldShowGood(queue))
         {
             entry.Good(queue, "Successfully sent a message.");
         }
     }
 }
예제 #6
0
		public static void RestoreCommand( string command )
		{try{

			if ( !HasMod( command ) )
			{
				s_Defaults.Remove( command );
				CommandSystem.Entries.Remove( command );
				return;
			}

			DefaultInfo info = (DefaultInfo)s_Defaults[command];
            CommandEntry entry = new CommandEntry(info.OldCommand, ((CommandEntry)CommandSystem.Entries[command]).Handler, info.OldAccess);
            CommandSystem.Entries.Remove(command);

			if ( HasMod( info.OldCommand ) )
				RestoreCommand( info.OldCommand );

            CommandSystem.Entries[info.OldCommand] = entry;

			s_Defaults.Remove( command );

			foreach( BaseCommandImplementor imp in BaseCommandImplementor.Implementors )
				foreach( string str in new ArrayList( imp.Commands.Keys ) )
					if ( str == command )
					{
						imp.Commands[info.OldCommand] = imp.Commands[str];
						((BaseCommand)imp.Commands[str]).AccessLevel = info.OldAccess;

						if ( str != info.OldCommand )
							imp.Commands.Remove( str );
					}

        }
        catch{ Errors.Report("Commands-> RestoreDefault"); }
    }
예제 #7
0
 public override void Execute(CommandQueue queue, CommandEntry entry)
 {
     if (entry.Arguments.Count < 1)
     {
         ShowUsage(queue, entry);
         return;
     }
     string sfx = entry.GetArgument(queue, 0);
     float pitch = 1f;
     float gain = 1f;
     Location loc = Location.NaN;
     if (entry.Arguments.Count > 1)
     {
         pitch = (float)Utilities.StringToFloat(entry.GetArgument(queue, 1));
     }
     if (entry.Arguments.Count > 2)
     {
         gain = (float)Utilities.StringToFloat(entry.GetArgument(queue, 2));
     }
     if (entry.Arguments.Count > 3)
     {
         loc = Location.FromString(entry.GetArgument(queue, 3));
     }
     float seek = 0;
     if (entry.Arguments.Count > 4)
     {
         seek = (float)(float)Utilities.StringToFloat(entry.GetArgument(queue, 4));
     }
     TheClient.Sounds.Play(TheClient.Sounds.GetSound(sfx), false, loc, pitch, gain, seek);
 }
 public override void Execute(CommandQueue queue, CommandEntry entry)
 {
     if (entry.Arguments[0].ToString() == "\0CALLBACK")
     {
         return;
     }
     if (entry.Arguments.Count < 3)
     {
         ShowUsage(queue, entry);
         return;
     }
     bool servermode = entry.GetArgument(queue, 0).ToLowerFast() == "server";
     string name = entry.GetArgument(queue, 1).ToLowerFast();
     string help = entry.GetArgument(queue, 2);
     if (entry.InnerCommandBlock == null)
     {
         queue.HandleError(entry, "Event command invalid: No block follows!");
         return;
     }
     // NOTE: Commands are compiled!
     CommandScript script = new CommandScript("ut_command_" + name, entry.InnerCommandBlock, entry.BlockStart, queue.CurrentEntry.Types, true) { Debug = DebugMode.MINIMAL };
     UnturnedCustomCommand ucc = new UnturnedCustomCommand(name, help, script);
     if (servermode)
     {
         Commander.commands.Insert(1, ucc);
     }
     else
     {
         UnturnedFreneticMod.Instance.PlayerCommands.Add(ucc);
     }
     if (entry.ShouldShowGood(queue))
     {
         entry.Good(queue, "Registered command!");
     }
 }
예제 #9
0
 public override void Execute(CommandQueue queue, CommandEntry entry)
 {
     if (entry.Arguments.Count < 1)
     {
         ShowUsage(queue, entry);
         return;
     }
     ListTag list = ListTag.For(entry.GetArgument(queue, 0));
     string message = "Kicked by the server.";
     if (entry.Arguments.Count >= 2)
     {
         message = "Kicked by the server: " + entry.GetArgument(queue, 1);
     }
     for (int i = 0; i < list.ListEntries.Count; i++)
     {
         PlayerEntity pl = TheServer.GetPlayerFor(list.ListEntries[i].ToString());
         if (pl == null)
         {
             entry.Bad(queue, "Unknown player " + TagParser.Escape(list.ListEntries[i].ToString()));
         }
         else
         {
             pl.Kick(message);
         }
     }
 }
예제 #10
0
 public override void Execute(CommandQueue queue, CommandEntry entry)
 {
     const string rn = "   Region Name Here   ";
     const string cr = "Chunk Exact RAM in MB";
     const string er = "Entity Est. RAM in MB";
     entry.Info(queue, "[<{text_color.emphasis}>" + rn + "<{text_color.base}>] [<{text_color.emphasis}>" + cr + "<{text_color.base}>] [<{text_color.emphasis}>" + er + "<{text_color.base}>]");
     long cht = 0;
     long entt = 0;
     int n = 0;
     foreach (World world in TheServer.LoadedWorlds)
     {
         n++;
         long chunk = Chunk.RAM_USAGE * world.MainRegion.LoadedChunks.Count;
         //string reg_cr = Utilities.Pad(Utilities.FormatNumber(chunk), ' ', cr.Length, false);
         long ent = 0;
         foreach (Entity e in world.MainRegion.Entities)
         {
             ent += e.GetRAMUsage();
         }
         string reg_er = Utilities.Pad(Utilities.FormatNumber(ent), ' ', er.Length, false);
         entry.Info(queue, "[<{text_color.emphasis}>" + n + "<{text_color.base}>] [<{text_color.emphasis}>" + TagParser.Escape(world.Name) + "<{text_color.base}>] [<{text_color.emphasis}>" + reg_er + "<{text_color.base}>]");
         cht += chunk;
         entt += ent;
     }
     entry.Info(queue, "Totals -> Chunks (Semi-accurate): <{text_color.emphasis}>" + Utilities.FormatNumber(cht) + "<{text_color.base}>, Entities (Estimated): <{text_color.emphasis}>" + Utilities.FormatNumber(entt)
         + "<{text_color.base}>, actual usage: <{text_color.emphasis}>" + Utilities.FormatNumber(GC.GetTotalMemory(false)) + "<{text_color.base}>.");
 }
예제 #11
0
 public override void Execute(CommandQueue queue, CommandEntry entry)
 {
     string key = entry.GetArgument(queue, 0);
     Key k = KeyHandler.GetKeyForName(key);
     KeyHandler.BindKey(k, (string)null);
     entry.Good(queue, "Keybind removed for " + k + ".");
 }
예제 #12
0
 private void RegisterCommandDefault(ExecutionContext context, string commandName, Type commandType)
 {
     CommandEntry entry = new CommandEntry();
     entry.command.Initialize(context, commandName, commandType);
     entry.command.AddNamedParameter("LineOutput", this.lo);
     this.defaultCommandEntry = entry;
 }
예제 #13
0
 public override void Execute(CommandQueue queue, CommandEntry entry)
 {
     if (entry.Arguments.Count < 1)
     {
         ShowUsage(queue, entry);
         return;
     }
     Location start = TheClient.Player.GetEyePosition();
     Location forward = TheClient.Player.ForwardVector();
     Location end = start + forward * 5;
     switch (entry.GetArgument(queue, 0).ToLowerFast())
     {
         case "cylinder":
             TheClient.Particles.Engine.AddEffect(ParticleEffectType.CYLINDER, (o) => start, (o) => end, (o) => 0.01f, 5f, Location.One, Location.One, true, TheClient.Textures.GetTexture("common/smoke"));
             break;
         case "line":
             TheClient.Particles.Engine.AddEffect(ParticleEffectType.LINE, (o) => start, (o) => end, (o) => 1f, 5f, Location.One, Location.One, true, TheClient.Textures.GetTexture("common/smoke"));
             break;
         case "explosion_small":
             TheClient.Particles.Explode(end, 2, 40);
             break;
         case "explosion_large":
             TheClient.Particles.Explode(end, 5);
             break;
         case "path_mark":
             TheClient.Particles.PathMark(end, () => TheClient.Player.GetPosition());
             break;
         default:
             entry.Bad(queue, "Unknown effect name.");
             return;
     }
     entry.Good(queue, "Created effect.");
 }
예제 #14
0
 public override void Execute(CommandQueue queue, CommandEntry entry)
 {
     TemplateObject cb = entry.GetArgumentObject(queue, 0);
     if (cb.ToString() == "\0CALLBACK")
     {
         return;
     }
     if (entry.InnerCommandBlock == null)
     {
         queue.HandleError(entry, "Invalid or missing command block!");
         return;
     }
     ListTag mode = ListTag.For(cb);
     List<ItemStack> items = new List<ItemStack>();
     for (int i = 1; i < entry.Arguments.Count; i++)
     {
         ItemTag required = ItemTag.For(TheServer, entry.GetArgumentObject(queue, i));
         if (required == null)
         {
             queue.HandleError(entry, "Invalid required item!");
             return;
         }
         items.Add(required.Internal);
     }
     TheServer.Recipes.AddRecipe(RecipeRegistry.ModeFor(mode), entry.InnerCommandBlock, entry.BlockStart, items.ToArray());
     queue.CurrentEntry.Index = entry.BlockEnd + 2;
     if (entry.ShouldShowGood(queue))
     {
         entry.Good(queue, "Added recipe!");
     }
 }
예제 #15
0
 public override void Execute(CommandQueue queue, CommandEntry entry)
 {
     try
     {
         IntegerTag num = IntegerTag.TryFor(entry.GetArgumentObject(queue, 1));
         if (num == null)
         {
             queue.HandleError(entry, "Invalid amount number!");
             return;
         }
         PlayerTag player = PlayerTag.For(entry.GetArgument(queue, 0));
         if (player == null)
         {
             queue.HandleError(entry, "Invalid player!");
             return;
         }
         player.Internal.player.life.askWarm((uint)num.Internal);
         if (entry.ShouldShowGood(queue))
         {
             entry.Good(queue, "Successfully adjusted the warmth level of a player!");
         }
     }
     catch (Exception ex) // TODO: Necessity?
     {
         queue.HandleError(entry, "Failed to adjust player's warmth level: " + ex.ToString());
     }
 }
예제 #16
0
 public override void AdaptBlockFollowers(CommandEntry entry, List<CommandEntry> input, List<CommandEntry> fblock)
 {
     entry.BlockEnd -= input.Count;
     input.Clear();
     base.AdaptBlockFollowers(entry, input, fblock);
     fblock.Add(GetFollower(entry));
 }
예제 #17
0
 public override void Execute(CommandQueue queue, CommandEntry entry)
 {
     bool enable = BooleanTag.TryFor(entry.GetArgumentObject(queue, 1)).Internal;
     EntityTag entity = EntityTag.For(entry.GetArgumentObject(queue, 0));
     if (entity == null)
     {
         queue.HandleError(entry, "Invalid entity!");
         return;
     }
     BarricadeTag barricadeTag;
     byte x;
     byte y;
     ushort plant;
     ushort index;
     if (entity.TryGetBarricade(out barricadeTag, out x, out y, out plant, out index))
     {
         UnityEngine.GameObject obj = barricadeTag.Internal.gameObject;
         InteractableDoor door = obj.GetComponent<InteractableDoor>();
         if (door != null)
         {
             SendMessage("tellToggleDoor", x, y, plant, index, !door.isOpen);
             barricadeTag.InternalData.barricade.state[16] = (byte)(!door.isOpen ? 0 : 1);
             return;
         }
         InteractableFire fire = obj.GetComponent<InteractableFire>();
         if (fire != null)
         {
             SendMessage("tellToggleFire", x, y, plant, index, !fire.isLit);
             barricadeTag.InternalData.barricade.state[0] = (byte)(!fire.isLit ? 0 : 1);
             return;
         }
         InteractableGenerator generator = obj.GetComponent<InteractableGenerator>();
         if (generator != null)
         {
             SendMessage("tellToggleGenerator", x, y, plant, index, !generator.isPowered);
             barricadeTag.InternalData.barricade.state[0] = (byte)(!generator.isPowered ? 0 : 1);
             EffectManager.sendEffect(8, EffectManager.SMALL, barricadeTag.Internal.position);
             return;
         }
         InteractableSafezone safezone = obj.GetComponent<InteractableSafezone>();
         if (generator != null)
         {
             SendMessage("tellToggleSafezone", x, y, plant, index, !safezone.isPowered);
             barricadeTag.InternalData.barricade.state[0] = (byte)(!safezone.isPowered ? 0 : 1);
             EffectManager.sendEffect(8, EffectManager.SMALL, barricadeTag.Internal.position);
             return;
         }
         InteractableSpot spot = obj.GetComponent<InteractableSpot>();
         if (spot != null)
         {
             SendMessage("tellToggleSpot", x, y, plant, index, !spot.isPowered);
             barricadeTag.InternalData.barricade.state[0] = (byte)(!spot.isPowered ? 0 : 1);
             EffectManager.sendEffect(8, EffectManager.SMALL, barricadeTag.Internal.position);
             return;
         }
     }
     queue.HandleError(entry, "That entity isn't powerable!");
 }
예제 #18
0
 public override void Execute(CommandQueue queue, CommandEntry entry)
 {
     try
     {
         LocationTag loc = LocationTag.For(entry.GetArgument(queue, 1));
         if (loc == null)
         {
             queue.HandleError(entry, "Invalid location!");
             return;
         }
         EntityTag entity = EntityTag.For(entry.GetArgumentObject(queue, 0));
         if (entity  == null)
         {
             queue.HandleError(entry, "Invalid entity!");
             return;
         }
         PlayerTag player;
         if (entity.TryGetPlayer(out player))
         {
             player.Internal.player.gameObject.AddComponent<LaunchComponent>().LaunchPlayer(loc.ToVector3());
             if (entry.ShouldShowGood(queue))
             {
                 entry.Good(queue, "Successfully launched player " + TagParser.Escape(player.ToString()) + " to " + TagParser.Escape(loc.ToString()) + "!");
             }
             return;
         }
         ZombieTag zombie;
         if (entity.TryGetZombie(out zombie))
         {
             zombie.Internal.gameObject.AddComponent<LaunchComponent>().Launch(loc.ToVector3());
             if (entry.ShouldShowGood(queue))
             {
                 entry.Good(queue, "Successfully launched zombie " + TagParser.Escape(zombie.ToString()) + " to " + TagParser.Escape(loc.ToString()) + "!");
             }
             return;
         }
         AnimalTag animal;
         if (entity.TryGetAnimal(out animal))
         {
             animal.Internal.gameObject.AddComponent<LaunchComponent>().Launch(loc.ToVector3());
             if (entry.ShouldShowGood(queue))
             {
                 entry.Good(queue, "Successfully launched animal " + TagParser.Escape(animal.ToString()) + " to " + TagParser.Escape(loc.ToString()) + "!");
             }
             return;
         }
         ItemEntityTag item;
         if (entity.TryGetItem(out item))
         {
             // TODO: Find some way to teleport items, barricades, etc without voiding the InstanceID?
         }
         queue.HandleError(entry, "That entity can't be launched!");
     }
     catch (Exception ex) // TODO: Necessity?
     {
         queue.HandleError(entry, "Failed to launch entity: " + ex.ToString());
     }
 }
예제 #19
0
 public override void Execute(CommandQueue queue, CommandEntry entry)
 {
     if (entry.Arguments.Count < 1)
     {
         ShowUsage(queue, entry);
         return;
     }
     entry.Good(queue, "'<{color.emphasis}>" + TagParser.Escape(entry.GetArgument(queue, 0)) + "<{color.base}>' to you as well from " + ThePlugin.Name + "!");
 }
예제 #20
0
 public override void Execute(CommandQueue queue, CommandEntry entry)
 {
     if (entry.Arguments.Count < 2)
     {
         ShowUsage(queue, entry);
         return;
     }
     entry.Good(queue, "Connecting...");
     TheClient.Network.Connect(entry.GetArgument(queue, 0), entry.GetArgument(queue, 1));
 }
예제 #21
0
 public override void Execute(CommandQueue queue, CommandEntry entry)
 {
     string text = "";
     if (entry.Arguments.Count > 0)
     {
         text = entry.GetArgument(queue, 0);
     }
     TheClient.ShowChat();
     TheClient.SetChatText(text);
 }
예제 #22
0
 public override void Execute(CommandQueue queue, CommandEntry entry)
 {
     if (TheClient.Player.ServerFlags.HasFlag(YourStatusFlags.RELOADING))
     {
         return;
     }
     TheClient.QuickBarPos = (TheClient.QuickBarPos + 1) % (TheClient.Items.Count + 1);
     TheClient.Network.SendPacket(new HoldItemPacketOut(TheClient.QuickBarPos));
     TheClient.RenderExtraItems = 3;
 }
예제 #23
0
 public override void Execute(CommandQueue queue, CommandEntry entry)
 {
     IntegerTag itag = IntegerTag.TryFor(entry.GetArgumentObject(queue, 0));
     uint ti = (uint)itag.Internal;
     SDG.Unturned.LightingManager.time = ti;
     if (entry.ShouldShowGood(queue))
     {
         entry.Good(queue, "World time set to " + ti + "!");
     }
 }
 public override void Execute(CommandQueue queue, CommandEntry entry)
 {
     IntegerTag num = IntegerTag.TryFor(entry.GetArgumentObject(queue, 1));
     if (num.Internal <= 0)
     {
         queue.HandleError(entry, "Must provide a number that is greater than 0!");
         return;
     }
     EntityTag entity = EntityTag.For(entry.GetArgumentObject(queue, 0));
     if (entity == null)
     {
         queue.HandleError(entry, "Invalid entity!");
         return;
     }
     ZombieTag zombie;
     if (entity.TryGetZombie(out zombie))
     {
         Zombie inZomb = zombie.Internal;
         inZomb.maxHealth = (ushort)num.Internal;
         if (inZomb.health > inZomb.maxHealth)
         {
             inZomb.health = inZomb.maxHealth;
         }
         if (entry.ShouldShowGood(queue))
         {
             entry.Good(queue, "Successfully set health of a zombie to " + inZomb.maxHealth + "!");
         }
         return;
     }
     PlayerTag player;
     if (entity.TryGetPlayer(out player))
     {
         GameObject playerObj = player.Internal.player.gameObject;
         UFMHealthController controller = playerObj.GetComponent<UFMHealthController>();
         if (controller == null)
         {
             controller = playerObj.AddComponent<UFMHealthController>();
         }
         controller.maxHealth = (uint)num.Internal;
         PlayerLife life = player.Internal.player.life;
         byte curr = life.health;
         controller.health = curr >= controller.maxHealth ? controller.maxHealth : curr;
         life._health = controller.Translate();
         life.channel.send("tellHealth", ESteamCall.OWNER, ESteamPacket.UPDATE_RELIABLE_BUFFER, new object[]
         {
             life.health
         });
         if (entry.ShouldShowGood(queue))
         {
             entry.Good(queue, "Successfully set max health of a player to " + controller.maxHealth + "!");
         }
         return;
     }
     queue.HandleError(entry, "That entity can't be healed!");
 }
예제 #25
0
 public override void Execute(CommandQueue queue, CommandEntry entry)
 {
     PlayerTag player = PlayerTag.For(entry.GetArgument(queue, 0));
     if (player == null)
     {
         queue.HandleError(entry, "Invalid player!");
         return;
     }
     ItemAssetTag item = ItemAssetTag.For(entry.GetArgument(queue, 1));
     if (item == null)
     {
         queue.HandleError(entry, "Invalid item!");
         return;
     }
     byte amount = 1;
     if (entry.Arguments.Count > 2)
     {
         amount = (byte)Utilities.StringToUInt(entry.GetArgument(queue, 2));
     }
     PlayerInventory inventory = player.Internal.player.inventory;
     byte remainingAmount = amount;
     InventorySearch search;
     while (remainingAmount > 0 && (search = inventory.has(item.Internal.id)) != null) // TODO: Less awkward code!?
     {
         if (search.jar.item.amount <= remainingAmount)
         {
             inventory.removeItem(search.page, inventory.getIndex(search.page, search.jar.x, search.jar.y));
             remainingAmount -= search.jar.item.amount;
         }
         else
         {
             inventory.sendUpdateAmount(search.page, search.jar.x, search.jar.y, (byte)(search.jar.item.amount - remainingAmount));
             remainingAmount = 0;
         }
     }
     if (remainingAmount == 0)
     {
         if (entry.ShouldShowGood(queue))
         {
             entry.Good(queue, "Successfully took " + amount + " " + TagParser.Escape(item.Internal.name) + "!");
         }
     }
     else if (remainingAmount < amount)
     {
         if (entry.ShouldShowGood(queue))
         {
             entry.Good(queue, "Successfully took " + (amount - remainingAmount) + " " + TagParser.Escape(item.Internal.name) + "! (" + remainingAmount + " more not found!)");
         }
     }
     else
     {
         queue.HandleError(entry, "Failed to take item (does the inventory contain any?)!");
     }
 }
예제 #26
0
 public override void Execute(CommandQueue queue, CommandEntry entry)
 {
     if (entry.Arguments.Count < 1)
     {
         ShowUsage(queue, entry);
         return;
     }
     DateTime Now = DateTime.Now;
     // TODO: Better format (customizable!)
     TheServer.ChatMessage("^r^7[^d^5" + Utilities.Pad(Now.Hour.ToString(), '0', 2, true) + "^7:^5" + Utilities.Pad(Now.Minute.ToString(), '0', 2, true)
         + "^7:^5" + Utilities.Pad(Now.Second.ToString(), '0', 2, true) + "^r^7] ^3^dSERVER^r^7:^2^d " + entry.AllArguments(queue), "^r^2^d");
 }
예제 #27
0
 public override void Execute(CommandEntry entry)
 {
     if (entry.Arguments.Count < 1)
     {
         ShowUsage(entry);
     }
     else
     {
         bool modechoice = entry.GetArgument(0).ToLower() == "on";
         entry.Queue.ParseTags = modechoice;
         entry.Good("Queue parsing <{color.emphasis}>" + (modechoice ? "enabled" : "disabled") + "<{color.base}>.");
     }
 }
예제 #28
0
 public override void Execute(CommandQueue queue, CommandEntry entry)
 {
     if (entry.Arguments.Count < 1)
     {
         entry.Bad(queue, "Must specify a slot number!");
         return;
     }
     if (TheClient.Player.ServerFlags.HasFlag(YourStatusFlags.RELOADING))
     {
         return;
     }
     int slot = Math.Abs(Utilities.StringToInt(entry.GetArgument(queue, 0))) % (TheClient.Items.Count + 1);
     TheClient.SetHeldItemSlot(slot, DEFAULT_RENDER_EXTRA_ITEMS);
 }
예제 #29
0
 /// <summary>
 /// Executes the command.
 /// </summary>
 /// <param name="entry">Entry to be executed.</param>
 public override void Execute(CommandEntry entry)
 {
     if (entry.Arguments.Count < 1)
     {
         ShowUsage(entry);
     }
     else
     {
         string name = entry.GetArgument(0);
         List<string> args = new List<string>(entry.Arguments);
         args.RemoveAt(0);
         entry.Output.UnknownCommand(entry.Queue, name, args.ToArray());
     }
 }
예제 #30
0
 public override void Execute(CommandQueue queue, CommandEntry entry)
 {
     LocationTag loc = LocationTag.For(entry.GetArgument(queue, 1));
     if (loc == null)
     {
         queue.HandleError(entry, "Invalid location!");
         return;
     }
     EntityTag entity = EntityTag.For(entry.GetArgumentObject(queue, 0));
     if (entity == null)
     {
         queue.HandleError(entry, "Invalid entity!");
         return;
     }
     ZombieTag zombie;
     if (entity.TryGetZombie(out zombie))
     {
         zombie.Internal.target.position = loc.ToVector3();
         zombie.Internal.seeker.canMove = true;
         zombie.Internal.seeker.canSearch = true;
         zombie.Internal.path = EZombiePath.RUSH; // TODO: Option for this?
         if (!zombie.Internal.isTicking)
         {
             zombie.Internal.isTicking = true;
             ZombieManager.tickingZombies.Add(zombie.Internal);
         }
         if (entry.ShouldShowGood(queue))
         {
             entry.Good(queue, "Successfully started a zombie walking to " + TagParser.Escape(loc.ToString()) + "!");
         }
         return;
     }
     AnimalTag animal;
     if (entity.TryGetAnimal(out animal))
     {
         animal.Internal.target = loc.ToVector3();
         if (!animal.Internal.isTicking)
         {
             animal.Internal.isTicking = true;
             AnimalManager.tickingAnimals.Add(animal.Internal);
         }
         if (entry.ShouldShowGood(queue))
         {
             entry.Good(queue, "Successfully started an animal walking to " + TagParser.Escape(loc.ToString()) + "!");
         }
         return;
     }
     queue.HandleError(entry, "That entity can't be made to walk!");
 }
예제 #31
0
        public override void Execute(CommandQueue queue, CommandEntry entry)
        {
            if (entry.Arguments.Count < 1)
            {
                ShowUsage(queue, entry);
                return;
            }
            switch (entry.GetArgument(queue, 0))
            {
            case "lightDebug":
            {
                Location pos = TheClient.Player.GetPosition();
                pos.Z = pos.Z + 1;
                int XP = (int)Math.Floor(pos.X / Chunk.CHUNK_SIZE);
                int YP = (int)Math.Floor(pos.Y / Chunk.CHUNK_SIZE);
                int ZP = (int)Math.Floor(pos.Z / Chunk.CHUNK_SIZE);
                int x  = (int)(Math.Floor(pos.X) - (XP * Chunk.CHUNK_SIZE));
                int y  = (int)(Math.Floor(pos.Y) - (YP * Chunk.CHUNK_SIZE));
                int z  = (int)(Math.Floor(pos.Z) - (ZP * Chunk.CHUNK_SIZE));
                while (true)
                {
                    Chunk ch = TheClient.TheRegion.GetChunk(new Vector3i(XP, YP, ZP));
                    if (ch == null)
                    {
                        entry.Good(queue, "Passed with flying light sources!");
                        goto end;
                    }
                    while (z < Chunk.CHUNK_SIZE)
                    {
                        if (ch.GetBlockAt((int)x, (int)y, (int)z).IsOpaque())
                        {
                            entry.Info(queue, "Died: " + x + ", " + y + ", " + z + " -- " + XP + ", " + YP + ", " + ZP);
                            goto end;
                        }
                        z++;
                    }
                    ZP++;
                    z = 0;
                }
end:
                break;
            }

            case "vramUsage":
            {
                long c = 0;
                foreach (Tuple <string, long> val in TheClient.CalculateVRAMUsage())
                {
                    entry.Info(queue, "-> " + val.Item1 + ": " + val.Item2 + " (" + (val.Item2 / 1024 / 1024) + "MB)");
                    c += val.Item2;
                }
                entry.Info(queue, "-> Total: " + c + " (" + (c / 1024 / 1024) + "MB)");
                break;
            }

            case "speakText":
            {
                if (entry.Arguments.Count < 3)
                {
                    ShowUsage(queue, entry);
                    break;
                }
                bool male = !entry.GetArgument(queue, 1).ToString().ToLowerFast().StartsWith("f");
                TextToSpeech.Speak(entry.GetArgument(queue, 2), male, entry.Arguments.Count > 3 ? (int)IntegerTag.TryFor(entry.GetArgumentObject(queue, 3)).Internal : 0);
                break;
            }

            case "chunkInfo":
            {
                Chunk ch = TheClient.TheRegion.GetChunk(TheClient.TheRegion.ChunkLocFor(TheClient.Player.GetPosition()));
                if (ch == null)
                {
                    entry.Info(queue, "Chunk is null!");
                    break;
                }
                entry.Info(queue, "Plants: " + ch.Plant_C + ", generated as ID: " + ch.Plant_VAO);
                int  c                     = 0;
                long verts                 = 0;
                long verts_transp          = 0;
                int  total                 = 0;
                int  total_rendered        = 0;
                int  total_rendered_transp = 0;
                foreach (Chunk chunk in TheClient.TheRegion.LoadedChunks.Values)
                {
                    total++;
                    if (chunk._VBOSolid != null && ch._VBOSolid != null && chunk._VBOSolid._VAO == ch._VBOSolid._VAO)
                    {
                        c++;
                    }
                    if (chunk._VBOSolid != null && chunk._VBOSolid.generated)
                    {
                        verts += chunk._VBOSolid.vC;
                        total_rendered++;
                    }
                    if (chunk._VBOTransp != null && chunk._VBOTransp.generated)
                    {
                        verts_transp += chunk._VBOTransp.vC;
                        total_rendered_transp++;
                    }
                }
                entry.Info(queue, "Chunk rendering as " + (ch._VBOSolid == null ? "{NULL}" : ch._VBOSolid._VAO.ToString()) + ", which is seen in " + c + " chunks!");
                entry.Info(queue, "Chunks: " + total + ", rendering " + verts + " solid verts and " + verts_transp +
                           " transparent verts, with " + total_rendered + " solid-existent chunks, and " + total_rendered_transp + " transparent-existent chunks!");
                break;
            }

            case "blockInfo":
            {
                BlockInternal bi = TheClient.TheRegion.GetBlockInternal(TheClient.Player.GetPosition());
                entry.Info(queue, "BLOCK: Material=" + bi.Material + ", Shape=" + bi.BlockData + ", Damage=" + bi.Damage + ", Paint=" + bi.BlockPaint + ",Light=" + bi.BlockLocalData);
                break;
            }

            case "igniteBlock":
            {
                Location   pos = TheClient.Player.GetPosition().GetUpperBlockBorder();
                FireEntity fe  = new FireEntity(pos, null, TheClient.TheRegion);
                TheClient.TheRegion.SpawnEntity(fe);
                break;
            }

            case "torchBlocks":
            {
                Location pos = TheClient.Player.GetPosition().GetUpperBlockBorder();
                for (int x = -3; x <= 3; x++)
                {
                    for (int y = -3; y <= 3; y++)
                    {
                        FireEntity fe = new FireEntity(pos + new Location(x, y, 0), null, TheClient.TheRegion);
                        TheClient.TheRegion.SpawnEntity(fe);
                    }
                }
                break;
            }

            case "lateVR":
            {
                if (!VRSupport.Available())
                {
                    entry.Info(queue, "Can't load VR. Not available!");
                    break;
                }
                if (TheClient.VR != null)
                {
                    entry.Info(queue, "Can't load VR. Already loaded!");
                    break;
                }
                TheClient.VR = VRSupport.TryInit(TheClient);
                break;
            }

            case "fogEnhance":
            {
                double time   = NumberTag.TryFor(entry.GetArgumentObject(queue, 1)).Internal;
                double fogVal = NumberTag.TryFor(entry.GetArgumentObject(queue, 2)).Internal;
                TheClient.FogEnhanceStrength = (float)fogVal;
                TheClient.FogEnhanceTime     = time;
                break;
            }

            case "flashBang":
            {
                double time = NumberTag.TryFor(entry.GetArgumentObject(queue, 1)).Internal;
                TheClient.MainWorldView.Flashbang(time);
                break;
            }

            case "earRing":
            {
                double time = NumberTag.TryFor(entry.GetArgumentObject(queue, 1)).Internal;
                TheClient.Sounds.Deafen(time);
                break;
            }

            case "topInfo":
            {
                Location pos      = TheClient.Player.GetPosition().GetBlockLocation();
                Vector3i chunkLoc = TheClient.TheRegion.ChunkLocFor(pos);
                Vector2i buaPos   = new Vector2i(chunkLoc.X, chunkLoc.Y);
                if (!TheClient.TheRegion.UpperAreas.TryGetValue(buaPos, out BlockUpperArea bua))
                {
                    entry.Info(queue, "Failed to grab Top data: Out of map?");
                }
                else
                {
                    entry.Info(queue, pos + ": " + bua.Blocks[bua.BlockIndex((int)pos.X - chunkLoc.X * Chunk.CHUNK_SIZE, (int)pos.Y - chunkLoc.Y * Chunk.CHUNK_SIZE)]);
                }
                break;
            }

            case "testDecal":
            {
                Location pos = TheClient.Player.GetPosition() + new Location(0, 0, BEPUphysics.Settings.CollisionDetectionSettings.AllowedPenetration);
                TheClient.AddDecal(pos, new Location(0, 0, 1), Vector4.One, 1f, "white", 15);
                break;
            }

            case "traceDecal":
            {
                Location pos  = TheClient.Player.GetEyePosition();
                Location forw = TheClient.Player.ForwardVector();
                if (TheClient.TheRegion.SpecialCaseRayTrace(pos, forw, 50.0f, MaterialSolidity.FULLSOLID, TheClient.Player.IgnoreThis, out RayCastResult rcr))
                {
                    Location nrm = new Location(rcr.HitData.Normal).Normalize();
                    TheClient.AddDecal(new Location(rcr.HitData.Location) + nrm * 0.005, nrm, Vector4.One, 1f, "white", 15);
                    entry.Info(queue, "Marked at normal " + nrm);
                }
                break;
            }

            case "soundCount":
            {
                entry.Info(queue, "Sound effects: " + TheClient.Sounds.Effects.Count + ", playing now: " + TheClient.Sounds.PlayingNow.Count);
                break;
            }

            default:
                ShowUsage(queue, entry);
                break;
            }
        }
예제 #32
0
 /// <summary>Executes the command.</summary>
 /// <param name="queue">The command queue involved.</param>
 /// <param name="entry">Entry to be executed.</param>
 public static void Execute(CommandQueue queue, CommandEntry entry)
 {
     queue.HandleError(entry, "Cannot Execute() a foreach, must compile!");
 }
예제 #33
0
 public static string GetUsage(this CommandEntry e)
 {
     return(GetUsage(e.Handler));
 }
예제 #34
0
 public static MenuItem CreateMenuItem(CommandEntry ce)
 {
     return(ce.CreateMenuItem(GlobalCommand.GlobalCmdManager));
 }
예제 #35
0
        public override void Execute(FreneticScript.CommandSystem.CommandQueue queue, CommandEntry entry)
        {
            bool      enable = BooleanTag.TryFor(entry.GetArgumentObject(queue, 1)).Internal;
            EntityTag entity = EntityTag.For(entry.GetArgumentObject(queue, 0));

            if (entity == null)
            {
                queue.HandleError(entry, "Invalid entity!");
                return;
            }
            ZombieTag zombie;

            if (entity.TryGetZombie(out zombie))
            {
                zombie.Internal.UFM_AIDisabled = !enable;
                if (entry.ShouldShowGood(queue))
                {
                    entry.Good(queue, "AI for a zombie " + (enable ? "enabled!" : "disabled!"));
                }
                return;
            }
            AnimalTag animal;

            if (entity.TryGetAnimal(out animal))
            {
                animal.Internal.UFM_AIDisabled = !enable;
                if (entry.ShouldShowGood(queue))
                {
                    entry.Good(queue, "AI for an animal " + (enable ? "enabled!" : "disabled!"));
                }
                return;
            }
            queue.HandleError(entry, "That entity doesn't have AI!");
        }
예제 #36
0
        public static bool Register(string value, AccessLevel access, CommandEventHandler handler, out CommandEntry entry)
        {
            entry = null;

            if (String.IsNullOrWhiteSpace(value))
            {
                return(false);
            }

            if (CommandSystem.Entries.ContainsKey(value))
            {
                return(Replace(value, access, handler, value, out entry));
            }

            CommandSystem.Register(value, access, handler);

            return(CommandSystem.Entries.TryGetValue(value, out entry));
        }
예제 #37
0
        private static void ParseTouchCommandEntryNode(string fileName, XElement parent, ICollection <CommandEntry> entries)
        {
            foreach (XElement childNode in parent.Elements())
            {
                if (childNode.Name.LocalName.ToLowerInvariant() != "entry")
                {
                    Interface.AddMessage(MessageType.Error, false, $"Invalid entry node {childNode.Name.LocalName} in XML node {parent.Name.LocalName} at line {((IXmlLineInfo)childNode).LineNumber}");
                }
                else
                {
                    CommandEntry entry = new CommandEntry();
                    System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.InvariantCulture;

                    string section = childNode.Name.LocalName;

                    foreach (XElement keyNode in childNode.Elements())
                    {
                        string key        = keyNode.Name.LocalName;
                        string value      = keyNode.Value;
                        int    lineNumber = ((IXmlLineInfo)keyNode).LineNumber;

                        switch (keyNode.Name.LocalName.ToLowerInvariant())
                        {
                        case "name":
                            if (string.Compare(value, "N/A", StringComparison.InvariantCultureIgnoreCase) == 0)
                            {
                                break;
                            }

                            int i;

                            for (i = 0; i < Translations.CommandInfos.Length; i++)
                            {
                                if (string.Compare(value, Translations.CommandInfos[i].Name, StringComparison.OrdinalIgnoreCase) == 0)
                                {
                                    break;
                                }
                            }

                            if (i == Translations.CommandInfos.Length || Translations.CommandInfos[i].Type != Translations.CommandType.Digital)
                            {
                                Interface.AddMessage(MessageType.Error, false, $"value is invalid in {key} in {section} at line {lineNumber.ToString(culture)} in {fileName}");
                            }
                            else
                            {
                                entry.Command = Translations.CommandInfos[i].Command;
                            }
                            break;

                        case "option":
                            if (value.Any())
                            {
                                int option;

                                if (!NumberFormats.TryParseIntVb6(value, out option))
                                {
                                    Interface.AddMessage(MessageType.Error, false, $"value is invalid in {key} in {section} at line {lineNumber.ToString(culture)} in {fileName}");
                                }
                                else
                                {
                                    entry.Option = option;
                                }
                            }
                            break;
                        }
                    }

                    entries.Add(entry);
                }
            }
        }
예제 #38
0
 public override void Execute(CommandQueue queue, CommandEntry entry)
 {
     TheServer.ShutDown();
 }
예제 #39
0
        /// <summary>Executes the command.</summary>
        /// <param name="queue">The command queue involved.</param>
        /// <param name="entry">Entry to be executed.</param>
        public static void Execute(CommandQueue queue, CommandEntry entry)
        {
            if (entry.IsCallback)
            {
                return;
            }
            string type      = entry.GetArgument(queue, 0).ToLowerFast();
            string eventname = entry.GetArgument(queue, 1).ToLowerFast();

            if (type == "clear" && eventname == "all")
            {
                foreach (KeyValuePair <string, ScriptEvent> evt in queue.Engine.Events)
                {
                    evt.Value.Clear();
                }
                if (entry.ShouldShowGood(queue))
                {
                    entry.GoodOutput(queue, "Cleared all events.");
                }
                return;
            }
            if (!queue.Engine.Events.TryGetValue(eventname, out ScriptEvent theEvent))
            {
                queue.HandleError(entry, "Unknown event '" + TextStyle.Separate + eventname + TextStyle.Base + "'.");
                return;
            }
            if (type == "clear")
            {
                theEvent.Clear();
                if (entry.ShouldShowGood(queue))
                {
                    entry.GoodOutput(queue, "Cleared event '" + TextStyle.Separate + eventname + TextStyle.Base + "' of all handlers.");
                }
            }
            else if (type == "remove")
            {
                if (entry.Arguments.Length < 3)
                {
                    ShowUsage(queue, entry);
                    return;
                }
                string name    = entry.GetArgument(queue, 2).ToLowerFast();
                bool   success = theEvent.RemoveEventHandler(name);
                if (success)
                {
                    if (entry.ShouldShowGood(queue))
                    {
                        entry.GoodOutput(queue, "Removed event handler '" + TextStyle.Separate + name + TextStyle.Base + "'.");
                    }
                }
                else
                {
                    if (BooleanTag.TryFor(entry.GetNamedArgumentObject(queue, "quiet_fail"))?.Internal ?? false)
                    {
                        if (entry.ShouldShowGood(queue))
                        {
                            entry.GoodOutput(queue, "Unknown event handler '" + TextStyle.Separate + name + TextStyle.Base + "'.");
                        }
                    }
                    else
                    {
                        queue.HandleError(entry, "Unknown event handler '" + TextStyle.Separate + name + TextStyle.Base + "'.");
                    }
                }
            }
            else if (type == "add")
            {
                if (entry.Arguments.Length < 3)
                {
                    ShowUsage(queue, entry);
                    return;
                }
                string name = entry.GetArgument(queue, 2).ToLowerFast();
                if (entry.InnerCommandBlock == null)
                {
                    queue.HandleError(entry, "Event command invalid: No block follows!");
                    return;
                }
                if (theEvent.HasHandler(name))
                {
                    if (BooleanTag.TryFor(entry.GetNamedArgumentObject(queue, "quiet_fail"))?.Internal ?? false)
                    {
                        if (entry.ShouldShowGood(queue))
                        {
                            entry.GoodOutput(queue, "Handler '" + TextStyle.Separate + name + TextStyle.Base + "' already exists!");
                        }
                    }
                    else
                    {
                        queue.HandleError(entry, "Handler '" + TextStyle.Separate + name + TextStyle.Base + "' already exists!");
                    }
                }
                double priority = 0;
                if (entry.Arguments.Length > 3)
                {
                    priority = NumberTag.For(entry.GetArgumentObject(queue, 3), queue.Error).Internal;
                }
                List <CommandEntry> entries = new(entry.InnerCommandBlock.Length + 2);
                MapTag expectedContext      = new();
                expectedContext.Internal.Add("context", entry.System.TagTypes.Type_Map.TagForm);
                entries.Add(entry.System.TheRequireCommand.GenerateEntry(expectedContext, entry.ScriptName, entry.ScriptLine));
                entries.AddRange(entry.InnerCommandBlock);
                CommandScript script = new(theEvent.Name + "__handler__" + name,
                                           CommandScript.TYPE_NAME_EVENT, entries.ToArray(), entry.System, entry.BlockStart, DebugMode.MINIMAL);
                theEvent.RegisterEventHandler(priority, script, name);
                entry.GoodOutput(queue, "Handler '" + TextStyle.Separate + name + "" + TextStyle.Base
                                 + "' defined for event '" + TextStyle.Separate + theEvent.Name + TextStyle.Base + "'.");
            }
            else
            {
                ShowUsage(queue, entry);
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="args"></param>
        public void Run(string[] args)
        {
            Getopt = new Getopt(args);

            CommandEntries = new List <CommandEntry>();

            foreach (var member in GetType()
                     .GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
            {
                var descriptionAttribute = member.GetSingleAttribute <DescriptionAttribute>();
                var valuesAttribute      = member.GetSingleAttribute <ValuesAttribute>();

                var commandDefaultAttribute = member.GetSingleAttribute <CommandDefaultAttribute>();
                if (commandDefaultAttribute != null)
                {
                    if (member is MethodInfo)
                    {
                        BindDefaultMethod(commandDefaultAttribute, member as MethodInfo);
                    }
                }

                var commandAttribute = member.GetSingleAttribute <CommandAttribute>();
                if (commandAttribute == null)
                {
                    continue;
                }

                var commandEntry = new CommandEntry()
                {
                    Aliases     = commandAttribute.Aliases,
                    MemberInfo  = member,
                    Examples    = member.GetAttribute <ExampleAttribute>().Select(item => item.Example).ToArray(),
                    Description = (descriptionAttribute != null) ? descriptionAttribute.Description : "",
                    Values      = (valuesAttribute != null) ? valuesAttribute.Values : new object[0],
                };

                CommandEntries.Add(commandEntry);

                if (member is MethodInfo)
                {
                    BindMethod(commandEntry);
                }
                else if (member is FieldInfo)
                {
                    BindField(commandEntry);
                }
                else
                {
                    throw(new NotImplementedException("Don't know how to handle type " + member.GetType()));
                }
            }

            try
            {
                Getopt.Process();
            }
            catch (TargetInvocationException targetInvocationException)
            {
                Console.Error.WriteLine(targetInvocationException.InnerException);
                Environment.Exit(-1);
            }
            catch (Exception exception)
            {
                //Console.Error.WriteLine(Exception.Message);
                Console.Error.WriteLine(exception);
                Environment.Exit(-2);
            }

            if (Debugger.IsAttached)
            {
                Console.ReadKey();
            }
        }
예제 #41
0
 public override void Execute(CommandQueue queue, CommandEntry entry)
 {
     TheClient.Window.Close();
 }
        public TitleMenuItem(MonoDevelop.Components.Commands.CommandManager manager, CommandEntry entry, CommandInfo commandArrayInfo = null, CommandSource commandSource = CommandSource.MainMenu, object initialCommandTarget = null)
        {
            this.manager = manager;
            this.initialCommandTarget = initialCommandTarget;
            this.commandSource        = commandSource;
            this.commandArrayInfo     = commandArrayInfo;

            menuEntry     = entry;
            menuEntrySet  = entry as CommandEntrySet;
            menuLinkEntry = entry as LinkCommandEntry;

            if (commandArrayInfo != null)
            {
                Header = commandArrayInfo.Text;

                var commandArrayInfoSet = commandArrayInfo as CommandInfoSet;
                if (commandArrayInfoSet != null)
                {
                    foreach (var item in commandArrayInfoSet.CommandInfos)
                    {
                        if (item.IsArraySeparator)
                        {
                            Items.Add(new Separator {
                                UseLayoutRounding = true,
                            });
                        }
                        else
                        {
                            Items.Add(new TitleMenuItem(manager, entry, item, commandSource, initialCommandTarget));
                        }
                    }
                }
            }

            if (menuEntrySet != null)
            {
                Header = menuEntrySet.Name;

                foreach (CommandEntry item in menuEntrySet)
                {
                    if (item.CommandId == MonoDevelop.Components.Commands.Command.Separator)
                    {
                        Items.Add(new Separator {
                            UseLayoutRounding = true,
                        });
                    }
                    else
                    {
                        Items.Add(new TitleMenuItem(manager, item));
                    }
                }
            }
            else if (menuLinkEntry != null)
            {
                Header = menuLinkEntry.Text;
                Click += OnMenuLinkClicked;
            }
            else if (entry != null)
            {
                actionCommand = manager.GetCommand(menuEntry.CommandId) as ActionCommand;
                if (actionCommand == null)
                {
                    return;
                }

                IsCheckable = actionCommand.ActionType == ActionType.Check;

                // FIXME: Use proper keybinding text.
                if (actionCommand.KeyBinding != null)
                {
                    InputGestureText = actionCommand.KeyBinding.ToString();
                }

                if (!actionCommand.Icon.IsNull)
                {
                    Icon = new Image {
                        Source = actionCommand.Icon.GetImageSource(Xwt.IconSize.Small)
                    }
                }
                ;
                Click += OnMenuClicked;
            }

            Height            = SystemParameters.CaptionHeight;
            UseLayoutRounding = true;
        }

        /// <summary>
        /// Updates a command entry. Should only be called from a toplevel node.
        /// This will update all the menu's children.
        /// </summary>
        void Update()
        {
            hasCommand = false;
            if (menuLinkEntry != null)
            {
                return;
            }

            if (menuEntrySet != null || commandArrayInfo is CommandInfoSet)
            {
                for (int i = 0; i < Items.Count; ++i)
                {
                    var titleMenuItem = Items[i] as TitleMenuItem;

                    if (titleMenuItem != null)
                    {
                        titleMenuItem.Update();
                        continue;
                    }

                    // If we have a separator, don't draw another one if the previous visible item is a separator.
                    var separatorMenuItem = Items [i] as Separator;
                    separatorMenuItem.Visibility = Visibility.Collapsed;
                    for (int j = i - 1; j >= 0; --j)
                    {
                        var iterMenuItem = Items [j] as Control;

                        if (iterMenuItem is Separator)
                        {
                            break;
                        }

                        if (iterMenuItem.Visibility != Visibility.Visible)
                        {
                            continue;
                        }

                        separatorMenuItem.Visibility = Visibility.Visible;
                        break;
                    }
                }
                if (menuEntrySet != null && menuEntrySet.AutoHide)
                {
                    Visibility = Items.Cast <Control> ().Any(item => item.Visibility == Visibility.Visible) ? Visibility.Visible : Visibility.Collapsed;
                }
                return;
            }

            var info = manager.GetCommandInfo(menuEntry.CommandId, new CommandTargetRoute(initialCommandTarget));

            if (actionCommand != null)
            {
                if (!string.IsNullOrEmpty(info.Description) && (string)ToolTip != info.Description)
                {
                    ToolTip = info.Description;
                }

                if (actionCommand.CommandArray && commandArrayInfo == null)
                {
                    Visibility = Visibility.Collapsed;

                    var parent = (TitleMenuItem)Parent;

                    int count       = 1;
                    int indexOfThis = parent.Items.IndexOf(this);
                    foreach (var child in info.ArrayInfo)
                    {
                        Control toAdd;
                        if (child.IsArraySeparator)
                        {
                            toAdd = new Separator();
                        }
                        else
                        {
                            toAdd = new TitleMenuItem(manager, menuEntry, child);
                        }

                        toRemoveFromParent.Add(toAdd);
                        parent.Items.Insert(indexOfThis + (count++), toAdd);
                    }
                    return;
                }
            }

            SetInfo(commandArrayInfo != null ? commandArrayInfo : info);
        }

        bool hasCommand = false;
        void SetInfo(CommandInfo info)
        {
            hasCommand = true;
            Header     = info.Text;
            Icon       = new Image {
                Source = info.Icon.GetImageSource(Xwt.IconSize.Small)
            };
            IsEnabled  = info.Enabled;
            Visibility = info.Visible && (menuEntry.DisabledVisible || IsEnabled) ?
                         Visibility.Visible : Visibility.Collapsed;
            IsChecked = info.Checked || info.CheckedInconsistent;
            ToolTip   = info.Description;
        }

        /// <summary>
        /// Clears a command entry's saved data. Should only be called from a toplevel node.
        /// This will update all the menu's children.
        /// </summary>
        IEnumerable <Control> Clear()
        {
            if (menuLinkEntry != null)
            {
                return(Enumerable.Empty <TitleMenuItem> ());
            }

            if (menuEntrySet != null)
            {
                var toRemove = Enumerable.Empty <Control> ();
                foreach (var item in Items)
                {
                    var titleMenuItem = item as TitleMenuItem;
                    if (titleMenuItem == null)
                    {
                        continue;
                    }

                    toRemove = toRemove.Concat(titleMenuItem.Clear());
                }

                foreach (var item in toRemove)
                {
                    Items.Remove(item);
                }

                return(Enumerable.Empty <TitleMenuItem> ());
            }

            var ret = toRemoveFromParent;

            toRemoveFromParent = new List <Control> ();
            return(ret);
        }
예제 #43
0
        public override void Execute(CommandQueue queue, CommandEntry entry)
        {
            if (entry.Marker == 0 || entry.Marker == 3)
            {
                queue.HandleError(entry, "Must use + or -");
            }
            else if (TheClient.Player.ServerFlags.HasFlag(YourStatusFlags.RELOADING))
            {
                return;
            }
            else if (entry.Marker == 1)
            {
                if (entry.Arguments.Count < 1)
                {
                    entry.Bad(queue, "Must specify a use type and a slot number!");
                    return;
                }
                if (TheClient.PrevQuickItem != -1)
                {
                    return;
                }
                string useType = entry.GetArgument(queue, 0).ToLowerFast();
                if (useType != "hold" && useType != "throw" && useType != "click" && useType != "alt" && useType != "drop")
                {
                    entry.Bad(queue, "Invalid use type!");
                    return;
                }
                TheClient.PrevQuickItem    = TheClient.QuickBarPos;
                TheClient.QuickItemUseType = useType;
                int slot = Math.Abs(Utilities.StringToInt(entry.GetArgument(queue, 1))) % (TheClient.Items.Count + 1);
                TheClient.SetHeldItemSlot(slot);
                switch (useType)
                {
                case "hold":
                    break;

                case "throw":
                    break;

                case "click":
                    TheClient.Player.Click = true;
                    break;

                case "alt":
                    TheClient.Player.AltClick = true;
                    break;

                case "drop":
                    break;
                }
            }
            else if (entry.Marker == 2)
            {
                if (TheClient.PrevQuickItem == -1)
                {
                    return;
                }
                TheClient.SetHeldItemSlot(TheClient.PrevQuickItem);
                TheClient.PrevQuickItem = -1;
                switch (TheClient.QuickItemUseType)
                {
                case "hold":
                    break;

                case "throw":
                    break;

                case "click":
                    TheClient.Player.Click = false;
                    break;

                case "alt":
                    TheClient.Player.AltClick = false;
                    break;

                case "drop":
                    break;
                }
            }
        }
예제 #44
0
        public static void Execute(CommandQueue queue, CommandEntry entry)
        {
            if (entry.Arguments.Count < 1)
            {
                ShowUsage(queue, entry);
                return;
            }
            Client TheClient = (entry.Command as CdevelCommand).TheClient;

            switch (entry.GetArgument(queue, 0))
            {
            case "lightDebug":
            {
                Location pos = TheClient.Player.GetPosition();
                pos.Z = pos.Z + 1;
                int XP = (int)Math.Floor(pos.X / Chunk.CHUNK_SIZE);
                int YP = (int)Math.Floor(pos.Y / Chunk.CHUNK_SIZE);
                int ZP = (int)Math.Floor(pos.Z / Chunk.CHUNK_SIZE);
                int x  = (int)(Math.Floor(pos.X) - (XP * Chunk.CHUNK_SIZE));
                int y  = (int)(Math.Floor(pos.Y) - (YP * Chunk.CHUNK_SIZE));
                int z  = (int)(Math.Floor(pos.Z) - (ZP * Chunk.CHUNK_SIZE));
                while (true)
                {
                    Chunk ch = TheClient.TheRegion.GetChunk(new Vector3i(XP, YP, ZP));
                    if (ch == null)
                    {
                        entry.Good(queue, "Passed with flying light sources!");
                        goto end;
                    }
                    while (z < Chunk.CHUNK_SIZE)
                    {
                        if (ch.GetBlockAt((int)x, (int)y, (int)z).IsOpaque())
                        {
                            entry.Info(queue, "Died: " + x + ", " + y + ", " + z + " -- " + XP + ", " + YP + ", " + ZP);
                            goto end;
                        }
                        z++;
                    }
                    ZP++;
                    z = 0;
                }
end:
                break;
            }

            case "vramUsage":
            {
                long c = 0;
                foreach (Tuple <string, long> val in TheClient.CalculateVRAMUsage())
                {
                    entry.Info(queue, "-> " + val.Item1 + ": " + val.Item2 + " (" + (val.Item2 / 1024 / 1024) + "MB)");
                    c += val.Item2;
                }
                entry.Info(queue, "-> Total: " + c + " (" + (c / 1024 / 1024) + "MB)");
                break;
            }

            case "speakText":
            {
                if (entry.Arguments.Count < 3)
                {
                    ShowUsage(queue, entry);
                    break;
                }
                bool male = !entry.GetArgument(queue, 1).ToString().ToLowerFast().StartsWith("f");
                TextToSpeech.Speak(entry.GetArgument(queue, 2), male, entry.Arguments.Count > 3 ? (int)IntegerTag.TryFor(entry.GetArgumentObject(queue, 3)).Internal : 0);
                break;
            }

            case "chunkInfo":
            {
                Chunk ch = TheClient.TheRegion.GetChunk(TheClient.TheRegion.ChunkLocFor(TheClient.Player.GetPosition()));
                if (ch == null)
                {
                    entry.Info(queue, "Chunk is null!");
                    break;
                }
                Vector3i        chunk_pos = ch.WorldPosition;
                ChunkSLODHelper slod      = TheClient.TheRegion.GetSLODHelp(ch.WorldPosition, false);
                if (slod == null)
                {
                    entry.Info(queue, "No SLOD.");
                }
                else
                {
                    bool isgen = slod._VBO != null && slod._VBO.generated;
                    entry.Info(queue, "SLOD: " + slod.Coordinate + ", live chunks contained: " + slod.Users + ", verts: " + slod.FullBlock.Vertices.Count + ", generated: " + isgen);
                    foreach (KeyValuePair <Vector3i, Chunk> entryx in TheClient.TheRegion.LoadedChunks)
                    {
                        if (entryx.Value.PosMultiplier < 5)
                        {
                            continue;
                        }
                        Vector3i slodposser = new Vector3i((int)Math.Floor(entryx.Key.X / (float)Constants.CHUNKS_PER_SLOD), (int)Math.Floor(entryx.Key.Y / (float)Constants.CHUNKS_PER_SLOD), (int)Math.Floor(entryx.Key.Z / (float)Constants.CHUNKS_PER_SLOD));
                        if (slodposser == slod.Coordinate)
                        {
                            entry.Info(queue, "Chunk at " + entryx.Key + " is held");
                        }
                    }
                }
                entry.Info(queue, "Plants: " + ch.Plant_C + ", generated as ID: " + ch.Plant_VAO);
                int  c                     = 0;
                long verts                 = 0;
                long verts_transp          = 0;
                int  total                 = 0;
                int  total_rendered        = 0;
                int  total_rendered_transp = 0;
                foreach (Chunk chunk in TheClient.TheRegion.LoadedChunks.Values)
                {
                    total++;
                    if (chunk._VBOSolid != null && ch._VBOSolid != null && chunk._VBOSolid._VAO == ch._VBOSolid._VAO)
                    {
                        c++;
                    }
                    if (chunk._VBOSolid != null && chunk._VBOSolid.generated)
                    {
                        verts += chunk._VBOSolid.vC;
                        total_rendered++;
                    }
                    if (chunk._VBOTransp != null && chunk._VBOTransp.generated)
                    {
                        verts_transp += chunk._VBOTransp.vC;
                        total_rendered_transp++;
                    }
                }
                entry.Info(queue, "Chunk rendering as " + (ch._VBOSolid == null ? "{NULL}" : ch._VBOSolid._VAO.ToString()) + ", which is seen in " + c + " chunks!");
                entry.Info(queue, "Chunks: " + total + ", rendering " + verts + " solid verts and " + verts_transp +
                           " transparent verts, with " + total_rendered + " solid-existent chunks, and " + total_rendered_transp + " transparent-existent chunks!");
                break;
            }

            case "blockInfo":
            {
                BlockInternal bi = TheClient.TheRegion.GetBlockInternal(TheClient.Player.GetPosition());
                entry.Info(queue, "BLOCK: Material=" + bi.Material + ", Shape=" + bi.BlockData + ", Damage=" + bi.Damage + ", Paint=" + bi.BlockPaint + ",Light=" + bi.BlockLocalData);
                break;
            }

            case "igniteBlock":
            {
                Location   pos = TheClient.Player.GetPosition().GetUpperBlockBorder();
                FireEntity fe  = new FireEntity(pos, null, TheClient.TheRegion);
                TheClient.TheRegion.SpawnEntity(fe);
                break;
            }

            case "torchBlocks":
            {
                Location pos = TheClient.Player.GetPosition().GetUpperBlockBorder();
                for (int x = -3; x <= 3; x++)
                {
                    for (int y = -3; y <= 3; y++)
                    {
                        FireEntity fe = new FireEntity(pos + new Location(x, y, 0), null, TheClient.TheRegion);
                        TheClient.TheRegion.SpawnEntity(fe);
                    }
                }
                break;
            }

            case "lateVR":
            {
                if (!VRSupport.Available())
                {
                    entry.Info(queue, "Can't load VR. Not available!");
                    break;
                }
                if (TheClient.VR != null)
                {
                    entry.Info(queue, "Can't load VR. Already loaded!");
                    break;
                }
                TheClient.VR         = VRSupport.TryInit(TheClient.CWindow);
                TheClient.CWindow.VR = TheClient.VR;
                if (TheClient.VR != null)
                {
                    TheClient.VR.VRScale = 1.5f;         // TODO: VR Scale CVar?
                }
                break;
            }

            case "debugVR":
            {
                if (TheClient.VR == null)
                {
                    entry.Info(queue, "VR not running!");
                    break;
                }
                entry.Info(queue, "Left: " + TheClient.VR.Left?.ToString() + " ||| Right: " + TheClient.VR.Right?.ToString());
                break;
            }

            case "fogEnhance":
            {
                double time   = NumberTag.TryFor(entry.GetArgumentObject(queue, 1)).Internal;
                double fogVal = NumberTag.TryFor(entry.GetArgumentObject(queue, 2)).Internal;
                TheClient.FogEnhanceStrength = (float)fogVal;
                TheClient.FogEnhanceTime     = time;
                break;
            }

            case "flashBang":
            {
                double time = NumberTag.TryFor(entry.GetArgumentObject(queue, 1)).Internal;
                TheClient.MainWorldView.Flashbang(time);
                break;
            }

            case "earRing":
            {
                double time = NumberTag.TryFor(entry.GetArgumentObject(queue, 1)).Internal;
                // TODO: Fix!
                //TheClient.Sounds.Deafen(time);
                break;
            }

            case "topInfo":
            {
                Location pos      = TheClient.Player.GetPosition().GetBlockLocation();
                Vector3i chunkLoc = TheClient.TheRegion.ChunkLocFor(pos);
                Vector2i buaPos   = new Vector2i(chunkLoc.X, chunkLoc.Y);
                if (!TheClient.TheRegion.UpperAreas.TryGetValue(buaPos, out BlockUpperArea bua))
                {
                    entry.Info(queue, "Failed to grab Top data: Out of map?");
                }
                else
                {
                    entry.Info(queue, pos + ": " + bua.Blocks[bua.BlockIndex((int)pos.X - chunkLoc.X * Chunk.CHUNK_SIZE, (int)pos.Y - chunkLoc.Y * Chunk.CHUNK_SIZE)]);
                }
                break;
            }

            case "testDecal":
            {
                Location pos = TheClient.Player.GetPosition() + new Location(0, 0, BEPUphysics.Settings.CollisionDetectionSettings.AllowedPenetration);
                TheClient.AddDecal(pos, new Location(0, 0, 1), Vector4.One, 1f, "white", 15);
                break;
            }

            case "traceDecal":
            {
                Location pos  = TheClient.Player.GetEyePosition();
                Location forw = TheClient.Player.ForwardVector();
                if (TheClient.TheRegion.SpecialCaseRayTrace(pos, forw, 50.0f, MaterialSolidity.FULLSOLID, TheClient.Player.IgnoreThis, out RayCastResult rcr))
                {
                    Location nrm = new Location(rcr.HitData.Normal).Normalize();
                    TheClient.AddDecal(new Location(rcr.HitData.Location) + nrm * 0.005, nrm, Vector4.One, 1f, "white", 15);
                    entry.Info(queue, "Marked at normal " + nrm);
                }
                break;
            }

            case "traceDecalTarg":
            {
                Location pos  = TheClient.Player.GetEyePosition();
                Location forw = TheClient.Player.ForwardVector();
                if (TheClient.TheRegion.SpecialCaseRayTrace(pos, forw, 50.0f, MaterialSolidity.FULLSOLID, TheClient.Player.IgnoreThis, out RayCastResult rcr))
                {
                    Location nrm = new Location(rcr.HitData.Normal).Normalize();
                    TheClient.AddDecal(new Location(rcr.HitData.Location) + nrm * 0.005, nrm, Vector4.One, 1f, "decal_target", 15);
                    entry.Info(queue, "Marked at normal " + nrm);
                }
                break;
            }

            case "soundCount":
            {
                entry.Info(queue, "Sound effects: " + TheClient.Sounds.Effects.Count + ", playing now: " + TheClient.Sounds.PlayingNow.Count);
                break;
            }

            case "testCompute":
            {
                Chunk ch = TheClient.TheRegion.GetChunk(TheClient.TheRegion.ChunkLocFor(TheClient.Player.GetPosition()));
                if (ch == null)
                {
                    throw new Exception("Chunk is null!");
                }
                TheClient.VoxelComputer.sw1.Reset();
                TheClient.VoxelComputer.sw1a.Reset();
                TheClient.VoxelComputer.sw2.Reset();
                TheClient.VoxelComputer.sw3.Reset();
                TheClient.VoxelComputer.Calc(ch);
                entry.Good(queue, "Took: " + TheClient.VoxelComputer.sw1.ElapsedMilliseconds + " (" + TheClient.VoxelComputer.sw1a.ElapsedMilliseconds + ") / "
                           + TheClient.VoxelComputer.sw2.ElapsedMilliseconds + " / " + TheClient.VoxelComputer.sw3.ElapsedMilliseconds);
                break;
            }

            case "testComputeAll":
            {
                TheClient.VoxelComputer.sw1.Reset();
                TheClient.VoxelComputer.sw1a.Reset();
                TheClient.VoxelComputer.sw2.Reset();
                TheClient.VoxelComputer.sw3.Reset();
                TheClient.VoxelComputer.Calc(TheClient.TheRegion.LoadedChunks.Values.ToArray());
                entry.Good(queue, "Took: " + TheClient.VoxelComputer.sw1.ElapsedMilliseconds + " (" + TheClient.VoxelComputer.sw1a.ElapsedMilliseconds + ") / "
                           + TheClient.VoxelComputer.sw2.ElapsedMilliseconds + " / " + TheClient.VoxelComputer.sw3.ElapsedMilliseconds);
                break;
            }

            default:
                ShowUsage(queue, entry);
                break;
            }
        }
예제 #45
0
 public override void Execute(FreneticScript.CommandSystem.CommandQueue queue, CommandEntry entry)
 {
     try
     {
         IntegerTag num = IntegerTag.TryFor(entry.GetArgumentObject(queue, 1));
         if (num.Internal < 0)
         {
             queue.HandleError(entry, "Must provide a non-negative number!");
             return;
         }
         EntityTag entity = EntityTag.For(entry.GetArgumentObject(queue, 0));
         if (entity == null)
         {
             queue.HandleError(entry, "Invalid entity!");
             return;
         }
         EPlayerKill kill; // for use with "out EPlayerKill" parameters
         PlayerTag   player;
         if (entity.TryGetPlayer(out player))
         {
             PlayerLife          life             = player.Internal.player.life;
             UFMHealthController healthController = player.Internal.player.GetComponent <UFMHealthController>();
             uint health = healthController != null ? healthController.health : life.health;
             if (num.Internal >= health)
             {
                 uint amount = (uint)num.Internal;
                 if (healthController != null)
                 {
                     healthController.health = 0;
                 }
                 if (amount >= byte.MaxValue) // TODO: better handling
                 {
                     life._health = 0;
                     amount       = 1;
                 }
                 life.askDamage((byte)amount, Vector3.zero, EDeathCause.KILL, ELimb.SPINE, CSteamID.Nil, out kill, null);
             }
             else
             {
                 uint amount = (uint)num.Internal;
                 if (healthController != null)
                 {
                     healthController.Damage((uint)num.Internal);
                 }
                 life._health = healthController.Translate();
                 life.channel.send("tellHealth", ESteamCall.OWNER, ESteamPacket.UPDATE_RELIABLE_BUFFER, new object[]
                 {
                     life.health
                 });
             }
             if (entry.ShouldShowGood(queue))
             {
                 entry.Good(queue, "Successfully damaged a player by " + TagParser.Escape(num.ToString()) + "!");
             }
             return;
         }
         ZombieTag zombie;
         if (entity.TryGetZombie(out zombie))
         {
             uint xp;
             zombie.Internal.askDamage((byte)num.Internal, Vector3.zero, out kill, out xp);
             if (entry.ShouldShowGood(queue))
             {
                 entry.Good(queue, "Successfully damaged a zombie by " + TagParser.Escape(num.ToString()) + "!");
             }
             return;
         }
         AnimalTag animal;
         if (entity.TryGetAnimal(out animal))
         {
             uint xp;
             animal.Internal.askDamage((byte)num.Internal, Vector3.zero, out kill, out xp);
             if (entry.ShouldShowGood(queue))
             {
                 entry.Good(queue, "Successfully damaged an animal by " + TagParser.Escape(num.ToString()) + "!");
             }
             return;
         }
         BarricadeTag barricade;
         if (entity.TryGetBarricade(out barricade))
         {
             // TODO: Use BarricadeManager?
             barricade.InternalData.barricade.askDamage((ushort)num.Internal);
             if (entry.ShouldShowGood(queue))
             {
                 entry.Good(queue, "Successfully damaged a barricade by " + TagParser.Escape(num.ToString()) + "!");
             }
             return;
         }
         ResourceTag resource;
         if (entity.TryGetResource(out resource))
         {
             // TODO: Use ResourceManager?
             resource.Internal.askDamage((ushort)num.Internal);
             if (entry.ShouldShowGood(queue))
             {
                 entry.Good(queue, "Successfully damaged a resource by " + TagParser.Escape(num.ToString()) + "!");
             }
             return;
         }
         StructureTag structure;
         if (entity.TryGetStructure(out structure))
         {
             // TODO: Use StructureManager?
             structure.InternalData.structure.askDamage((ushort)num.Internal);
             if (entry.ShouldShowGood(queue))
             {
                 entry.Good(queue, "Successfully damaged a structure by " + TagParser.Escape(num.ToString()) + "!");
             }
             return;
         }
         VehicleTag vehicle;
         if (entity.TryGetVehicle(out vehicle))
         {
             vehicle.Internal.askDamage((ushort)num.Internal, false);
             if (entry.ShouldShowGood(queue))
             {
                 entry.Good(queue, "Successfully damaged a vehicle by " + TagParser.Escape(num.ToString()) + "!");
             }
             return;
         }
         queue.HandleError(entry, "That entity can't be damaged!");
     }
     catch (Exception ex) // TODO: Necessity?
     {
         queue.HandleError(entry, "Failed to damage entity: " + ex.ToString());
     }
 }
예제 #46
0
        private void ProcessingFunc()
        {
            CommandEntry currentEntry = null;

            while (Processing)
            {
                try
                {
                    if (currentEntry != null)
                    {
                        lock (ProcessAnswerSignal)
                        {
                            /* wait until response arrives or we get a timeout */
                            if (!Monitor.Wait(ProcessAnswerSignal, Math.Min(currentEntry.Timeout, IdleTimeout)))
                            {
                                /* did we hit the timeout for the current command? */
                                if (currentEntry.Timeout > IdleTimeout)
                                {
                                    /* not yet, check when the last response was */
                                    currentEntry.Timeout -= IdleTimeout;

                                    if ((DateTime.Now - LastResponse).TotalMilliseconds > CommandTimeout)
                                    {
                                        /* the last answer was e.g. 10 sec ago. seems we are disconnected */
                                        Log.AddMessage(Remote, "Kraken did not response within the configured command timeout. Closing connection.");
                                        CloseConnection();
                                        return;
                                    }

                                    /* everything okay, send another idle command */
                                    if (CurrentRequestId >= 0)
                                    {
                                        Send("progess " + CurrentRequestId);
                                    }
                                    else
                                    {
                                        Send("idle");
                                    }
                                }
                                else
                                {
                                    currentEntry.Timeout = 0;

                                    /* in case of timeout */
                                    lock (currentEntry.Signal)
                                    {
                                        currentEntry.Result.Length = 0;
                                        Monitor.Pulse(currentEntry.Signal);
                                    }
                                    currentEntry = null;
                                }
                            }
                            else
                            {
                                /* answer received */
                                lock (currentEntry.Signal)
                                {
                                    currentEntry.Result.Append(ProcessAnswerString);
                                    Monitor.Pulse(currentEntry.Signal);
                                }
                                currentEntry = null;
                            }
                        }
                    }
                    else
                    {
                        if (CommandQueue.Count == 0)
                        {
                            lock (ProcessingThreadSignal)
                            {
                                Monitor.Wait(ProcessingThreadSignal, 500);
                            }
                        }
                        else
                        {
                            currentEntry = CommandQueue.Dequeue();
                            Send(currentEntry.Request);
                        }
                    }
                }
                catch (Exception e)
                {
                    Thread.Sleep(100);
                }
            }
        }
예제 #47
0
        private static void ParsePanelAnimatedNode(XElement Element, string FileName, string TrainPath, TrainManager.Train Train, int Car, CarSection CarSection, int GroupIndex)
        {
            System.Globalization.CultureInfo Culture = System.Globalization.CultureInfo.InvariantCulture;

            int    currentSectionElement   = 0;
            int    numberOfSectionElements = Element.Elements().Count();
            double invfac = numberOfSectionElements == 0 ? Loading.TrainProgressCurrentWeight : Loading.TrainProgressCurrentWeight / (double)numberOfSectionElements;

            foreach (XElement SectionElement in Element.Elements())
            {
                Loading.TrainProgress = Loading.TrainProgressCurrentSum + invfac * (double)currentSectionElement;
                if ((currentSectionElement & 4) == 0)
                {
                    System.Threading.Thread.Sleep(1);
                    if (Loading.Cancel)
                    {
                        return;
                    }
                }

                string Section = SectionElement.Name.LocalName;

                switch (SectionElement.Name.LocalName.ToLowerInvariant())
                {
                case "group":
                    if (GroupIndex == 0)
                    {
                        int n = 0;

                        foreach (XElement KeyNode in SectionElement.Elements())
                        {
                            string Key        = KeyNode.Name.LocalName;
                            string Value      = KeyNode.Value;
                            int    LineNumber = ((IXmlLineInfo)KeyNode).LineNumber;

                            switch (Key.ToLowerInvariant())
                            {
                            case "number":
                                if (Value.Length != 0 && !NumberFormats.TryParseIntVb6(Value, out n))
                                {
                                    Interface.AddMessage(MessageType.Error, false, "Value is invalid in " + Key + " in " + Section + " at line " + LineNumber.ToString(Culture) + " in " + FileName);
                                }
                                break;
                            }
                        }

                        if (n + 1 >= CarSection.Groups.Length)
                        {
                            Array.Resize(ref CarSection.Groups, n + 2);
                            CarSection.Groups[n + 1] = new ElementsGroup(ObjectType.Overlay);
                        }

                        ParsePanelAnimatedNode(SectionElement, FileName, TrainPath, Train, Car, CarSection, n + 1);
                    }
                    break;

                case "touch":
                    if (GroupIndex > 0)
                    {
                        Vector3             Position       = Vector3.Zero;
                        Vector3             Size           = Vector3.Zero;
                        int                 JumpScreen     = GroupIndex - 1;
                        List <int>          SoundIndices   = new List <int>();
                        List <CommandEntry> CommandEntries = new List <CommandEntry>();
                        CommandEntry        CommandEntry   = new CommandEntry();

                        foreach (XElement KeyNode in SectionElement.Elements())
                        {
                            string Key        = KeyNode.Name.LocalName;
                            string Value      = KeyNode.Value;
                            int    LineNumber = ((IXmlLineInfo)KeyNode).LineNumber;

                            switch (Key.ToLowerInvariant())
                            {
                            case "position":
                                if (!Vector3.TryParse(KeyNode.Value, ',', out Position))
                                {
                                    Interface.AddMessage(MessageType.Error, false, "Position is invalid in " + Key + " in " + Section + " at line " + LineNumber.ToString(Culture) + " in " + FileName);
                                }
                                break;

                            case "size":
                                if (!Vector3.TryParse(KeyNode.Value, ',', out Size))
                                {
                                    Interface.AddMessage(MessageType.Error, false, "Size is invalid in " + Key + " in " + Section + " at line " + LineNumber.ToString(Culture) + " in " + FileName);
                                }
                                break;

                            case "jumpscreen":
                                if (Value.Length != 0 && !NumberFormats.TryParseIntVb6(Value, out JumpScreen))
                                {
                                    Interface.AddMessage(MessageType.Error, false, "Value is invalid in " + Key + " in " + Section + " at line " + LineNumber.ToString(Culture) + " in " + FileName);
                                }
                                break;

                            case "soundindex":
                                if (Value.Length != 0)
                                {
                                    int SoundIndex;

                                    if (!NumberFormats.TryParseIntVb6(Value, out SoundIndex))
                                    {
                                        Interface.AddMessage(MessageType.Error, false, "Value is invalid in " + Key + " in " + Section + " at line " + LineNumber.ToString(Culture) + " in " + FileName);
                                    }

                                    SoundIndices.Add(SoundIndex);
                                }
                                break;

                            case "command":
                            {
                                if (!CommandEntries.Contains(CommandEntry))
                                {
                                    CommandEntries.Add(CommandEntry);
                                }

                                if (string.Compare(Value, "N/A", StringComparison.InvariantCultureIgnoreCase) == 0)
                                {
                                    break;
                                }

                                int i;
                                for (i = 0; i < Translations.CommandInfos.Length; i++)
                                {
                                    if (string.Compare(Value, Translations.CommandInfos[i].Name, StringComparison.OrdinalIgnoreCase) == 0)
                                    {
                                        break;
                                    }
                                }
                                if (i == Translations.CommandInfos.Length || Translations.CommandInfos[i].Type != Translations.CommandType.Digital)
                                {
                                    Interface.AddMessage(MessageType.Error, false, "Value is invalid in " + Key + " in " + Section + " at line " + LineNumber.ToString(Culture) + " in " + FileName);
                                }
                                else
                                {
                                    CommandEntry.Command = Translations.CommandInfos[i].Command;
                                }
                            }
                            break;

                            case "commandoption":
                                if (!CommandEntries.Contains(CommandEntry))
                                {
                                    CommandEntries.Add(CommandEntry);
                                }

                                if (Value.Length != 0 && !NumberFormats.TryParseIntVb6(Value, out CommandEntry.Option))
                                {
                                    Interface.AddMessage(MessageType.Error, false, "Value is invalid in " + Key + " in " + Section + " at line " + LineNumber.ToString(Culture) + " in " + FileName);
                                }
                                break;

                            case "soundentries":
                                if (!KeyNode.HasElements)
                                {
                                    Interface.AddMessage(MessageType.Error, false, $"An empty list of touch sound indices was defined at line {((IXmlLineInfo)KeyNode).LineNumber} in XML file {FileName}");
                                    break;
                                }

                                ParseTouchSoundEntryNode(FileName, KeyNode, SoundIndices);
                                break;

                            case "commandentries":
                                if (!KeyNode.HasElements)
                                {
                                    Interface.AddMessage(MessageType.Error, false, $"An empty list of touch commands was defined at line {((IXmlLineInfo)KeyNode).LineNumber} in XML file {FileName}");
                                    break;
                                }

                                ParseTouchCommandEntryNode(FileName, KeyNode, CommandEntries);
                                break;
                            }
                        }
                        CreateTouchElement(CarSection.Groups[GroupIndex], Position, Size, JumpScreen, SoundIndices.ToArray(), CommandEntries.ToArray());
                    }
                    break;

                case "include":
                {
                    foreach (XElement KeyNode in SectionElement.Elements())
                    {
                        string Key        = KeyNode.Name.LocalName;
                        string Value      = KeyNode.Value;
                        int    LineNumber = ((IXmlLineInfo)KeyNode).LineNumber;

                        switch (Key.ToLowerInvariant())
                        {
                        case "filename":
                        {
                            string File = OpenBveApi.Path.CombineFile(TrainPath, Value);
                            if (System.IO.File.Exists(File))
                            {
                                System.Text.Encoding e = TextEncoding.GetSystemEncodingFromFile(File);
                                UnifiedObject        currentObject;
                                Program.CurrentHost.LoadObject(File, e, out currentObject);
                                var a = currentObject as AnimatedObjectCollection;
                                if (a != null)
                                {
                                    for (int i = 0; i < a.Objects.Length; i++)
                                    {
                                        Program.CurrentHost.CreateDynamicObject(ref a.Objects[i].internalObject);
                                    }
                                    CarSection.Groups[GroupIndex].Elements = a.Objects;
                                }
                                else
                                {
                                    Interface.AddMessage(MessageType.Error, false, "Value is invalid in " + Key + " in " + Section + " at line " + LineNumber.ToString(Culture) + " in " + FileName);
                                }
                            }
                        }
                        break;
                        }
                    }
                }
                break;
                }
            }
        }
예제 #48
0
        public override void Execute(FreneticScript.CommandSystem.CommandQueue queue, CommandEntry entry)
        {
            try
            {
                TemplateObject spawned = null;
                LocationTag    loc     = LocationTag.For(entry.GetArgument(queue, 1));
                if (loc == null)
                {
                    queue.HandleError(entry, "Invalid location!");
                    return;
                }
                string     targetAssetType = entry.GetArgument(queue, 0).ToLowerFast();
                EntityType etype           = EntityType.ValueOf(targetAssetType);
                if (etype == null)
                {
                    queue.HandleError(entry, "Invalid entity type!");
                    return;
                }
                if (etype.Type == EntityAssetType.ZOMBIE)
                {
                    Vector3 vec3    = loc.ToVector3();
                    byte    reg     = 0; // TODO: Optionally specifiable
                    float   closest = float.MaxValue;
                    for (int r = 0; r < LevelZombies.zombies.Length; r++)
                    {
                        for (int i = 0; i < LevelZombies.zombies[r].Count; i++)
                        {
                            float dist = (LevelZombies.zombies[r][i].point - vec3).sqrMagnitude;
                            if (dist < closest)
                            {
                                closest = dist;
                                reg     = (byte)r;
                            }
                        }
                    }
                    ZombieManager.manager.addZombie(reg, 0, 0, 0, 0, 0, 0, 0, 0, vec3, 0, false);
                    Zombie zombie = ZombieManager.regions[reg].zombies[ZombieManager.regions[reg].zombies.Count - 1];
                    // TODO: Make this actually work! (See complaints file!)

                    /*
                     * foreach (SteamPlayer player in PlayerTool.getSteamPlayers())
                     * {
                     *  ZombieManager.manager.channel.openWrite();
                     *  ZombieManager.manager.channel.write(reg);
                     *  ZombieManager.manager.channel.write((ushort)1);
                     *  ZombieManager.manager.channel.write(new object[]
                     *      {
                     *          zombie.type,
                     *          (byte)zombie.speciality,
                     *          zombie.shirt,
                     *          zombie.pants,
                     *          zombie.hat,
                     *          zombie.gear,
                     *          zombie.move,
                     *          zombie.idle,
                     *          zombie.transform.position,
                     *          MeasurementTool.angleToByte(zombie.transform.rotation.eulerAngles.y),
                     *          zombie.isDead
                     *      });
                     *  ZombieManager.manager.channel.closeWrite("tellZombies", player.playerID.steamID, ESteamPacket.UPDATE_RELIABLE_CHUNK_BUFFER);
                     * }
                     */
                    if (entry.ShouldShowGood(queue))
                    {
                        entry.Good(queue, "Successfully spawned a zombie at " + TagParser.Escape(loc.ToString()) + "! (WARNING: IT WILL BE INVISIBLE CURRENTLY - SEE THE COMPLAINTS FILE)");
                    }
                    spawned = new ZombieTag(zombie);
                }
                else if (etype.Type == EntityAssetType.ANIMAL)
                {
                    AnimalAssetTag asset = AnimalAssetTag.For(targetAssetType);
                    if (asset == null)
                    {
                        queue.HandleError(entry, "Invalid animal type!");
                        return;
                    }
                    // TODO: Make this bit optional!
                    RaycastHit rch;
                    while (Physics.Raycast(loc.ToVector3(), new Vector3(0, 1, 0), out rch, 5))
                    {
                        loc.Y += 3;
                    }
                    // END TODO
                    AnimalManager.manager.addAnimal(asset.Internal.id, loc.ToVector3(), 0, false);
                    Animal animal = AnimalManager.animals[AnimalManager.animals.Count - 1];
                    foreach (SteamPlayer player in PlayerTool.getSteamPlayers())
                    {
                        AnimalManager.manager.channel.openWrite();
                        AnimalManager.manager.channel.write((ushort)1);
                        AnimalManager.manager.channel.write(new object[]
                        {
                            animal.id,
                            animal.transform.position,
                            MeasurementTool.angleToByte(animal.transform.rotation.eulerAngles.y),
                            animal.isDead
                        });
                        AnimalManager.manager.channel.closeWrite("tellAnimals", player.playerID.steamID, ESteamPacket.UPDATE_RELIABLE_CHUNK_BUFFER);
                    }
                    if (entry.ShouldShowGood(queue))
                    {
                        entry.Good(queue, "Successfully spawned a " + TagParser.Escape(asset.ToString()) + " at " + TagParser.Escape(loc.ToString()) + "! (" + animal.gameObject.GetInstanceID() + ")");
                    }
                    spawned = new AnimalTag(animal);
                }
                else if (etype.Type == EntityAssetType.VEHICLE)
                {
                    VehicleAssetTag asset = VehicleAssetTag.For(targetAssetType);
                    if (asset == null)
                    {
                        queue.HandleError(entry, "Invalid vehicle type!");
                        return;
                    }
                    // TODO: Make this bit optional!
                    RaycastHit rch;
                    while (Physics.Raycast(loc.ToVector3(), new Vector3(0, 1, 0), out rch, 5))
                    {
                        loc.Y += 3;
                    }
                    // END TODO
                    VehicleManager.spawnVehicle(asset.Internal.id, loc.ToVector3(), Quaternion.identity);
                    if (entry.ShouldShowGood(queue))
                    {
                        entry.Good(queue, "Successfully spawned a " + TagParser.Escape(asset.ToString()) + " at " + TagParser.Escape(loc.ToString()) + "!");
                    }
                    // TODO: Get the vehicle entity!
                }
                else if (etype.Type == EntityAssetType.WORLD_OBJECT)
                {
                    WorldObjectAssetTag asset = WorldObjectAssetTag.For(targetAssetType);
                    if (asset == null)
                    {
                        queue.HandleError(entry, "Invalid world object type!");
                        return;
                    }
                    LevelObjects.addObject(loc.ToVector3(), Quaternion.identity, Vector3.one, asset.Internal.id, asset.Internal.name, asset.Internal.GUID, ELevelObjectPlacementOrigin.MANUAL);
                    // TODO: Network!
                    entry.Good(queue, "Successfully spawned a " + TagParser.Escape(asset.ToString()) + " at " + TagParser.Escape(loc.ToString()) + "! (WARNING: IT WILL BE INVISIBLE CURRENTLY - SEE THE COMPLAINTS FILE)");
                    // TODO: Get the world entity!
                }
                else if (etype.Type == EntityAssetType.ITEM)
                {
                    ItemAssetTag asset = ItemAssetTag.For(targetAssetType);
                    if (asset == null)
                    {
                        queue.HandleError(entry, "Invalid item type!");
                        return;
                    }
                    byte x;
                    byte y;
                    if (Regions.tryGetCoordinate(loc.ToVector3(), out x, out y))
                    {
                        Item     item = new Item(asset.Internal.id, 1, asset.Internal.quality);
                        ItemData data = new ItemData(item, ++ItemManager.instanceCount, loc.ToVector3(), Dedicator.isDedicated);
                        ItemManager.regions[x, y].items.Add(data);
                        ItemModelTracker.Track(data, loc.ToVector3());
                        ItemManager.manager.channel.send("tellItem", ESteamCall.CLIENTS, x, y, ItemManager.ITEM_REGIONS, ESteamPacket.UPDATE_RELIABLE_BUFFER, new object[]
                        {
                            x,
                            y,
                            item.id,
                            item.amount,
                            item.quality,
                            item.state,
                            loc.ToVector3()
                        });
                        if (entry.ShouldShowGood(queue))
                        {
                            entry.Good(queue, "Successfully spawned a " + TagParser.Escape(asset.ToString()) + " at " + TagParser.Escape(loc.ToString()) + "!");
                        }
                        // TODO: Get the item entity!
                    }
                    else
                    {
                        queue.HandleError(entry, "Trying to spawn item outside any valid item regions!");
                    }
                }
                else if (etype.Type == EntityAssetType.BARRICADE)
                {
                    ItemAssetTag asset = ItemAssetTag.For(targetAssetType.Substring("barricade_".Length));
                    if (asset == null || !(asset.Internal is ItemBarricadeAsset))
                    {
                        queue.HandleError(entry, "Invalid item barricade type!");
                        return;
                    }
                    Barricade barric = new Barricade(asset.Internal.id);
                    BarricadeManager.dropBarricade(barric, null, loc.ToVector3(), 0f, 0f, 0f, CSteamID.Nil.m_SteamID, CSteamID.Nil.m_SteamID);
                    if (entry.ShouldShowGood(queue))
                    {
                        entry.Good(queue, "Successfully spawned a " + TagParser.Escape(asset.ToString()) + " at " + TagParser.Escape(loc.ToString()) + "!");
                    }
                    // TODO: Get the game object!
                }
                else if (etype.Type == EntityAssetType.STRUCTURE)
                {
                    ItemAssetTag asset = ItemAssetTag.For(targetAssetType.Substring("structure_".Length));
                    if (asset == null || !(asset.Internal is ItemStructureAsset))
                    {
                        queue.HandleError(entry, "Invalid item structure type!");
                        return;
                    }
                    StructureManager.dropStructure(new Structure(asset.Internal.id), loc.ToVector3(), 0f, 0f, 0f, CSteamID.Nil.m_SteamID, CSteamID.Nil.m_SteamID);
                    if (entry.ShouldShowGood(queue))
                    {
                        entry.Good(queue, "Successfully spawned a " + TagParser.Escape(asset.ToString()) + " at " + TagParser.Escape(loc.ToString()) + "!");
                    }
                    // TODO: Get the game object!
                }
                else
                {
                    queue.HandleError(entry, "Invalid or unspawnable entity type!");
                    return;
                }
                if (spawned != null)
                {
                    queue.SetVariable("spawned", spawned);
                }
            }
            catch (Exception ex) // TODO: Necessity?
            {
                queue.HandleError(entry, "Failed to spawn entity: " + ex.ToString());
            }
        }
예제 #49
0
        public static bool Replace(
            string value, AccessLevel access, CommandEventHandler handler, string newValue, out CommandEntry entry)
        {
            entry = null;

            if (String.IsNullOrWhiteSpace(value))
            {
                if (String.IsNullOrWhiteSpace(newValue))
                {
                    return(false);
                }

                value = newValue;
            }

            if (handler == null)
            {
                if (!CommandSystem.Entries.ContainsKey(value))
                {
                    return(false);
                }

                handler = CommandSystem.Entries[value].Handler;
            }

            if (value != newValue)
            {
                if (String.IsNullOrWhiteSpace(newValue))
                {
                    Unregister(value);
                    return(true);
                }

                value = newValue;
            }

            Unregister(value);
            CommandSystem.Register(value, access, handler);

            return(CommandSystem.Entries.TryGetValue(value, out entry));
        }
예제 #50
0
        public override void Execute(CommandQueue queue, CommandEntry entry)
        {
            if (entry.Arguments.Count < 1)
            {
                ShowUsage(queue, entry);
                return;
            }
            string arg         = entry.GetArgument(queue, 0).ToLowerFast();
            bool   success     = false;
            bool   is_all      = arg == "all";
            bool   is_textures = arg == "textures";
            bool   is_blocks   = arg == "blocks";

            if (is_textures || is_all)
            {
                success = true;
                TheClient.Textures.Empty();
                TheClient.Textures.InitTextureSystem(TheClient.Files);
            }
            if (is_blocks || is_textures || is_all)
            {
                success = true;
                MaterialHelpers.Populate(TheClient.Files);
                // TODO: Delay TBlock generation with time!
                TheClient.TBlock.Generate(TheClient, TheClient.CVars, TheClient.Textures, true);
            }
            if (arg == "chunks" || is_blocks || is_textures || is_all)
            {
                // TODO: Efficiency of this method!
                // TODO: Ensure this method allows for
                success = true;
                TheClient.TheRegion.RenderingNow.Clear();
                Location pos    = TheClient.Player.GetPosition();
                double   delay  = 0.0;
                double   adder  = 5.0 / TheClient.TheRegion.LoadedChunks.Count;
                Vector3i lpos   = Vector3i.Zero;
                double   ldelay = 0.0;
                foreach (Chunk chunk in TheClient.TheRegion.LoadedChunks.Values.OrderBy((c) => (c.WorldPosition.ToLocation() * new Location(Constants.CHUNK_WIDTH)).DistanceSquared_Flat(pos)))
                {
                    delay += adder;
                    if (chunk.WorldPosition != lpos)
                    {
                        ldelay = delay;
                        lpos   = chunk.WorldPosition;
                    }
                    TheClient.Schedule.ScheduleSyncTask(() =>
                    {
                        if (chunk.IsAdded)
                        {
                            chunk.OwningRegion.UpdateChunk(chunk);
                        }
                    }, ldelay);
                }
            }
            if (arg == "screen" || is_all)
            {
                success = true;
                TheClient.UpdateWindow();
            }
            if (arg == "shaders" || is_all)
            {
                success = true;
                TheClient.Shaders.Clear();
                TheClient.ShadersCheck();
            }
            if (arg == "audio" || is_all)
            {
                success = true;
                TheClient.Sounds.Init(TheClient, TheClient.CVars);
            }
            if (!success)
            {
                entry.Bad(queue, "Invalid argument.");
            }
            else
            {
                entry.Good(queue, "Successfully reloaded specified values.");
            }
        }
예제 #51
0
        public override void Execute(FreneticScript.CommandSystem.CommandQueue queue, CommandEntry entry)
        {
            LocationTag loc = LocationTag.For(entry.GetArgument(queue, 1));

            if (loc == null)
            {
                queue.HandleError(entry, "Invalid location!");
                return;
            }
            EntityTag entity = EntityTag.For(entry.GetArgumentObject(queue, 0));

            if (entity == null)
            {
                queue.HandleError(entry, "Invalid entity!");
                return;
            }
            ZombieTag zombie;

            if (entity.TryGetZombie(out zombie))
            {
                zombie.Internal.target.position  = loc.ToVector3();
                zombie.Internal.seeker.canMove   = true;
                zombie.Internal.seeker.canSearch = true;
                zombie.Internal.path             = EZombiePath.RUSH; // TODO: Option for this?
                if (!zombie.Internal.isTicking)
                {
                    zombie.Internal.isTicking = true;
                    ZombieManager.tickingZombies.Add(zombie.Internal);
                }
                if (entry.ShouldShowGood(queue))
                {
                    entry.Good(queue, "Successfully started a zombie walking to " + TagParser.Escape(loc.ToString()) + "!");
                }
                return;
            }
            AnimalTag animal;

            if (entity.TryGetAnimal(out animal))
            {
                animal.Internal.target = loc.ToVector3();
                if (!animal.Internal.isTicking)
                {
                    animal.Internal.isTicking = true;
                    AnimalManager.tickingAnimals.Add(animal.Internal);
                }
                if (entry.ShouldShowGood(queue))
                {
                    entry.Good(queue, "Successfully started an animal walking to " + TagParser.Escape(loc.ToString()) + "!");
                }
                return;
            }
            queue.HandleError(entry, "That entity can't be made to walk!");
        }
예제 #52
0
 public override void AdaptBlockFollowers(CommandEntry entry, List <CommandEntry> input, List <CommandEntry> fblock)
 {
     entry.BlockEnd -= input.Count;
     input.Clear();
     base.AdaptBlockFollowers(entry, input, fblock);
 }
예제 #53
0
 public static string GetDescription(this CommandEntry e)
 {
     return(GetDescription(e.Handler));
 }
예제 #54
0
 public override void Execute(CommandQueue queue, CommandEntry entry)
 {
     entry.Info(queue, "Network usage (last second): " + GetUsages(TheClient.Network.UsagesLastSecond));
     entry.Info(queue, "Network usage (total): " + GetUsages(TheClient.Network.UsagesTotal));
 }
예제 #55
0
        public TitleMenuItem(MonoDevelop.Components.Commands.CommandManager manager, CommandEntry entry, CommandInfo commandArrayInfo = null, CommandSource commandSource = CommandSource.MainMenu, object initialCommandTarget = null, Menu menu = null)
        {
            this.manager = manager;
            this.initialCommandTarget = initialCommandTarget;
            this.commandSource        = commandSource;
            this.commandArrayInfo     = commandArrayInfo;

            this.menu     = menu;
            menuEntry     = entry;
            menuEntrySet  = entry as CommandEntrySet;
            menuLinkEntry = entry as LinkCommandEntry;

            if (commandArrayInfo != null)
            {
                Header = commandArrayInfo.Text;

                var commandArrayInfoSet = commandArrayInfo as CommandInfoSet;
                if (commandArrayInfoSet != null)
                {
                    foreach (var item in commandArrayInfoSet.CommandInfos)
                    {
                        if (item.IsArraySeparator)
                        {
                            Items.Add(new Separator {
                                UseLayoutRounding = true,
                            });
                        }
                        else
                        {
                            Items.Add(new TitleMenuItem(manager, entry, item, commandSource, initialCommandTarget, menu));
                        }
                    }
                }
            }

            if (menuEntrySet != null)
            {
                Header = menuEntrySet.Name;

                foreach (CommandEntry item in menuEntrySet)
                {
                    if (item.CommandId == MonoDevelop.Components.Commands.Command.Separator)
                    {
                        Items.Add(new Separator {
                            UseLayoutRounding = true,
                        });
                    }
                    else
                    {
                        Items.Add(new TitleMenuItem(manager, item, menu: menu));
                    }
                }
            }
            else if (menuLinkEntry != null)
            {
                Header = menuLinkEntry.Text;
                Click += OnMenuLinkClicked;
            }
            else if (entry != null)
            {
                actionCommand = manager.GetCommand(menuEntry.CommandId) as ActionCommand;
                if (actionCommand == null)
                {
                    return;
                }

                IsCheckable = actionCommand.ActionType == ActionType.Check;

                // FIXME: Use proper keybinding text.
                if (actionCommand.KeyBinding != null)
                {
                    InputGestureText = KeyBindingManager.BindingToDisplayLabel(actionCommand.KeyBinding, true);
                }

                try {
                    if (!actionCommand.Icon.IsNull)
                    {
                        Icon = new ImageBox(actionCommand.Icon.GetStockIcon().WithSize(Xwt.IconSize.Small));
                    }
                } catch (Exception ex) {
                    MonoDevelop.Core.LoggingService.LogError("Failed loading menu icon: " + actionCommand.Icon, ex);
                }
                Click += OnMenuClicked;
            }

            Height            = SystemParameters.CaptionHeight;
            UseLayoutRounding = true;
        }
예제 #56
0
 public override void Execute(FreneticScript.CommandSystem.CommandQueue queue, CommandEntry entry)
 {
     try
     {
         IntegerTag num = IntegerTag.TryFor(entry.GetArgumentObject(queue, 1));
         if (num.Internal < 0)
         {
             queue.HandleError(entry, "Must provide a non-negative number!");
             return;
         }
         EntityTag entity = EntityTag.For(entry.GetArgumentObject(queue, 0));
         if (entity == null)
         {
             queue.HandleError(entry, "Invalid entity!");
             return;
         }
         PlayerTag player;
         if (entity.TryGetPlayer(out player))
         {
             UFMHealthController healthController = player.Internal.player.gameObject.GetComponent <UFMHealthController>();
             uint amount = (uint)num.Internal;
             if (healthController != null)
             {
                 healthController.Heal(amount);
                 amount = (uint)(((double)amount / healthController.maxHealth) * 100.0);
             }
             PlayerLife life = player.Internal.player.life;
             life._health = healthController.Translate();
             life.channel.send("tellHealth", ESteamCall.OWNER, ESteamPacket.UPDATE_RELIABLE_BUFFER, new object[]
             {
                 life.health
             });
             if (entry.ShouldShowGood(queue))
             {
                 uint finalHealth = healthController != null ? healthController.health : life.health;
                 entry.Good(queue, "Successfully healed a player to a new health value of " + finalHealth + "!");
             }
             return;
         }
         ZombieTag zombie;
         if (entity.TryGetZombie(out zombie))
         {
             Zombie inZomb = zombie.Internal;
             inZomb.health += (ushort)num.Internal;
             if (inZomb.health > inZomb.maxHealth)
             {
                 inZomb.health = inZomb.maxHealth;
             }
             if (entry.ShouldShowGood(queue))
             {
                 entry.Good(queue, "Successfully healed a zombie to a new health value of " + inZomb.health + "!");
             }
             return;
         }
         AnimalTag animal;
         if (entity.TryGetAnimal(out animal))
         {
             Animal inAnimal = animal.Internal;
             inAnimal.health += (ushort)num.Internal;
             if (inAnimal.health > inAnimal.asset.health)
             {
                 inAnimal.health = inAnimal.asset.health;
             }
             if (entry.ShouldShowGood(queue))
             {
                 entry.Good(queue, "Successfully healed an animal to a new health value of " + inAnimal.health + "!");
             }
             return;
         }
         BarricadeTag barricade;
         if (entity.TryGetBarricade(out barricade))
         {
             Barricade inBarricade = barricade.InternalData.barricade;
             inBarricade.health += (ushort)num.Internal;
             ushort max = ((ItemBarricadeAsset)Assets.find(EAssetType.ITEM, inBarricade.id)).health;
             if (inBarricade.health > max)
             {
                 inBarricade.health = max;
             }
             if (entry.ShouldShowGood(queue))
             {
                 entry.Good(queue, "Successfully healed a barricade to a new health value of " + inBarricade.health + "!");
             }
             return;
         }
         ResourceTag resource;
         if (entity.TryGetResource(out resource))
         {
             ResourceSpawnpoint inResource = resource.Internal;
             inResource.health += (ushort)num.Internal;
             ushort max = ((ResourceAsset)Assets.find(EAssetType.RESOURCE, inResource.id)).health;
             if (inResource.health > max)
             {
                 inResource.health = max;
             }
             if (entry.ShouldShowGood(queue))
             {
                 entry.Good(queue, "Successfully healed a resource to a new health value of " + inResource.health + "!");
             }
             return;
         }
         StructureTag structure;
         if (entity.TryGetStructure(out structure))
         {
             Structure inStructure = structure.InternalData.structure;
             inStructure.health += (ushort)num.Internal;
             ushort max = ((ItemStructureAsset)Assets.find(EAssetType.ITEM, inStructure.id)).health;
             if (inStructure.health > max)
             {
                 inStructure.health = max;
             }
             if (entry.ShouldShowGood(queue))
             {
                 entry.Good(queue, "Successfully healed a structure to a new health value of " + inStructure.health + "!");
             }
             return;
         }
         VehicleTag vehicle;
         if (entity.TryGetVehicle(out vehicle))
         {
             vehicle.Internal.askRepair((ushort)num.Internal);
             if (entry.ShouldShowGood(queue))
             {
                 entry.Good(queue, "Successfully healed a vehicle to a new health value of " + vehicle.Internal.health + "!");
             }
             return;
         }
         queue.HandleError(entry, "That entity can't be healed!");
     }
     catch (Exception ex) // TODO: Necessity?
     {
         queue.HandleError(entry, ("Failed to heal entity: " + ex.ToString()));
     }
 }
예제 #57
0
        /// <summary>Adapts a command entry to CIL.</summary>
        /// <param name="values">The adaptation-relevant values.</param>
        /// <param name="entry">The present entry ID.</param>
        public override void AdaptToCIL(CILAdaptationValues values, int entry)
        {
            CommandEntry cent = values.CommandAt(entry);
            bool         db   = cent.DBMode <= DebugMode.FULL;

            if (cent.IsCallback)
            {
                int lvar_ind_loc = GetSaveLoc(values, entry);
                values.LoadQueue();
                if (db)
                {
                    values.LoadEntry(entry);
                }
                else
                {
                    values.ILGen.Emit(OpCodes.Ldc_I4, cent.BlockStart - 1);
                }
                values.LoadLocalVariable(lvar_ind_loc);
                values.ILGen.Emit(OpCodes.Call, db ? TryForeachCILMethod : TryForeachCILMethodNoDebug);
                values.ILGen.Emit(OpCodes.Brtrue, values.Entry.AdaptedILPoints[cent.BlockStart]);
                return;
            }
            string arg = cent.Arguments[0].ToString();

            if (arg == "stop")
            {
                for (int i = entry - 1; i >= 0; i--)
                {
                    CommandEntry nextEntry = values.Entry.Entries[i];
                    if (nextEntry.Command is not ForeachCommand || nextEntry.IsCallback)
                    {
                        continue;
                    }
                    string a0 = nextEntry.Arguments[0].ToString();
                    if (a0 == "start" && nextEntry.InnerCommandBlock != null)
                    {
                        if (db)
                        {
                            values.LoadQueue();
                            values.LoadEntry(entry);
                            values.ILGen.Emit(OpCodes.Call, DebugStopMethod);
                        }
                        values.ILGen.Emit(OpCodes.Br, values.Entry.AdaptedILPoints[nextEntry.BlockEnd + 2]);
                        return;
                    }
                }
                throw new ErrorInducedException("Invalid 'foreach stop' command: not inside a foreach block!");
            }
            else if (arg == "next")
            {
                for (int i = entry - 1; i >= 0; i--)
                {
                    CommandEntry nextEntry = values.Entry.Entries[i];
                    if (nextEntry.Command is not ForeachCommand || nextEntry.IsCallback)
                    {
                        continue;
                    }
                    string a0 = nextEntry.Arguments[0].ToString();
                    if (a0 == "start" && nextEntry.InnerCommandBlock != null)
                    {
                        if (db)
                        {
                            values.LoadQueue();
                            values.LoadEntry(entry);
                            values.ILGen.Emit(OpCodes.Call, DebugNextMethod);
                        }
                        values.ILGen.Emit(OpCodes.Br, values.Entry.AdaptedILPoints[nextEntry.BlockEnd + 1]);
                        return;
                    }
                }
                throw new ErrorInducedException("Invalid 'foreach next' command: not inside a foreach block!");
            }
            else if (arg == "start")
            {
                SingleCILVariable locVar = cent.VarLookup[cent.GetSaveNameNoParse("foreach_value")];
                values.LoadQueue();
                values.LoadEntry(entry);
                values.LoadRunnable();
                values.ILGen.Emit(OpCodes.Call, CreateListItemMethod);
                values.ILGen.Emit(OpCodes.Stfld, locVar.Field);
                values.LoadLocalVariable(locVar.Index);
                values.ILGen.Emit(OpCodes.Call, db ? TryForeachNumberedCILMethod : TryForeachNumberedCIL_NoDebugMethod);
                values.ILGen.Emit(OpCodes.Brfalse, values.Entry.AdaptedILPoints[cent.BlockEnd + 2]);
            }
            else
            {
                throw new ErrorInducedException("Invalid 'foreach' command: unknown argument: " + arg);
            }
        }
예제 #58
0
 private bool IsCurrentEntry(CommandEntry entry)
 {
     var(entryHostname, entryPort)     = SplitAddressAndPort(entry.Address);
     var(currentHostname, currentPort) = SplitAddressAndPort(currentAddress);
     return(entryHostname == currentHostname && entryPort == currentPort);
 }
예제 #59
0
        public override void Execute(FreneticScript.CommandSystem.CommandQueue queue, CommandEntry entry)
        {
            ListTag        players = ListTag.For(entry.GetArgument(queue, 0));
            TemplateObject tcolor  = entry.GetArgumentObject(queue, 1);
            ColorTag       color   = ColorTag.For(tcolor);

            if (color == null)
            {
                queue.HandleError(entry, "Invalid color: " + TagParser.Escape(tcolor.ToString()));
                return;
            }
            string    tchatter = entry.GetArgument(queue, 2);
            PlayerTag chatter  = PlayerTag.For(tchatter);

            if (chatter == null)
            {
                queue.HandleError(entry, "Invalid chatting player: " + TagParser.Escape(tchatter));
                return;
            }
            string message = entry.GetArgument(queue, 3);

            foreach (TemplateObject tplayer in players.ListEntries)
            {
                PlayerTag player = PlayerTag.For(tplayer.ToString());
                if (player == null)
                {
                    queue.HandleError(entry, "Invalid player: " + TagParser.Escape(tplayer.ToString()));
                    continue;
                }
                ChatManager.manager.channel.send("tellChat", player.Internal.playerID.steamID, ESteamPacket.UPDATE_UNRELIABLE_BUFFER,
                                                 chatter.Internal.playerID.steamID, (byte)0 /* TODO: Configurable mode? */, color.Internal, message);
                if (entry.ShouldShowGood(queue))
                {
                    entry.Good(queue, "Successfully sent a message.");
                }
            }
        }
예제 #60
0
 public override void Execute(CommandQueue queue, CommandEntry entry)
 {
     TheClient.ShowInventory();
 }