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.");
         }
     }
 }
 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());
     }
 }
 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)
 {
     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!");
     }
 }
Beispiel #5
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!");
     }
 }
 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
     });
 }
Beispiel #7
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 + ".");
 }
Beispiel #8
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);
         }
     }
 }
Beispiel #9
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}>.");
 }
Beispiel #10
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);
 }
Beispiel #11
0
        public void AfterEngineInit()
        {
            // Basics.
            {
                var deviceDesc = new Device.Descriptor {DebugDevice = true};
                renderDevice = new ClearSight.RendererDX12.Device(ref deviceDesc,
                    ClearSight.RendererDX12.Device.FeatureLevel.Level_11_0);

                var descCQ = new CommandQueue.Descriptor() {Type = CommandListType.Graphics};
                commandQueue = renderDevice.Create(ref descCQ);

                var wih = new WindowInteropHelper(window);
                var swapChainDesc = new SwapChain.Descriptor()
                {
                    AssociatedGraphicsQueue = commandQueue,

                    MaxFramesInFlight = 3,
                    BufferCount = 3,

                    Width = (uint) window.Width,
                    Height = (uint) window.Height,
                    Format = Format.R8G8B8A8_UNorm,

                    SampleCount = 1,
                    SampleQuality = 0,

                    WindowHandle = wih.Handle,
                    Fullscreen = false
                };
                swapChain = renderDevice.Create(ref swapChainDesc);

                var commandListDesc = new CommandList.Descriptor()
                {
                    Type = CommandListType.Graphics,
                    AllocationPolicy = new CommandListInFlightFrameAllocationPolicy(CommandListType.Graphics, swapChain)
                };
                commandList = renderDevice.Create(ref commandListDesc);
            }

            // Render targets.
            {
                var descHeapDesc = new DescriptorHeap.Descriptor()
                {
                    Type = DescriptorHeap.Descriptor.ResourceDescriptorType.RenderTarget,
                    NumResourceDescriptors = swapChain.Desc.BufferCount
                };
                descHeapRenderTargets = renderDevice.Create(ref descHeapDesc);

                var rtvViewDesc = new RenderTargetViewDescription()
                {
                    Format = swapChain.Desc.Format,
                    Dimension = Dimension.Texture2D,
                    Texture = new TextureSubresourceDesc(mipSlice: 0)
                };
                for (uint i = 0; i < swapChain.Desc.BufferCount; ++i)
                {
                    renderDevice.CreateRenderTargetView(descHeapRenderTargets, i, swapChain.BackbufferResources[i], ref rtvViewDesc);
                }
            }
        }
Beispiel #12
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.");
 }
 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!");
 }
Beispiel #14
0
        public SimpleRequestActor(CommandQueue queue, IRequestService requestService)
        {
            _queue = queue;
            _requestService = requestService;

            _body.AppendLine("Actor created on thread: " + Thread.CurrentThread.ManagedThreadId);
        }
 protected void CreateContext()
 {
     xenStore = MockRepository.GenerateMock<IXenStore>();
     commandFactory = MockRepository.GenerateMock<ICommandFactory>();
     executableCommand = MockRepository.GenerateMock<IExecutableCommand>();
     logger = MockRepository.GenerateMock<ILogger>();
     commandQueue = new CommandQueue(xenStore, commandFactory, logger);
 }
 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());
     }
 }
 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!");
 }
Beispiel #18
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 + "!");
 }
 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 + "!");
     }
 }
Beispiel #20
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);
 }
Beispiel #21
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));
 }
Beispiel #22
0
 public override void UnknownCommand(CommandQueue queue, string basecommand, string[] arguments)
 {
     WriteLine(TextStyle.Color_Error + "Unknown command '" +
         TextStyle.Color_Standout + basecommand + TextStyle.Color_Error + "'.");
     if (queue.Outputsystem != null)
     {
         queue.Outputsystem.Invoke("Unknown command '" + TextStyle.Color_Standout
             + basecommand + TextStyle.Color_Error + "'.", MessageType.BAD);
     }
 }
Beispiel #23
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;
 }
 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!");
 }
 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?)!");
     }
 }
Beispiel #26
0
        public ClientModel(string localIP, string serverHost, DesktopViewer.DesktopChangedEventHandler onDesktopChanged)
        {
            _connected = false;
            _id = -1;
            _serverHost = serverHost;
            _ip = localIP;
            _hostname = Dns.GetHostName();
            _commands = new CommandQueue();
            _singletonServer = (IServerModel)Activator.GetObject(typeof(IServerModel), _serverHost);

            _viewer = new DesktopViewer( onDesktopChanged);
        }
Beispiel #27
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");
 }
