bool CollectParts(IMyTerminalBlock block)
        {
            if (block.CubeGrid.EntityId != Context.Reference.CubeGrid.EntityId)
            {
                return(false);
            }
            if (block is IMyLargeTurretBase)
            {
                Turret = (IMyLargeTurretBase)block;
            }
            if (block is IMyShipController)
            {
                Controller = (IMyShipController)block;
            }
            if (block is IMyTextPanel)
            {
                var startIndex = block.CustomName.IndexOf("[");
                var endIndex   = block.CustomName.IndexOf("]");
                if (startIndex < endIndex && startIndex > -1)
                {
                    var tagStrings = block.CustomName.Substring(startIndex + 1, endIndex - startIndex - 1).Split(',');
                    var coords     = new Vector2I(int.Parse(tagStrings[0]), int.Parse(tagStrings[1]));
                    Panels.Add(coords, (IMyTextPanel)block);
                }
            }

            return(false);
        }
예제 #2
0
            private Vector3D CalculateTargetVector(MyDetectedEntityInfo info, IMyLargeTurretBase turret, double ammoSpeed = 1000d)            //projectile speed 1000m/s (300 auto canon)
            {
                ///prediction = position + velocity * time + 0.5 * acceleration * time * time
                ///time ~ distance(m)/1000 (1000m/s 300 AC ammmo speed
                ///

                Vector3D shotOrigin = turret.GetPosition();

                Vector3D directionToTarget = Vector3D.Normalize(info.Position - shotOrigin);

                //double targetSpeedInLineOfFire = Vector3D.Dot(directionToTarget, info.Velocity);
                double relativeSpeed = ammoSpeed;                // - targetSpeedInLineOfFire;

                double   distance     = Vector3D.Distance(turret.GetPosition(), info.Position);
                double   time         = distance / relativeSpeed;
                Vector3D displacement = ToVector3D(info.Velocity) * time;
                Vector3D targetVector = info.Position + displacement;
                //Vector3D targetVector = info.Position;

                /// Own velocity correction TESTED ON 300
                Vector3D mySpeed = shipcontroller.GetShipVelocities().LinearVelocity;

                //targetVector = targetVector + mySpeed * -1 * distance / 2500;
                targetVector = targetVector + (mySpeed * -1) * time / 1.5d;

                //_program.Echo($"T:{time}");
                return(targetVector);
            }
예제 #3
0
 private void ResetTurret(IMyLargeTurretBase turret)
 {
     if (!turret.MarkedForClose && turret.IsFunctional)
     {
         turret.ApplyAction("ShootOnce");
     }
 }
예제 #4
0
        //private void SettingsRequest(ulong steamid)
        //{
        //	NetSettings.SetValue(Settings.Static);

        //	Tools.Debug(MyAPIGateway.Utilities.SerializeToXML(Settings.Static));

        //}

        private void Changed(VRage.Game.ModAPI.Interfaces.IMyControllableEntity o, VRage.Game.ModAPI.Interfaces.IMyControllableEntity n)
        {
            foreach (WeaponBase w in GridWeapons)
            {
                w.State.Value &= ~WeaponState.ManualShoot;
            }

            GridWeapons.Clear();
            ControlledGridId = 0;

            ActiveTurret = n?.Entity as IMyLargeTurretBase;

            if (ActiveTurret == null)
            {
                ActiveShipController = n?.Entity as IMyShipController;
                SelectedDefinitionId = Tools.GetSelectedHotbarDefinition(ActiveShipController);
            }

            MyCubeGrid grid = (n?.Entity as MyCubeBlock)?.CubeGrid;

            if (grid != null)
            {
                ControlledGridId = grid.EntityId;
                foreach (MyCubeBlock block in grid.GetFatBlocks())
                {
                    WeaponControlLayer layer = block.GameLogic.GetAs <WeaponControlLayer>();

                    if (layer != null)
                    {
                        GridWeapons.Add(layer.Weapon);
                    }
                }
            }
        }
