void Sandbox.ModAPI.Ingame.IMyLargeTurretBase.SetTarget(IMyEntity entity)
 {
     if (entity != null)
     {
         SyncObject.SendSetTarget(entity.EntityId, false);
     }
 }
 public NavInfo(Vector3D fromPosition, Vector3D toPosition, IMyEntity shipControls)
 {
     _fromPosition = fromPosition;
     _toPosition = toPosition;
     _shipControls = shipControls;
     Init();
 }
 private static void Process(IMyEntity entity, MessageSyncEntity syncEntity)
 {
     if (MyAPIGateway.Multiplayer.MultiplayerActive)
         ConnectionHelper.SendMessageToAll(syncEntity);
     else
         syncEntity.CommonProcess(entity);
 }
        /// <summary>
        /// Adds the child.
        /// </summary>
        /// <param name="child">The child.</param>
        /// <param name="preserveWorldPos">if set to <c>true</c> [preserve absolute position].</param>
        public void AddChild(IMyEntity child, bool preserveWorldPos = false, bool insertIntoSceneIfNeeded = true)
        {
            //MyEntities.Remove(child);  // if it's already in the world, remove it

            MyHierarchyComponentBase childHierarchy = child.Components.Get<MyHierarchyComponentBase>();
            childHierarchy.Parent = this;

            if (preserveWorldPos)
            {
                var tmpWorldMatrix = child.WorldMatrix;

                this.Children.Add(childHierarchy);

                child.WorldMatrix = tmpWorldMatrix;
            }
            else
            {
                this.Children.Add(childHierarchy);

                MyPositionComponentBase positionComponent = Container.Get<MyPositionComponentBase>();
                MyPositionComponentBase childPositionComponent = child.Components.Get<MyPositionComponentBase>();

                var m = positionComponent.WorldMatrix;
                childPositionComponent.UpdateWorldMatrix(ref m);
            }

            if (Container.Entity.InScene && !child.InScene && insertIntoSceneIfNeeded)
                child.OnAddedToScene(Container.Entity);
        }
Пример #5
0
 public EntityComponent(IMyEntity entity)
     : base()
 {
     Entity = entity;
     Log = new Logger("SEGarden.Logic.EntityComponent", (() => EntityId.ToString()));
     //Log.Trace("Finished EntityComponent ctr", "ctr");
 }
Пример #6
0
        /// <param name="damage">Not used for now but could be used as a multiplier instead of random decal size</param>
        public static void HandleAddDecal(IMyEntity entity, MyHitInfo hitInfo, MyStringHash source = default(MyStringHash), float damage = -1)
        {
            if (entity == null)
                DebugNullEntity();

            IMyDecalProxy proxy = entity as IMyDecalProxy;
            if (proxy != null)
            {
                AddDecal(proxy, ref hitInfo, damage, source);
                return;
            }

            MyCubeGrid grid = entity.GetTopMostParent() as MyCubeGrid;
            if (grid != null)
            {
                var block = grid.GetTargetedBlock(hitInfo.Position);
                if (block != null)
                {
                    var compoundBlock = block.FatBlock as MyCompoundCubeBlock;
                    if (compoundBlock == null)
                        proxy = block;
                    else
                        proxy = compoundBlock;
                }
            }

            if (proxy != null)
                AddDecal(proxy, ref hitInfo, damage, source);
        }
        private IMyPlayer FindPlayer(IMyEntity entity)
        {
            List<IMyPlayer> players = new List<IMyPlayer>();
            MyAPIGateway.Players.GetPlayers(players);

            double nearestDistance = 5; // usually the distance between player and handtool is about 2 to 3, 5 is plenty 
            IMyPlayer nearestPlayer = null;

            foreach (IMyPlayer player in players)
            {
                var character = player.GetCharacter();
                if (character != null)
                {
                    var distance = (((IMyEntity)character).GetPosition() - entity.GetPosition()).LengthSquared();

                    if (distance < nearestDistance)
                    {
                        nearestDistance = distance;
                        nearestPlayer = player;
                    }
                }
            }

            return nearestPlayer;
        }
Пример #8
0
        /// <param name="damage">Not used for now but could be used as a multiplier instead of random decal size</param>
        public static void HandleAddDecal(IMyEntity entity, MyHitInfo hitInfo, MyStringHash source = default(MyStringHash), object customdata = null, float damage = -1)
        {
            IMyDecalProxy proxy = entity as IMyDecalProxy;
            if (proxy != null)
            {
                AddDecal(proxy, ref hitInfo, damage, source, customdata);
                return;
            }

            MyCubeGrid grid = entity as MyCubeGrid;
            if (grid != null)
            {
                var block = grid.GetTargetedBlock(hitInfo.Position);
                if (block != null)
                {
                    var compoundBlock = block.FatBlock as MyCompoundCubeBlock;
                    if (compoundBlock == null)
                        proxy = block;
                    else
                        proxy = compoundBlock;
                }
            }

            if (proxy == null)
                return;

            AddDecal(proxy, ref hitInfo, damage, source, customdata);
        }
        public override void Use(UseActionEnum actionEnum, IMyEntity entity)
        {
            var user = entity as MyCharacter;
            var block = Entity as MyCubeBlock;

            if (block != null)
            {
                var relation = block.GetUserRelationToOwner(user.ControllerInfo.ControllingIdentityId);
                if (!relation.IsFriendly())
                {
                    if (user.ControllerInfo.IsLocallyHumanControlled())
                    {
                        MyHud.Notifications.Add(MyNotificationSingletons.AccessDenied);
                    }
                    return;
                }
            }

            switch (actionEnum)
            {
                case UseActionEnum.OpenInventory:
                case UseActionEnum.OpenTerminal:
                    MyGuiScreenTerminal.Show(MyTerminalPageEnum.Inventory, user, Entity);
                    break;
                default:
                    //MyGuiScreenTerminal.Show(MyTerminalPageEnum.Inventory, user, Block);
                    break;
            }
        }
Пример #10
0
        public Waypoint(Mover mover, AllNavigationSettings navSet, AllNavigationSettings.SettingsLevelName level, IMyEntity targetEntity, Vector3D worldOffset)
            : base(mover, navSet)
        {
            this.m_logger = new Logger(GetType().Name, m_controlBlock.CubeBlock);
            this.m_level = level;
            this.m_targetEntity = targetEntity;
            this.m_targetOffset = worldOffset;

            m_logger.debugLog(targetEntity != targetEntity.GetTopMostParent(), "targetEntity is not top-most", Logger.severity.FATAL);

            IMyCubeGrid asGrid = targetEntity as IMyCubeGrid;
            if (asGrid != null && Attached.AttachedGrid.IsGridAttached(asGrid, m_controlBlock.CubeGrid, Attached.AttachedGrid.AttachmentKind.Physics))
            {
                m_logger.debugLog("Cannot fly to entity, attached: " + targetEntity.getBestName() + ", creating GOLIS", Logger.severity.WARNING);
                new GOLIS(mover, navSet, TargetPosition, level);
                return;
            }
            if (targetEntity.Physics == null)
            {
                m_logger.debugLog("Target has no physics: " + targetEntity.getBestName() + ", creating GOLIS", Logger.severity.WARNING);
                new GOLIS(mover, navSet, TargetPosition, level);
                return;
            }

            var setLevel = navSet.GetSettingsLevel(level);
            setLevel.NavigatorMover = this;
            //setLevel.DestinationEntity = mover.Block.CubeBlock; // to force avoidance

            m_logger.debugLog("created, level: " + level + ", target: " + targetEntity.getBestName() + ", target position: " + targetEntity.GetPosition() + ", offset: " + worldOffset + ", position: " + TargetPosition, Logger.severity.DEBUG);
        }