Beispiel #28
0
        public GPURadixSort(
             CommandQueue commandQue,
             Context context,
            Device device
            )
        {
            gpuConstants = new GPUConstants();
            gpuConstants.L = radix_BitsL;
            gpuConstants.numGroupsPerBlock = NumGroupsPerBlock;
            gpuConstants.R = R;
            gpuConstants.numThreadsPerGroup = numThreadsPerBlock/NumGroupsPerBlock;
            gpuConstants.numThreadsPerBlock = numThreadsPerBlock;
            gpuConstants.numBlocks = numBlocks;
            gpuConstants.numRadices = num_Radices;
            gpuConstants.numRadicesPerBlock = num_Radices/numBlocks;
            gpuConstants.bitMask = BIT_MASK_START;
            counters.Initialize();
            OpenCL.Net.ErrorCode error;
            cxGPUContext = context;
            cqCommandQueue = commandQue;
            _device = device;
            //Create a command queue, where all of the commands for execution will be added
            /*cqCommandQueue = Cl.CreateCommandQueue(cxGPUContext, _device, (CommandQueueProperties)0, out  error);
            CheckErr(error, "Cl.CreateCommandQueue");*/
            string programSource = System.IO.File.ReadAllText(programPath1);
             IntPtr[] progSize = new IntPtr[] { (IntPtr)programSource.Length };
            OpenCL.Net.Program clProgramRadix = Cl.CreateProgramWithSource(cxGPUContext, 1, new[] { programSource },progSize,
                out error);
            CheckErr(error,"createProgramm");
            string flags = "-cl-fast-relaxed-math";

                error = Cl.BuildProgram(clProgramRadix, 1, new[] { _device }, flags, null, IntPtr.Zero);
            CheckErr(error, "Cl.BuildProgram");
            //Check for any compilation errors
            if (Cl.GetProgramBuildInfo(clProgramRadix, _device, ProgramBuildInfo.Status, out error).CastTo<BuildStatus>()
                != BuildStatus.Success)
            {
                CheckErr(error, "Cl.GetProgramBuildInfo");
                Console.WriteLine("Cl.GetProgramBuildInfo != Success");
                Console.WriteLine(Cl.GetProgramBuildInfo(clProgramRadix, _device, ProgramBuildInfo.Log, out error));
                return;
            }
            int ciErrNum;

            ckSetupAndCount = Cl.CreateKernel(clProgramRadix, "SetupAndCount", out error);
            CheckErr(error, "Cl.CreateKernel");
            ckSumIt = Cl.CreateKernel(clProgramRadix, "SumIt", out error);
            CheckErr(error, "Cl.CreateKernel");
            ckReorderingKeysOnly = Cl.CreateKernel(clProgramRadix, "ReorderingKeysOnly", out error);
            CheckErr(error, "Cl.CreateKernel");
            ckReorderingKeyValue = Cl.CreateKernel(clProgramRadix, "ReorderingKeyValue", out error);
            CheckErr(error, "Cl.CreateKernel");
        }
Beispiel #29
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);
 }
 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!");
 }
        /// <summary>Executes the callback part of the while command.</summary>
        /// <param name="queue">The command queue involved.</param>
        /// <param name="entry">Entry to be executed.</param>
        /// <param name="integer">While Index holder.</param>
        public static bool TryWhileCIL(CommandQueue queue, CommandEntry entry, IntegerTag integer)
        {
            WhileCommandData dat = queue.CurrentRunnable.EntryData[entry.BlockStart - 1] as WhileCommandData;

            integer.Internal = ++dat.Index;
            if (IfCommand.TryIf(queue, entry, new List <Argument>(dat.ComparisonArgs)))
            {
                if (entry.ShouldShowGood(queue))
                {
                    entry.GoodOutput(queue, "While looping: " + TextStyle.Separate + dat.Index + TextStyle.Base + "...");
                }
                return(true);
            }
            if (entry.ShouldShowGood(queue))
            {
                entry.GoodOutput(queue, "While stopping.");
            }
            return(false);
        }
Beispiel #32
0
        /// <summary>Executes the callback part of the repeat command.</summary>
        /// <param name="queue">The command queue involved.</param>
        /// <param name="entry">Entry to be executed.</param>
        public static bool TryRepeatCIL(CommandQueue queue, CommandEntry entry)
        {
            RepeatCommandData dat = queue.CurrentRunnable.EntryData[entry.BlockStart - 1] as RepeatCommandData;

            ++dat.Index;
            if (dat.Index <= dat.Total)
            {
                if (entry.ShouldShowGood(queue))
                {
                    entry.GoodOutput(queue, "Repeating...: " + TextStyle.Separate + dat.Index + TextStyle.Base + "/" + TextStyle.Separate + dat.Total);
                }
                return(true);
            }
            if (entry.ShouldShowGood(queue))
            {
                entry.GoodOutput(queue, "Repeat stopping.");
            }
            return(false);
        }