예제 #5
0
        public Program()
        {
            m_missileControl = new MissileControl(this);

            List <IMyTerminalBlock> TempCollection3 = new List <IMyTerminalBlock>();

            //GridTerminalSystem.GetBlocksOfType<IMyShipController>(TempCollection3, a => a.DetailedInfo != "NoUse");
            GridTerminalSystem.GetBlocksOfType <IMyShipController> (TempCollection3);

            if (TempCollection3.Count > 0)
            {
                m_RC = TempCollection3[0] as IMyShipController;
            }

            m_remoteTurretBlock = ( IMyLargeTurretBase )GridTerminalSystem.GetBlockWithName("#RemoteTurret#");

            List <IMyCameraBlock> cameraBlockList = new List <IMyCameraBlock> ();

            GridTerminalSystem.GetBlocksOfType <IMyCameraBlock> (cameraBlockList);

            if (cameraBlockList.Count > 0)
            {
                m_TOWCamera = cameraBlockList[0] as IMyCameraBlock;
            }

            ThisShipSize = (Me.CubeGrid.WorldVolume.Radius);

            ThisShipSize = LaunchDist == 0 ? ThisShipSize : LaunchDist;

            Runtime.UpdateFrequency = UpdateFrequency.Update1;
        }
예제 #6
0
        //Function to check if targeting own grid, only fire if not own grid.
        public static Boolean targetIsFine(IMyLargeTurretBase elem, VRage.Game.ModAPI.IMyCubeGrid grid, Vector3D targetPos)
        {
            var gun    = elem as IMyGunObject <Sandbox.Game.Weapons.MyGunBase>;
            var matrix = gun.GunBase.GetMuzzleWorldMatrix();

            var from = matrix.Translation;
            var to   = targetPos - from;

            to.Normalize();
            to.X *= 200;
            to.Y *= 200;
            to.Z *= 200;
            to   += from;

            List <VRage.Game.ModAPI.IHitInfo> hits = new List <VRage.Game.ModAPI.IHitInfo>();

            MyAPIGateway.Physics.CastRay(from, to, hits);

            if (hits.Count > 0)
            {
                //MyLog.Default.WriteLine(" first hit=" + hits[0].HitEntity.ToString() + " own grid=" + grid.ToString());
                if (hits[0].HitEntity.EntityId.Equals(grid.EntityId))
                {
                    return(false);
                }
                return(true);
            }
            return(true);
        }
        public override void UpdateBeforeSimulation()
        {
            if (MyAPIGateway.Utilities.IsDedicated)
            {
                return;
            }

            IMyLargeTurretBase turret = MyAPIGateway.Session?.Player?.Controller?.ControlledEntity?.Entity as IMyLargeTurretBase;

            if (turret == null)
            {
                ClearGPS();
                return;
            }

            _wasInTurretLastFrame = true;
            _gunBase = turret as IMyGunObject <MyGunBase>;

            if (_gunBase.GunBase.CurrentAmmoDefinition == null)
            {
                ClearGPS();
                return;
            }

            Vector3D turretLoc              = turret.GetPosition();
            float    projectileSpeed        = _gunBase.GunBase.CurrentAmmoDefinition.DesiredSpeed;
            float    projectileRange        = _gunBase.GunBase.CurrentAmmoDefinition.MaxTrajectory + 100;
            float    projectileRangeSquared = projectileRange * projectileRange;

            foreach (IMyCubeGrid grid in _grids)
            {
                if (grid.Physics == null)
                {
                    RemoveGPS(grid.EntityId);
                    continue;
                }

                Vector3D gridLoc = grid.WorldAABB.Center;

                if (grid.EntityId == turret.CubeGrid.EntityId ||
                    Vector3D.DistanceSquared(gridLoc, turretLoc) > projectileRangeSquared ||
                    !GridHasHostileOwners(grid))
                {
                    RemoveGPS(grid.EntityId);
                    continue;
                }

                Vector3D interceptPoint = CalculateProjectileInterceptPosition(
                    projectileSpeed,
                    turret.CubeGrid.Physics.LinearVelocity,
                    turretLoc,
                    grid.Physics.LinearVelocity,
                    gridLoc, 10);

                AddGPS(grid.EntityId, interceptPoint);
            }
        }
예제 #8
0
            void ResetTarget(IMyLargeTurretBase turret)
            {
                //Idle Movement setting gets reset when calling ResetTargetingToDefault(), so need to re-apply it.
                bool idleMovement = turret.EnableIdleRotation;

                turret.ResetTargetingToDefault();
                DeleteCustomProperty(turret, "target");
                turret.EnableIdleRotation = idleMovement;
            }
