public override void Init(MyObjectBuilder_EntityBase objectBuilder)
        {
            base.Init(objectBuilder);
            this.objectBuilder = objectBuilder;

            Entity.NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME | MyEntityUpdateEnum.EACH_FRAME | MyEntityUpdateEnum.EACH_100TH_FRAME;

            functionalBlock = Entity as Sandbox.ModAPI.IMyFunctionalBlock;
            cubeBlock       = Entity as IMyCubeBlock;
            terminalBlock   = Entity as Sandbox.ModAPI.IMyTerminalBlock;

            subtypeName = functionalBlock.BlockDefinition.SubtypeName;

            getAttractorWeaponInfo(subtypeName);
            initCharges();

            cubeBlock.AddUpgradeValue("PowerEfficiency", 1.0f);
            cubeBlock.OnUpgradeValuesChanged += onUpgradeValuesChanged;

            terminalBlock.AppendingCustomInfo += appendCustomInfo;

            IMyCubeBlock cube = Entity as IMyCubeBlock;

            lastShootTime = ((MyObjectBuilder_LargeGatlingTurret)cube.GetObjectBuilderCubeBlock()).GunBase.LastShootTime;
        }
示例#2
0
文件: MainLock.cs 项目: zrisher/ARMS
        public static MyObjectBuilder_CubeBlock GetObjectBuilder_Safe(this IMyCubeBlock block)
        {
            MyObjectBuilder_CubeBlock result = null;

            UsingShared(() => result = block.GetObjectBuilderCubeBlock());
            return(result);
        }
示例#3
0
        private static long BeaconValue(IMyCubeBlock block)         //Returns the points value of specified beacon.
        {
            MyObjectBuilder_CubeBlock cube = block.GetObjectBuilderCubeBlock();

            if (cube is MyObjectBuilder_Beacon)
            {
                MyObjectBuilder_Beacon beaconval = (MyObjectBuilder_Beacon)cube;
                float radius = beaconval.BroadcastRadius;
                return(Convert.ToInt64(Math.Floor(Convert.ToDouble(radius / 5000))));
            }
            return(0);
        }
 void GetTurretMaxRange()
 {
     //init turret power draw function constants
     if (Entity is IMyLargeTurretBase)
     {
         turret = Entity as IMyLargeTurretBase;
         var def = cube.SlimBlock.BlockDefinition as MyLargeTurretBaseDefinition;
         _turretMaxRange = def.MaxRangeMeters;
         var ob = (MyObjectBuilder_TurretBase)cube.GetObjectBuilderCubeBlock();
         ob.Range = _turretMaxRange;
         GetTurretPowerDrawConstants(_idlePowerDrawBase, _idlePowerDrawMax, _turretMaxRange);
     }
 }
示例#5
0
        void GetTurretMaxRange()
        {
            //init turret power draw function constants
            if (Entity is IMyLargeTurretBase)
            {
                turret = Entity as IMyLargeTurretBase;
                var def = cube.SlimBlock.BlockDefinition as MyLargeTurretBaseDefinition;
                _turretMaxRange = def.MaxRangeMeters;
                var ob = (MyObjectBuilder_TurretBase)cube.GetObjectBuilderCubeBlock();
                ob.Range = _turretMaxRange;
                GetTurretPowerDrawConstants(_idlePowerDrawBase, _idlePowerDrawMax, _turretMaxRange);

                //_turretMaxRange = turret.GetMaximum<float>("Range");
                //this.m_shootingRange.SetLocalValue(Math.Min(this.BlockDefinition.MaxRangeMeters, Math.Max(0f, myObjectBuilder_TurretBase.Range)));
            }
        }