Beispiel #33
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)
        {
            int count = 1;

            if (entry.Arguments.Length > 0)
            {
                IntegerTag inter = IntegerTag.TryFor(entry.GetArgumentObject(queue, 0));
                if (inter != null)
                {
                    count = (int)inter.Internal;
                }
            }
            if (count <= 0)
            {
                ShowUsage(queue, entry);
                return;
            }
            for (int i = 0; i < count; i++)
            {
                CompiledCommandRunnable runnable = queue.CurrentRunnable;
                for (int ind = runnable.Index; ind < runnable.Entry.Entries.Length; ind++)
                {
                    CommandEntry tentry = runnable.Entry.Entries[ind];
                    if (tentry.Command.Meta.IsBreakable && tentry.IsCallback)
                    {
                        runnable.Index = ind + 1;
                        goto completed;
                    }
                }
                if (queue.RunningStack.Count > 1)
                {
                    queue.RunningStack.Pop();
                }
                else
                {
                    queue.HandleError(entry, "Not in that many blocks!");
                    return;
                }
completed:
                continue;
            }
            entry.GoodOutput(queue, "Broke free successfully.");
        }
Beispiel #34
0
        public Bitmap RunImageKernel(Bitmap tex, string kernelKey)
        {
            Kernel k      = _kernels[kernelKey];
            int    width  = tex.Width;
            int    height = tex.Height;

            byte[] buffer = new byte[(width * height * 4)];



            BitmapData data = tex.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite,
                                           PixelFormat.Format32bppArgb);

            Marshal.Copy(data.Scan0, buffer, 0, buffer.Length);

            MemoryBuffer mb = c.CreateBuffer(MemoryFlag.ReadWrite | MemoryFlag.CopyHostPointer, buffer);

            k.SetKernelArgument(0, mb);

            CommandQueue cq = CommandQueue.CreateCommandQueue(c, d);

            cq.EnqueueNDRangeKernel(k, 1, buffer.Length);

            buffer = cq.EnqueueReadBuffer <byte>(mb, buffer.Length);


            Marshal.Copy(buffer, 0, data.Scan0, buffer.Length);

            tex.UnlockBits(data);
            return(tex);
            //System.Drawing.Bitmap bmp = new System.Drawing.Bitmap((int)width, (int)height);
            //BitmapData data = bmp.LockBits(new System.Drawing.Rectangle(0, 0, (int)width, (int)height),
            //    System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            //Marshal.Copy(buffer, 0, data.Scan0, buffer.Length);
            //bmp.UnlockBits(data);

            //bmp.Save("testimage.png");

            //GL.DeleteTexture(tex.textureID);


            //GL.TexSubImage2D(TextureTarget.Texture2D, 0, 0,0, (int)width, (int)height, PixelFormat.Rgba, PixelType.UnsignedByte, buffer);
        }
Beispiel #35
0
        private void ParseLine(string line)
        {
            if (line == "")
            {
                return;
            }

            var matches       = Regex.Matches(line, "[nmgxyzf][+-]?[0-9]*\\.?[0-9]*", RegexOptions.IgnoreCase).Cast <Match>();
            var parsedCommand = string.Join("", matches.Select(m => m.Value));

            if (parsedCommand != line)
            {
                AddError("Строка имеет неверный формат");
            }

            var lexemes  = matches.Select(m => Tokenize(m.Value)).ToList();
            var commands = lexemes.Where(lexeme => lexeme.Type == LexemeType.Command);

            if (commands.Count() > 1)
            {
                AddError("Допустима только одна команда в строке");
            }
            if (commands.Count() < 1)
            {
                AddError("В строке отсутствует команда");
            }

            if (matches.Count() == 0)
            {
                return;
            }

            var commandLexeme = commands.First();

            lexemes.Remove(commandLexeme);

            var command = ParseCommand(commandLexeme.Name, lexemes.ToArray());

            if (!CommandIsPersisted)
            {
                CommandQueue.Enqueue(command);
            }
        }
        /// <summary>Executes the callback part of the foreach command.</summary>
        /// <param name="queue">The command queue involved.</param>
        /// <param name="entry">Entry to be executed.</param>
        /// <param name="listItem">Dynamic tag to hold the item in the list.</param>
        public static bool TryForeachCIL(CommandQueue queue, CommandEntry entry, DynamicTag listItem)
        {
            ForeachCommandData dat = queue.CurrentRunnable.EntryData[entry.BlockStart - 1] as ForeachCommandData;

            if (++dat.Index < dat.List.Count)
            {
                listItem.Internal = dat.List[dat.Index];
                if (entry.ShouldShowGood(queue))
                {
                    entry.GoodOutput(queue, "Looping...: " + TextStyle.Separate + dat.Index + TextStyle.Base + "/" + TextStyle.Separate + dat.List.Count);
                }
                return(true);
            }
            if (entry.ShouldShowGood(queue))
            {
                entry.GoodOutput(queue, "Foreach stopping.");
            }
            return(false);
        }
    protected override void OnEnter()
    {
        _scenarioController.GetPlayerDialogueSuccessEvent    += UpdatePlayerDialogue;
        _scenarioController.GetCharacterDialogueSuccessEvent += UpdateCharacterDialogue;
        _scenarioController.FinalStateEvent += HandleFinalState;

        TrackerEventSender.SendEvaluationEvent(TrackerEvalautionEvent.GameFlow, new Dictionary <TrackerEvaluationKey, string>
        {
            { TrackerEvaluationKey.PieceType, "QuestionnaireState" },
            { TrackerEvaluationKey.PieceId, "0" },
            { TrackerEvaluationKey.PieceCompleted, "success" }
        });
        _panel.SetActive(true);
        _background.SetActive(true);
        CommandQueue.AddCommand(new RefreshPlayerDialogueCommand());
        CommandQueue.AddCommand(new RefreshCharacterResponseCommand());
        _questionText.text = string.Empty;
        ShowCharacter();
    }