Пример #11
0
        private void ProtectedEntity(IMyEntity entity, ProtectedItem item)
        {
            //Logging.WriteLineAndConsole(string.Format("Protecting: {0}", entity.EntityId));
            //CubeGridEntity gridEntity = new CubeGridEntity((MyObjectBuilder_CubeGrid)entity.GetObjectBuilder(), entity);
            CubeGridEntity gridEntity = (CubeGridEntity)GameEntityManager.GetEntity(entity.EntityId);
            MyObjectBuilder_CubeGrid grid = (MyObjectBuilder_CubeGrid)entity.GetObjectBuilder();

            int count = 0;
            while (gridEntity.IsLoading)
            {
                if (count >= 20)
                    return;

                Thread.Sleep(100);
                count++;
            }

            bool found = false;
            /*
            foreach(CubeBlockEntity block in gridEntity.CubeBlocks)
            {
                if (block.IntegrityPercent != item.IntegrityIncrease || block.BuildPercent != item.IntegrityIncrease || block.BoneDamage > 0f)
                {
                    found = true;
                    block.FixBones(0, 100);
                    block.IntegrityPercent = item.IntegrityIncrease;
                    block.BuildPercent = item.IntegrityIncrease;
                }
            }
            */
            if(found)
             			Logging.WriteLineAndConsole(string.Format("Repaired Grid: {0}", gridEntity.EntityId));
        }
 void IMyPlayerCollection.TryExtendControl(IMyControllableEntity entityWithControl, IMyEntity entityGettingControl)
 {
     var e1 = entityWithControl as Sandbox.Game.Entities.IMyControllableEntity;
     var e2 = entityGettingControl as MyEntity;
     if (e1 != null && e2 != null)
         TryExtendControl(e1, e2);
 }
 void IMyPlayerCollection.ReduceControl(IMyControllableEntity entityWhichKeepsControl, IMyEntity entityWhichLoosesControl)
 {
     var e1 = entityWhichKeepsControl as Sandbox.Game.Entities.IMyControllableEntity;
     var e2 = entityWhichLoosesControl as MyEntity;
     if (e1 != null && e2 != null)
         ReduceControl(e1, e2);
 }
 bool IMyEntities.TryGetEntityByName(string name, out IMyEntity entity)
 {
     MyEntity baseEntity;
     var retVal = MyEntities.TryGetEntityByName(name, out baseEntity);
     entity = baseEntity;
     return retVal;
 }
 bool IMyEntities.TryGetEntityById(long id, out IMyEntity entity)
 {
     MyEntity baseEntity;
     var retVal = MyEntities.TryGetEntityById(id, out baseEntity);
     entity = baseEntity;
     return retVal;
 }
Пример #16
0
        /// <summary>
        /// Creates a missile with homing and target finding capabilities.
        /// </summary>
        public GuidedMissile(IMyEntity missile, IMyCubeBlock firedBy, TargetingOptions opt, Ammo ammo, LastSeen initialTarget = null, bool isSlave = false)
            : base(missile, firedBy)
        {
            myLogger = new Logger("GuidedMissile", () => missile.getBestName(), () => m_stage.ToString());
            myAmmo = ammo;
            myDescr = ammo.Description;
            if (ammo.Description.HasAntenna)
                myAntenna = new MissileAntenna(missile);
            TryHard = true;

            AllGuidedMissiles.Add(this);
            missile.OnClose += missile_OnClose;

            if (myAmmo.IsCluster && !isSlave)
                myCluster = new Cluster(myAmmo.MagazineDefinition.Capacity - 1);
            accelerationPerUpdate = (myDescr.Acceleration + myAmmo.MissileDefinition.MissileAcceleration) / 60f;
            addSpeedPerUpdate = myDescr.Acceleration / 60f;

            Options = opt;
            Options.TargetingRange = ammo.Description.TargetRange;
            myTargetSeen = initialTarget;

            myLogger.debugLog("Options: " + Options, "GuidedMissile()");
            //myLogger.debugLog("AmmoDescription: \n" + MyAPIGateway.Utilities.SerializeToXML<Ammo.AmmoDescription>(myDescr), "GuidedMissile()");
        }
Пример #17
0
 public PlayerData()
 {
     thirst = 100;
     hunger = 100;
     entity = null;
     loaded = false;
 }
 public void Use(UseActionEnum actionEnum, IMyEntity entity)
 {
     var user = entity as MyCharacter;
     switch(actionEnum)
     {
         case UseActionEnum.Manipulate:
             if (!m_buttonPanel.IsWorking)
                 return;
             if (!m_buttonPanel.AnyoneCanUse && !m_buttonPanel.HasLocalPlayerAccess())
             {
                 MyHud.Notifications.Add(MyNotificationSingletons.AccessDenied);
                 return;
             }
             m_buttonPanel.Toolbar.UpdateItem(m_index);
             m_buttonPanel.Toolbar.ActivateItemAtIndex(m_index);
             m_buttonPanel.PressButton(m_index);
             break;
         case UseActionEnum.OpenTerminal:
             if (!m_buttonPanel.HasLocalPlayerAccess())
                 return;
             MyToolbarComponent.CurrentToolbar = m_buttonPanel.Toolbar;
             MyGuiScreenBase screen = MyGuiScreenCubeBuilder.Static;
             if (screen == null)
                 screen = MyGuiSandbox.CreateScreen(MyPerGameSettings.GUI.ToolbarConfigScreen, 0, m_buttonPanel);
             MyToolbarComponent.AutoUpdate = false;
             screen.Closed += (source) => MyToolbarComponent.AutoUpdate = true;
             MyGuiSandbox.AddScreen(screen);
             break;
         default:
             break;
     }
 }
 public MyUseObjectCryoChamberDoor(IMyEntity owner, string dummyName, MyModelDummy dummyData, uint key)
 {
     CryoChamber = owner as MyCryoChamber;
     Debug.Assert(CryoChamber != null, "MyUseObjectCryoChamberDoor should only be used with MyCryoChamber blocks!");
     
     LocalMatrix = dummyData.Matrix;
 }
Пример #20
0
		public static short GetWeaponsTargetingProjectile(IMyEntity entity)
		{
			short result;
			if (!WeaponsTargetingProjectile.TryGetValue(entity.EntityId, out result))
				result = 0;
			return result;
		}
Пример #21
0
 public Character(IMyEntity entity)
     : base(entity)
 {
     Log.ClassName = "GP.Concealment.World.Entities.Character";
     Log.Trace("New Character " + Entity.EntityId + " " + DisplayName, "ctr");
     CharacterEntity = Entity as IMyCharacter;
 }
 void Sandbox.ModAPI.Ingame.IMyLargeTurretBase.SetTarget(IMyEntity entity)
 {
     if (entity != null)
     {
         MyMultiplayer.RaiseEvent(this, x => x.SetTargetRequest, entity.EntityId, false);
     } 
 }
        private void RepairShip(IMyEntity shipEntity)
        {
            // We SHOULD NOT make any changes directly to the prefab, we need to make a Value copy using Clone(), and modify that instead.
            var gridObjectBuilder = shipEntity.GetObjectBuilder().Clone() as MyObjectBuilder_CubeGrid;

            shipEntity.Physics.Deactivate();

            // This will Delete the entity and sync to all.
            // Using this, also works with player ejection in the same Tick.
            shipEntity.SyncObject.SendCloseRequest();

            gridObjectBuilder.EntityId = 0;

            if (gridObjectBuilder.Skeleton == null)
                gridObjectBuilder.Skeleton = new List<BoneInfo>();
            else
                gridObjectBuilder.Skeleton.Clear();

            foreach (var cube in gridObjectBuilder.CubeBlocks)
            {
                cube.IntegrityPercent = cube.BuildPercent;
                cube.DeformationRatio = 0;
                // No need to set bones for individual blocks like rounded armor, as this is taken from the definition within the game itself.
            }

            var tempList = new List<MyObjectBuilder_EntityBase>();
            tempList.Add(gridObjectBuilder);
            tempList.CreateAndSyncEntities();

            MyAPIGateway.Utilities.ShowMessage("repair", "Ship '{0}' has been repairded.", shipEntity.DisplayName);
        }
        private void TurnOnShip(IMyEntity shipEntity, out int reactorCounter, out int batteryCounter)
        {
            reactorCounter = 0;
            batteryCounter = 0;
            var grids = shipEntity.GetAttachedGrids(AttachedGrids.Static);

            foreach (var cubeGrid in grids)
            {
                var blocks = new List<Sandbox.ModAPI.IMySlimBlock>();
                cubeGrid.GetBlocks(blocks, f => f.FatBlock != null
                    && f.FatBlock is IMyFunctionalBlock
                    && (f.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_Reactor)
                      || f.FatBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_BatteryBlock)));

                var list = blocks.Select(f => (IMyFunctionalBlock)f.FatBlock).Where(f => !f.Enabled).ToArray();

                foreach (var item in list)
                {
                    MessageSyncBlock.Process(item, SyncBlockType.PowerOn);

                    if (item.BlockDefinition.TypeId == typeof(MyObjectBuilder_Reactor))
                        reactorCounter++;
                    else
                        batteryCounter++;
                }
            }
        }