예제 #9
0
        bool CollectParts(IMyTerminalBlock block, IMyCubeBlock reference)
        {
            if (reference.CubeGrid.EntityId != block.CubeGrid.EntityId)
            {
                return(false);
            }

            if (block is IMyGyro)
            {
                Drive.AddGyro((IMyGyro)block);
            }

            if (block is IMySmallGatlingGun)
            {
                Gats.Add((IMySmallGatlingGun)block);
            }

            if (block is IMyCameraBlock)
            {
                Cameras.Add((IMyCameraBlock)block);
            }

            if (block is IMyMotorStator)
            {
                TurretRotor = (IMyMotorStator)block;
            }

            if (block is IMyLargeTurretBase)
            {
                Designator = (IMyLargeTurretBase)block;
            }

            if (block is IMyThrust)
            {
                Drive.AddEngine(new HoverEngineDriver((IMyThrust)block));
            }

            if (block is IMyRadioAntenna)
            {
                Antenna = (IMyRadioAntenna)block;
            }

            if (block is IMyBeacon)
            {
                ((IMyBeacon)block).Enabled = false;
            }

            if (block is IMyShipController)
            {
                Controller = (IMyShipController)block;
                Controller.TryGetPlanetPosition(out PlanetPos);
                Drive.Controller = Controller;
            }

            return(false);
        }
예제 #10
0
        //Initialiser
        #region Setup Stages
        Program()
        {
            //Sets Runtime
            Runtime.UpdateFrequency = Global_Timestep == 0.16? UpdateFrequency.Update10 : UpdateFrequency.Update1;

            //Setup String
            string SetupString = "Rdavs Guided Missile Script Hints Tips & Setup \n================================================== \n \n \nSystem Setup \n=================== \n \nTo Set Up The Ship: \n------------------------ \n- Put this Code Into a P-block \n- Install a sound block (optional) \n- Install a turret called #A# (seeker turret) \n- Recompile if prompted to 'reset' \n- To fire from the toolbar 'run' this Pb with \n  the argument 'Fire' \n \n\nTo Set Up A Missile: \n--------------------------- \n- Every Missile Requires: \n    ~ 1 gyro\n    ~ Forward thrusters \n    ~ 1 Merge Block \n    ~ 1 battery/power source \n    ~ Warheads (optional) \n    ~ Side thrusters (if in gravity)\n \n- Call everything on missile #A# \n- Weld/paste missile onto launching ship \n- Same missile design can be pasted multiple times \n- Missile(s) are now ready to fire!\n\n \n\nSystem Usage \n=================== \n \nMove to engagement distance (800m), a distinctive  \ntarget lock bleeping will sound from the sound block. \n(if sound block installed) \n \n'Run' The programmable block with the argument  \n'Fire' this will launch the next available missile.  \nthis action can be bound to the toolbar of any cockpit. \n \nA ship can have up to 100 missiles active at any one  \npoint, missile setup for every missile is identical  \nand thus missiles can be printed, copy pasted, etc. \n\n- NOTE:\n- For ALL missiles the weight of the missile\n  (can be found in the 'info' tab in kg)\n  should be written as a number into the \n  custom data of the missiles gyro.\n  This is not compulsory but is necessary for\n  accurate guidance.\n\n\nTroubleshooting: \n============================\n\nif you find that your missiles are:\n\n - Sinking and hit the ground in gravity\n - Miss the target / have sub par guidance\n - Not tracking an enemy\n - Not firing at all\n\nHere are some of the most common faults:\n\n- Check the terminal of the PB, this might show\n  some useful error readouts\n\n- Boost the acceleration of the missile! \n  (especially if unable to hit targets)\n\n- Ensure the turret (called #A#) is turned on \n  and set to attack enemy targets, what this turret\n  targets is what the script will track\n\n- The weight of the missile should be input\n  into the gyros custom data,\n\n- Lateral (side) thrusters are not compulsory but\n  are very useful at helping the guidance\n  especially in natural gravity\n\n \n \nHints & Tips \n=================== \n \n  \nPerformance Tips:  \n------------------------ \n \n- Use light and fast missiles for best small ship  \n  tracking capability, the key to a good hit rate is \n  good missile design!\n \n- For 'best' target tracking ensure your missile has  \n  at least 3x the acceleration of the ship you are  \n  intending to take out. \n \n- Lateral (sideways) thrusters can be used for better  \n  gravity correction and handling. \n \n \nUsage Tips: \n---------------------- \n \n- ID'ing the target can be done with common sense, (ie looking \n  at what the seeker turret is currently looking at) \n \n- you can fire a missile without lock to 'laser guide it'  \n  (ie it follows where you are pointing your ship) \n  towards an enemy, once close tracking will engage \n \n- The missile will (by default) not engage guidance until further  \n  than the ships radius away from where it launched. This should  \n  make it practical for launch tubes/ not damaging the launching ship.  \n\n- If a customn launch distance is required this can be changed by changing\n  the 'launch distance' value in the code shortly after the introduction\n\n- An extra seeker turret can be put on the missile itself (must be called #A#)\n  this missile will then use that turret to guide itself.\n\n- The missile tracking is good but as with anything depends on the pilots\n  ability to use them well, read up on real-world missile usage to help \n  boost your hit rate.\n\n\n\n  \n";

            Me.CustomData = SetupString;

            //Sets ShipSize
            ThisShipSize = (Me.CubeGrid.WorldVolume.Radius);
            ThisShipSize = LaunchDist == 0 ? ThisShipSize : LaunchDist;

            //Collects First Turret
            List <IMyTerminalBlock> TempCollection = new List <IMyTerminalBlock>();

            GridTerminalSystem.GetBlocksOfType <IMyLargeTurretBase>(TempCollection, a => a.CustomName.Contains(MissileTag) && a.DetailedInfo != "NoUse");
            if (TempCollection.Count > 0)
            {
                Turret = TempCollection[0] as IMyLargeTurretBase;
            }

            //Collects Sound/Alarm
            List <IMyTerminalBlock> TempCollection2 = new List <IMyTerminalBlock>();

            GridTerminalSystem.GetBlocksOfType <IMySoundBlock>(TempCollection2, a => a.DetailedInfo != "NoUse");
            if (TempCollection2.Count > 0)
            {
                Alarm = TempCollection2[0] as IMySoundBlock;
                Alarm.SelectedSound = "SoundBlockAlert2";
                Alarm.LoopPeriod    = 99999;
                Alarm.Play();
                Alarm.Enabled = false;
            }

            //Collects RC Unit
            List <IMyTerminalBlock> TempCollection3 = new List <IMyTerminalBlock>();

            GridTerminalSystem.GetBlocksOfType <IMyShipController>(TempCollection3, a => a.DetailedInfo != "NoUse");
            if (TempCollection3.Count > 0)
            {
                RC = TempCollection3[0] as IMyShipController;
            }

            //Collects TOW CameraBlock
            List <IMyTerminalBlock> TempCollection4 = new List <IMyTerminalBlock>();

            GridTerminalSystem.GetBlocksOfType <IMyCameraBlock>(TempCollection3, a => a.DetailedInfo == "#A#");
            if (TempCollection3.Count > 0)
            {
                TOWCamera = TempCollection3[0] as IMyCameraBlock; TOWCamera.EnableRaycast = true;
            }
        }