Beispiel #38
0
 public override void Execute(CommandQueue queue, CommandEntry entry)
 {
     if (entry.Marker == 0)
     {
         queue.HandleError(entry, "Must use +, -, or !");
     }
     else if (entry.Marker == 1)
     {
         TheClient.Player.Use = true;
     }
     else if (entry.Marker == 2)
     {
         TheClient.Player.Use = false;
     }
     else if (entry.Marker == 3)
     {
         TheClient.Player.Use = !TheClient.Player.Use;
     }
 }
        public void When_no_commands_were_processed_it_returns_the_first_command()
        {
            var fixture = new Fixture();

            var unique = fixture.Create <int>();
            var sut    = new CommandQueue(SessionFactory);

            using (var session = SessionFactory.OpenSession())
                using (var tx = session.BeginTransaction())
                {
                    CommandQueue.Enqueue(new TestCommand(unique), session, DateTime.UtcNow);
                    tx.Commit();
                }

            var lastProcessed = sut.GetLastProcessed();
            var command       = (TestCommand)sut.Dequeue(1).First().Payload;

            Assert.AreEqual(unique, command.SomeUniqueProperty);
        }
        public void If_multiple_commands_were_enqueued_it_returns_them_in_FIFO_order()
        {
            var fixture = new Fixture();

            fixture.Customize(new NumericSequencePerTypeCustomization());

            var firstUnique  = fixture.Create <int>();
            var secondUnique = fixture.Create <int>();

            var sut = new CommandQueue(SessionFactory);

            Enqueue(firstUnique);
            Enqueue(secondUnique);

            var lastProcessed = sut.GetLastProcessed();
            var uniques       = sut.Dequeue(2).Select(x => x.Payload).Cast <TestCommand>().Select(x => x.SomeUniqueProperty).ToList();

            CollectionAssert.AreEqual(new[] { firstUnique, secondUnique }, uniques);
        }
        protected override void Draw(GameTimer gt)
        {
            // Reuse the memory associated with command recording.
            // We can only reset when the associated command lists have finished execution on the GPU.
            DirectCmdListAlloc.Reset();

            // A command list can be reset after it has been added to the command queue via ExecuteCommandList.
            // Reusing the command list reuses memory.
            CommandList.Reset(DirectCmdListAlloc, null);

            // Indicate a state transition on the resource usage.
            CommandList.ResourceBarrierTransition(CurrentBackBuffer, ResourceStates.Present, ResourceStates.RenderTarget);

            // Set the viewport and scissor rect. This needs to be reset whenever the command list is reset.
            CommandList.SetViewport(Viewport);
            CommandList.SetScissorRectangles(ScissorRectangle); // TODO: API suggestion: SetScissorRectangle overload similar to SetViewport

            // Clear the back buffer and depth buffer.
            CommandList.ClearRenderTargetView(CurrentBackBufferView, Color.LightSteelBlue);
            // TODO: API suggestion: simplify flags naming to ClearFlags.Depth|Stencil
            CommandList.ClearDepthStencilView(DepthStencilView, ClearFlags.FlagsDepth | ClearFlags.FlagsStencil, 1.0f, 0);

            // Specify the buffers we are going to render to.
            CommandList.SetRenderTargets(CurrentBackBufferView, DepthStencilView);

            // Indicate a state transition on the resource usage.
            CommandList.ResourceBarrierTransition(CurrentBackBuffer, ResourceStates.RenderTarget, ResourceStates.Present);

            // Done recording commands.
            CommandList.Close();

            // Add the command list to the queue for execution.
            CommandQueue.ExecuteCommandList(CommandList);

            // Present the buffer to the screen. Presenting will automatically swap the back and front buffers.
            // Ref: https://msdn.microsoft.com/en-us/library/windows/desktop/bb174576(v=vs.85).aspx
            SwapChain.Present(0, PresentFlags.None);

            // Wait until frame commands are complete. This waiting is inefficient and is
            // done for simplicity. Later we will show how to organize our rendering code
            // so we do not have to wait per frame.
            FlushCommandQueue();
        }