Пример #25
0
 // Creation from ingame entity
 public RevealedEntity(IMyEntity entity)
     : base(entity)
 {
     Log.Trace("Start RevealedEntity constructor", "ctr");
     MovedSinceIsInAsteroidCheck = true;
     Log.ClassName = "GP.Concealment.World.Entities.RevealedEntity";
     Log.Trace("Finished RevealedEntity constructor", "ctr");
 }
 bool IMyPlayerCollection.TryReduceControl(IMyControllableEntity entityWhichKeepsControl, IMyEntity entityWhichLoosesControl)
 {
     var e1 = entityWhichKeepsControl as Sandbox.Game.Entities.IMyControllableEntity;
     var e2 = entityWhichLoosesControl as MyEntity;
     if (e1 != null && e2 != null)
         return TryReduceControl(e1, e2);
     return false;
 }
 // Creation from ingame entity
 public ControllableEntity(IMyEntity entity)
     : base(entity)
 {
     //Log.Trace("Running ControllableEntity ctr", "ctr");
     Log.ClassName = "GP.Concealment.World.Entities.ControllableEntity";
     Log.Trace("New Controllable Entity " + DisplayName, "ctr");
     //Log.Trace("Finished ControllableEntity ctr", "ctr");
 }
Пример #28
0
        public Sandbox.Common.MyIntersectionResultLineTriangleEx? GetIntersectionWithLine(IMyEntity physObject, ref LineD line, ref MatrixD customInvMatrix, IntersectionFlags flags)
        {
            LineD lineInModelSpace = new LineD(Vector3D.Transform(line.From, ref customInvMatrix), Vector3D.Transform(line.To, ref customInvMatrix));

            MyIntersectionResultLineTriangleEx? ret = m_rootNode.GetIntersectionWithLine(physObject, m_model, ref lineInModelSpace, null, flags);

            return ret;
        }
Пример #29
0
		/// <summary>
		/// Tests the WorldAABB of an entity for intersection with a capsule
		/// </summary>
		/// <param name="cap">Capsule to test for intersection</param>
		/// <param name="entity">WorldAABB will be tested against capsule</param>
		/// <param name="distance">Distance at which path intersects AABB</param>
		/// <returns>true if there is an intersection (including boundary)</returns>
		public static bool IntersectsAABB(this Capsule cap, IMyEntity entity, out float distance)
		{
			BoundingBox AABB = (BoundingBox)entity.WorldAABB;
			Vector3 Radius = new Vector3(cap.Radius, cap.Radius, cap.Radius);
			AABB = new BoundingBox(AABB.Min - Radius, AABB.Max + Radius);
			//myLogger.debugLog("Testing AABB: " + AABB.Min + ", " + AABB.Max + " against line: " + cap.P0 + ", " + cap.P1, "IntersectsAABB()");
			return (AABB.Intersects(cap.get_Line(), out distance));
		}
Пример #30
0
 public PlayerData(ulong id)
 {
     thirst = 100;
     hunger = 100;
     entity = null;
     steamid = id;
     loaded = false;
 }
Пример #31
0
 public virtual void CloseEntity(IMyEntity entity)
 {
     Closed = true;
 }
Пример #32
0
 private Vector3 ComputePredictionOffset(IMyEntity entity)
 {
     return(entity.Physics.LinearVelocity * m_predictionSize);
 }
Пример #33
0
 public Destination(IMyEntity entity, Vector3D offset)
 {
     Entity   = entity;
     Position = offset;
 }