예제 #11
0
        private bool WeaponCheck()
        {
            bool TargetFound = false;

            if (Weapons.Count > 0)
            {
                //if (Command == "C.Freelance")
                //{
                //	CommandOverride = true;
                //}

                foreach (IMyLargeTurretBase item in Weapons)
                {
                    item.ApplyAction("OnOff_On");
                }

                IMyLargeTurretBase Weapon = Weapons[0];

                for (int i = 0; i < Weapons.Count; i++)
                {
                    if (Weapons[i].IsShooting && Weapons[i].HasTarget)
                    {
                        Weapon      = Weapons[i];
                        TargetFound = true;
                        break;
                    }
                }

                if (TargetFound | CommandOverride)
                {
                    Echo("Attack Mode Activated");

                    MyDetectedEntityInfo entityInfo = Weapon.GetTargetedEntity();

                    Vector3D transformedTargetVec = Vector3D.Normalize(entityInfo.Position - GblPosition);

                    Target = entityInfo.Position + transformedTargetVec * (Weapon.Range / 3);

                    Echo("Target: " + TargetFound);
                    //Echo("Position: " + entityInfo.Position);

                    return(TargetFound);
                }
                else
                {
                    Echo("No enemies found");
                    return(TargetFound);
                }
            }
            Echo("No turrets on grid");
            return(TargetFound);
        }