Beispiel #42
0
        public override Event WriteDirect(
            CommandQueue commandQueue,
            bool blocking,
            long bufferOffset, int length,
            sbyte[] data, int dataOffset,
            params Event[] eventWaitList)
        {
            fixed(sbyte *sbytePtr = data)
            {
                void *dataPointer = sbytePtr + dataOffset;

                return(WriteUnsafe(
                           commandQueue,
                           blocking,
                           bufferOffset * sizeof(sbyte), length * sizeof(sbyte),
                           dataPointer,
                           eventWaitList));
            }
        }
Beispiel #43
0
        protected virtual void Initialize(DeviceType deviceType, string source)
        {
            Devices = Platform.QueryDevices(deviceType);
            if (Devices.Length == 0)
            {
                throw new OpenCLException("No devices of type " + deviceType + " present");
            }

            Context = Platform.CreateContext(null, Devices, null, IntPtr.Zero);
            CQs     = new CommandQueue[Devices.Length];
            for (int i = 0; i < CQs.Length; i++)
            {
                CQs[i] = Context.CreateCommandQueue(Devices[i], CommandQueueProperties.PROFILING_ENABLE);
            }
            CQ      = CQs[0];
            Program = Context.CreateProgramWithSource(source);
            Program.Build();
            Kernels = Program.CreateKernelDictionary();
        }
Beispiel #44
0
    static void uniformUpdate_1Batch(
        CommandQueue cqCommandQueue,
        Mem d_Dst,
        Mem d_Buffer,
        int n,
        int ofsDataOffset
        )
    {
        int[] localWorkSize = new int[1], globalWorkSize = new int[1];

        ckUniformUpdate.SetArg(0, d_Dst);
        ckUniformUpdate.SetArg(1, d_Buffer);
        ckUniformUpdate.SetArg(2, ofsDataOffset);

        localWorkSize[0]  = WORKGROUP_SIZE;
        globalWorkSize[0] = n * WORKGROUP_SIZE;

        cqCommandQueue.EnqueueNDRangeKernel(ckUniformUpdate, 1, null, globalWorkSize, localWorkSize);
    }
Beispiel #45
0
    private void Initiate(Meeple meeple)
    {
        this.meeple = meeple;
        this.start  = meeple.standingOn;
        startCenter = start.Position.Center.ToVector2();
        curArrow    = new ArrowAnimatable(start.Position, "movementarrow", start.ZPosition + 1);
        CommandQueue.Queue(new AddToBoardCommand(curArrow));

        // build direction vectors to each connected field
        directions = new Vector2[start.connectedFields.Count];
        for (int i = 0; i < directions.Length; i++)
        {
            directions[i] = start.connectedFields[i].Position.Center.ToVector2() - startCenter;
            directions[i].Normalize();
        }

        isActive  = true;
        initiated = DateTime.Now;
    }
Beispiel #46
0
        public override Event ReadDirect(
            CommandQueue commandQueue,
            bool blocking,
            long bufferOffset, int length,
            double[] data, int dataOffset,
            params Event[] eventWaitList)
        {
            fixed(double *doublePtr = data)
            {
                void *dataPointer = doublePtr + dataOffset;

                return(ReadUnsafe(
                           commandQueue,
                           blocking,
                           bufferOffset * sizeof(double), length * sizeof(double),
                           dataPointer,
                           eventWaitList));
            }
        }
Beispiel #47
0
        private void button2_Click(object sender, EventArgs e)
        {
            m_currentloc = comboBox1.Text;
            today        = today.AddDays(-1);
            DisableButtons();
            if (DataStore.Instance().m_start == DataStore.Instance().m_left)
            {
                //fetch new data
                input.query       = m_currentloc;
                input.num_of_days = "1";

                WeatherInput past = null;
                past       = new WeatherInput();
                past.query = m_currentloc;

                DateTime startdate = DataStore.Instance().m_start.datetime;
                startdate = startdate.AddDays(-5);
                string date_s = startdate.ToString("yyyy-MM-dd");
                past.date = date_s;

                DateTime enddate = DataStore.Instance().m_start.datetime;

                enddate = enddate.AddDays(-1);
                string enddate_s = enddate.ToString("yyyy-MM-dd");
                past.enddate = enddate_s;



                Command cmd = new Command();
                cmd.SetInput(input, past, RefreshType.AddLeft);
                cmd.SetCallback(updateui);
                CommandQueue.Instance().add(cmd);
            }
            else
            {
                DataStore.Instance().moveleft();
                //Uncomment following line if you want to change todays weather when you click left button
                //DataStore.Instance().m_today = DataStore.Instance().m_today.prev;
                updateui(null);
            }
            SetButtonNames();
        }
