Exemplo n.º 1
0
 public virtual IEnumerable<Entity> Generate(EntitySystem entitySystem, EntityFieldModel entityDefinition, EntityFieldPositionModel entityPlacing, Vector3 position)
 {
     return new List<Entity>
     {
         entitySystem.CreateEntityFromDataModel(entityDefinition.Entity, entityPlacing, position)
     };
 }
        public EntityHierarchyEnumerator(EntitySystem EntitySystem, ViewModelContext selectedEntitiesContext)
        {
            isSelectedProperty = new PropertyKey<bool>("IsSelected", typeof(EntityHierarchyEnumerator), new StaticDefaultValueMetadata(false) { PropertyUpdateCallback = IsSelectedChanged });

            this.EntitySystem = EntitySystem;
            this.selectedEntitiesContext = selectedEntitiesContext;
        }
        public override void Initialize()
        {
            base.Initialize();

            Database = EntitySystem.Get <CargoConsoleSystem>().StationOrderDatabase;
        }
Exemplo n.º 4
0
        private void Stop(IConsoleShell shell, IPlayerSession?player)
        {
            var resultText = EntitySystem.Get <StationEventSystem>().StopEvent();

            shell.WriteLine(resultText);
        }
        public async Task <bool> InteractUsing(InteractUsingEventArgs eventArgs)
        {
            var user      = eventArgs.User;
            var usingItem = eventArgs.Using;

            if (usingItem == null || usingItem.Deleted || !ActionBlockerSystem.CanInteract(user))
            {
                return(false);
            }

            if (usingItem.TryGetComponent(out SeedComponent? seeds))
            {
                if (Seed == null)
                {
                    if (seeds.Seed == null)
                    {
                        user.PopupMessageCursor(Loc.GetString("The packet seems to be empty. You throw it away."));
                        usingItem.Delete();
                        return(false);
                    }

                    user.PopupMessageCursor(Loc.GetString("You plant the {0} {1}.", seeds.Seed.SeedName, seeds.Seed.SeedNoun));

                    Seed       = seeds.Seed;
                    Dead       = false;
                    Age        = 1;
                    Health     = Seed.Endurance;
                    _lastCycle = _gameTiming.CurTime;

                    usingItem.Delete();

                    CheckLevelSanity();
                    UpdateSprite();

                    return(true);
                }

                user.PopupMessageCursor(Loc.GetString("The {0} already has seeds in it!", Owner.Name));
                return(false);
            }

            if (usingItem.HasComponent <HoeComponent>())
            {
                if (WeedLevel > 0)
                {
                    user.PopupMessageCursor(Loc.GetString("You remove the weeds from the {0}.", Owner.Name));
                    user.PopupMessageOtherClients(Loc.GetString("{0} starts uprooting the weeds.", user.Name));
                    WeedLevel = 0;
                    UpdateSprite();
                }
                else
                {
                    user.PopupMessageCursor(Loc.GetString("This plot is devoid of weeds! It doesn't need uprooting."));
                }

                return(true);
            }

            if (usingItem.TryGetComponent(out SolutionContainerComponent? solution) && solution.CanRemoveSolutions)
            {
                var amount  = 5f;
                var sprayed = false;

                if (usingItem.TryGetComponent(out SprayComponent? spray))
                {
                    sprayed = true;
                    amount  = 1f;
                    EntitySystem.Get <AudioSystem>().PlayFromEntity(spray.SpraySound, usingItem, AudioHelpers.WithVariation(0.125f));
                }

                var chemAmount = ReagentUnit.New(amount);

                var split = solution.Solution.SplitSolution(chemAmount <= solution.Solution.TotalVolume ? chemAmount : solution.Solution.TotalVolume);

                user.PopupMessageCursor(Loc.GetString(sprayed ? $"You spray {Owner.Name} with {usingItem.Name}." : $"You transfer {split.TotalVolume.ToString()}u to {Owner.Name}"));

                _solutionContainer?.TryAddSolution(split);

                SkipAging++; // We're forcing an update cycle, so one age hasn't passed.
                ForceUpdate = true;
                Update();

                return(true);
            }

            if (usingItem.HasComponent <PlantSampleTakerComponent>())
            {
                if (Seed == null)
                {
                    user.PopupMessageCursor(Loc.GetString("There is nothing to take a sample of!"));
                    return(false);
                }

                if (Sampled)
                {
                    user.PopupMessageCursor(Loc.GetString("This plant has already been sampled."));
                    return(false);
                }

                if (Dead)
                {
                    user.PopupMessageCursor(Loc.GetString("This plant is dead."));
                    return(false);
                }

                var seed = Seed.SpawnSeedPacket(user.Transform.Coordinates);
                seed.RandomOffset(0.25f);
                user.PopupMessageCursor(Loc.GetString($"You take a sample from the {Seed.DisplayName}."));
                Health -= (_random.Next(3, 5) * 10);

                if (_random.Prob(0.3f))
                {
                    Sampled = true;
                }

                // Just in case.
                CheckLevelSanity();
                SkipAging++; // We're forcing an update cycle, so one age hasn't passed.
                ForceUpdate = true;
                Update();

                return(true);
            }

            if (usingItem.HasComponent <BotanySharpComponent>())
            {
                return(DoHarvest(user));
            }

            return(false);
        }
Exemplo n.º 6
0
 private void ClickSound()
 {
     EntitySystem.Get <AudioSystem>().Play("/Audio/machines/machine_switch.ogg", Owner, AudioParams.Default.WithVolume(-2f));
 }
Exemplo n.º 7
0
 public static void RegisterAll(EntitySystem system)
 {
     system.Register(new MotionAnimationStateSelector());
     system.Register(new Animator());
 }
Exemplo n.º 8
0
        private void UpdateUserInterface()
        {
            string?error = null;

            // Check if the player is still holding the gas analyzer => if not, don't update
            foreach (var session in _userInterface.SubscribedSessions)
            {
                if (session.AttachedEntity == null)
                {
                    return;
                }

                if (!session.AttachedEntity.TryGetComponent(out IHandsComponent handsComponent))
                {
                    return;
                }

                var activeHandEntity = handsComponent?.GetActiveHand?.Owner;
                if (activeHandEntity == null || !activeHandEntity.TryGetComponent(out GasAnalyzerComponent gasAnalyzer))
                {
                    return;
                }
            }

            var pos = Owner.Transform.GridPosition;

            if (!_checkPlayer && _position.HasValue)
            {
                // Check if position is out of range => don't update
                if (!_position.Value.InRange(_mapManager, pos, SharedInteractionSystem.InteractionRange))
                {
                    return;
                }

                pos = _position.Value;
            }

            var gam  = EntitySystem.Get <AtmosphereSystem>().GetGridAtmosphere(pos.GridID);
            var tile = gam?.GetTile(pos).Air;

            if (tile == null)
            {
                error = "No Atmosphere!";
                _userInterface.SetState(
                    new GasAnalyzerBoundUserInterfaceState(
                        0,
                        0,
                        null,
                        error));
                return;
            }

            var gases = new List <GasEntry>();

            for (int i = 0; i < Atmospherics.TotalNumberOfGases; i++)
            {
                var gas = Atmospherics.GetGas(i);

                if (tile.Gases[i] <= Atmospherics.GasMinMoles)
                {
                    continue;
                }

                gases.Add(new GasEntry(gas.Name, tile.Gases[i], gas.Color));
            }

            _userInterface.SetState(
                new GasAnalyzerBoundUserInterfaceState(
                    tile.Pressure,
                    tile.Temperature,
                    gases.ToArray(),
                    error));
        }