Пример #34
0
        public static bool PlaceEncounterToWorld(BoundingBoxD boundingVolume, int seed, MyObjectSeedType seedType)
        {
            if (MySession.Static.Settings.EnableEncounters == false)
            {
                return(false);
            }

            boundingVolume.Max.X = Math.Round(boundingVolume.Max.X, 2);
            boundingVolume.Max.Y = Math.Round(boundingVolume.Max.Y, 2);
            boundingVolume.Max.Z = Math.Round(boundingVolume.Max.Z, 2);

            boundingVolume.Min.X = Math.Round(boundingVolume.Min.X, 2);
            boundingVolume.Min.Y = Math.Round(boundingVolume.Min.Y, 2);
            boundingVolume.Min.Z = Math.Round(boundingVolume.Min.Z, 2);

            Vector3D placePosition = boundingVolume.Center;

            m_random.SetSeed(seed);

            if (m_spawnGroups.Count == 0)
            {
                var allSpawnGroups = MyDefinitionManager.Static.GetSpawnGroupDefinitions();
                foreach (var spawnGroup in allSpawnGroups)
                {
                    if (spawnGroup.IsEncounter)
                    {
                        m_spawnGroups.Add(spawnGroup);
                    }
                }
            }

            if (m_spawnGroups.Count > 0)
            {
                m_randomEncounters.Clear();
                m_placePositions.Clear();
                m_encountersId.Clear();
                int numEncoutersToPlace = 1;
                List <MySpawnGroupDefinition> currentSpawnGroup = m_spawnGroups;

                for (int i = 0; i < numEncoutersToPlace; ++i)
                {
                    MyEncounterId encounterPosition = new MyEncounterId(boundingVolume, seed, i);
                    if (true == m_savedEncounters.Contains(encounterPosition))
                    {
                        continue;
                    }
                    m_randomEncounters.Add(PickRandomEncounter(currentSpawnGroup));
                    Vector3D newPosition   = placePosition + (numEncoutersToPlace - 1) * (i == 0 ? -1 : 1) * GetEncounterBoundingBox(currentSpawnGroup[m_randomEncounters[m_randomEncounters.Count - 1]]).HalfExtents;
                    Vector3D savedPosition = Vector3D.Zero;
                    if (true == m_movedOnlyEncounters.Dictionary.TryGetValue(encounterPosition, out savedPosition))
                    {
                        newPosition = savedPosition;
                    }
                    encounterPosition.PlacePosition = newPosition;

                    m_encountersId.Add(encounterPosition);

                    m_placePositions.Add(newPosition);
                }

                //first place voxels becaose voxel needs to be created even on client and if grids were created first
                //entity ids woudn't match
                for (int i = 0; i < m_randomEncounters.Count; ++i)
                {
                    foreach (var selectedVoxel in currentSpawnGroup[m_randomEncounters[i]].Voxels)
                    {
                        var filePath = MyWorldGenerator.GetVoxelPrefabPath(selectedVoxel.StorageName);

                        var storage = MyStorageBase.LoadFromFile(filePath);
                        storage.DataProvider = MyCompositeShapeProvider.CreateAsteroidShape(0, 1.0f, MySession.Static.Settings.VoxelGeneratorVersion);
                        IMyEntity voxel = MyWorldGenerator.AddVoxelMap(String.Format("Asteroid_{0}_{1}_{2}", m_entityToEncounterConversion.Count, seed, m_random.Next()), storage, m_placePositions[i] + selectedVoxel.Offset);
                        voxel.Save              = false;
                        voxel.OnPhysicsChanged += OnCreatedEntityChanged;
                        m_entityToEncounterConversion[voxel] = m_encountersId[i];
                    }
                }

                if (Sync.IsServer == true)
                {
                    for (int i = 0; i < m_randomEncounters.Count; ++i)
                    {
                        SpawnEncounter(m_encountersId[i], m_placePositions[i], currentSpawnGroup, m_randomEncounters[i]);
                    }
                }
            }

            return(true);
        }
        public override bool HandleInput()
        {
            m_counter++;
            if (base.HandleInput())
            {
                return(true);
            }

            bool handled = false;

            if (MyInput.Static.IsAnyCtrlKeyPressed() && MyInput.Static.IsNewLeftMouseReleased())
            {
                Hammer();
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad1))
            {
                ApplyMassMultiplier = !ApplyMassMultiplier;
                handled             = true;
            }
            var mul = 1;

            if (MyInput.Static.IsKeyPress(MyKeys.N))
            {
                mul = 10;
            }
            if (MyInput.Static.IsKeyPress(MyKeys.B))
            {
                mul = 100;
            }
            if (MyInput.Static.IsNewKeyPressed(MyKeys.OemQuotes))
            {
                if (MassMultiplier > 1)
                {
                    MassMultiplier += mul;
                }
                else
                {
                    MassMultiplier *= mul;
                }
                handled = true;
            }
            if (MyInput.Static.IsNewKeyPressed(MyKeys.OemSemicolon))
            {
                if (MassMultiplier > 1)
                {
                    MassMultiplier -= mul;
                }
                else
                {
                    MassMultiplier /= mul;
                }
                handled = true;
            }

            if (MyInput.Static.IsAnyCtrlKeyPressed() && MyInput.Static.IsNewLeftMousePressed() && SpawnFlora != null)
            {
                MyDefinitionId id = new MyDefinitionId(typeof(MyObjectBuilder_ConsumableItem), "Mushrooms");
                SpawnFlora(MySector.MainCamera.Position + MySector.MainCamera.ForwardVector, new BoundingBox(Vector3.Zero, Vector3.One), id, 1);
                SpawnFlora(MySector.MainCamera.Position + MySector.MainCamera.ForwardVector, new BoundingBox(Vector3.Zero, Vector3.One), id, 1);
                SpawnFlora(MySector.MainCamera.Position + MySector.MainCamera.ForwardVector, new BoundingBox(Vector3.Zero, Vector3.One), id, 1);
                SpawnFlora(MySector.MainCamera.Position + MySector.MainCamera.ForwardVector, new BoundingBox(Vector3.Zero, Vector3.One), id, 1);
                SpawnFlora(MySector.MainCamera.Position + MySector.MainCamera.ForwardVector, new BoundingBox(Vector3.Zero, Vector3.One), id, 1);
                SpawnFlora(MySector.MainCamera.Position + MySector.MainCamera.ForwardVector, new BoundingBox(Vector3.Zero, Vector3.One), id, 1);
                SpawnFlora(MySector.MainCamera.Position + MySector.MainCamera.ForwardVector, new BoundingBox(Vector3.Zero, Vector3.One), id, 1);
                SpawnFlora(MySector.MainCamera.Position + MySector.MainCamera.ForwardVector, new BoundingBox(Vector3.Zero, Vector3.One), id, 1);
            }

            Vector2 pos = new Vector2(400, 10);

            if (MyInput.Static.IsAnyShiftKeyPressed() && MyInput.Static.IsNewLeftMousePressed() && SelectedEntity != null)
            {
                SelectedEntity = null;
            }

            HkRigidBody body = null;

            if (SelectedEntity != null && SelectedEntity.Physics != null)
            {
                body = ((MyEntity)SelectedEntity).Physics.RigidBody;
            }

            if (MySector.MainCamera != null && body == null)
            {
                List <MyPhysics.HitInfo> lst = new List <MyPhysics.HitInfo>();
                MyPhysics.CastRay(MySector.MainCamera.Position, MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 100, lst);
                foreach (var hit in lst)
                {
                    body = hit.HkHitInfo.Body;
                    if (body == null || body.Layer == MyPhysics.NoCollisionLayer)
                    {
                        continue;
                    }
                    if (MyInput.Static.IsAnyShiftKeyPressed() && MyInput.Static.IsNewLeftMousePressed())
                    {
                        SelectedEntity = hit.HkHitInfo.GetHitEntity();
                    }
                    var sb = new System.Text.StringBuilder("ShapeKeys: ");
                    for (int i = 0; i < HkWorld.HitInfo.ShapeKeyCount; i++)
                    {
                        var key = hit.HkHitInfo.GetShapeKey(i);
                        if (key == uint.MaxValue)
                        {
                            break;
                        }
                        sb.Append(string.Format("{0} ", key));
                    }
                    VRageRender.MyRenderProxy.DebugDrawText2D(pos, sb.ToString(), Color.White, 0.7f);
                    pos.Y += 20;
                    if (body.GetBody() != null)
                    {
                        VRageRender.MyRenderProxy.DebugDrawText2D(pos, string.Format("Weld: {0}", body.GetBody().WeldInfo.Children.Count), Color.White, 0.7f);
                    }
                    pos.Y += 20;
                    break;
                }
            }
            if (MySector.MainCamera != null)
            {
                LineD line      = new LineD(MySector.MainCamera.Position, MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 100);
                var   intersect = MyEntities.GetIntersectionWithLine(ref line, MySession.ControlledEntity.Entity, null);
                if (intersect.HasValue)
                {
                    VRageRender.MyRenderProxy.DebugDrawText2D(pos, intersect.Value.Entity.ToString() + " "
                                                              , Color.White, 0.8f);
                }
            }

            if (body != null && m_drawBodyInfo)
            {
                //VRageRender.MyRenderProxy.DebugDrawText2D(pos, body.GetEntity(0).ToString() + " "
                //       + MyDestructionHelper.MassFromHavok(body.Mass), Color.White, 0.8f);
                pos.Y += 20;
                VRageRender.MyRenderProxy.DebugDrawText2D(pos, "Layer: " + body.Layer, Color.White, 0.7f);
                pos.Y += 20;
                VRageRender.MyRenderProxy.DebugDrawText2D(pos, string.Format("Friction: {0}  Restitution: {1}", body.Friction, body.Restitution), Color.White, 0.7f);
                pos.Y += 20;
                VRageRender.MyRenderProxy.DebugDrawText2D(pos, "Lin: " + body.LinearVelocity.Length(), Color.White, 0.7f);
                pos.Y += 20;
                VRageRender.MyRenderProxy.DebugDrawText2D(pos, "Ang: " + body.AngularVelocity.Length(), Color.White, 0.7f);
                pos.Y += 20;
                VRageRender.MyRenderProxy.DebugDrawText2D(pos, "Act: " + (body.IsActive ? "true" : "false"), Color.White, 0.7f);
                pos.Y += 20;
                VRageRender.MyRenderProxy.DebugDrawText2D(pos, "Stat: " + (body.IsFixedOrKeyframed ? "true" : "false"), Color.White, 0.7f);
                pos.Y += 20;
                VRageRender.MyRenderProxy.DebugDrawText2D(pos, "Solver: " + (body.Motion.GetDeactivationClass()), Color.White, 0.7f);
                pos.Y += 20;
                //VRageRender.MyRenderProxy.DebugDrawText2D(pos, "CharLin: " + MySession.ControlledEntity.Entity.Physics.LinearVelocity.Length(), Color.White, 0.7f);
            }

            if (SelectedEntity != null && m_drawUpdateInfo)
            {
                VRageRender.MyRenderProxy.DebugDrawText2D(pos, "Updates: " + m_counter, Color.White, 0.7f);
                pos.Y += 20;
                VRageRender.MyRenderProxy.DebugDrawText2D(pos, "PositionUpd: " + dbgPosCounter, Color.White, 0.7f);
                pos.Y += 20;
                VRageRender.MyRenderProxy.DebugDrawText2D(pos, "Frames per update: " + m_counter / (float)dbgPosCounter, Color.White, 0.7f);
                pos.Y += 20;
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad9))
            {
                MyScriptManager.Static.LoadData();
            }

            if (MyAudio.Static != null)
            {
                foreach (var em in MyAudio.Static.Get3DSounds())
                {
                    VRageRender.MyRenderProxy.DebugDrawSphere(em.SourcePosition, 0.1f, Color.Red, 1, false);
                }
            }

            return(handled);
        }