Beispiel #48
0
        public void TestIfSpirV()
        {
            var a = new int[] { 7, 14, 6, 10 };
            var b = new int[] { 5, 10, 6, 14 };
            var r = new int[4];

            // compile SPIR-V kernel
            var module = new MemoryStream();

            SpirCompiler.EmitKernel("opencl-tests", "OpenCl.Tests.TestIf", "test_if", module);
            // ***DEBUG***
            using (var stream = new FileStream("test_if.spv", FileMode.Create))
            {
                var buf = module.ToArray();
                stream.Write(buf, 0, buf.Length);
            }
            // ***ENDEBUG***

            // test SPIR-V kernel
            var platform = Platform.GetPlatformIDs().First();
            var device   = Device.GetDeviceIDs(platform, DeviceType.All).First();

            using (var context = Context.CreateContext(null, device, null, null))
                using (var queue = CommandQueue.CreateCommandQueue(context, device))
                    using (var program = Program.CreateProgramWithIL(context, device, module.ToArray()))
                        using (var kernel = Kernel.CreateKernel(program, "test_if"))
                            using (var ma = Mem <int> .CreateBuffer(context, MemFlags.ReadOnly | MemFlags.CopyHostPtr, a))
                                using (var mb = Mem <int> .CreateBuffer(context, MemFlags.ReadOnly | MemFlags.CopyHostPtr, b))
                                    using (var mr = Mem <int> .CreateBuffer(context, MemFlags.ReadWrite, 4 * Marshal.SizeOf <int>()))
                                    {
                                        kernel.SetKernelArg(0, (HandleObject)ma);
                                        kernel.SetKernelArg(1, (HandleObject)mb);
                                        kernel.SetKernelArg(2, (HandleObject)mr);
                                        queue.EnqueueNDRangeKernel(kernel, null, new int[] { 4 }, null, null);
                                        queue.Finish();
                                        queue.EnqueueReadBuffer(mr, true, r);
                                    }
            Assert.AreEqual(2, r[0]);
            Assert.AreEqual(4, r[1]);
            Assert.AreEqual(0, r[2]);
            Assert.AreEqual(4, r[3]);
        }
Beispiel #49
0
        public EditorWindow(Editor e)
        {
            Editor = e;

            EntityEditor.Editor = e;
            TileEditor.Window   = this;
            TileEditor.Editor   = e;

            Commands = new CommandQueue {
                Editor = e
            };

            if (!Engine.EditingLevel)
            {
                TileEditor.ReloadBiome();
                return;
            }

            var locales = FileHandle.FromRoot("Prefabs/");

            if (!locales.Exists())
            {
                levels = new[] {
                    "test"
                };

                return;
            }

            var names = new List <string>();

            foreach (var f in locales.ListFileHandles())
            {
                if (f.Extension == ".lvl")
                {
                    names.Add(f.NameWithoutExtension);
                }
            }

            levels = names.ToArray();
            Load();
        }
Beispiel #50
0
        private States ProcessCommands()
        {
            if (loopStopRequested)
            {
                return(States.Stopping);
            }
            else if (CommandQueue.Available)
            {
                var command = CommandQueue.DequeueCommand();
                switch ((Commands)command.CommandSignal)
                {
                case Commands.StartTask:
                    var taskStartRequest = (TaskStartRequest)command.Parameters[0];
                    this.task = new Task(this, taskStartRequest);
                    return(States.StartTask);
                }
            }

            return(States.Idle);
        }
Beispiel #51
0
 // TODO: Get an Argument[] here.
 public override void UnknownCommand(CommandQueue queue, string basecommand, string[] arguments)
 {
     if (TheClient.Network.IsAlive)
     {
         StringBuilder sb = new StringBuilder();
         sb.Append(basecommand);
         for (int i = 0; i < arguments.Length; i++)
         {
             // TODO: parsed Argument value!
             sb.Append("\n").Append(arguments[i]);
         }
         CommandPacketOut packet = new CommandPacketOut(sb.ToString());
         TheClient.Network.SendPacket(packet);
     }
     else
     {
         WriteLine(TextStyle.Color_Error + "Unknown command '" +
                   TextStyle.Color_Standout + basecommand + TextStyle.Color_Error + "'.");
     }
 }