示例#6
0
        private static Boolean TestBeacon(IMyCubeBlock block)
        {
            MyObjectBuilder_CubeBlock cube = block.GetObjectBuilderCubeBlock();

            if (cube is MyObjectBuilder_Beacon)
            {
                MyObjectBuilder_Beacon beacontest = (MyObjectBuilder_Beacon)cube;
                bool  enabled = block.IsWorking;
                float radius  = beacontest.BroadcastRadius;
                if (radius > 4999 && enabled)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            return(false);
        }
示例#7
0
        public override bool HandleCommand(ulong userId, string[] words)
        {
            if (!PluginSettings.Instance.DockingEnabled)
            {
                return(false);
            }

            if (words.Length < 1)
            {
                Communication.SendPrivateInformation(userId, GetHelp());
                return(true);
            }

            if (m_undocking)
            {
                Communication.SendPrivateInformation(userId, string.Format("Server is busy, try again"));
                return(true);
            }

            m_undocking = true;
            try
            {
                String pylonName = String.Join(" ", words);
                if (PlayerMap.Instance.GetPlayerIdsFromSteamId(userId).Count < 1)
                {
                    Communication.SendPrivateInformation(userId, string.Format("Unable to find player Id: {0}", userId));
                    return(true);
                }

                long playerId = PlayerMap.Instance.GetPlayerIdsFromSteamId(userId).First( );

                Dictionary <String, List <IMyCubeBlock> > testList;
                List <IMyCubeBlock> beaconList;
                DockingZone.FindByName(pylonName, out testList, out beaconList, playerId);

                if (beaconList.Count == 4)
                {
                    foreach (IMyCubeBlock entity in beaconList)
                    {
                        if (!Entity.CheckOwnership(entity, playerId))
                        {
                            Communication.SendPrivateInformation(userId, string.Format("You do not have permission to use '{0}'.  You must either own all the beacons or they must be shared with faction.", pylonName));
                            return(true);
                        }
                    }

                    IMyCubeBlock e      = beaconList.First( );
                    IMyCubeGrid  parent = (IMyCubeGrid)e.Parent;

                    long[]             beaconListIds = beaconList.Select(p => p.EntityId).ToArray( );
                    long               ownerId       = beaconList.First( ).OwnerId;
                    List <DockingItem> dockingItems  = Docking.Instance.Find(d => d.PlayerId == ownerId && d.TargetEntityId == parent.EntityId && d.DockingBeaconIds.Intersect(beaconListIds).Count( ) == 4);
                    if (dockingItems.Count < 1)
                    {
                        Communication.SendPrivateInformation(userId, string.Format("You have no ships docked in docking zone '{0}'.", pylonName));
                        return(true);
                    }

                    DockingItem dockingItem = dockingItems.First( );

                    // Figure out center of docking area, and other distance information
                    double   maxDistance = 99;
                    Vector3D vPos        = new Vector3D(0, 0, 0);
                    foreach (IMyCubeBlock b in beaconList)
                    {
                        Vector3D beaconPos = Entity.GetBlockEntityPosition(b);
                        vPos += beaconPos;
                    }

                    vPos = vPos / 4;
                    foreach (IMyCubeBlock b in beaconList)
                    {
                        Vector3D beaconPos = Entity.GetBlockEntityPosition(b);
                        maxDistance = Math.Min(maxDistance, Vector3D.Distance(vPos, beaconPos));
                    }

                    List <IMySlimBlock> blocks = new List <IMySlimBlock>( );
                    parent.GetBlocks(blocks);
                    foreach (IMySlimBlock slim_cbe in blocks)
                    {
                        if (slim_cbe is IMyCubeBlock)
                        {
                            IMyCubeBlock cbe = slim_cbe.FatBlock;
                            if (cbe.GetObjectBuilderCubeBlock( ) is MyObjectBuilder_Cockpit)
                            {
                                MyObjectBuilder_Cockpit c = (MyObjectBuilder_Cockpit)cbe.GetObjectBuilderCubeBlock( );
                                if (c.Pilot != null)
                                {
                                    Communication.SendPrivateInformation(userId,
                                                                         string.Format(
                                                                             "Carrier ship has a pilot.  The carrier should be unpiloted and fully stopped before undocking.  (Sometimes this can lag a bit.  Wait 10 seconds and try again)",
                                                                             pylonName));
                                    return(true);
                                }
                            }
                        }
                    }

                    String dockedShipFileName = Essentials.PluginPath + String.Format("\\Docking\\docked_{0}_{1}_{2}.sbc", ownerId, dockingItem.TargetEntityId, dockingItem.DockedEntityId);

                    // Load Entity From File and add to game
                    FileInfo fileInfo = new FileInfo(dockedShipFileName);
                    //CubeGridEntity cubeGrid = new CubeGridEntity(fileInfo);

                    MyObjectBuilder_CubeGrid cubeGrid = BaseObjectManager.ReadSpaceEngineersFile <MyObjectBuilder_CubeGrid, MyObjectBuilder_CubeGridSerializer>(dockedShipFileName);

                    // Rotate our ship relative to our saved rotation and the new carrier rotation
                    cubeGrid.PositionAndOrientation =
                        new MyPositionAndOrientation(Matrix.CreateFromQuaternion(Quaternion.CreateFromRotationMatrix(parent.Physics.GetWorldMatrix( ).GetOrientation( )) * dockingItem.SaveQuat).GetOrientation( ));
                    // Move our ship relative to the new carrier position and orientation
                    Quaternion newQuat    = Quaternion.CreateFromRotationMatrix(parent.Physics.GetWorldMatrix( ).GetOrientation( ));
                    Vector3D   rotatedPos = Vector3D.Transform(dockingItem.SavePos, newQuat);
                    //cubeGrid.Position = rotatedPos + parent.GetPosition();
                    cubeGrid.PositionAndOrientation = new MyPositionAndOrientation(rotatedPos + parent.GetPosition( ), cubeGrid.PositionAndOrientation.Value.Forward, cubeGrid.PositionAndOrientation.Value.Up);

                    // Add object to world
                    cubeGrid.EntityId        = BaseEntity.GenerateEntityId( );
                    cubeGrid.LinearVelocity  = Vector3.Zero;
                    cubeGrid.AngularVelocity = Vector3.Zero;

                    bool undock = false;
                    Wrapper.GameAction(() =>
                    {
                        try
                        {
                            MyAPIGateway.Entities.CreateFromObjectBuilderAndAdd(cubeGrid);
                            List <MyObjectBuilder_EntityBase> addList = new List <MyObjectBuilder_EntityBase>( );
                            addList.Add(cubeGrid);
                            MyAPIGateway.Multiplayer.SendEntitiesCreated(addList);
                            undock = true;
                        }
                        catch (Exception Ex)
                        {
                            Log.Info(string.Format("Error undocking ship: {0}", Ex.ToString( )));
                            Communication.SendPrivateInformation(userId, string.Format("Unable to undock ship due to error."));
                        }
                    });

                    if (!undock)
                    {
                        return(true);
                    }

                    //SectorObjectManager.Instance.AddEntity(cubeGrid);

                    // Remove the docking file
                    File.Delete(dockedShipFileName);
                    Docking.Instance.Remove(dockingItem);

                    Communication.SendPrivateInformation(userId, string.Format("The ship '{0}' has been undocked from docking zone '{1}'", dockingItem.DockedName, pylonName));

                    /*
                     * // Queue for cooldown
                     * DockingCooldownItem cItem = new DockingCooldownItem();
                     * cItem.Name = pylonName;
                     * cItem.startTime = DateTime.Now;
                     *
                     * lock (m_cooldownList)
                     *      m_cooldownList.Add(cItem);
                     *
                     * IMyEntity gridEntity = MyAPIGateway.Entities.GetEntityById(dockingItem.DockedEntityId);
                     * IMyCubeGrid cubeGrid = (IMyCubeGrid)gridEntity;
                     *
                     * Quaternion q = Quaternion.CreateFromRotationMatrix(parent.WorldMatrix.GetOrientation()) * dockingItem.SaveQuat;
                     * Quaternion newQuat = Quaternion.CreateFromRotationMatrix(parent.WorldMatrix.GetOrientation());
                     * Vector3 parentPosition = parent.GetPosition();
                     * Vector3 rotatedPos = Vector3.Transform(dockingItem.savePos, newQuat);
                     * Vector3 position = rotatedPos + parentPosition;
                     * Matrix positionMatrix = Matrix.CreateFromQuaternion(q);
                     *
                     * cubeGrid.ChangeGridOwnership(playerId, MyOwnershipShareModeEnum.None);
                     * gridEntity.SetPosition(dockingItem.savePos);
                     *
                     * gridEntity.WorldMatrix = positionMatrix;
                     * gridEntity.SetPosition(position);
                     *
                     * // We need to update again, as this doesn't seem to sync properly?  I set world matrix, and setposition, and it doesn't go where it should, and I
                     * // have to bump into it for it to show up, it's mega weird.
                     *
                     * if (PluginDocking.Settings.DockingItems == null)
                     *      throw new Exception("DockingItems is null");
                     *
                     * // Remove from docked items
                     * PluginDocking.Settings.DockingItems.Remove(dockingItem);
                     *
                     * // Notify user
                     * Communication.SendPrivateInformation(userId, string.Format("The ship '{0}' has been undocked from docking zone '{1}'", gridEntity.DisplayName, pylonName));
                     */
                    // Queue for cooldown

                    /*
                     * DockingCooldownItem cItem = new DockingCooldownItem();
                     * cItem.name = pylonName;
                     * cItem.startTime = DateTime.Now;
                     * PluginDocking.CooldownList.Add(cItem);
                     */
                }
                else if (beaconList.Count > 4)                   // Too many beacons, must be 4
                {
                    Communication.SendPrivateInformation(userId,
                                                         string.Format("Too many beacons with the name or another zone with the name '{0}'.  Place only 4 beacons to create a zone or try a different zone name.",
                                                                       pylonName));
                }
                else                 // Can't find docking zone
                {
                    Communication.SendPrivateInformation(userId,
                                                         string.Format("Can not locate docking zone '{0}'.  There must be 4 beacons with the name '{0}' to create a docking zone.  Beacons must be fully built!",
                                                                       pylonName));
                }
            }
            catch (NullReferenceException ex)
            {
                Log.Error(ex);
            }
            finally
            {
                m_undocking = false;
            }

            return(true);
        }
        public override void UpdateBeforeSimulation()
        {
            int chargesInInventory = (int)m_inventory.GetItemAmount(chargeDefinitionIds [damageUpgrades]);

            IMyCubeBlock cube = Entity as IMyCubeBlock;

            long currentShootTime = ((MyObjectBuilder_InteriorTurret)cube.GetObjectBuilderCubeBlock()).GunBase.LastShootTime;


            if (currentHeat > 0f)
            {
                if ((ticks - lastShootTimeTicks) > beamWeaponInfo.heatDissipationDelay)
                {
                    currentHeat -= beamWeaponInfo.heatDissipationPerTick;

                    if (currentHeat <= 0f)
                    {
                        currentHeat = 0f;

                        overheated = false;
                    }
                }
            }

            //MyAPIGateway.Utilities.ShowNotification("TIME: " + currentShootTime + " :: " + lastShootTime, 17, MyFontEnum.Red);


            if (currentShootTime != lastShootTime)
            {
                // test

                hitBool = false;

                MyEntitySubpart subpart1 = cubeBlock.GetSubpart("InteriorTurretBase1");
                MyEntitySubpart subpart2 = subpart1.GetSubpart("InteriorTurretBase2");;
                //MyAPIGateway.Utilities.ShowNotification("Dif: " + (currentShootTime - lastShootTime), 17, MyFontEnum.Blue);

                from = subpart2.WorldMatrix.Translation + subpart2.WorldMatrix.Forward * 1.25d;
                to   = subpart2.WorldMatrix.Translation + subpart2.WorldMatrix.Forward * 3000d;

                LineD testRay = new LineD(from, to);

                List <MyLineSegmentOverlapResult <MyEntity> > result = new List <MyLineSegmentOverlapResult <MyEntity> >();

                MyGamePruningStructure.GetAllEntitiesInRay(ref testRay, result);


                foreach (var resultItem in result)
                {
                    IMyCubeGrid grid = resultItem.Element as IMyCubeGrid;

                    IMyDestroyableObject destroyableEntity = resultItem.Element as IMyDestroyableObject;

                    if (grid != null)
                    {
                        IMySlimBlock slimblock;

                        double hitd;

                        Vector3D?resultVec = grid.GetLineIntersectionExactAll(ref testRay, out hitd, out slimblock);

                        if (resultVec != null)
                        {
                            hitBool = true;

                            toTarget = from + subpart2.WorldMatrix.Forward * hitd;

                            if (!MyAPIGateway.Session.CreativeMode)
                            {
                                slimblock.DoDamage(beamWeaponInfo.damage * (currentHeat / beamWeaponInfo.maxHeat + 0.2f), MyStringHash.GetOrCompute("Laser"), false, default(MyHitInfo), cubeBlock.EntityId);
                            }
                            else
                            {
                                slimblock.DoDamage(beamWeaponInfo.damage * 1.2f, MyStringHash.GetOrCompute("Laser"), false, default(MyHitInfo), cubeBlock.EntityId);
                            }
                            //MyAPIGateway.Utilities.ShowNotification("" + s.BlockDefinition.Id.SubtypeId + " ::: " + resultItem.Distance, 17);
                        }
                    }
                    if (destroyableEntity != null)
                    {
                        IMyEntity ent  = (IMyEntity)destroyableEntity;
                        double    hitd = (from - ent.WorldMatrix.Translation).Length();

                        toTarget = from + subpart2.WorldMatrix.Forward * hitd;

                        hitBool = true;

                        if (!MyAPIGateway.Session.CreativeMode)
                        {
                            destroyableEntity.DoDamage(beamWeaponInfo.damage * (currentHeat / beamWeaponInfo.maxHeat + 0.2f), MyStringHash.GetOrCompute("Laser"), false, default(MyHitInfo), cubeBlock.EntityId);
                        }
                        else
                        {
                            destroyableEntity.DoDamage(beamWeaponInfo.damage * 1.2f, MyStringHash.GetOrCompute("Laser"), false, default(MyHitInfo), cubeBlock.EntityId);
                        }
                    }
                }


                // test

                lastShootTime      = currentShootTime;
                lastShootTimeTicks = ticks;

                currentHeat += beamWeaponInfo.heatPerTick;

                if (currentHeat > beamWeaponInfo.maxHeat)
                {
                    currentHeat = beamWeaponInfo.maxHeat;

                    overheated = true;
                }
            }

            if (ticks - lastShootTimeTicks < 3)
            {
                var beamcolor     = Color.DodgerBlue;
                var beamcolor_aux = Color.LightSkyBlue;
                var maincolor     = new Vector4(beamcolor.X / 30, beamcolor.Y / 30, beamcolor.Z / 30, 1f);
                var auxcolor      = new Vector4(beamcolor_aux.X / 30, beamcolor_aux.Y / 30, beamcolor_aux.Z / 30, 1f);
                var material      = MyStringId.GetOrCompute("WeaponLaser");
                if (hitBool == false)
                {
                    if (!MyAPIGateway.Utilities.IsDedicated)
                    {
                        if (!MyAPIGateway.Session.CreativeMode)
                        {
                            VRage.Game.MySimpleObjectDraw.DrawLine(from, to, material, ref auxcolor, 0.30f);
                            VRage.Game.MySimpleObjectDraw.DrawLine(from, to, material, ref maincolor, 1.0f);
                        }
                        else
                        {
                            VRage.Game.MySimpleObjectDraw.DrawLine(from, to, material, ref auxcolor, 0.30f * 1.2f);
                            VRage.Game.MySimpleObjectDraw.DrawLine(from, to, material, ref maincolor, 1.0f * 1.2f);
                        }
                    }
                }
                else
                {
                    if (!MyAPIGateway.Utilities.IsDedicated)
                    {
                        if (!MyAPIGateway.Session.CreativeMode)
                        {
                            VRage.Game.MySimpleObjectDraw.DrawLine(from, toTarget, material, ref auxcolor, 0.30f);
                            VRage.Game.MySimpleObjectDraw.DrawLine(from, toTarget, material, ref maincolor, 1.0f);
                        }
                        else
                        {
                            VRage.Game.MySimpleObjectDraw.DrawLine(from, toTarget, material, ref auxcolor, 0.30f * 1.2f);
                            VRage.Game.MySimpleObjectDraw.DrawLine(from, toTarget, material, ref maincolor, 1.0f * 1.2f);
                        }
                    }
                }
            }

            if (chargesInInventory < beamWeaponInfo.keepAtCharge)
            {
                if (resourceSink.RequiredInputByType(electricityDefinition) != (beamWeaponInfo.powerUsage / efficiencyUpgrades))
                {
                    resourceSink.SetRequiredInputByType(electricityDefinition, (beamWeaponInfo.powerUsage / efficiencyUpgrades));

                    setPowerConsumption = (beamWeaponInfo.powerUsage / efficiencyUpgrades);
                    powerConsumption    = (beamWeaponInfo.powerUsage / efficiencyUpgrades);
                }
                else
                {
                    if (!functionalBlock.Enabled)
                    {
                        powerConsumption = 0.0001f;
                    }
                }

                if (resourceSink.CurrentInputByType(electricityDefinition) == (beamWeaponInfo.powerUsage / efficiencyUpgrades))
                {
                    if (!overheated)
                    {
                        m_inventory.AddItems((MyFixedPoint)(beamWeaponInfo.keepAtCharge - chargesInInventory), chargeObjectBuilders [damageUpgrades]);
                    }
                }
            }
            else if (chargesInInventory > beamWeaponInfo.keepAtCharge)
            {
                m_inventory.RemoveItemsOfType((MyFixedPoint)(chargesInInventory - beamWeaponInfo.keepAtCharge), chargeObjectBuilders [damageUpgrades]);
            }
            else
            {
                if (setPowerConsumption != 0.0001f)
                {
                    resourceSink.SetRequiredInputByType(electricityDefinition, 0.0001f);

                    setPowerConsumption = 0.0001f;
                    powerConsumption    = 0.0001f;
                }
            }

            terminalBlock.RefreshCustomInfo();

            ticks++;
        }
示例#9
0
        private static void CheckGridConnection(IMyEntity block)
        {
            IMyCubeBlock cubeBlock = (IMyCubeBlock)block;

            if (cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_PistonBase))
            {
                MyObjectBuilder_PistonBase pistonBase = (MyObjectBuilder_PistonBase)cubeBlock.GetObjectBuilderCubeBlock();
                IMyEntity connectedEntity             = null;
                if (pistonBase.TopBlockId.HasValue && MyAPIGateway.Entities.TryGetEntityById(pistonBase.TopBlockId.Value, out connectedEntity))
                {
                    IMyEntity parent = connectedEntity.Parent;

                    if (parent is IMyCubeGrid)
                    {
                        if (!m_conveyorConnected.ContainsKey(parent.EntityId))
                        {
                            m_conveyorConnected.Add(parent.EntityId, new long[] { pistonBase.TopBlockId.Value, pistonBase.EntityId });
                        }
                    }
                }
            }
            else if (cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_ExtendedPistonBase))
            {
                MyObjectBuilder_PistonBase pistonBase = (MyObjectBuilder_PistonBase)cubeBlock.GetObjectBuilderCubeBlock();
                IMyEntity connectedEntity             = null;
                if (pistonBase.TopBlockId.HasValue && MyAPIGateway.Entities.TryGetEntityById(pistonBase.TopBlockId.Value, out connectedEntity))
                {
                    IMyEntity parent = connectedEntity.Parent;

                    if (parent is IMyCubeGrid)
                    {
                        if (!m_conveyorConnected.ContainsKey(parent.EntityId))
                        {
                            m_conveyorConnected.Add(parent.EntityId, new long[] { pistonBase.TopBlockId.Value, pistonBase.EntityId });
                        }
                    }
                }
            }
            else if (cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_ShipConnector))
            {
                MyObjectBuilder_ShipConnector connector = (MyObjectBuilder_ShipConnector)cubeBlock.GetObjectBuilderCubeBlock();
                IMyEntity connectedEntity = null;
                if (connector.Connected && MyAPIGateway.Entities.TryGetEntityById(connector.ConnectedEntityId, out connectedEntity))
                {
                    if (!m_conveyorConnected.ContainsKey(connectedEntity.Parent.EntityId))
                    {
                        //IMyCubeGrid grid = MyAPIGateway.Entities.GetEntityById(connectedEntity.Parent.EntityId);
                        m_conveyorConnected.Add(connectedEntity.Parent.EntityId, new long[] { connectedEntity.EntityId, connector.EntityId });
                    }
                }
            }
            else if (cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MotorAdvancedStator))
            {
                MyObjectBuilder_MotorAdvancedStator stator = (MyObjectBuilder_MotorAdvancedStator)cubeBlock.GetObjectBuilderCubeBlock();
                IMyEntity connectedEntity = null;
                if (stator.RotorEntityId.HasValue && MyAPIGateway.Entities.TryGetEntityById(stator.RotorEntityId.Value, out connectedEntity))
                {
                    IMyEntity parent = connectedEntity.Parent;

                    if (parent is IMyCubeGrid)
                    {
                        if (!m_conveyorConnected.ContainsKey(parent.EntityId))
                        {
                            m_conveyorConnected.Add(parent.EntityId, new long[] { stator.RotorEntityId.Value, stator.EntityId });
                        }
                    }
                }
            }
        }