Пример #36
0
 public IMyTerminalBlock MatchEntToShieldFast(IMyEntity entity, bool onlyIfOnline) => _matchEntToShieldFast?.Invoke(entity, onlyIfOnline) ?? null;
Пример #37
0
 public static Vector3D GetDirection(IMyEntity refBlock, string dirStr)
 {
     return(GetDirection(refBlock.WorldMatrix, dirStr));
 }
Пример #38
0
 public static void HandleClose(IMyEntity entity)
 {
     MyLog.Default.WriteLine(String.Format("SettingsStore entity {0} removed from world, deleting settings.", entity.EntityId));
     dict.Remove(entity.EntityId);
     Save();
 }
Пример #39
0
 public Destination(Vector3D worldPosition)
 {
     Entity   = null;
     Position = worldPosition;
 }
 public MyUseObjectCockpitDoor(IMyEntity owner, string dummyName, MyModelDummy dummyData, int key)
 {
     Cockpit     = owner;
     LocalMatrix = dummyData.Matrix;
 }
Пример #41
0
 // ReSharper disable UnusedMember.Local
 private static SlimProfilerEntry SingleMethodEntryProvider_Entity(IMyEntity __instance, string __key)
 {
     return(ProfilerData.EntityEntry(__instance)?.GetSlim(__key));
 }
Пример #42
0
 public MyUseObjectInventory(IMyEntity owner, string dummyName, MyModelDummy dummyData, uint key)
 {
     Block       = owner as MyCubeBlock;
     LocalMatrix = dummyData.Matrix;
 }
Пример #43
0
 protected IMyEntity GetTarget(IMyEntity missile)
 {
     return(null);
 }
        public MyIntersectionResultLineTriangleEx(MyIntersectionResultLineTriangle triangle, IMyEntity entity, ref LineD line)
        {
            Triangle = triangle;
            Entity   = entity;
            InputLineInObjectSpace = line;

            NormalInObjectSpace            = MyUtils.GetNormalVectorFromTriangle(ref Triangle.InputTriangle);
            IntersectionPointInObjectSpace = line.From + line.Direction * Triangle.Distance;

            if (Entity is IMyVoxelMap)
            {
                IntersectionPointInWorldSpace = (Vector3D)IntersectionPointInObjectSpace;
                NormalInWorldSpace            = NormalInObjectSpace;

                //  This will move intersection point from world space into voxel map's object space
                IntersectionPointInObjectSpace = IntersectionPointInObjectSpace - ((IMyVoxelMap)Entity).PositionLeftBottomCorner;
            }
            else
            {
                var worldMatrix = Entity.WorldMatrix;
                NormalInWorldSpace            = (Vector3)MyUtils.GetTransformNormalNormalized((Vector3D)NormalInObjectSpace, ref worldMatrix);
                IntersectionPointInWorldSpace = Vector3D.Transform((Vector3D)IntersectionPointInObjectSpace, ref worldMatrix);
            }
        }
Пример #45
0
 public IMyTerminalBlock GetShieldBlock(IMyEntity entity) => _getShieldBlock?.Invoke(entity) ?? null;
Пример #46
0
 void Entity_OnClose(IMyEntity obj)
 {
     UnweldAll(true);
 }
        void IMyUseObject.Use(UseActionEnum actionEnum, IMyEntity entity)
        {
            var user = entity as MyCharacter;

            CryoChamber.RequestUse(actionEnum, user);
        }
Пример #48
0
 public bool ProtectedByShield(IMyEntity entity) => _protectedByShield?.Invoke(entity) ?? false;
        public MyIntersectionResultLineTriangleEx(MyIntersectionResultLineTriangle triangle, IMyEntity entity, ref LineD line, Vector3D intersectionPointInWorldSpace, Vector3 normalInWorldSpace)
        {
            Triangle = triangle;
            Entity   = entity;
            InputLineInObjectSpace = line;

            NormalInObjectSpace            = NormalInWorldSpace = normalInWorldSpace;
            IntersectionPointInWorldSpace  = intersectionPointInWorldSpace;
            IntersectionPointInObjectSpace = (Vector3)IntersectionPointInWorldSpace;
        }
Пример #50
0
 public bool EntityBypass(IMyTerminalBlock block, IMyEntity entity, bool remove = false) => _entityBypass?.Invoke(block, entity, remove) ?? false;
Пример #51
0
 public Destination(ref IHitInfo hitInfo)
 {
     Entity   = hitInfo.HitEntity;
     Position = hitInfo.Position - Entity.GetCentre();
 }
Пример #52
0
        public static bool Move(string userName, Vector3D position)
        {
            //CharacterEntity charEntity = SectorObjectManager.Instance.GetTypedInternalData<CharacterEntity>().FirstOrDefault(x => x.DisplayName.ToLower() == userName.ToLower() && x.Health > 0);
            MyObjectBuilder_Character charEntity = FindCharacter(userName);

            if (charEntity == null)
            {
                Logging.WriteLineAndConsole(string.Format("Unable to find CharacterEntity of '{0}'", userName));
                return(false);
            }

            CubeGridEntity gridEntity = new CubeGridEntity(new FileInfo(Essentials.PluginPath + "MovePlayer.sbc"));

            gridEntity.EntityId = BaseEntity.GenerateEntityId();
            foreach (MyObjectBuilder_CubeBlock block in gridEntity.BaseCubeBlocks)
            {
                // set ownership
                MyObjectBuilder_Cockpit cockpit = block as MyObjectBuilder_Cockpit;
                if (cockpit != null)
                {
                    cockpit.Pilot = charEntity;
                }
            }

            gridEntity.PositionAndOrientation = new MyPositionAndOrientation(position, Vector3.Forward, Vector3.Up);

            Wrapper.GameAction(() =>
            {
                MyObjectBuilder_EntityBase baseEntity = gridEntity.Export();
                MyAPIGateway.Entities.RemapObjectBuilder(baseEntity);
                IMyEntity entity = MyAPIGateway.Entities.CreateFromObjectBuilderAndAdd(baseEntity);
                Type someManager = SandboxGameAssemblyWrapper.Instance.GetAssemblyType(SectorObjectManager.EntityBaseNetManagerNamespace, SectorObjectManager.EntityBaseNetManagerClass);
                Wrapper.InvokeStaticMethod(someManager, SectorObjectManager.EntityBaseNetManagerSendEntity, new object[] { entity.GetObjectBuilder() });
                gridEntity = new CubeGridEntity((MyObjectBuilder_CubeGrid)entity.GetObjectBuilder(), entity);
            });


            int count = 0;

            while (gridEntity.IsLoading)
            {
                Thread.Sleep(100);
                count++;
                if (count > 40)
                {
                    break;
                }
            }

            if (gridEntity.IsLoading)
            {
                Logging.WriteLineAndConsole(string.Format("Failed to load cockpit entity: {0}", gridEntity.EntityId));
                return(false);
            }

            foreach (CubeBlockEntity block in gridEntity.CubeBlocks)
            {
                if (block is CockpitEntity)
                {
                    block.IntegrityPercent = 0.1f;
                }
            }

            gridEntity.Dispose();
            return(true);
        }