Exemplo n.º 9
0
    public void Execute(IConsoleShell shell, string argStr, string[] args)
    {
        if (args.Length < 4)
        {
            shell.WriteError("Expected at least 5 arguments.");
            return;
        }

        if (!int.TryParse(args[0], out var gridIdRaw))
        {
            shell.WriteError($"Failed parsing gridId '{args[3]}'.");
            return;
        }

        if (!uint.TryParse(args[1], out var uid))
        {
            shell.WriteError($"Failed parsing uid '{args[1]}'.");
            return;
        }

        var gridId = new GridId(gridIdRaw);

        if (!IoCManager.Resolve <IMapManager>().GridExists(gridId))
        {
            shell.WriteError($"No grid with gridId {gridId} exists.");
            return;
        }

        var decalSystem = EntitySystem.Get <DecalSystem>();

        switch (args[2].ToLower())
        {
        case "position":
            if (args.Length != 5)
            {
                shell.WriteError("Expected 6 arguments.");
                return;
            }

            if (!float.TryParse(args[3], out var x) || !float.TryParse(args[4], out var y))
            {
                shell.WriteError("Failed parsing position.");
                return;
            }

            if (!decalSystem.SetDecalPosition(gridId, uid, gridId, new Vector2(x, y)))
            {
                shell.WriteError("Failed changing decalposition.");
            }
            break;

        case "color":
            if (args.Length != 4)
            {
                shell.WriteError("Expected 5 arguments.");
                return;
            }

            if (!Color.TryFromName(args[3], out var color))
            {
                shell.WriteError("Failed parsing color.");
                return;
            }

            if (!decalSystem.SetDecalColor(gridId, uid, color))
            {
                shell.WriteError("Failed changing decal color.");
            }
            break;

        case "id":
            if (args.Length != 4)
            {
                shell.WriteError("Expected 5 arguments.");
                return;
            }

            if (!decalSystem.SetDecalId(gridId, uid, args[3]))
            {
                shell.WriteError("Failed changing decal id.");
            }
            break;

        case "rotation":
            if (args.Length != 4)
            {
                shell.WriteError("Expected 5 arguments.");
                return;
            }

            if (!double.TryParse(args[3], out var degrees))
            {
                shell.WriteError("Failed parsing degrees.");
                return;
            }

            if (!decalSystem.SetDecalRotation(gridId, uid, Angle.FromDegrees(degrees)))
            {
                shell.WriteError("Failed changing decal rotation.");
            }
            break;

        case "zindex":
            if (args.Length != 4)
            {
                shell.WriteError("Expected 5 arguments.");
                return;
            }

            if (!int.TryParse(args[3], out var zIndex))
            {
                shell.WriteError("Failed parsing zIndex.");
                return;
            }

            if (!decalSystem.SetDecalZIndex(gridId, uid, zIndex))
            {
                shell.WriteError("Failed changing decal zIndex.");
            }
            break;

        case "clean":
            if (args.Length != 4)
            {
                shell.WriteError("Expected 5 arguments.");
                return;
            }

            if (!bool.TryParse(args[3], out var cleanable))
            {
                shell.WriteError("Failed parsing cleanable.");
                return;
            }

            if (!decalSystem.SetDecalCleanable(gridId, uid, cleanable))
            {
                shell.WriteError("Failed changing decal cleanable flag.");
            }
            break;

        default:
            shell.WriteError("Invalid mode.");
            return;
        }
    }
        /// <summary>
        ///     Places item in user's active hand to an inventory slot.
        /// </summary>
        private async void PlaceActiveHandItemInInventory(EntityUid user, Slots slot)
        {
            var inventory = _entities.GetComponent <InventoryComponent>(Owner);
            var userHands = _entities.GetComponent <HandsComponent>(user);
            var item      = userHands.GetActiveHand;

            bool Check()
            {
                if (!EntitySystem.Get <ActionBlockerSystem>().CanInteract(user))
                {
                    return(false);
                }

                if (item == null)
                {
                    user.PopupMessageCursor(Loc.GetString("strippable-component-not-holding-anything"));
                    return(false);
                }

                if (!userHands.CanDrop(userHands.ActiveHand !))
                {
                    user.PopupMessageCursor(Loc.GetString("strippable-component-cannot-drop"));
                    return(false);
                }

                if (!inventory.HasSlot(slot))
                {
                    return(false);
                }

                if (inventory.TryGetSlotItem(slot, out ItemComponent? _))
                {
                    user.PopupMessageCursor(Loc.GetString("strippable-component-item-slot-occupied", ("owner", Owner)));
                    return(false);
                }

                if (!inventory.CanEquip(slot, item, false))
                {
                    user.PopupMessageCursor(Loc.GetString("strippable-component-cannot-equip-message", ("owner", Owner)));
                    return(false);
                }

                return(true);
            }

            var doAfterSystem = EntitySystem.Get <DoAfterSystem>();

            var doAfterArgs = new DoAfterEventArgs(user, StripDelay, CancellationToken.None, Owner)
            {
                ExtraCheck        = Check,
                BreakOnStun       = true,
                BreakOnDamage     = true,
                BreakOnTargetMove = true,
                BreakOnUserMove   = true,
                NeedHand          = true,
            };

            var result = await doAfterSystem.WaitDoAfter(doAfterArgs);

            if (result != DoAfterStatus.Finished)
            {
                return;
            }

            userHands.Drop(item !.Owner, false);
            inventory.Equip(slot, item !.Owner, false);

            UpdateSubscribed();
        }
        /// <summary>
        ///     Places item in user's active hand in one of the entity's hands.
        /// </summary>
        private async void PlaceActiveHandItemInHands(EntityUid user, string hand)
        {
            var hands     = _entities.GetComponent <HandsComponent>(Owner);
            var userHands = _entities.GetComponent <HandsComponent>(user);
            var item      = userHands.GetActiveHand;

            bool Check()
            {
                if (!EntitySystem.Get <ActionBlockerSystem>().CanInteract(user))
                {
                    return(false);
                }

                if (item == null)
                {
                    user.PopupMessageCursor(Loc.GetString("strippable-component-not-holding-anything"));
                    return(false);
                }

                if (!userHands.CanDrop(userHands.ActiveHand !))
                {
                    user.PopupMessageCursor(Loc.GetString("strippable-component-cannot-drop"));
                    return(false);
                }

                if (!hands.HasHand(hand))
                {
                    return(false);
                }

                if (hands.TryGetItem(hand, out var _))
                {
                    user.PopupMessageCursor(Loc.GetString("strippable-component-item-slot-occupied-message", ("owner", Owner)));
                    return(false);
                }

                if (!hands.CanPickupEntity(hand, item.Owner, checkActionBlocker: false))
                {
                    user.PopupMessageCursor(Loc.GetString("strippable-component-cannot-put-message", ("owner", Owner)));
                    return(false);
                }

                return(true);
            }

            var doAfterSystem = EntitySystem.Get <DoAfterSystem>();

            var doAfterArgs = new DoAfterEventArgs(user, StripDelay, CancellationToken.None, Owner)
            {
                ExtraCheck        = Check,
                BreakOnStun       = true,
                BreakOnDamage     = true,
                BreakOnTargetMove = true,
                BreakOnUserMove   = true,
                NeedHand          = true,
            };

            var result = await doAfterSystem.WaitDoAfter(doAfterArgs);

            if (result != DoAfterStatus.Finished)
            {
                return;
            }

            userHands.Drop(hand);
            hands.TryPickupEntity(hand, item !.Owner, checkActionBlocker: false);
            UpdateSubscribed();
        }
Exemplo n.º 12
0
        bool IAttack.WideAttack(AttackEventArgs eventArgs)
        {
            if (!eventArgs.WideAttack)
            {
                return(true);
            }

            var curTime = _gameTiming.CurTime;

            if (curTime < _cooldownEnd)
            {
                return(true);
            }

            var location = eventArgs.User.Transform.Coordinates;
            var angle    = new Angle(eventArgs.ClickLocation.ToMapPos(Owner.EntityManager) - location.ToMapPos(Owner.EntityManager));

            // This should really be improved. GetEntitiesInArc uses pos instead of bounding boxes.
            var entities = ArcRayCast(eventArgs.User.Transform.WorldPosition, angle, eventArgs.User);

            var audioSystem = EntitySystem.Get <AudioSystem>();

            if (entities.Count != 0)
            {
                audioSystem.PlayFromEntity(_hitSound, entities.First());
            }
            else
            {
                audioSystem.PlayFromEntity(_missSound, eventArgs.User);
            }

            var hitEntities = new List <IEntity>();

            foreach (var entity in entities)
            {
                if (!entity.Transform.IsMapTransform || entity == eventArgs.User)
                {
                    continue;
                }

                if (entity.TryGetComponent(out IDamageableComponent damageComponent))
                {
                    damageComponent.ChangeDamage(DamageType, Damage, false, Owner);
                    hitEntities.Add(entity);
                }
            }
            SendMessage(new MeleeHitMessage(hitEntities));

            if (!OnHitEntities(hitEntities, eventArgs))
            {
                return(false);
            }

            if (Arc != null)
            {
                var sys = EntitySystem.Get <MeleeWeaponSystem>();
                sys.SendAnimation(Arc, angle, eventArgs.User, Owner, hitEntities);
            }

            _lastAttackTime = curTime;
            _cooldownEnd    = _lastAttackTime + TimeSpan.FromSeconds(ArcCooldownTime);

            if (Owner.TryGetComponent(out ItemCooldownComponent cooldown))
            {
                cooldown.CooldownStart = _lastAttackTime;
                cooldown.CooldownEnd   = _cooldownEnd;
            }

            return(true);
        }
Exemplo n.º 13
0
 void IExamine.Examine(FormattedMessage message, bool inDetailsRange)
 {
     EntitySystem.Get <SharedConstructionSystem>().DoExamine(message, Prototype, Stage, inDetailsRange);
 }
Exemplo n.º 14
0
        bool IAttack.ClickAttack(AttackEventArgs eventArgs)
        {
            if (eventArgs.WideAttack)
            {
                return(false);
            }

            var curTime = _gameTiming.CurTime;

            if (curTime < _cooldownEnd || !eventArgs.Target.IsValid())
            {
                return(true);
            }

            var target = eventArgs.TargetEntity;

            var location = eventArgs.User.Transform.Coordinates;
            var angle    = new Angle(eventArgs.ClickLocation.ToMapPos(Owner.EntityManager) - location.ToMapPos(Owner.EntityManager));

            var audioSystem = EntitySystem.Get <AudioSystem>();

            if (target != null)
            {
                audioSystem.PlayFromEntity(_hitSound, target);
            }
            else
            {
                audioSystem.PlayFromEntity(_missSound, eventArgs.User);
                return(false);
            }

            if (target.TryGetComponent(out IDamageableComponent damageComponent))
            {
                damageComponent.ChangeDamage(DamageType, Damage, false, Owner);
            }
            SendMessage(new MeleeHitMessage(new List <IEntity> {
                target
            }));

            var targets = new[] { target };

            if (!OnHitEntities(targets, eventArgs))
            {
                return(false);
            }

            if (ClickArc != null)
            {
                var sys = EntitySystem.Get <MeleeWeaponSystem>();
                sys.SendAnimation(ClickArc, angle, eventArgs.User, Owner, targets, ClickAttackEffect, false);
            }

            _lastAttackTime = curTime;
            _cooldownEnd    = _lastAttackTime + TimeSpan.FromSeconds(CooldownTime);

            if (Owner.TryGetComponent(out ItemCooldownComponent cooldown))
            {
                cooldown.CooldownStart = _lastAttackTime;
                cooldown.CooldownEnd   = _cooldownEnd;
            }

            return(true);
        }