Beispiel #52
0
        public void TakeBusinessDecisionAnComplete()
        {
            Logger.Info("[DemoSaga] Evaluating business logic");
            if (State.Event1Arrived && State.Event2Arrived)
            {
                Logger.Info("[DemoSaga] both 'DemoEvent1' and 'DemoEvent2' arrived, sending out 'SagaCommand'");
                CommandQueue.Enqueue(new SagaCommand()
                {
                    Id = State.Id
                });

                Logger.Info("[DemoSaga] marking the operation as completed");
                MarkAsCompleted();
                Logger.Info("[DemoSaga] Saga ended");
            }
            else
            {
                Logger.Info("[DemoSaga] Saga not completed yet, awaiting for more events.");
            }
        }
Beispiel #53
0
 public void Transfer(ITransferable receiver, decimal transferAmount)
 {
     Console.WriteLine("Transaction: account " + _accountNumber + " sending " + transferAmount + " to account " + receiver.GetAccountNumber());
     Console.WriteLine("Account " + _accountNumber + " balance:  " + _moneyAmount);
     Console.WriteLine("Account " + receiver.GetAccountNumber() + " balance:  " + receiver.GetBalance());
     if (transferAmount < _moneyAmount)
     {
         _moneyAmount -= transferAmount;
         receiver.AddMoney(transferAmount);
         Console.WriteLine("Account " + _accountNumber + " balance: " + _moneyAmount);
         Console.WriteLine("Account " + receiver.GetAccountNumber() + " balance:  " + receiver.GetBalance());
         Console.WriteLine("Transaction successful\n");
     }
     else
     {
         CommandQueue commands = CommandQueue.GetInstance();
         commands.AddCommand(new TransferCommand(receiver.GetAccount(), this, transferAmount));
         Console.WriteLine("Transaction unsuccessful\n");
     }
 }
Beispiel #54
0
    protected sealed override void GetComponents()
    {
        base.GetComponents();
        grabber      = gameObject.AddComponent <GrabberComponent>();
        commandQueue = gameObject.AddComponent <CommandQueue>();
        vision       = gameObject.AddComponent <VisionComponent>();

        foreach (Transform tf in transform)
        {
            if (tf.name == "HeldObjectPosition")
            {
                grabber.SetObjectHoldPosition(tf);
            }
            else if (tf.name == "Particle System")
            {
                explosionPS = gameObject.GetComponentInChildren <ParticleSystem>();
                explosionPS.Stop();
            }
        }
    }
 public static SwapChain3 CreateSwapchain(RenderForm form, CommandQueue queue, Config config)
 {
     using (var Factory = new Factory4())
     {
         var swapChainDesc = new SwapChainDescription()
         {
             BufferCount       = config.FrameCount,
             ModeDescription   = new ModeDescription(config.Width, config.Height, new Rational(config.RefreshRate, 1), config.Format),
             Usage             = Usage.RenderTargetOutput,
             SwapEffect        = SwapEffect.FlipDiscard,
             OutputHandle      = form.Handle,
             SampleDescription = new SampleDescription(config.SampleCount, config.SampleQuality),
             IsWindowed        = true
         };
         var tempSwapChain = new SwapChain(Factory, queue, swapChainDesc);
         var SwapChain     = tempSwapChain.QueryInterface <SwapChain3>();
         tempSwapChain.Dispose();
         return(SwapChain);
     }
 }
Beispiel #56
0
        protected void FlushCommandQueue()
        {
            // Advance the fence value to mark commands up to this fence point.
            CurrentFence++;

            // Add an instruction to the command queue to set a new fence point.  Because we
            // are on the GPU timeline, the new fence point won't be set until the GPU finishes
            // processing all the commands prior to this Signal().
            CommandQueue.Signal(Fence, CurrentFence);

            // Wait until the GPU has completed commands up to this fence point.
            if (Fence.CompletedValue < CurrentFence)
            {
                // Fire event when GPU hits current fence.
                Fence.SetEventOnCompletion(CurrentFence, _fenceEvent.SafeWaitHandle.DangerousGetHandle());

                // Wait until the GPU hits current fence event is fired.
                _fenceEvent.WaitOne();
            }
        }