Пример #53
0
        private void Flee(List <Ingame.MyDetectedEntityInfo> radarData = null)
        {
            try
            {
                if (!IsFleeing)
                {
                    return;
                }

                try
                {
                    if (!FleeTimersTriggered)
                    {
                        TriggerFleeTimers();
                    }

                    try
                    {
                        if (radarData == null)
                        {
                            radarData = LookForEnemies(_freighterSetup.FleeTriggerDistance);
                        }
                        if (radarData.Count == 0)
                        {
                            return;
                        }

                        try
                        {
                            Ingame.MyDetectedEntityInfo closestEnemy = radarData.OrderBy(x => GridPosition.DistanceTo(x.Position)).FirstOrDefault();

                            if (closestEnemy.IsEmpty())
                            {
                                Grid.DebugWrite("Flee", "Cannot find closest hostile");
                                return;
                            }

                            try
                            {
                                IMyEntity enemyEntity = MyAPIGateway.Entities.GetEntityById(closestEnemy.EntityId);
                                if (enemyEntity == null)
                                {
                                    Grid.DebugWrite("Flee", "Cannot find enemy entity from closest hostile ID");
                                    return;
                                }

                                try
                                {
                                    //Grid.DebugWrite("Flee", $"Fleeing from '{EnemyEntity.DisplayName}'. Distance: {Math.Round(GridPosition.DistanceTo(ClosestEnemy.Position))}m; FleeTriggerDistance: {FreighterSetup.FleeTriggerDistance}");
                                    //ShowIngameMessage.ShowMessage($"Fleeing from '{enemyEntity.DisplayName}'. Distance: {Math.Round(GridPosition.DistanceTo(closestEnemy.Position))}m; FleeTriggerDistance: {_freighterSetup.FleeTriggerDistance}");
                                    Vector3D fleePoint = GridPosition.InverseVectorTo(closestEnemy.Position, 100 * 1000);
                                    //ShowIngameMessage.ShowMessage($"Flee point: {fleePoint} which is {GridPosition.DistanceTo(fleePoint)}m from me and enemy {enemyEntity.DisplayName}");
                                    //ShowIngameMessage.ShowMessage($"Fleeing at: {DetermineFleeSpeed()}m/s...");
                                    Rc.AddWaypoint(fleePoint, "Flee Point");
                                    (Rc as MyRemoteControl)?.ChangeFlightMode(Ingame.FlightMode.OneWay);
                                    (Rc as MyRemoteControl)?.SetAutoPilotSpeedLimit(DetermineFleeSpeed());
                                    Rc.SetAutoPilotEnabled(true);
                                }
                                catch (Exception scrap)
                                {
                                    Grid.LogError("Flee.AddWaypoint", scrap);
                                }
                            }
                            catch (Exception scrap)
                            {
                                Grid.LogError("Flee.LookForEnemies.GetEntity", scrap);
                            }
                        }
                        catch (Exception scrap)
                        {
                            Grid.LogError("Flee.LookForEnemies.Closest", scrap);
                        }
                    }
                    catch (Exception scrap)
                    {
                        Grid.LogError("Flee.LookForEnemies", scrap);
                    }
                }
                catch (Exception scrap)
                {
                    Grid.LogError("Flee.TriggerTimers", scrap);
                }
            }
            catch (Exception scrap)
            {
                Grid.LogError("Flee", scrap);
            }
        }
Пример #54
0
        public void Update()
        {
            if (Entity == null || Entity.Closed || Entity.MarkedForClose)
            {
                return;
            }
            if (CoreMagRails.instance == null)
            {
                return;
            }
            if (!valid)
            {
                return;
            }
            if (initDirty)
            {
                initBlockSettings();
            }
            if (CoreMagRails.instance.debug != DebugLevel.Verbose)
            {
                if (updateHook)
                {
                    CoreMagRails.UpdateHook -= Update;
                    updateHook = false;
                }

                return;
            }


            if (ents.Count == 0)
            {
                int n = 30;
                while (n-- > 0)
                {
                    var prefab = MyDefinitionManager.Static.GetPrefabDefinition("HoloProjectionPrefab");
                    MyObjectBuilder_CubeGrid p_grid = prefab.CubeGrids[0];
                    MyAPIGateway.Entities.RemapObjectBuilder(p_grid);
                    p_grid.CreatePhysics = false;
                    IMyEntity grid = MyAPIGateway.Entities.CreateFromObjectBuilder(p_grid);
                    grid.Flags &= ~EntityFlags.Save;                    //do not save
                    grid.Flags &= ~EntityFlags.Sync;                    //do not sync
                    MyAPIGateway.Entities.AddEntity(grid);
                    ents.Add(grid);
                }
            }
            Vector3D home = WorldtoGrid(Entity.WorldMatrix.Translation, Entity.WorldMatrixNormalizedInv);

            home.X -= def.X;
            home.Y -= def.Y;
            home.Z -= def.Z;

            if (def.type == RailType.curve)
            {
                Vector3D baseangle = new Vector3D(0, 0, 1);

                foreach (var ent in ents)
                {
                    int index = ents.IndexOf(ent);

                    //MyAPIGateway.Utilities.ShowMessage("Test", Entity.WorldMatrix.Translation.ToString());
                    //MyAPIGateway.Utilities.ShowMessage("TestD", (Entity.WorldMatrix.Translation + Vector3D.Multiply(Entity.WorldMatrix.Down, 3)).ToString());
                    //going to use X and Z
                    double d_angle = ((double)index / 30) / 2;
                    d_angle += 0.5d;
                    if (def.X > 0)
                    {
                        d_angle += 0.5d;
                    }
                    d_angle *= Math.PI;
                    double s            = Math.Sin(d_angle);
                    double c            = Math.Cos(d_angle);
                    var    angle        = new Vector3D(-baseangle.Z * s, 0, baseangle.Z * c);          //note that for the rail part this will be easier...
                    var    radianvector = angle * def.radius;
                    radianvector += home;
                    ent.SetPosition(GridToWorld(radianvector, Entity.WorldMatrix));
                }
            }
            else if (def.type == RailType.straight)
            {
                home.Z -= def.size.Z * 0.5d * def.sizeenum;
                foreach (var ent in ents)
                {
                    double index = ents.IndexOf(ent);
                    var    lerp  = Vector3.Lerp(home, new Vector3(home.X, home.Y, def.size.Z * 0.5d * def.sizeenum), (float)(index / 30.0d));
                    //var newpos = home + new Vector3D(0,  0, (index - 15d) / 5);
                    ent.SetPosition(GridToWorld(lerp, Entity.WorldMatrix));
                }
            }
            else if (def.type == RailType.slant)
            {
                home.Z -= def.size.Z * 0.5d * def.sizeenum;
                //Log.DebugWrite( DebugLevel.Info, "Drawing line");
                //Log.DebugWrite(DebugLevel.Info, home);
                foreach (var ent in ents)
                {
                    double index = ents.IndexOf(ent);
                    var    lerp  = Vector3.Lerp(home, new Vector3(home.X, -def.min.Y, def.size.Z * 0.5d * def.sizeenum), (float)(index / 30.0d));
                    //var newpos = new Vector3D(home.X, ( home.Y + (def.min.Y - home.Y) * (((index - 15d) / 5) / def.size.Z)), home.Z + ((index - 15d) / 5));

                    //Log.DebugWrite(DebugLevel.Info, lerp);
                    ent.SetPosition(GridToWorld(lerp, Entity.WorldMatrix));
                }
            }
            else if (def.type == RailType.cross)
            {
                var ftb = new Vector3D(home);
                ftb.Z -= def.size.Z * 0.5d * def.sizeenum;
                var ltr = new Vector3D(home);
                ltr.X -= def.size.X * 0.5d * def.sizeenum;
                foreach (var ent in ents)
                {
                    double   index = ents.IndexOf(ent);
                    Vector3D lerp;
                    if (index % 2 == 0)
                    {
                        lerp = Vector3D.Lerp(ftb, new Vector3D(ftb.X, ftb.Y, def.size.Z * 0.5d * def.sizeenum), (float)(index / 30.0d));
                    }
                    else
                    {
                        lerp = Vector3D.Lerp(ltr, new Vector3D(def.size.X * 0.5d * def.sizeenum, ltr.Y, ltr.Z), (float)(index / 30.0d));
                    }
                    ent.SetPosition(GridToWorld(lerp, Entity.WorldMatrix));
                }
            }



            //DOSTUFF
        }
Пример #55
0
 private void Weapon_OnClosing(IMyEntity obj)
 {
     m_weaponDataDirty = true;
 }