Exemplo n.º 15
0
        public async Task ProcessGizmoAndPicking(EngineContext engineContext)
        {
            var gizmoTargetPlugin = (RenderTargetsPlugin)engineContext.DataContext.RenderPassPlugins.TryGetValue("GizmoTargetPlugin");

            if (gizmoTargetPlugin == null)
            {
                return;
            }

            var pickingResults = new Queue <PickingAction>();

            var effectGizmo = engineContext.RenderContext.BuildEffect("Gizmo")
                              .Using(
                new BasicShaderPlugin(
                    new ShaderMixinSource()
            {
                "ShaderBase",
                "TransformationWVP",
                "AlbedoFlatShading",
            })
            {
                RenderPassPlugin = gizmoTargetPlugin
            })
                              .Using(new MaterialShaderPlugin()
            {
                RenderPassPlugin = gizmoTargetPlugin
            })
                              //.Using(new LightingShaderPlugin() { RenderPassPlugin = renderingSetup.LightingPlugin })
            ;

            effectGizmo.PickingPassMainPlugin = gizmoTargetPlugin;

            //effectGizmo.Permutations.Set(LightingPermutation.Key, new LightingPermutation { Lights = new Light[] { new DirectionalLight { LightColor = new Color3(1.0f), LightDirection = new R32G32B32_Float(-1.0f, -1.0f, 1.0f) } } });

            engineContext.RenderContext.Effects.Add(effectGizmo);

            editorEntitySystem = new EntitySystem();
            editorEntitySystem.Processors.Add(new MeshProcessor(engineContext.RenderContext, engineContext.AssetManager));
            editorEntitySystem.Processors.Add(new HierarchicalProcessor());
            editorEntitySystem.Processors.Add(new TransformationProcessor());
            editorEntitySystem.Processors.Add(new TransformationUpdateProcessor());

            // Prepare gizmo entities
            translationGizmo = GenerateTranslationGizmo();
            rotationGizmo    = GenerateRotationGizmo();
            UpdateGizmoHighlighting(GizmoAction.None);

            RenderPassPlugin renderPassPlugin;

            engineContext.DataContext.RenderPassPlugins.TryGetValue("PickingPlugin", out renderPassPlugin);
            var pickingPlugin = renderPassPlugin as PickingPlugin;

            engineContext.DataContext.RenderPassPlugins.TryGetValue("MouseOverPickingPlugin", out renderPassPlugin);
            var mouseOverPickingPlugin = renderPassPlugin as PickingPlugin;

            // States
            var    pickingGizmoOrigin    = new Vector3();
            var    previousMouseLocation = new Vector2();
            var    currentGizmoAction    = GizmoAction.None;
            var    nextGizmoAction       = GizmoAction.None;
            Entity nextSelectedEntity    = null;

            var previousMousePosition = Vector2.Zero;

            while (true)
            {
                await engineContext.Scheduler.NextFrame();

                lock (pickingResults)
                {
                    var mousePosition = engineContext.InputManager.MousePosition;
                    if (engineContext.InputManager.IsMouseButtonPressed(MouseButton.Left))
                    {
                        pickingResults.Enqueue(new PickingAction
                        {
                            Type          = PickingActionType.MouseDown,
                            MouseLocation = mousePosition,
                            PickingResult = pickingPlugin.Pick(engineContext.InputManager.MousePosition),
                        });
                    }
                    else if (engineContext.InputManager.IsMouseButtonReleased(MouseButton.Left))
                    {
                        pickingResults.Enqueue(new PickingAction
                        {
                            Type          = PickingActionType.MouseUp,
                            MouseLocation = mousePosition,
                        });
                    }

                    if (engineContext.InputManager.IsMouseButtonDown(MouseButton.Left) && previousMousePosition != mousePosition)
                    {
                        pickingResults.Enqueue(new PickingAction
                        {
                            Type          = PickingActionType.MouseMove,
                            MouseLocation = mousePosition,
                        });
                    }

                    pickingResults.Enqueue(new PickingAction
                    {
                        Type          = PickingActionType.MouseOver,
                        MouseLocation = mousePosition,
                        PickingResult = mouseOverPickingPlugin.Pick(mousePosition)
                    });

                    previousMousePosition = mousePosition;

                    while (pickingResults.Count > 0 && (pickingResults.Peek().PickingResult == null || pickingResults.Peek().PickingResult.IsCompleted))
                    {
                        // State machine handling mouse down/move/over. Everything work in async deferred (picking results only comes after a few frames due to GPU asynchronism).
                        // Possible improvements:
                        // - If user do a mouse down and no gizmo action active, it should either be gizmo action if selected item didn't change, or instant picking (no wait for mouse up) if picking changed.
                        //   Gizmo action could probably start on new entity if MouseMove happens during the same sequence.
                        var pickingAction = pickingResults.Dequeue();
                        var pickedEntity  = pickingAction.PickingResult != null?GetPickedEntity(engineContext, pickingAction.PickingResult.Result.EffectMesh) : null;

                        switch (pickingAction.Type)
                        {
                        case PickingActionType.MouseOver:
                            if (currentGizmoAction == GizmoAction.None)
                            {
                                // Mouse over or click on gizmo: highlight the appropriate parts (yellow)
                                nextGizmoAction = pickedEntity != null?pickedEntity.Get(GizmoActionKey) : GizmoAction.None;

                                UpdateGizmoHighlighting(nextGizmoAction);
                                if (pickedEntity != null)
                                {
                                    pickingGizmoOrigin = pickingAction.PickingResult.Result.Position;
                                }
                            }
                            break;

                        case PickingActionType.MouseDown:
                            nextSelectedEntity    = pickedEntity;
                            previousMouseLocation = pickingAction.MouseLocation;

                            // User isn't around a "mouse over gizmo" so it is a picking selection for sure, doesn't wait for mouse move or mouse up
                            if (nextGizmoAction == GizmoAction.None)
                            {
                                UpdateSelectedEntities(engineContext, nextSelectedEntity);

                                // Force gizmo refresh (otherwise it won't happen as we enforce gizmo action right away, however we don't want it to be highlighted until used)
                                RefreshGizmos(GizmoAction.None);
                                UpdateGizmoHighlighting(currentGizmoAction);

                                // Engage default action
                                if (currentActiveGizmoActionMode == GizmoAction.Translation)
                                {
                                    currentGizmoAction = GizmoAction.TranslationXY;
                                    if (pickedEntity != null)
                                    {
                                        pickingGizmoOrigin = pickingAction.PickingResult.Result.Position;
                                    }
                                }
                                else if (currentGizmoAction == GizmoAction.Rotation)
                                {
                                    currentGizmoAction = GizmoAction.RotationZ;
                                }
                            }

                            if (selectedEntities != null && selectedEntities.Length > 0)
                            {
                                // Save aside picking object origin in case it turns out to be a translation
                                foreach (var selectedEntity in selectedEntities)
                                {
                                    var transformationComponent = selectedEntity.Entity.Transformation.Value as TransformationTRS;
                                    selectedEntity.PickingObjectOrigin = transformationComponent != null ? transformationComponent.Translation : Vector3.Zero;
                                }
                            }
                            break;

                        case PickingActionType.MouseMove:
                            // Gizmo action just started?
                            if (currentGizmoAction == GizmoAction.None)
                            {
                                currentGizmoAction = nextGizmoAction;
                            }
                            UpdateGizmoHighlighting(currentGizmoAction);
                            if (selectedEntities != null && selectedEntities.Length > 0)
                            {
                                // Performs translation
                                if ((currentGizmoAction & GizmoAction.Translation) != GizmoAction.None)
                                {
                                    // Translation is computed from origin position during mouse down => mouse delta is not reset
                                    foreach (var selectedEntity in selectedEntities)
                                    {
                                        MoveEntity(engineContext, selectedEntity.Entity, currentGizmoAction, pickingGizmoOrigin, selectedEntity.PickingObjectOrigin, pickingAction.MouseLocation - previousMouseLocation);
                                    }
                                }
                                else if ((currentGizmoAction & GizmoAction.Rotation) != GizmoAction.None)
                                {
                                    foreach (var selectedEntity in selectedEntities)
                                    {
                                        RotateEntity(engineContext, selectedEntity.Entity, currentGizmoAction, pickingAction.MouseLocation - previousMouseLocation);
                                    }
                                    // Rotation is using incremental => reset delta
                                    previousMouseLocation = pickingAction.MouseLocation;
                                }
                            }
                            break;

                        case PickingActionType.MouseUp:
                            if (currentGizmoAction == GizmoAction.None)
                            {
                                // Selection
                                UpdateSelectedEntities(engineContext, nextSelectedEntity);
                            }

                            // Reset states
                            currentGizmoAction = GizmoAction.None;
                            nextGizmoAction    = GizmoAction.None;
                            UpdateGizmoHighlighting(nextGizmoAction);
                            nextSelectedEntity = null;
                            break;
                        }
                    }
                }

                if (currentGizmoAction == GizmoAction.None)
                {
                    if (!EnumerableExtensions.Equals(SelectedEntities, selectedEntities != null ? selectedEntities.Select(x => x.Entity) : null))
                    {
                        selectedEntities = SelectedEntities.Select(x => new SelectedEntity(x)).ToArray();
                    }
                }

                RefreshGizmos(currentGizmoAction);
                editorEntitySystem.Update();
            }
        }