示例#10
0
		private static long BeaconValue(IMyCubeBlock block) //Returns the points value of specified beacon.
		{
			MyObjectBuilder_CubeBlock cube = block.GetObjectBuilderCubeBlock();
			if (cube is MyObjectBuilder_Beacon)
			{
				MyObjectBuilder_Beacon beaconval = (MyObjectBuilder_Beacon)cube;
				float radius = beaconval.BroadcastRadius;
				return Convert.ToInt64(Math.Floor(Convert.ToDouble(radius / 5000)));
			}
			return 0;
		}
示例#11
0
		private static Boolean TestBeacon(IMyCubeBlock block)
		{
			MyObjectBuilder_CubeBlock cube = block.GetObjectBuilderCubeBlock();
			if (cube is MyObjectBuilder_Beacon)
			{
				MyObjectBuilder_Beacon beacontest = (MyObjectBuilder_Beacon)cube;
				bool enabled = block.IsWorking;
				float radius = beacontest.BroadcastRadius;
				if (radius > 4999 && enabled)
				{
					return true;
				}
				else
				{
					return false;
				}
			}
			return false;
		}
        // Utility
        public static List <SortDefinitionItem> CreateFromEntity(IMyEntity entity)
        {
            List <SortDefinitionItem> result = new List <SortDefinitionItem>();

            try
            {
                if (!(entity is IMyCubeBlock))
                {
                    return(result);
                }

                IMyCubeBlock block = (IMyCubeBlock)entity;
                MyObjectBuilder_TerminalBlock terminal = (MyObjectBuilder_TerminalBlock)block.GetObjectBuilderCubeBlock();
                String customName = terminal.CustomName;
                if (customName == null || customName == "")
                {
                    return(result);
                }

                Regex regexObj     = new Regex(".*[[|(](.*)[]|)]", RegexOptions.Singleline);
                Match matchResults = regexObj.Match(customName);
                while (matchResults.Success)
                {
                    if (matchResults.Groups.Count < 2 || matchResults.Groups[1].Value == "")
                    {
                        matchResults = matchResults.NextMatch();
                        continue;
                    }

                    String componentList = matchResults.Groups[1].Value;
                    Regex  splitRegexObj = new Regex("\"(?:[^\"]|\"\")*\"|[^,]*", RegexOptions.Singleline);
                    Match  splitResults  = splitRegexObj.Match(componentList);
                    while (splitResults.Success)
                    {
                        if (splitResults.Value == "")
                        {
                            splitResults = splitResults.NextMatch();
                            continue;
                        }

                        String componentName = splitResults.Value.Replace(" ", "");
                        if (componentName != "")
                        {
                            TryParseSortItem(result, componentName, entity);
                        }

                        splitResults = splitResults.NextMatch();
                    }

                    matchResults = matchResults.NextMatch();
                }
            }
            catch (Exception ex)
            {
                Logging.Instance.WriteLine(String.Format("BuildSortListFromEntity(): {0}", ex.ToString()));
            }

            return(result);
        }