Пример #56
0
        void Buillding(IMyEntity myEntity)
        {
            Type Entity = myEntity.GetType();

            Title.Text = $"CLASS Name: {Entity.Name}. INTERFACE Name:";

            Type[] Interfaca = Entity.GetInterfaces();
            foreach (Type inter in  Interfaca)
            {
                Title.Text += inter.Name + ", ";

                //"hallo"
            }


            PropertyInfo[] properties = Entity.GetProperties();

            StackPanel LineTitle = new StackPanel()
            {
                Orientation = Orientation.Horizontal
            };

            LineTitle.Margin          = new Thickness(2);
            LineTitle.BorderBrush     = new SolidColorBrush(Windows.UI.Colors.Black);
            LineTitle.BorderThickness = new Thickness(2);
            LineTitle.Children.Add(new TextBlock()
            {
                Margin = new Thickness(3, 0, 3, 0), Text = "Type", MinWidth = 100
            });
            LineTitle.Children.Add(new TextBlock()
            {
                Margin = new Thickness(3, 0, 3, 0), Text = "Name", MinWidth = 100
            });
            LineTitle.Children.Add(new TextBlock()
            {
                Margin = new Thickness(3, 0, 3, 0), Text = "Value", MinWidth = 100
            });
            MainPanel.Children.Add(LineTitle);

            foreach (PropertyInfo property in properties)
            {
                if (!property.CanRead)
                {
                    continue;
                }
                StackPanel LineProperty = new StackPanel()
                {
                    Orientation = Orientation.Horizontal
                };


                LineProperty.Margin          = new Thickness(2);
                LineProperty.BorderBrush     = new SolidColorBrush(Windows.UI.Colors.Black);
                LineProperty.BorderThickness = new Thickness(1);
                LineProperty.Children.Add(new TextBlock()
                {
                    Margin = new Thickness(3, 0, 3, 0), Text = property.PropertyType.Name, MinWidth = 100
                });
                LineProperty.Children.Add(new TextBlock()
                {
                    Margin = new Thickness(3, 0, 3, 0), Text = property.Name, MinWidth = 100
                });
                TextBox textBox = new TextBox()
                {
                    Name = property.Name, Margin = new Thickness(3, 0, 3, 0), MinWidth = 100, IsEnabled = false
                };

                LineProperty.Children.Add(textBox);

                /* TextBox textBox2 = new TextBox() { Name = property.Name, Margin = new Thickness(3, 0, 3, 0), Text = property.GetValue(myEntity)?.ToString() ?? "", MinWidth = 100, IsEnabled = false };
                 * LineProperty.Children.Add(textBox2);*/

                if (property.CanWrite)
                {
                    Button buttonEdit = new Button()
                    {
                        Name = "Edit", Margin = new Thickness(3, 0, 3, 0), Content = "Edit", MinWidth = 100
                    };
                    buttonEdit.Click += ButtonEdit_Click;
                    LineProperty.Children.Add(buttonEdit);

                    Button buttonSave = new Button()
                    {
                        Name = "Save", Margin = new Thickness(3, 0, 3, 0), Content = "Save", MinWidth = 100, Visibility = Visibility.Collapsed
                    };
                    buttonSave.Click += ButtonSave_Click;
                    LineProperty.Children.Add(buttonSave);

                    Button buttonСancel = new Button()
                    {
                        Name = "Сancel", Margin = new Thickness(3, 0, 3, 0), Content = "Сancel", MinWidth = 100, Visibility = Visibility.Collapsed
                    };
                    buttonСancel.Click += buttonСancel_Click;
                    LineProperty.Children.Add(buttonСancel);
                }
                if (property.PropertyType == typeof(IMyEntity))
                {
                    if (property.GetValue(myEntity) != null)
                    {
                        Button buttonEditEntity = new Button()
                        {
                            Name = $"{property.Name}", Margin = new Thickness(3, 0, 3, 0), Content = "Edit Entity", MinWidth = 100
                        };
                        buttonEditEntity.Click += ButtonEditEntity_Click;
                        LineProperty.Children.Add(buttonEditEntity);
                    }
                }

                MainPanel.Children.Add(LineProperty);


                Binding binding = new Binding();

                // binding.ElementName = "ParametMy"; // элемент-источник
                binding.Path = new PropertyPath("Paramet." + property.Name); // свойство элемента-источника
                textBox.SetBinding(TextBox.TextProperty, binding);           // установка привязки для элемента-приемника

                /* if (property.CanWrite)
                 * {
                 *   binding.Mode = BindingMode.TwoWay;
                 * }*/

                /*  Binding binding2 = new Binding();
                 *
                 * // binding2.ElementName = property.Name; // элемент-источник
                 * binding2.Path = new PropertyPath("ParametMy." + property.Name); // свойство элемента-источника
                 * textBox2.SetBinding(TextBox.TextProperty, binding2); // установка привязки для элемента-приемника*/
                /*  if (property.CanWrite)
                 * {
                 *    binding2.Mode = BindingMode.TwoWay;
                 * }*/
            }
        }
Пример #57
0
    public static void Set(IMyEntity entity, string prop, object value)
    {
        var value_str = value.ToString();

        SetKey(entity.EntityId, prop, value_str);
    }
Пример #58
0
 public static Destination FromWorld(IMyEntity entity, Vector3D worldPostion)
 {
     return(new Destination(entity, worldPostion - entity.GetCentre()));
 }