Exemplo n.º 16
0
 protected override void OnKnockdown()
 {
     EntitySystem.Get <StandingStateSystem>().Down(Owner);
 }
Exemplo n.º 17
0
 public void Rollback()
 {
     base.Prepare();
     sut = new EntitySystem(MortarComponent);
 }
        /// <summary>
        ///     Takes an item from the inventory and places it in the user's active hand.
        /// </summary>
        private async void TakeItemFromInventory(EntityUid user, Slots slot)
        {
            var inventory = _entities.GetComponent <InventoryComponent>(Owner);
            var userHands = _entities.GetComponent <HandsComponent>(user);

            bool Check()
            {
                if (!EntitySystem.Get <ActionBlockerSystem>().CanInteract(user))
                {
                    return(false);
                }

                if (!inventory.HasSlot(slot))
                {
                    return(false);
                }

                if (!inventory.TryGetSlotItem(slot, out ItemComponent? itemToTake))
                {
                    user.PopupMessageCursor(Loc.GetString("strippable-component-item-slot-free-message", ("owner", Owner)));
                    return(false);
                }

                if (!inventory.CanUnequip(slot, false))
                {
                    user.PopupMessageCursor(Loc.GetString("strippable-component-cannot-unequip-message", ("owner", Owner)));
                    return(false);
                }

                return(true);
            }

            var doAfterSystem = EntitySystem.Get <DoAfterSystem>();

            var doAfterArgs = new DoAfterEventArgs(user, StripDelay, CancellationToken.None, Owner)
            {
                ExtraCheck        = Check,
                BreakOnStun       = true,
                BreakOnDamage     = true,
                BreakOnTargetMove = true,
                BreakOnUserMove   = true,
            };

            var result = await doAfterSystem.WaitDoAfter(doAfterArgs);

            if (result != DoAfterStatus.Finished)
            {
                return;
            }

            var item = inventory.GetSlotItem(slot);

            inventory.Unequip(slot, false);

            if (item != null)
            {
                userHands.PutInHandOrDrop(item);
            }

            UpdateSubscribed();
        }
 private void PlaceAt(IMapGrid mapGrid, EntityCoordinates location, ushort tileId, float offset = 0)
 {
     mapGrid.SetTile(location.Offset(new Vector2(offset, offset)), new Tile(tileId));
     EntitySystem.Get <AudioSystem>().PlayAtCoords("/Audio/Items/genhit.ogg", location, AudioHelpers.WithVariation(0.125f));
 }
        /// <summary>
        ///     Takes an item from a hand and places it in the user's active hand.
        /// </summary>
        private async void TakeItemFromHands(EntityUid user, string hand)
        {
            var hands     = _entities.GetComponent <HandsComponent>(Owner);
            var userHands = _entities.GetComponent <HandsComponent>(user);

            bool Check()
            {
                if (!EntitySystem.Get <ActionBlockerSystem>().CanInteract(user))
                {
                    return(false);
                }

                if (!hands.HasHand(hand))
                {
                    return(false);
                }

                if (!hands.TryGetItem(hand, out var heldItem))
                {
                    user.PopupMessageCursor(Loc.GetString("strippable-component-item-slot-free-message", ("owner", Owner)));
                    return(false);
                }

                if (_entities.HasComponent <HandVirtualItemComponent>(heldItem.Owner))
                {
                    return(false);
                }

                if (!hands.CanDrop(hand, false))
                {
                    user.PopupMessageCursor(Loc.GetString("strippable-component-cannot-drop-message", ("owner", Owner)));
                    return(false);
                }

                return(true);
            }

            var doAfterSystem = EntitySystem.Get <DoAfterSystem>();

            var doAfterArgs = new DoAfterEventArgs(user, StripDelay, CancellationToken.None, Owner)
            {
                ExtraCheck        = Check,
                BreakOnStun       = true,
                BreakOnDamage     = true,
                BreakOnTargetMove = true,
                BreakOnUserMove   = true,
            };

            var result = await doAfterSystem.WaitDoAfter(doAfterArgs);

            if (result != DoAfterStatus.Finished)
            {
                return;
            }

            var item = hands.GetItem(hand);

            hands.Drop(hand, false);
            userHands.PutInHandOrDrop(item !);
            UpdateSubscribed();
        }
        public void Update(float frameTime)
        {
            if (!Owner.TryGetComponent(out DamageableComponent damageable))
            {
                return;
            }
            Owner.TryGetComponent(out ServerStatusEffectsComponent status);

            var coordinates = Owner.Transform.GridPosition;
            var gridAtmos   = EntitySystem.Get <AtmosphereSystem>().GetGridAtmosphere(coordinates.GridID);
            var tile        = gridAtmos?.GetTile(coordinates);

            var pressure = 1f;
            var highPressureMultiplier = 1f;
            var lowPressureMultiplier  = 1f;

            foreach (var protection in Owner.GetAllComponents <IPressureProtection>())
            {
                highPressureMultiplier *= protection.HighPressureMultiplier;
                lowPressureMultiplier  *= protection.LowPressureMultiplier;
            }

            if (tile?.Air != null)
            {
                pressure = MathF.Max(tile.Air.Pressure, 1f);
            }

            switch (pressure)
            {
            // Low pressure.
            case var p when p <= Atmospherics.WarningLowPressure:
                pressure *= lowPressureMultiplier;

                if (pressure > Atmospherics.WarningLowPressure)
                {
                    goto default;
                }

                damageable.TakeDamage(DamageType.Brute, Atmospherics.LowPressureDamage, Owner);

                if (status == null)
                {
                    break;
                }

                if (pressure <= Atmospherics.HazardLowPressure)
                {
                    status.ChangeStatusEffect(StatusEffect.Pressure, "/Textures/Interface/StatusEffects/Pressure/lowpressure2.png", null);
                    break;
                }

                status.ChangeStatusEffect(StatusEffect.Pressure, "/Textures/Interface/StatusEffects/Pressure/lowpressure1.png", null);
                break;

            // High pressure.
            case var p when p >= Atmospherics.WarningHighPressure:
                pressure *= highPressureMultiplier;

                if (pressure < Atmospherics.WarningHighPressure)
                {
                    goto default;
                }

                var damage = (int)MathF.Min((pressure / Atmospherics.HazardHighPressure) * Atmospherics.PressureDamageCoefficient, Atmospherics.MaxHighPressureDamage);

                damageable.TakeDamage(DamageType.Brute, damage, Owner);

                if (status == null)
                {
                    break;
                }

                if (pressure >= Atmospherics.HazardHighPressure)
                {
                    status.ChangeStatusEffect(StatusEffect.Pressure, "/Textures/Interface/StatusEffects/Pressure/highpressure2.png", null);
                    break;
                }

                status.ChangeStatusEffect(StatusEffect.Pressure, "/Textures/Interface/StatusEffects/Pressure/highpressure1.png", null);
                break;

            // Normal pressure.
            default:
                status?.RemoveStatusEffect(StatusEffect.Pressure);
                break;
            }
        }
Exemplo n.º 22
0
        private void CreateCircleStack(MapId mapId)
        {
            var entityManager = IoCManager.Resolve <IEntityManager>();

            var groundUid = entityManager.SpawnEntity(null, new MapCoordinates(0, 0, mapId));
            var ground    = entityManager.AddComponent <PhysicsComponent>(groundUid);

            var horizontal        = new EdgeShape(new Vector2(-20, 0), new Vector2(20, 0));
            var horizontalFixture = new Fixture(ground, horizontal)
            {
                CollisionLayer = 2,
                CollisionMask  = 2,
                Hard           = true
            };

            var broadphase = EntitySystem.Get <FixtureSystem>();

            broadphase.CreateFixture(ground, horizontalFixture);

            var vertical        = new EdgeShape(new Vector2(10, 0), new Vector2(10, 10));
            var verticalFixture = new Fixture(ground, vertical)
            {
                CollisionLayer = 2,
                CollisionMask  = 2,
                Hard           = true
            };

            broadphase.CreateFixture(ground, verticalFixture);

            var xs = new[]
            {
                0.0f, -10.0f, -5.0f, 5.0f, 10.0f
            };

            var             columnCount = 1;
            var             rowCount    = 15;
            PhysShapeCircle shape;

            for (var j = 0; j < columnCount; j++)
            {
                for (var i = 0; i < rowCount; i++)
                {
                    var x = 0.0f;

                    var boxUid = entityManager.SpawnEntity(null,
                                                           new MapCoordinates(new Vector2(xs[j] + x, 0.55f + 2.1f * i), mapId));
                    var box = entityManager.AddComponent <PhysicsComponent>(boxUid);

                    box.BodyType = BodyType.Dynamic;
                    shape        = new PhysShapeCircle {
                        Radius = 0.5f
                    };
                    box.FixedRotation = false;
                    // TODO: Need to detect shape and work out if we need to use fixedrotation

                    var fixture = new Fixture(box, shape)
                    {
                        CollisionMask  = 2,
                        CollisionLayer = 2,
                        Hard           = true,
                    };

                    broadphase.CreateFixture(box, fixture);
                }
            }
        }