Beispiel #57
0
 public override void UnknownCommand(CommandQueue queue, string basecommand, string[] arguments)
 {
     if (TheClient.Network.IsAlive)
     {
         StringBuilder sb = new StringBuilder();
         sb.Append(basecommand);
         for (int i = 0; i < arguments.Length; i++)
         {
             sb.Append("\n").Append(queue.ParseTags != TagParseMode.OFF ? TheClient.Commands.CommandSystem.TagSystem.ParseTagsFromText(arguments[i],
                                                                                                                                       TextStyle.Color_Simple, null, DebugMode.MINIMAL, (o) => { throw new Exception("Tag exception: " + o); }, true) : arguments[i]);
         }
         CommandPacketOut packet = new CommandPacketOut(sb.ToString());
         TheClient.Network.SendPacket(packet);
     }
     else
     {
         WriteLine(TextStyle.Color_Error + "Unknown command '" +
                   TextStyle.Color_Standout + basecommand + TextStyle.Color_Error + "'.");
     }
 }
Beispiel #58
0
        public override void Execute(object sender)
        {
            var commandQueue = sender as CommandQueue;

            var waitList = from name in WaitList
                           let ev = CommandQueue.FindEvent(name)
                                    where ev != null
                                    select ev.Value;

            Event     eventID;
            ErrorCode error;
            var       mem         = (Buffer == null) ? Mem : Buffer.Mem;
            var       elementSize = (Buffer == null) ? ElementSize : Buffer.ElementSize;

            if (Data == null)
            {
                error = Cl.EnqueueReadBuffer(commandQueue.Queue, mem,
                                             Blocking ? Bool.True : Bool.False, (IntPtr)Offset,
                                             (IntPtr)(Count * elementSize), DataPtr, (uint)waitList.Count(), waitList.Count() == 0 ? null : waitList.ToArray(), out eventID);
            }
            else
            {
                error = Cl.EnqueueReadBuffer(commandQueue.Queue, mem,
                                             Blocking ? Bool.True : Bool.False, (IntPtr)Offset,
                                             (IntPtr)(Count * elementSize), Data, (uint)waitList.Count(), waitList.Count() == 0 ? null : waitList.ToArray(), out eventID);
            }

            if (error != ErrorCode.Success)
            {
                throw new Cl.Exception(error);
            }

            if (Name == string.Empty)
            {
                eventID.Dispose();
            }
            else
            {
                CommandQueue.AddEvent(Name, eventID);
            }
        }
Beispiel #59
0
        private static void InitializeStorageResources(CloudStorageAccount storageAccount)
        {
            var blobStorage = storageAccount.CreateCloudBlobClient();

            LogBlobContainer     = blobStorage.GetContainerReference("logitems");
            CommandBlobContainer = blobStorage.GetContainerReference("commands");

            var queueStorage = storageAccount.CreateCloudQueueClient();

            LogQueue     = queueStorage.GetQueueReference("logmessages");
            CommandQueue = queueStorage.GetQueueReference("commandmessages");

            bool isStorageFinalized = false;

            while (!isStorageFinalized)
            {
                try
                {
                    LogBlobContainer.CreateIfNotExist();
                    LogQueue.CreateIfNotExist();
                    CommandBlobContainer.CreateIfNotExist();
                    CommandQueue.CreateIfNotExist();

                    isStorageFinalized = true;
                }
                catch (StorageClientException sce)
                {
                    if (sce.ErrorCode == StorageErrorCode.TransportError)
                    {
                        Trace.TraceError("Storage services initialization failure.  " +
                                         "Check your storage account configuration settings.  " +
                                         "If running locally, ensure that the Development Storage service is running.  " +
                                         "Message: '{0}'", sce.Message);
                    }
                    else
                    {
                        throw sce;
                    }
                }
            }
        }
Beispiel #60
0
        /// <summary>
        /// Creates the rendering pipeline.
        /// </summary>
        void LoadPipeline()
        {
            // create swap chain descriptor
            var swapChainDescription1 = new SwapChainDescription1()
            {
                AlphaMode         = AlphaMode.Unspecified,
                BufferCount       = SwapBufferCount,
                Usage             = Usage.RenderTargetOutput,
                SwapEffect        = SwapEffect.FlipSequential,
                SampleDescription = new SampleDescription(1, 0),
                Format            = Format.R8G8B8A8_UNorm,
                Width             = width,
                Height            = height
            };

            // enable debug layer
            using (var debugInterface = DebugInterface.Get())
                debugInterface.EnableDebugLayer();

            // create device
            using (var factory = new Factory4())
            {
#if USE_WARP
                using (var warpAdapter = factory.GetWarpAdapter())
                {
                    device = Collect(new Device(warpAdapter, FeatureLevel.Level_12_0));
                }
#else
                using (var adapter = factory.Adapters[1])
                {
                    device = Collect(new Device(adapter, FeatureLevel.Level_11_0));
                }
#endif
                commandQueue = Collect(device.CreateCommandQueue(new CommandQueueDescription(CommandListType.Direct)));

                CreateSwapChain(ref swapChainDescription1, factory);
            }

            // create command queue and allocator objects
            commandListAllocator = Collect(device.CreateCommandAllocator(CommandListType.Direct));
        }