Пример #59
0
        private void CheckPath()
        {
            Vector3? pointOfObstruction = null;
            Vector3D WayDest            = Destination;
            Vector3D NavBlockPosition   = NavigationBlock.GetPosition();

            DistanceToDest = (float)(Destination - NavBlockPosition).Length();

            IMyEntity ObstructingEntity = null;

            //if (CNS.landingState == NavSettings.LANDING.OFF
            //	&& (!FlyTheLine || Waypoint == null)) // if flying a line and has a waypoint, do not reroute to destination
            if (SpecialFyingInstructions == NavSettings.SpecialFlying.None || Waypoint == null)
            {
                myLogger.debugLog("testing path to destination", "CheckPath()");
                ObstructingEntity = myPathChecker.TestPath(Destination, NavigationBlock, IgnoreAsteroids, out pointOfObstruction, DestGrid);
                if (ObstructingEntity == null)
                {
                    if (Waypoint == null)
                    {
                        myLogger.debugLog("Path to destination is clear", "CheckPath()", Logger.severity.DEBUG);
                        SetOutput(new PathfinderOutput(myPathChecker, PathfinderOutput.Result.Path_Clear));
                    }
                    else
                    {
                        myLogger.debugLog("Re-routing to destination, path is now clear", "CheckPath()", Logger.severity.DEBUG);
                        SetOutput(new PathfinderOutput(myPathChecker, PathfinderOutput.Result.Alternate_Path, null, Destination));
                    }
                    return;
                }
                CheckInterrupt();
                myLogger.debugLog("Path to destination is obstructed by " + ObstructingEntity.getBestName(), "CheckPath()", Logger.severity.DEBUG);
            }

            if (Waypoint != null)
            {
                WayDest = (Vector3)Waypoint;
                myLogger.debugLog("testing path to waypoint", "CheckPath()");
                ObstructingEntity = myPathChecker.TestPath((Vector3D)Waypoint, NavigationBlock, IgnoreAsteroids, out pointOfObstruction, DestGrid);
                if (ObstructingEntity == null)
                {
                    myLogger.debugLog("Path to waypoint is clear", "CheckPath()", Logger.severity.DEBUG);
                    SetOutput(new PathfinderOutput(myPathChecker, PathfinderOutput.Result.Path_Clear));
                    return;
                }
            }

            if (ObstructingEntity == null)
            {
                myLogger.debugLog("Neither Destination nor Waypoint were tested", "CheckPath()", Logger.severity.DEBUG);
                return;
            }

            CheckInterrupt();
            if (SpecialFyingInstructions != NavSettings.SpecialFlying.None)
            {
                //Vector3 direction = WayDest - NavBlockPosition;
                if (CanMoveInDirection(NavBlockPosition, WayDest - NavBlockPosition, "forward"))
                {
                    return;
                }
                //if (SpecialFyingInstructions == NavSettings.SpecialFlying.Line_Any && CanMoveInDirection(NavBlockPosition, NavBlockPosition - WayDest, "backward", false))
                //{
                //	myLogger.debugLog("Changing special instructions to Line_SidelForward", "CheckPath()");
                //	CNS.SpecialFlyingInstructions = NavSettings.SpecialFlying.Line_SidelForward;
                //	return;
                //}

                myLogger.debugLog("NoAlternateRoute, Obstruction = " + ObstructingEntity.getBestName(), "CheckPath()", Logger.severity.DEBUG);
                SetOutput(new PathfinderOutput(myPathChecker, PathfinderOutput.Result.No_Way_Forward, ObstructingEntity));
                return;
            }

            SetOutput(new PathfinderOutput(myPathChecker, PathfinderOutput.Result.Searching_Alt, ObstructingEntity));
            myLogger.debugLog("Path to Way/Dest is obstructed by " + ObstructingEntity.getBestName() + " at " + pointOfObstruction, "CheckPath()", Logger.severity.TRACE);

            Vector3 lineToWayDest = WayDest - CubeGrid.GetCentre();
            Vector3 newPath_v1, newPath_v2;

            lineToWayDest.CalculatePerpendicularVector(out newPath_v1);
            newPath_v2 = lineToWayDest.Cross(newPath_v1);
            newPath_v1 = Vector3.Normalize(newPath_v1);
            newPath_v2 = Vector3.Normalize(newPath_v2);
            Vector3[] NewPathVectors = { newPath_v1, newPath_v2, Vector3.Negate(newPath_v1), Vector3.Negate(newPath_v2) };

            for (int newPathDistance = 8; newPathDistance < 10000; newPathDistance *= 2)
            {
                myLogger.debugLog("newPathDistance = " + newPathDistance, "CheckPath()", Logger.severity.TRACE);

                // check far enough & sort alternate paths
                SortedDictionary <float, Vector3> Alternate_Path = new SortedDictionary <float, Vector3>();
                foreach (Vector3 PathVector in NewPathVectors)
                {
                    pointOfObstruction.throwIfNull_variable("pointOfObstruction");
                    Vector3 Alternate = (Vector3)pointOfObstruction + newPathDistance * PathVector;
                    myLogger.debugLog("Alternate = " + Alternate, "CheckPath()");
                    CNS.throwIfNull_variable("CNS");
                    if (!CNS.waypointFarEnough(Alternate))
                    {
                        myLogger.debugLog("waypoint is too close, throwing out: " + Alternate, "CheckPath()");
                        continue;
                    }
                    float distanceFromDest = Vector3.Distance(Destination, Alternate);
                    Alternate_Path.throwIfNull_variable("Alternate_Path");
                    while (Alternate_Path.ContainsKey(distanceFromDest))
                    {
                        distanceFromDest = distanceFromDest.IncrementSignificand();
                    }
                    Alternate_Path.Add(distanceFromDest, Alternate);

                    myLogger.debugLog("Added alt path: " + Alternate + " with distance of " + distanceFromDest, "CheckPath()");
                }

                foreach (Vector3 AlternatePoint in Alternate_Path.Values)
                {
                    if (TestAltPath(AlternatePoint))
                    {
                        return;
                    }
                }
            }

            // before going to No Way Forward, check if we can move around
            // try moving forward
            Vector3D GridCentre = CubeGrid.GetCentre();
            Vector3  Forward    = NavigationBlock.WorldMatrix.Forward;

            if (CanMoveInDirection(GridCentre, Forward, "forward"))
            {
                return;
            }
            // try moving backward
            Vector3 Backward = NavigationBlock.WorldMatrix.Backward;

            if (CanMoveInDirection(GridCentre, Backward, "backward"))
            {
                return;
            }

            SetOutput(new PathfinderOutput(myPathChecker, PathfinderOutput.Result.No_Way_Forward, ObstructingEntity));
            myLogger.debugLog("No Way Forward: " + ObstructingEntity.getBestName(), "CheckPath()", Logger.severity.INFO);
        }
        public override bool HandleCommand(ulong userId, string[] words)
        {
            if (!PluginSettings.Instance.WaypointsEnabled)
            {
                return(false);
            }

            if (words.Length != 6 && words.Length != 7 && words.Length != 1)
            {
                Communication.SendPrivateInformation(userId, GetHelp());
                return(true);
            }

            string     playerName = PlayerMap.Instance.GetPlayerNameFromSteamId(userId);
            long       playerId   = PlayerMap.Instance.GetFastPlayerIdFromSteamId(userId);
            IMyFaction faction    = MyAPIGateway.Session.Factions.TryGetPlayerFaction(playerId);

            if (faction == null)
            {
                Communication.SendPrivateInformation(userId, string.Format("Unable to find your faction information.  You must be in a faction to use this."));
                return(true);
            }

            List <WaypointItem> items = Waypoints.Instance.Get((ulong)faction.FactionId);

            if (PluginSettings.Instance.WaypointsMaxPerFaction > 0 && items.Count >= PluginSettings.Instance.WaypointsMaxPerFaction)
            {
                Communication.SendPrivateInformation(userId, string.Format("Waypoint limit has been reached.  You may only have {0} faction waypoints at a time on this server.  Please remove some waypoints in order to add new ones.", PluginSettings.Instance.WaypointsMaxPerPlayer));
                return(true);
            }

            if (words.Length == 1)
            {
                IMyEntity playerEntity = Player.FindControlledEntity(playerId);
                if (playerEntity == null)
                {
                    Communication.SendPrivateInformation(userId, string.Format("Can't find your position"));
                    return(true);
                }

                Vector3D pos  = playerEntity.GetPosition();
                string   name = words[0];

                foreach (ulong steamId in PlayerManager.Instance.ConnectedPlayers)
                {
                    if (Player.CheckPlayerSameFaction(userId, steamId))
                    {
                        Communication.SendClientMessage(steamId, string.Format("/waypoint add '{0}' '{0}' Neutral {1} {2} {3}", name, Math.Floor(pos.X), Math.Floor(pos.Y), Math.Floor(pos.Z)));
                    }
                }

                WaypointItem item = new WaypointItem
                {
                    SteamId      = (ulong)faction.FactionId,
                    Name         = name,
                    Text         = name,
                    Position     = pos,
                    WaypointType = WaypointTypes.Neutral,
                    Leader       = faction.IsLeader(playerId)
                };
                Waypoints.Instance.Add(item);

                Communication.SendFactionClientMessage(userId, string.Format("/message Server {2} has added the waypoint: '{0}' at {1} by '{2}'", item.Name, General.Vector3DToString(item.Position), playerName));
            }
            else
            {
                for (int r = 3; r < 6; r++)
                {
                    double test;
                    if (!double.TryParse(words[r], out test))
                    {
                        Communication.SendPrivateInformation(userId, string.Format("Invalid position information: {0} is invalid", words[r]));
                        return(true);
                    }
                }

                string add = string.Join(" ", words.Select(s => s.ToLowerInvariant()));

                foreach (ulong steamId in PlayerManager.Instance.ConnectedPlayers)
                {
                    if (Player.CheckPlayerSameFaction(userId, steamId))
                    {
                        Communication.SendClientMessage(steamId, string.Format("/waypoint add {0}", add));
                    }
                }

                string group = "";
                if (words.Length == 7)
                {
                    group = words[7];
                }

                WaypointItem item = new WaypointItem
                {
                    SteamId = (ulong)faction.FactionId,
                    Name    = words[0],
                    Text    = words[1]
                };
                WaypointTypes type;
                Enum.TryParse(words[2], true, out type);
                item.WaypointType = type;
                item.Position     = new Vector3D(double.Parse(words[3]), double.Parse(words[4]), double.Parse(words[5]));
                item.Group        = group;
                item.Leader       = faction.IsLeader(playerId);
                Waypoints.Instance.Add(item);

                Communication.SendFactionClientMessage(userId, string.Format("/message Server {2} has added the waypoint: '{0}' at {1} by '{2}'", item.Name, General.Vector3DToString(item.Position), playerName));
            }
            return(true);
        }