예제 #12
0
        public Program()
        {
            test_panel             = (IMyTextPanel)GridTerminalSystem.GetBlockWithName("LCD");
            test_panel.ContentType = ContentType.TEXT_AND_IMAGE;

            turret = (IMyLargeTurretBase)GridTerminalSystem.GetBlockWithName("test_turret");
            Runtime.UpdateFrequency = UpdateFrequency.Update10;

            sensor            = (IMySensorBlock)GridTerminalSystem.GetBlockWithName("turret_sensor");
            detected_entities = new List <MyDetectedEntityInfo>();

            Runtime.UpdateFrequency = UpdateFrequency.Update100;
        }
예제 #13
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);
     }
 }
예제 #14
0
        public RegularWeapon(IMyTerminalBlock block, IMyRemoteControl remoteControl, IBehavior behavior) : base(block, remoteControl, behavior)
        {
            if (!_isValid)
            {
                return;
            }

            GetWeaponDefinition(_block);

            if (_weaponDefinition == null)
            {
                Logger.MsgDebug(_block.CustomName + " Weapon Definition Not Found", DebugTypeEnum.WeaponSetup);
                _isValid = false;
                return;
            }

            foreach (var ammoData in _weaponDefinition.WeaponAmmoDatas)
            {
                if (ammoData == null)
                {
                    continue;
                }

                if (ammoData.RateOfFire > 0)
                {
                    _rateOfFire = ammoData.RateOfFire;
                }
            }

            if (_block as IMyLargeTurretBase != null)
            {
                _isTurret = true;
                _turret   = _block as IMyLargeTurretBase;
                _gunBase  = _turret as IMyGunObject <MyGunBase>;
            }
            else if (_block as IMyUserControllableGun != null)
            {
                _isStatic  = true;
                _staticGun = _block as IMyUserControllableGun;
                _gunBase   = _staticGun as IMyGunObject <MyGunBase>;
            }
            else
            {
                Logger.MsgDebug(_block.CustomName + " Is Neither Gun Or Turret?", DebugTypeEnum.WeaponSetup);
                _isValid = false;
                return;
            }

            //Get Rate of Fire
            //Determine If Barrage Capable
        }
예제 #15
0
            public DesignatorTurret(IMyLargeTurretBase block, List <IMyCameraBlock> ShipCameras)
            {
                turret           = block;
                scanRange        = turret.Range + 10;
                currentScanRange = scanRange;

                foreach (IMyCameraBlock camera in ShipCameras)
                {
                    if (camera.CubeGrid == turret.CubeGrid)
                    {
                        camera.EnableRaycast = true;
                        Cameras.Add(camera);
                    }
                }
            }
예제 #16
0
        private void SetTurretTarget(IMyLargeTurretBase turret, MyEntity targetentity)
        {
            if (turret == null)
            {
                return;
            }
            turret.TrackTarget(targetentity);            //was SetTarget
            MyEntity outtracker;

            if (TurretTrackers.TryGetValue(turret, out outtracker))
            {
                TurretTrackers.Remove(turret);
            }
            TurretTrackers.Add(turret, targetentity);
        }
예제 #17
0
 private TurretType getTurretType(IMyLargeTurretBase tur)
 {
     if (tur is IMyLargeMissileTurret || tur is IMySmallMissileLauncher)
     {
         return(TurretType.MISSILE);
     }
     if (tur is IMyLargeGatlingTurret)
     {
         return(TurretType.GATLING);
     }
     if (tur is IMyLargeInteriorTurret)
     {
         return(TurretType.INTERIOR);
     }
     return(TurretType.UNKNOWN);
 }
예제 #18
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)));
            }
        }
예제 #19
0
        public Program()
        {
            debug_panel = (IMyTextPanel)GridTerminalSystem.GetBlockWithName("debug_LCD");
            debug_panel.ContentType = ContentType.TEXT_AND_IMAGE;

            targeting_turret = (IMyLargeTurretBase)GridTerminalSystem.GetBlockWithName("targeting_turret");
            
            azimuth_rotor = (IMyMotorStator)GridTerminalSystem.GetBlockWithName("azimuth_rotor");
            left_rotor = (IMyMotorStator)GridTerminalSystem.GetBlockWithName("left_rotor");
            right_rotor = (IMyMotorStator)GridTerminalSystem.GetBlockWithName("right_rotor");

            sensor = (IMySensorBlock)GridTerminalSystem.GetBlockWithName("test_sensor");
            detected_entities = new List<MyDetectedEntityInfo>();

            Runtime.UpdateFrequency = UpdateFrequency.Update1;
            debug_panel.WriteText("");
        }