Exemplo n.º 23
0
 public override void Effect(DiseaseEffectArgs args)
 {
     EntitySystem.Get <DiseaseSystem>().SneezeCough(args.DiseasedEntity, args.Disease, SnoughMessage, AirTransmit);
 }
Exemplo n.º 24
0
        private void CreateTumbler(MapId mapId)
        {
            var broadphaseSystem = EntitySystem.Get <FixtureSystem>();
            var entityManager    = IoCManager.Resolve <IEntityManager>();

            var groundUid = entityManager.SpawnEntity(null, new MapCoordinates(0f, 0f, mapId));
            var ground    = entityManager.AddComponent <PhysicsComponent>(groundUid);

            var bodyUid = entityManager.SpawnEntity(null, new MapCoordinates(0f, 10f, mapId));
            var body    = entityManager.AddComponent <PhysicsComponent>(bodyUid);

            body.BodyType        = BodyType.Dynamic;
            body.SleepingAllowed = false;
            body.FixedRotation   = false;

            // TODO: Box2D just derefs, bleh shape structs someday
            var shape1 = new PolygonShape();

            shape1.SetAsBox(0.5f, 10.0f, new Vector2(10.0f, 0.0f), 0.0f);
            broadphaseSystem.CreateFixture(body, shape1, 20.0f);

            var shape2 = new PolygonShape();

            shape2.SetAsBox(0.5f, 10.0f, new Vector2(-10.0f, 0.0f), 0f);
            broadphaseSystem.CreateFixture(body, shape2, 20.0f);

            var shape3 = new PolygonShape();

            shape3.SetAsBox(10.0f, 0.5f, new Vector2(0.0f, 10.0f), 0f);
            broadphaseSystem.CreateFixture(body, shape3, 20.0f);

            var shape4 = new PolygonShape();

            shape4.SetAsBox(10.0f, 0.5f, new Vector2(0.0f, -10.0f), 0f);
            broadphaseSystem.CreateFixture(body, shape4, 20.0f);

            foreach (var fixture in body.Fixtures)
            {
                fixture.CollisionLayer = 2;
            }

            var revolute = EntitySystem.Get <SharedJointSystem>().CreateRevoluteJoint(groundUid, bodyUid);

            revolute.LocalAnchorA   = new Vector2(0f, 10f);
            revolute.LocalAnchorB   = new Vector2(0f, 0f);
            revolute.ReferenceAngle = 0f;
            revolute.MotorSpeed     = 0.05f * MathF.PI;
            revolute.MaxMotorTorque = 100000000f;
            revolute.EnableMotor    = true;

            // Box2D has this as 800 which is jesus christo.
            // Wouldn't recommend higher than 100 in debug and higher than 300 on release unless
            // you really want a profile.
            var count      = 300;
            var mapManager = IoCManager.Resolve <IMapManager>();

            for (var i = 0; i < count; i++)
            {
                Timer.Spawn(i * 20, () =>
                {
                    if (!mapManager.MapExists(mapId))
                    {
                        return;
                    }
                    var boxUid        = entityManager.SpawnEntity(null, new MapCoordinates(0f, 10f, mapId));
                    var box           = entityManager.AddComponent <PhysicsComponent>(boxUid);
                    box.BodyType      = BodyType.Dynamic;
                    box.FixedRotation = false;
                    var shape         = new PolygonShape();
                    shape.SetAsBox(0.125f, 0.125f);
                    broadphaseSystem.CreateFixture(box, shape, 0.0625f);
                    box.Fixtures[0].CollisionMask  = 2;
                    box.Fixtures[0].CollisionLayer = 2;
                });
            }
        }
Exemplo n.º 25
0
        public AtmosDebugOverlay()
        {
            IoCManager.InjectDependencies(this);

            _atmosDebugOverlaySystem = EntitySystem.Get <AtmosDebugOverlaySystem>();
        }
Exemplo n.º 26
0
        public void Execute(IConsoleShell shell, IPlayerSession player, string[] args)
        {
            if (args.Length == 0)
            {
                var result = new StringBuilder();
                foreach (Faction value in Enum.GetValues(typeof(Faction)))
                {
                    if (value == Faction.None)
                    {
                        continue;
                    }
                    result.Append(value + "\n");
                }

                shell.SendText(player, result.ToString());
                return;
            }

            if (args.Length < 2)
            {
                shell.SendText(player, Loc.GetString("Need more args"));
                return;
            }

            if (!Enum.TryParse(args[0], true, out Faction faction))
            {
                shell.SendText(player, Loc.GetString("Invalid faction"));
                return;
            }

            Faction targetFaction;

            switch (args[1])
            {
            case "friendly":
                if (args.Length < 3)
                {
                    shell.SendText(player, Loc.GetString("Need to supply a target faction"));
                    return;
                }

                if (!Enum.TryParse(args[2], true, out targetFaction))
                {
                    shell.SendText(player, Loc.GetString("Invalid target faction"));
                    return;
                }

                EntitySystem.Get <AiFactionTagSystem>().MakeFriendly(faction, targetFaction);
                shell.SendText(player, Loc.GetString("Command successful"));
                break;

            case "hostile":
                if (args.Length < 3)
                {
                    shell.SendText(player, Loc.GetString("Need to supply a target faction"));
                    return;
                }

                if (!Enum.TryParse(args[2], true, out targetFaction))
                {
                    shell.SendText(player, Loc.GetString("Invalid target faction"));
                    return;
                }

                EntitySystem.Get <AiFactionTagSystem>().MakeHostile(faction, targetFaction);
                shell.SendText(player, Loc.GetString("Command successful"));
                break;

            case "list":
                shell.SendText(player, EntitySystem.Get <AiFactionTagSystem>().GetHostileFactions(faction).ToString());
                break;

            default:
                shell.SendText(player, Loc.GetString("Unknown faction arg"));
                break;
            }

            return;
        }
Exemplo n.º 27
0
        private void List(IConsoleShell shell, IPlayerSession?player)
        {
            var resultText = "Random\n" + EntitySystem.Get <StationEventSystem>().GetEventNames();

            shell.WriteLine(resultText);
        }
Exemplo n.º 28
0
        public ShadeGame(GraphicsConfiguration graphicsConfiguration, Renderer renderer, EntitySystem entitySystem)
        {
            this.graphicsConfiguration = graphicsConfiguration;
             this.renderer = renderer;
             this.entitySystem = entitySystem;

             this.graphicsDeviceManager = new GraphicsDeviceManager(this);
             this.graphicsDeviceManager.PreferredBackBufferWidth = graphicsConfiguration.Width;
             this.graphicsDeviceManager.PreferredBackBufferHeight = graphicsConfiguration.Height;
            //         this.graphicsDeviceManager.DeviceCreationFlags |= DeviceCreationFlags.Debug;

             Content.RootDirectory = "Content";
        }
        public void Execute(IConsoleShell shell, string argStr, string[] args)
        {
            if (args.Length != 2)
            {
                shell.WriteLine(Loc.GetString("list-verbs-command-invalid-args"));
                return;
            }

            var entityManager = IoCManager.Resolve <IEntityManager>();
            var verbSystem    = EntitySystem.Get <SharedVerbSystem>();

            // get the 'player' entity (defaulting to command user, otherwise uses a uid)
            EntityUid?playerEntity = null;

            if (!int.TryParse(args[0], out var intPlayerUid))
            {
                if (args[0] == "self" && shell.Player?.AttachedEntity != null)
                {
                    playerEntity = shell.Player.AttachedEntity;
                }
                else
                {
                    shell.WriteError(Loc.GetString("list-verbs-command-invalid-player-uid"));
                    return;
                }
            }
            else
            {
                entityManager.EntityExists(new EntityUid(intPlayerUid));
            }

            // gets the target entity
            if (!int.TryParse(args[1], out var intUid))
            {
                shell.WriteError(Loc.GetString("list-verbs-command-invalid-target-uid"));
                return;
            }

            if (playerEntity == null)
            {
                shell.WriteError(Loc.GetString("list-verbs-command-invalid-player-entity"));
                return;
            }

            var target = new EntityUid(intUid);

            if (!entityManager.EntityExists(target))
            {
                shell.WriteError(Loc.GetString("list-verbs-command-invalid-target-entity"));
                return;
            }

            var verbs = verbSystem.GetLocalVerbs(target, playerEntity.Value, VerbType.All, true);

            foreach (var(type, set) in verbs)
            {
                foreach (var verb in set)
                {
                    shell.WriteLine(Loc.GetString("list-verbs-verb-listing", ("type", type), ("verb", verb.Text)));
                }
            }
        }
        public override IEnumerable<Entity> Generate(EntitySystem entitySystem, EntityFieldModel entityDefinition, EntityFieldPositionModel entityPlacing, Vector3 position)
        {
            // scale of the entity is the entire cube's scale.
            // generate 6 entities from the one definition that is passed in
            // the definition has to hold either 1, 5 or 6 textures.
            // if there are only 5 textures, then do not generate a bottom.
            // This is an option, because often times, there is no bottom needed.
            // if there is only 1 texture, it gets put on all 6 sides.

            //int? textureEnumLength = entityDefinition?.Entity?.RenderMode?.Textures?.Length;

            //if (textureEnumLength.HasValue && (textureEnumLength.Value == 1 || textureEnumLength.Value == 5 || textureEnumLength.Value == 6))
            //{
            //    TextureSourceModel[] textures = null;

            //    if (textureEnumLength.Value == 1)
            //    {
            //        textures = new TextureSourceModel[]
            //        {
            //            entityDefinition.Entity.RenderMode.Textures[0],
            //            entityDefinition.Entity.RenderMode.Textures[0],
            //            entityDefinition.Entity.RenderMode.Textures[0],
            //            entityDefinition.Entity.RenderMode.Textures[0],
            //            entityDefinition.Entity.RenderMode.Textures[0],
            //            entityDefinition.Entity.RenderMode.Textures[0]
            //        };
            //    }
            //    else if (textureEnumLength.Value == 5)
            //    {
            //        textures = new TextureSourceModel[]
            //        {
            //            entityDefinition.Entity.RenderMode.Textures[0],
            //            entityDefinition.Entity.RenderMode.Textures[1],
            //            entityDefinition.Entity.RenderMode.Textures[2],
            //            entityDefinition.Entity.RenderMode.Textures[3],
            //            entityDefinition.Entity.RenderMode.Textures[4]
            //        };
            //    }
            //    else if (textureEnumLength.Value == 6)
            //    {
            //        textures = new TextureSourceModel[]
            //        {
            //            entityDefinition.Entity.RenderMode.Textures[0],
            //            entityDefinition.Entity.RenderMode.Textures[1],
            //            entityDefinition.Entity.RenderMode.Textures[2],
            //            entityDefinition.Entity.RenderMode.Textures[3],
            //            entityDefinition.Entity.RenderMode.Textures[4],
            //            entityDefinition.Entity.RenderMode.Textures[5]
            //        };
            //    }

            //    // Front side:
            //    var frontEntityModel = entityDefinition.Entity.CloneModel();
            //    var frontEntityPlacing = new EntityFieldPositionModel();

            //    frontEntityModel.RenderMode.Textures = new TextureSourceModel[] { textures[0] };
            //    frontEntityPlacing.CardinalRotation = true;
            //    frontEntityPlacing.Rotation = new Vector3Model()
            //    {
            //        X = 0,
            //        Y = 0,
            //        Z = 0
            //    };
            //    frontEntityPlacing.Scale = new Vector3Model()
            //    {
            //        X = entityPlacing.Scale.X,
            //        Y = entityPlacing.Scale.Y,
            //        Z = 1
            //    };
            //    var frontEntityPosition = new Vector3()
            //    {
            //        X = position.X,
            //        Y = position.Y,
            //        Z = position.Z + entityPlacing.Scale.Z / 2
            //    };

            //    yield return  entitySystem.CreateEntityFromDataModel(frontEntityModel, frontEntityPlacing, frontEntityPosition);

            //    // Back side:
            //    var backEntityModel = entityDefinition.Entity.CloneModel();
            //    var backEntityPlacing = new EntityFieldPositionModel();

            //    backEntityModel.RenderMode.Textures = new TextureSourceModel[] { textures[1] };
            //    backEntityPlacing.CardinalRotation = true;
            //    backEntityPlacing.Rotation = new Vector3Model()
            //    {
            //        X = 0,
            //        Y = 2,
            //        Z = 0
            //    };
            //    backEntityPlacing.Scale = new Vector3Model()
            //    {
            //        X = entityPlacing.Scale.X,
            //        Y = entityPlacing.Scale.Y,
            //        Z = 1
            //    };
            //    var backEntityPosition = new Vector3()
            //    {
            //        X = position.X,
            //        Y = position.Y,
            //        Z = position.Z - entityPlacing.Scale.Z / 2
            //    };

            //    yield return entitySystem.CreateEntityFromDataModel(backEntityModel, backEntityPlacing, backEntityPosition);

            //    //Left side:
            //    var leftEntityModel = entityDefinition.Entity.CloneModel();
            //    var leftEntityPlacing = new EntityFieldPositionModel();

            //    leftEntityModel.RenderMode.Textures = new TextureSourceModel[] { textures[2] };
            //    leftEntityPlacing.CardinalRotation = true;
            //    leftEntityPlacing.Rotation = new Vector3Model()
            //    {
            //        X = 0,
            //        Y = 3,
            //        Z = 0
            //    };
            //    leftEntityPlacing.Scale = new Vector3Model()
            //    {
            //        X = entityPlacing.Scale.X,
            //        Y = entityPlacing.Scale.Y,
            //        Z = 1
            //    };
            //    var leftEntityPosition = new Vector3()
            //    {
            //        X = position.X - entityPlacing.Scale.X / 2,
            //        Y = position.Y,
            //        Z = position.Z
            //    };

            //    yield return entitySystem.CreateEntityFromDataModel(leftEntityModel, leftEntityPlacing, leftEntityPosition);

            //    //right side:
            //    var rightEntityModel = entityDefinition.Entity.CloneModel();
            //    var rightEntityPlacing = new EntityFieldPositionModel();

            //    rightEntityModel.RenderMode.Textures = new TextureSourceModel[] { textures[3] };
            //    rightEntityPlacing.CardinalRotation = true;
            //    rightEntityPlacing.Rotation = new Vector3Model()
            //    {
            //        X = 0,
            //        Y = 1,
            //        Z = 0
            //    };
            //    rightEntityPlacing.Scale = new Vector3Model()
            //    {
            //        X = entityPlacing.Scale.X,
            //        Y = entityPlacing.Scale.Y,
            //        Z = 1
            //    };
            //    var rightEntityPosition = new Vector3()
            //    {
            //        X = position.X + entityPlacing.Scale.X / 2,
            //        Y = position.Y,
            //        Z = position.Z
            //    };

            //    yield return entitySystem.CreateEntityFromDataModel(rightEntityModel, rightEntityPlacing, rightEntityPosition);

            //    //top:
            //    var topEntityModel = entityDefinition.Entity.CloneModel();
            //    var topEntityPlacing = new EntityFieldPositionModel();

            //    topEntityModel.RenderMode.Textures = new TextureSourceModel[] { textures[4] };
            //    topEntityPlacing.CardinalRotation = true;
            //    topEntityPlacing.Rotation = new Vector3Model()
            //    {
            //        X = 3,
            //        Y = 0,
            //        Z = 0
            //    };
            //    topEntityPlacing.Scale = new Vector3Model()
            //    {
            //        X = entityPlacing.Scale.X,
            //        Y = entityPlacing.Scale.Y,
            //        Z = 1
            //    };
            //    var topEntityPosition = new Vector3()
            //    {
            //        X = position.X,
            //        Y = position.Y + entityPlacing.Scale.Y / 2,
            //        Z = position.Z
            //    };

            //    yield return entitySystem.CreateEntityFromDataModel(topEntityModel, topEntityPlacing, topEntityPosition);

            //    //bottom:
            //    if (textureEnumLength.Value != 5)
            //    {
            //        var bottomEntityModel = entityDefinition.Entity.CloneModel();
            //        var bottomEntityPlacing = new EntityFieldPositionModel();

            //        bottomEntityModel.RenderMode.Textures = new TextureSourceModel[] { textures[5] };
            //        bottomEntityPlacing.CardinalRotation = true;
            //        bottomEntityPlacing.Rotation = new Vector3Model()
            //        {
            //            X = 1,
            //            Y = 0,
            //            Z = 0
            //        };
            //        bottomEntityPlacing.Scale = new Vector3Model()
            //        {
            //            X = entityPlacing.Scale.X,
            //            Y = entityPlacing.Scale.Y,
            //            Z = 1
            //        };
            //        var bottomEntityPosition = new Vector3()
            //        {
            //            X = position.X,
            //            Y = position.Y - entityPlacing.Scale.Y / 2,
            //            Z = position.Z
            //        };

            //        yield return entitySystem.CreateEntityFromDataModel(bottomEntityModel, bottomEntityPlacing, bottomEntityPosition);
            //    }
            //}
            throw new NotImplementedException();
        }
Exemplo n.º 31
0
        public void Execute(IConsoleShell shell, string argStr, string[] args)
        {
            var       player = shell.Player as IPlayerSession;
            EntityUid?gridId;
            Gas?      gas = null;

            var entMan = IoCManager.Resolve <IEntityManager>();

            switch (args.Length)
            {
            case 0:
            {
                if (player == null)
                {
                    shell.WriteLine("A grid must be specified when the command isn't used by a player.");
                    return;
                }

                if (player.AttachedEntity is not {
                        Valid : true
                    } playerEntity)
                {
                    shell.WriteLine("You have no entity to get a grid from.");
                    return;
                }

                gridId = entMan.GetComponent <TransformComponent>(playerEntity).GridUid;

                if (gridId == null)
                {
                    shell.WriteLine("You aren't on a grid to delete gas from.");
                    return;
                }

                break;
            }

            case 1:
            {
                if (!EntityUid.TryParse(args[0], out var number))
                {
                    // Argument is a gas
                    if (player == null)
                    {
                        shell.WriteLine("A grid id must be specified if not using this command as a player.");
                        return;
                    }

                    if (player.AttachedEntity is not {
                            Valid : true
                        } playerEntity)
                    {
                        shell.WriteLine("You have no entity from which to get a grid id.");
                        return;
                    }

                    gridId = entMan.GetComponent <TransformComponent>(playerEntity).GridUid;

                    if (gridId == null)
                    {
                        shell.WriteLine("You aren't on a grid to delete gas from.");
                        return;
                    }

                    if (!Enum.TryParse <Gas>(args[0], true, out var parsedGas))
                    {
                        shell.WriteLine($"{args[0]} is not a valid gas name.");
                        return;
                    }

                    gas = parsedGas;
                    break;
                }

                // Argument is a grid
                gridId = number;
                break;
            }

            case 2:
            {
                if (!EntityUid.TryParse(args[0], out var first))
                {
                    shell.WriteLine($"{args[0]} is not a valid integer for a grid id.");
                    return;
                }

                gridId = first;

                if (gridId.Value.IsValid())
                {
                    shell.WriteLine($"{gridId} is not a valid grid id.");
                    return;
                }

                if (!Enum.TryParse <Gas>(args[1], true, out var parsedGas))
                {
                    shell.WriteLine($"{args[1]} is not a valid gas.");
                    return;
                }

                gas = parsedGas;

                break;
            }

            default:
                shell.WriteLine(Help);
                return;
            }

            var mapManager = IoCManager.Resolve <IMapManager>();

            if (!mapManager.TryGetGrid(gridId, out _))
            {
                shell.WriteLine($"No grid exists with id {gridId}");
                return;
            }

            var atmosphereSystem = EntitySystem.Get <AtmosphereSystem>();

            var tiles = 0;
            var moles = 0f;

            if (gas == null)
            {
                foreach (var tile in atmosphereSystem.GetAllTileMixtures(gridId.Value, true))
                {
                    if (tile.Immutable)
                    {
                        continue;
                    }

                    tiles++;
                    moles += tile.TotalMoles;

                    tile.Clear();
                }
            }
            else
            {
                foreach (var tile in atmosphereSystem.GetAllTileMixtures(gridId.Value, true))
                {
                    if (tile.Immutable)
                    {
                        continue;
                    }

                    tiles++;
                    moles += tile.TotalMoles;

                    tile.SetMoles(gas.Value, 0);
                }
            }

            if (gas == null)
            {
                shell.WriteLine($"Removed {moles} moles from {tiles} tiles.");
                return;
            }

            shell.WriteLine($"Removed {moles} moles of gas {gas} from {tiles} tiles.");
        }
 public override void Initialize()
 {
     base.Initialize();
     _ammo         = maxAmmo;
     doAfterSystem = EntitySystem.Get <DoAfterSystem>();
 }
Exemplo n.º 33
0
        private static void Main(string[] args)
        {
            Application.EnableVisualStyles();

             // Implement the Gruenes Schaf
             new Thread(() => {
            while (true) {
               GC.Collect();
               Thread.Sleep(5000);
            }
             }).Start();

             var gridWidth = 2;
             var gridHeight = 2;

             var grid = new GridFactory().Create(gridWidth, gridHeight);
             var manipulator = new GridManipulator(grid, new Random(0));
             var spiral = new SpiralParametricFunction(1, 10, 3, (float)gridWidth / 2, (float)gridHeight / 2, 0);
             manipulator.CutParametric(spiral.TInitial, spiral.TFinal, 20f, spiral.PointAt);
             var lastSpiralPoint = spiral.PointAt(spiral.TFinal - 30);
             var v = new Vector2D(lastSpiralPoint, new Point2D(gridWidth / 2.0f, gridHeight / 2.0f));
             v = v.ToUnitVector();
             var cutDestination = lastSpiralPoint + v * 3;
             manipulator.CutLine(new Line2D(lastSpiralPoint, cutDestination));
             var entranceCell = grid.Cells[(gridHeight / 2) * grid.Width + (gridWidth / 2)];
             var cells = manipulator.FillRegion(entranceCell);

             var graphicsConfiguration = new GraphicsConfiguration { Width = 1600, Height = 900 };
             var gridletFactory = new GridletFactory();
            //         IReadOnlyList<NavigationGridlet> gridlets = CreateGridletsFromDungeonGrid(grid, gridletFactory);
             IReadOnlyList<NavigationGridlet> gridlets = new List<NavigationGridlet> {
            gridletFactory.Quad(0, 0, 0, 0, 0, 0, 60, 60),
            //            gridletFactory.Quad(37, 0, 2, -0.3f, 0, 0, 15, 7),
            //            gridletFactory.Quad(47.60f, -9.0f, 4.22f, 0, 0, 0, 7, 25),
            //            gridletFactory.Quad(58.05f, -18.0f, 4.22f, 0, 0, 0, 15, 7)
             };
             var navigationGrid = new NavigationGrid(gridlets);
             navigationGrid.Initialize();
             var pathfinder = new Pathfinder(navigationGrid);
             var renderer = new Renderer();

             CommandFactory commandFactory = new CommandFactory(pathfinder);
             var entityFactory = new EntityFactory();
             var entitySystem = new EntitySystem();
             entitySystem.AddEntity(entityFactory.CreateUnitCubeEntity());
             navigationGrid.Gridlets.ForEach(gridlet => entitySystem.AddEntity(entityFactory.CreateAndAssociateGridletEntity(navigationGrid, gridlet, pathfinder, commandFactory)));
             var characterEntity = entityFactory.CreateCharacterEntity(pathfinder);
             entitySystem.AddEntity(characterEntity);
             entitySystem.AddEntity(entityFactory.CreateCameraEntity(graphicsConfiguration, characterEntity));
             entitySystem.AddBehavior(new PhysicsBehavior(navigationGrid));
             entitySystem.AddBehavior(new CommandQueueBehavior());

             // Dungeon Stuff
             DungeonKeyInventory dungeonKeyInventory = new DungeonKeyInventory();
            //         entitySystem.AddEntity(entityFactory.CreateDungeonKeyEntity(new Vector3(5, 10, 0), new Vector4(1, 0, 0, 1), commandFactory, dungeonKeyInventory));
            //         entitySystem.AddEntity(entityFactory.CreateDungeonLockEntity(new Vector3(0, 35, 0), new Vector4(1, 0, 0, 1), commandFactory, dungeonKeyInventory));
            //         entitySystem.AddBehavior(new DungeonLockDisablesGroundPathingBehavior(navigationGrid));
             foreach (var cell in cells) {
            if (cell.KeyColor != Color.Empty) {
               var color = new Vector4(cell.KeyColor.R / 255f, cell.KeyColor.G / 255f, cell.KeyColor.B / 255f, 1);
               entitySystem.AddEntity(entityFactory.CreateDungeonKeyEntity(new Vector3(cell.X * 70 + 5, cell.Y * 70 + 10, 0), color, commandFactory, dungeonKeyInventory));
            }
            if (cell.LockColor != Color.Empty) {
               var color = new Vector4(cell.LockColor.R / 255f, cell.LockColor.G / 255f, cell.LockColor.B / 255f, 1);
               entitySystem.AddEntity(entityFactory.CreateDungeonLockEntity(new Vector3(cell.X * 70, cell.Y * 70, 0), color, commandFactory, dungeonKeyInventory, navigationGrid));
            }
             }

             using (var game = new ShadeGame(graphicsConfiguration, renderer, entitySystem)) {
            game.Run();
             }
        }
Exemplo n.º 34
0
 public static void RegisterAll(EntitySystem system)
 {
     system.Register(new BoxCollision());
     system.Register(new MotionSystem());
 }