示例#13
0
        private static List <IMyCubeGrid> GetConnectedGridList(HashSet <IMyEntity> checkedGrids, List <IMySlimBlock> blocks)
        {
            List <IMyCubeGrid> connectedGrids = new List <IMyCubeGrid>();

            foreach (IMySlimBlock slimBlock in blocks)
            {
                try
                {
                    if (slimBlock.FatBlock != null && slimBlock.FatBlock is IMyCubeBlock)
                    {
                        IMyCubeBlock cubeBlock = (IMyCubeBlock)slimBlock.FatBlock;

                        // Check for Piston
                        if (cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_PistonBase))
                        {
                            MyObjectBuilder_PistonBase pistonBase = (MyObjectBuilder_PistonBase)cubeBlock.GetObjectBuilderCubeBlock();
                            IMyEntity entity = null;
                            if (MyAPIGateway.Entities.TryGetEntityById(pistonBase.TopBlockId, out entity))
                            {
                                IMyCubeGrid parent = (IMyCubeGrid)entity.Parent;
                                if (!checkedGrids.Contains(parent))
                                {
                                    connectedGrids.Add(parent);
                                }
                            }
                        }
                        else if (cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_ExtendedPistonBase))
                        {
                            MyObjectBuilder_PistonBase pistonBase = (MyObjectBuilder_PistonBase)cubeBlock.GetObjectBuilderCubeBlock();
                            IMyEntity entity = null;
                            if (MyAPIGateway.Entities.TryGetEntityById(pistonBase.TopBlockId, out entity))
                            {
                                IMyCubeGrid parent = (IMyCubeGrid)entity.Parent;
                                if (!checkedGrids.Contains(parent))
                                {
                                    connectedGrids.Add(parent);
                                }
                            }
                        }
                        // Connector
                        else if (cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_ShipConnector))
                        {
                            MyObjectBuilder_ShipConnector connector = (MyObjectBuilder_ShipConnector)cubeBlock.GetObjectBuilderCubeBlock();
                            IMyEntity entity = null;
                            if (MyAPIGateway.Entities.TryGetEntityById(connector.ConnectedEntityId, out entity))
                            //IMyEntity entity = MyAPIGateway.Entities.GetEntityById(connector.ConnectedEntityId);
                            //if(entity != null)
                            {
                                IMyCubeGrid parent = (IMyCubeGrid)entity.Parent;
                                if (!checkedGrids.Contains(parent))
                                {
                                    connectedGrids.Add(parent);
                                }
                            }
                        }
                        else if (cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MotorAdvancedStator))
                        {
                            MyObjectBuilder_MotorAdvancedStator stator = (MyObjectBuilder_MotorAdvancedStator)cubeBlock.GetObjectBuilderCubeBlock();
                            IMyEntity connectedEntity = null;
                            if (stator.RotorEntityId.HasValue && MyAPIGateway.Entities.TryGetEntityById(stator.RotorEntityId.Value, out connectedEntity))
                            {
                                IMyCubeGrid parent = (IMyCubeGrid)connectedEntity.Parent;
                                if (!checkedGrids.Contains(parent))
                                {
                                    connectedGrids.Add(parent);
                                }
                            }
                        }
                    }
                }
                catch
                {
                    continue;
                }
            }

            return(connectedGrids);
        }