예제 #20
0
            Vector3D GetTarget(IMyLargeTurretBase turret)
            {
                Vector3D target       = Vector3D.Zero;
                var      customTarget = GetCustomProperty(turret, "target");

                if (customTarget == null || !GetVector(customTarget, out target))
                {
                    if (turret.HasTarget)
                    {
                        target = GetPosition(turret.GetTargetedEntity());
                    }
                    else
                    {
                        target = Vector3D.Zero;
                    }
                }
                return(target);
            }
        //True if the turret can aim at its target.
        private static bool isInFiringArk(SmartTurret turret, Vector3D targetLocation)
        {
            IMyLargeTurretBase turretBase = turret.Entity as IMyLargeTurretBase;

            if (turretBase == null)
            {
                return(false);
            }

            MyLargeTurretBaseDefinition turretDefinition = (MyDefinitionManager.Static.GetCubeBlockDefinition(turretBase.BlockDefinition) as MyLargeTurretBaseDefinition);
            int azimuthMin   = turretDefinition.MinAzimuthDegrees;
            int azimuthMax   = turretDefinition.MaxAzimuthDegrees;
            int elevationMin = turretDefinition.MinElevationDegrees;
            int elevationMax = turretDefinition.MaxElevationDegrees;

            //Get turrets world rotation.
            Matrix3x3 turretRotation = turretBase.WorldMatrix.Rotation;

            //Make a Quaternion from the world rotation and invert it so we can rotate to ther way.
            Quaternion offset = Quaternion.CreateFromRotationMatrix(turretBase.WorldMatrix);

            offset.Conjugate();
            offset.Normalize();

            //Find the direction of the target from the turret.
            Vector3 dirToTarget = targetLocation - turretBase.GetPosition();

            dirToTarget.Normalize();

            //Rotate the dirrection of the target by the Quaternion to cancel out the turrets world rotation.
            dirToTarget = Vector3.Transform(dirToTarget, offset);

            //The targets direction is now relative to the world so we can get Azimuth and Elevation.
            float azimuth;
            float elevation;

            Vector3.GetAzimuthAndElevation(dirToTarget, out azimuth, out elevation);

            //Convert Azimuth and Elevation to deg for comparason with the turrets elevation and azimuth limits.
            azimuth   = (float)(180 / Math.PI * azimuth);
            elevation = (float)(180 / Math.PI * elevation);

            return(azimuth >= azimuthMin && azimuth <= azimuthMax && elevation >= elevationMin && elevation <= elevationMax);
        }
예제 #22
0
        public WeaponComponent(Session session, MyCubeBlock myCube, MyStringHash subtype)
        {
            Session     = session;
            MyCube      = myCube;
            Slim        = myCube.SlimBlock;
            SubtypeHash = subtype;

            MaxIntegrity = Slim.MaxIntegrity;

            var turret = MyCube as IMyLargeTurretBase;

            if (turret != null)
            {
                TurretBase = turret;
                TurretBase.EnableIdleRotation = false;
                BaseType = BlockType.Turret;
            }
            else if (MyCube is IMyConveyorSorter)
            {
                BaseType = BlockType.Sorter;
            }
            else
            {
                BaseType = BlockType.Fixed;
            }

            TerminalBlock   = myCube as IMyTerminalBlock;
            FunctionalBlock = myCube as IMyFunctionalBlock;

            BlockInventory = (MyInventory)MyCube.GetInventoryBase();
            SinkPower      = IdlePower;
            Platform       = session.PlatFormPool.Get();
            Platform.Setup(this);

            Monitors = new List <Action <long, int, ulong, long, Vector3D, bool> > [Platform.Weapons.Length];
            for (int i = 0; i < Monitors.Length; i++)
            {
                Monitors[i] = new List <Action <long, int, ulong, long, Vector3D, bool> >();
            }

            Data = new CompData(this);

            MyCube.OnClose += Session.CloseComps;
        }
 private bool isTurretsFunctionalAndLoaded(double minLoadFactor = 0.2)
 {
     for (int i_Turrets = 0; i_Turrets < Turrets.Count; i_Turrets++)
     {
         IMyLargeTurretBase Turret = Turrets[i_Turrets];
         if (!Turret.IsWorking || !Turret.IsFunctional)
         {
             return(false);
         }
         double maximumAmmoLoad   = (double)Turret.GetInventory(0).MaxVolume;
         double currentAmmoLoad   = (double)Turret.GetInventory(0).CurrentVolume;
         double currentLoadFactor = (maximumAmmoLoad <= 0.0)?(0.0):(currentAmmoLoad / maximumAmmoLoad);
         if (currentLoadFactor < minLoadFactor)
         {
             return(false);
         }
     }
     return((Turrets.Count > 0)? true :false);
 }
예제 #24
0
        public TurretWeaponProfile(IMyRemoteControl remoteControl, IMyTerminalBlock block) : base(remoteControl, block)
        {
            _turretWeaponBlock = block as IMyLargeTurretBase;

            if (_turretWeaponBlock != null)
            {
                _gunBase = (IMyGunObject <MyGunBase>)_turretWeaponBlock;
            }
            else
            {
                _weaponValid = false;
            }

            if (!_weaponValid)
            {
                return;
            }

            GetWeaponDefinition(_turretWeaponBlock);
        }
예제 #25
0
            public void Run()
            {
                var turrets = new List <IMyLargeTurretBase>();

                _program.GridTerminalSystem.GetBlocksOfType <IMyLargeTurretBase>(turrets);

                foreach (var turret in turrets)
                {
                    _program.Echo(turret.DisplayNameText);
                }


                var turret900 = turrets.FirstOrDefault(t => t.DisplayNameText.ToLower().Contains("900"));

                _program.Echo($"{turret900.Azimuth}");
                turret900.Azimuth = 100;
                turret900.SyncAzimuth();

                _turret900 = turret900;
            }
예제 #26
0
        public WeaponComponent(Session session, GridAi ai, MyCubeBlock myCube, MyStringHash subtype)
        {
            Ai          = ai;
            Session     = session;
            MyCube      = myCube;
            Seed        = MyCube.EntityId.GetHashCode();
            Slim        = myCube.SlimBlock;
            SubtypeHash = subtype;

            MaxIntegrity = Slim.MaxIntegrity;

            var turret = MyCube as IMyLargeTurretBase;

            if (turret != null)
            {
                TurretBase = turret;
                TurretBase.EnableIdleRotation = false;
                BaseType = BlockType.Turret;
            }
            else if (MyCube is IMyConveyorSorter)
            {
                BaseType = BlockType.Sorter;
            }
            else
            {
                BaseType = BlockType.Fixed;
            }

            TerminalBlock   = myCube as IMyTerminalBlock;
            FunctionalBlock = myCube as IMyFunctionalBlock;

            BlockInventory = (MyInventory)MyCube.GetInventoryBase();
            SinkPower      = IdlePower;
            Platform       = session.PlatFormPool.Get();
            Platform.Setup(this);

            State = new CompState(this);
            Set   = new CompSettings(this);

            MyCube.OnClose += Session.CloseComps;
        }
예제 #27
0
        private void Lock(IMyCubeBlock obj)
        {
            IMyLargeTurretBase Turret = Entity as IMyLargeTurretBase;

            if (obj.OwnerId == 0 && Turret.IsWorking)
            {
                Turret.Enabled = false;
                Turret.RefreshCustomInfo();
                return;
            }
            ITerminalAction TargetLarge = Turret.GetActionWithName("TargetLargeShips_Off");

            if (TargetLarge != null)
            {
                TargetLarge.Apply(Turret);
            }

            ITerminalAction TargetSmall = Turret.GetActionWithName("TargetSmallShips_Off");

            if (TargetSmall != null)
            {
                TargetSmall.Apply(Turret);
            }

            ITerminalAction TargetStation = Turret.GetActionWithName("TargetStations_Off");

            if (TargetStation != null)
            {
                TargetStation.Apply(Turret);
            }

            ITerminalAction TargetMoving = Turret.GetActionWithName("TargetMoving_Off");

            if (TargetMoving != null)
            {
                TargetMoving.Apply(Turret);
            }
        }
예제 #28
0
        private void UpdateSettings()
        {
            var parser = new MyIni();

            if (!parser.TryParse(Me.CustomData))
            {
                throw new InvalidOperationException("Couldn't parse CustomData as INI!");
            }
            this.tag       = parser.Get(SETTINGS_SECTION, "tag").ToString(MissileCommons.DEFAULT_TAG);
            this.statusTag = parser.Get(SETTINGS_SECTION, "statusTag").ToString(MissileCommons.STATUS_TAG);
            this.directing = parser.Get(SETTINGS_SECTION, "directing").ToBoolean(true);
            if (this.directing)
            {
                this.directorTurret = GridTerminalSystem.GetBlockOfType <IMyLargeTurretBase>(t => MyIni.HasSection(t.CustomData, DIRECTOR_TURRET_SECTION));
                if (this.directorTurret != null)
                {
                    LogLine($"Director mode on, found director turret {directorTurret.CustomName}");
                }
                else
                {
                    LogLine($"No director turret was found. If you have one, add the [{DIRECTOR_TURRET_SECTION}] line to its Custom Data. Disabling director mode.");
                    this.directing = false;
                }
            }
            if (missileMsgListener != null)
            {
                missileMsgListener.DisableMessageCallback();
            }
            missileMsgListener = IGC.RegisterBroadcastListener(this.tag);
            missileMsgListener.SetMessageCallback();

            if (missileStatusListener != null)
            {
                missileStatusListener.DisableMessageCallback();
            }
            missileStatusListener = IGC.RegisterBroadcastListener(MissileCommons.STATUS_TAG);
            missileStatusListener.SetMessageCallback();
        }
예제 #29
0
        void ShowReloadMessage()
        {
            var s = Settings.GetSettings(Entity);

            if (_isReloading && s.Recharging)
            {
                if (MyAPIGateway.Utilities.IsDedicated)
                {
                    return;
                }

                IMyShipController cockpit = MyAPIGateway.Session.Player?.Controller?.ControlledEntity?.Entity as IMyShipController;
                if (cockpit == null)
                {
                    IMyLargeTurretBase turret = MyAPIGateway.Session.Player?.Controller?.ControlledEntity?.Entity as IMyLargeTurretBase;
                    if (turret == null)
                    {
                        return;
                    }
                }

                MyAPIGateway.Utilities.ShowNotification($"Railgun reloading ({100 * _currentReloadTicks / _reloadTicks:n0}%)", 16);
            }
        }
예제 #30
0
        public static LeadingData GetLeadingData(IMyEntity block, LeadingData current)
        {
            try
            {
                if (block is IMyLargeTurretBase)
                {
                    IMyLargeTurretBase turret = block as IMyLargeTurretBase;

                    return(new LeadingData()
                    {
                        EntityId = turret.EntityId,
                        Position = turret.GetPosition(),
                        Velocity = turret.CubeGrid.Physics.LinearVelocity,
                        Ammo = (turret as IMyGunObject <MyGunBase>).GunBase.CurrentAmmoDefinition
                    });
                }
                else if (block is IMyShipController)
                {
                    IMyShipController cockpit = block as IMyShipController;

                    LeadingData data = new LeadingData
                    {
                        EntityId = block.EntityId,
                        Velocity = cockpit.CubeGrid.Physics.LinearVelocity,
                        Position = cockpit.CubeGrid.WorldAABB.Center
                    };

                    if (current != null)
                    {
                        SerializableDefinitionId definition = GetWeaponDef(cockpit, ref data.toolbarIndex);
                        if (current.toolbarIndex != data.toolbarIndex)
                        {
                            List <IMySlimBlock> blocks = new List <IMySlimBlock>();
                            cockpit.CubeGrid.GetBlocks(blocks, (b) =>
                            {
                                return(b.BlockDefinition.Id == definition &&
                                       b.FatBlock != null &&
                                       b.FatBlock.Orientation.Forward == cockpit.Orientation.Forward);
                            });

                            foreach (IMySlimBlock b in blocks)
                            {
                                data.offset += data.Position - b.FatBlock.PositionComp.WorldAABB.Center;

                                if (data.Ammo == null)
                                {
                                    data.Ammo = (b.FatBlock as IMyGunObject <MyGunBase>).GunBase.CurrentAmmoDefinition;
                                }
                            }

                            data.offset = data.offset / blocks.Count;
                        }
                        else
                        {
                            data.offset = current.offset;
                            data.Ammo   = current.Ammo;
                        }
                    }

                    data.Position = data.Position - data.offset;
                    return(data);
                }
            }
            catch (Exception e)
            {
                // bad fix i know
                //MyLog.Default.Info(e.ToString());
            }

            return(null);
        }
예제 #31
0
 public TurretInfo(IMyLargeTurretBase turret)
 {
     LastElevation = turret.Elevation;
     LastAzimuth = turret.Azimuth;
 }