Exemplo n.º 35
0
        public async Task ProcessGizmoAndPicking(EngineContext engineContext)
        {
            var gizmoTargetPlugin = (RenderTargetsPlugin)engineContext.DataContext.RenderPassPlugins.TryGetValue("GizmoTargetPlugin");
            if (gizmoTargetPlugin == null)
                return;

            var pickingResults = new Queue<PickingAction>();

            var effectGizmo = engineContext.RenderContext.BuildEffect("Gizmo")
                .Using(
                    new BasicShaderPlugin(
                        new ShaderMixinSource()
                            {
                                "ShaderBase",
                                "TransformationWVP",
                                "AlbedoFlatShading",
                            }) { RenderPassPlugin = gizmoTargetPlugin })
                .Using(new MaterialShaderPlugin() { RenderPassPlugin = gizmoTargetPlugin })
                //.Using(new LightingShaderPlugin() { RenderPassPlugin = renderingSetup.LightingPlugin })
                ;

            effectGizmo.PickingPassMainPlugin = gizmoTargetPlugin;

            //effectGizmo.Permutations.Set(LightingPermutation.Key, new LightingPermutation { Lights = new Light[] { new DirectionalLight { LightColor = new Color3(1.0f), LightDirection = new R32G32B32_Float(-1.0f, -1.0f, 1.0f) } } });

            engineContext.RenderContext.Effects.Add(effectGizmo);

            editorEntitySystem = new EntitySystem();
            editorEntitySystem.Processors.Add(new MeshProcessor(engineContext.RenderContext, engineContext.AssetManager));
            editorEntitySystem.Processors.Add(new HierarchicalProcessor());
            editorEntitySystem.Processors.Add(new TransformationProcessor());
            editorEntitySystem.Processors.Add(new TransformationUpdateProcessor());

            // Prepare gizmo entities
            translationGizmo = GenerateTranslationGizmo();
            rotationGizmo = GenerateRotationGizmo();
            UpdateGizmoHighlighting(GizmoAction.None);

            RenderPassPlugin renderPassPlugin;
            engineContext.DataContext.RenderPassPlugins.TryGetValue("PickingPlugin", out renderPassPlugin);
            var pickingPlugin = renderPassPlugin as PickingPlugin;
            engineContext.DataContext.RenderPassPlugins.TryGetValue("MouseOverPickingPlugin", out renderPassPlugin);
            var mouseOverPickingPlugin = renderPassPlugin as PickingPlugin;

            // States
            var pickingGizmoOrigin = new Vector3();
            var previousMouseLocation = new Vector2();
            var currentGizmoAction = GizmoAction.None;
            var nextGizmoAction = GizmoAction.None;
            Entity nextSelectedEntity = null;

            var previousMousePosition = Vector2.Zero;

            while (true)
            {
                await engineContext.Scheduler.NextFrame();

                lock (pickingResults)
                {
                    var mousePosition = engineContext.InputManager.MousePosition;
                    if (engineContext.InputManager.IsMouseButtonPressed(MouseButton.Left))
                    {
                        pickingResults.Enqueue(new PickingAction
                        {
                            Type = PickingActionType.MouseDown,
                            MouseLocation = mousePosition,
                            PickingResult = pickingPlugin.Pick(engineContext.InputManager.MousePosition),
                        });
                    }
                    else if (engineContext.InputManager.IsMouseButtonReleased(MouseButton.Left))
                    {
                        pickingResults.Enqueue(new PickingAction
                        {
                            Type = PickingActionType.MouseUp,
                            MouseLocation = mousePosition,
                        });
                    }

                    if (engineContext.InputManager.IsMouseButtonDown(MouseButton.Left) && previousMousePosition != mousePosition)
                    {
                        pickingResults.Enqueue(new PickingAction
                        {
                            Type = PickingActionType.MouseMove,
                            MouseLocation = mousePosition,
                        });
                    }

                    pickingResults.Enqueue(new PickingAction
                        {
                            Type = PickingActionType.MouseOver,
                            MouseLocation = mousePosition,
                            PickingResult = mouseOverPickingPlugin.Pick(mousePosition)
                        });

                    previousMousePosition = mousePosition;

                    while (pickingResults.Count > 0 && (pickingResults.Peek().PickingResult == null || pickingResults.Peek().PickingResult.IsCompleted))
                    {
                        // State machine handling mouse down/move/over. Everything work in async deferred (picking results only comes after a few frames due to GPU asynchronism).
                        // Possible improvements:
                        // - If user do a mouse down and no gizmo action active, it should either be gizmo action if selected item didn't change, or instant picking (no wait for mouse up) if picking changed.
                        //   Gizmo action could probably start on new entity if MouseMove happens during the same sequence.
                        var pickingAction = pickingResults.Dequeue();
                        var pickedEntity = pickingAction.PickingResult != null ? GetPickedEntity(engineContext, pickingAction.PickingResult.Result.EffectMesh) : null;
                        switch (pickingAction.Type)
                        {
                            case PickingActionType.MouseOver:
                                if (currentGizmoAction == GizmoAction.None)
                                {
                                    // Mouse over or click on gizmo: highlight the appropriate parts (yellow)
                                    nextGizmoAction = pickedEntity != null ? pickedEntity.Get(GizmoActionKey) : GizmoAction.None;
                                    UpdateGizmoHighlighting(nextGizmoAction);
                                    if (pickedEntity != null)
                                        pickingGizmoOrigin = pickingAction.PickingResult.Result.Position;
                                }
                                break;
                            case PickingActionType.MouseDown:
                                nextSelectedEntity = pickedEntity;
                                previousMouseLocation = pickingAction.MouseLocation;
                                
                                // User isn't around a "mouse over gizmo" so it is a picking selection for sure, doesn't wait for mouse move or mouse up
                                if (nextGizmoAction == GizmoAction.None)
                                {
                                    UpdateSelectedEntities(engineContext, nextSelectedEntity);

                                    // Force gizmo refresh (otherwise it won't happen as we enforce gizmo action right away, however we don't want it to be highlighted until used)
                                    RefreshGizmos(GizmoAction.None);
                                    UpdateGizmoHighlighting(currentGizmoAction);

                                    // Engage default action
                                    if (currentActiveGizmoActionMode == GizmoAction.Translation)
                                    {
                                        currentGizmoAction = GizmoAction.TranslationXY;
                                        if (pickedEntity != null)
                                            pickingGizmoOrigin = pickingAction.PickingResult.Result.Position;
                                    }
                                    else if (currentGizmoAction == GizmoAction.Rotation)
                                    {
                                        currentGizmoAction = GizmoAction.RotationZ;
                                    }
                                }

                                if (selectedEntities != null && selectedEntities.Length > 0)
                                {
                                    // Save aside picking object origin in case it turns out to be a translation
                                    foreach (var selectedEntity in selectedEntities)
                                    {
                                        var transformationComponent = selectedEntity.Entity.Transformation.Value as TransformationTRS;
                                        selectedEntity.PickingObjectOrigin = transformationComponent != null ? transformationComponent.Translation : Vector3.Zero;
                                    }
                                }
                                break;
                            case PickingActionType.MouseMove:
                                // Gizmo action just started?
                                if (currentGizmoAction == GizmoAction.None)
                                    currentGizmoAction = nextGizmoAction;
                                UpdateGizmoHighlighting(currentGizmoAction);
                                if (selectedEntities != null && selectedEntities.Length > 0)
                                {
                                    // Performs translation
                                    if ((currentGizmoAction & GizmoAction.Translation) != GizmoAction.None)
                                    {
                                        // Translation is computed from origin position during mouse down => mouse delta is not reset
                                        foreach (var selectedEntity in selectedEntities)
                                        {
                                            MoveEntity(engineContext, selectedEntity.Entity, currentGizmoAction, pickingGizmoOrigin, selectedEntity.PickingObjectOrigin, pickingAction.MouseLocation - previousMouseLocation);
                                        }
                                    }
                                    else if ((currentGizmoAction & GizmoAction.Rotation) != GizmoAction.None)
                                    {
                                        foreach (var selectedEntity in selectedEntities)
                                        {
                                            RotateEntity(engineContext, selectedEntity.Entity, currentGizmoAction, pickingAction.MouseLocation - previousMouseLocation);
                                        }
                                        // Rotation is using incremental => reset delta
                                        previousMouseLocation = pickingAction.MouseLocation;
                                    }
                                }
                                break;
                            case PickingActionType.MouseUp:
                                if (currentGizmoAction == GizmoAction.None)
                                {
                                    // Selection
                                    UpdateSelectedEntities(engineContext, nextSelectedEntity);
                                }

                                // Reset states
                                currentGizmoAction = GizmoAction.None;
                                nextGizmoAction = GizmoAction.None;
                                UpdateGizmoHighlighting(nextGizmoAction);
                                nextSelectedEntity = null;
                                break;
                        }
                    }
                }

                if (currentGizmoAction == GizmoAction.None)
                {
                    if (!EnumerableExtensions.Equals(SelectedEntities, selectedEntities != null ? selectedEntities.Select(x => x.Entity) : null))
                        selectedEntities = SelectedEntities.Select(x => new SelectedEntity(x)).ToArray();
                }

                RefreshGizmos(currentGizmoAction);
                editorEntitySystem.Update();
            }
        }
Exemplo n.º 36
0
        public GasTileOverlay()
        {
            IoCManager.InjectDependencies(this);

            _gasTileOverlaySystem = EntitySystem.Get <GasTileOverlaySystem>();
        }
Exemplo n.º 37
0
 public override void OnAddToSystem(EntitySystem EntitySystem, RenderContextBase renderContext)
 {
     base.OnAddToSystem(EntitySystem, renderContext);
     this.EntitySystem = EntitySystem;
     this.renderContext = renderContext;
 }
Exemplo n.º 38
0
 public override void Effect(ReagentEffectArgs args)
 {
     EntitySystem.Get <VocalSystem>().TryScream(args.SolutionEntity);
 }