示例#14
0
        private static bool CheckRevealBlockRules(IMyCubeGrid grid, List <IMyPlayer> players, out string reason)
        {
            reason = "";
            // This is actually faster, but doesn't include power checks

            // Live dangerously
            List <IMySlimBlock> blocks = new List <IMySlimBlock>();

            grid.GetBlocks(blocks, x => x.FatBlock != null);
            //CubeGrids.GetAllConnectedBlocks(m_processedGrids, grid, blocks, x => x.FatBlock != null);
            //bool found = false;
            //bool powered = false;
            foreach (IMySlimBlock block in blocks)
            {
                IMyCubeBlock cubeBlock = block.FatBlock;

                if (cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_Beacon))
                {
                    //MyObjectBuilder_Beacon beacon = (MyObjectBuilder_Beacon)cubeBlock.GetObjectBuilderCubeBlock();
                    Sandbox.ModAPI.Ingame.IMyBeacon beacon = (Sandbox.ModAPI.Ingame.IMyBeacon)cubeBlock;
                    if (!beacon.Enabled)
                    {
                        continue;
                    }

                    //Sandbox.ModAPI.Ingame.IMyFunctionalBlock functionalBlock = (Sandbox.ModAPI.Ingame.IMyFunctionalBlock)cubeBlock;
                    //if (!functionalBlock.Enabled)
                    //	continue;

                    //Console.WriteLine("Beacon: {0} {1} {2}", beacon.BroadcastRadius, terminalBlock.IsWorking, terminalBlock.IsFunctional);
                    //if (!terminalBlock.IsWorking)
                    //	continue;


                    foreach (IMyPlayer player in players)
                    {
                        double distance = 0d;
                        if (Entity.GetDistanceBetweenPointAndPlayer(grid.GetPosition(), player, out distance))
                        {
                            if (distance < beacon.Radius)
                            {
                                //found = true;
                                //break;
                                reason = string.Format("{0} distance to beacon broadcast: {1}", player.DisplayName, distance);
                                return(true);
                            }
                        }
                    }
                }

                if (cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_RadioAntenna))
                {
                    //MyObjectBuilder_RadioAntenna antenna = (MyObjectBuilder_RadioAntenna)cubeBlock.GetObjectBuilderCubeBlock();
                    Sandbox.ModAPI.Ingame.IMyRadioAntenna antenna = (Sandbox.ModAPI.Ingame.IMyRadioAntenna)cubeBlock;

                    if (!antenna.Enabled)
                    {
                        continue;
                    }

                    //Sandbox.ModAPI.Ingame.IMyFunctionalBlock functionalBlock = (Sandbox.ModAPI.Ingame.IMyFunctionalBlock)cubeBlock;
                    //if (!functionalBlock.Enabled)
                    //	continue;

                    foreach (IMyPlayer player in players)
                    {
                        double distance = 0d;
                        if (Entity.GetDistanceBetweenPointAndPlayer(grid.GetPosition(), player, out distance))
                        {
                            if (distance < antenna.Radius)
                            {
                                //found = true;
                                //break;
                                reason = string.Format("{0} distance to antenna broadcast: {1}", player.DisplayName, distance);
                                return(true);
                            }
                        }
                    }
                }

                if (cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MedicalRoom))
                {
                    //MyObjectBuilder_MedicalRoom medical = (MyObjectBuilder_MedicalRoom)cubeBlock.GetObjectBuilderCubeBlock();
                    Sandbox.ModAPI.Ingame.IMyMedicalRoom medical = (Sandbox.ModAPI.Ingame.IMyMedicalRoom)cubeBlock;
                    if (!medical.Enabled)
                    {
                        continue;
                    }

                    Sandbox.ModAPI.Ingame.IMyFunctionalBlock functionalBlock = (Sandbox.ModAPI.Ingame.IMyFunctionalBlock)cubeBlock;
                    if (!functionalBlock.IsFunctional)
                    {
                        continue;
                    }

                    //if (!functionalBlock.Enabled)
                    //	continue;

                    if (PluginSettings.Instance.DynamicConcealIncludeMedBays)
                    {
                        lock (m_online)
                        {
                            foreach (ulong connectedPlayer in m_online)
                            {
                                long playerId = PlayerMap.Instance.GetFastPlayerIdFromSteamId(connectedPlayer);
                                //if (medical.Owner == playerId || (medical.ShareMode == MyOwnershipShareModeEnum.Faction && Player.CheckPlayerSameFaction(medical.Owner, playerId)))
                                if (functionalBlock.OwnerId == playerId)
                                {
                                    reason = string.Format("Grid has medbay and player is logged in - playerid: {0}", playerId);
                                    return(true);
                                }

                                if (functionalBlock.GetUserRelationToOwner(playerId) == Sandbox.Common.MyRelationsBetweenPlayerAndBlock.FactionShare)
                                {
                                    reason = string.Format("Grid has medbay and player is factionshare - playerid: {0}", playerId);
                                    return(true);
                                }
                            }
                        }

                        /*
                         * foreach (ulong connectedPlayer in PlayerManager.Instance.ConnectedPlayers)
                         * {
                         *      long playerId = PlayerMap.Instance.GetFastPlayerIdFromSteamId(connectedPlayer);
                         *      //if (medical.Owner == playerId || (medical.ShareMode == MyOwnershipShareModeEnum.Faction && Player.CheckPlayerSameFaction(medical.Owner, playerId)))
                         *      //if (functionalBlock.OwnerId == playerId || (functionalBlock.GetUserRelationToOwner(playerId) == Sandbox.Common.MyRelationsBetweenPlayerAndBlock.FactionShare))
                         *      if(medical.HasPlayerAccess(playerId))
                         *      {
                         *              reason = string.Format("Grid has medbay and player is logged in - playerid: {0}", playerId);
                         *              return true;
                         *      }
                         * }
                         */
                    }
                    else
                    {
                        reason = string.Format("Grid has medbay and conceal can not include medbays");
                        return(true);
                    }
                }

                if (cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_ProductionBlock))
                {
                    MyObjectBuilder_ProductionBlock production = (MyObjectBuilder_ProductionBlock)cubeBlock.GetObjectBuilderCubeBlock();
                    if (!production.Enabled)
                    {
                        continue;
                    }

                    Sandbox.ModAPI.Ingame.IMyProductionBlock productionBlock = (Sandbox.ModAPI.Ingame.IMyProductionBlock)cubeBlock;
                    if (production.Queue.Length > 0)
                    {
                        reason = string.Format("Grid has production facility that has a queue");
                        return(true);
                    }
                }
            }

            return(false);
        }
示例#15
0
        private static bool CheckConcealForce(IMyCubeGrid grid, ulong steamId)
        {
            List <IMySlimBlock> blocks = new List <IMySlimBlock>();

            // Live dangerously
            grid.GetBlocks(blocks, x => x.FatBlock != null);
            foreach (IMySlimBlock block in blocks)
            {
                IMyCubeBlock cubeBlock = block.FatBlock;

                if (cubeBlock.BlockDefinition.TypeId == typeof(MyObjectBuilder_MedicalRoom))
                {
                    MyObjectBuilder_MedicalRoom medical = (MyObjectBuilder_MedicalRoom)cubeBlock.GetObjectBuilderCubeBlock();

                    if (!medical.Enabled)
                    {
                        continue;
                    }

                    Sandbox.ModAPI.Ingame.IMyTerminalBlock terminalBlock = (Sandbox.ModAPI.Ingame.IMyTerminalBlock)cubeBlock;
                    long playerId = PlayerMap.Instance.GetFastPlayerIdFromSteamId(steamId);
                    if (medical.Owner == playerId || (medical.ShareMode == MyOwnershipShareModeEnum.Faction && Player.CheckPlayerSameFaction(medical.Owner, playerId)))
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }