Distance() public static method

public static Distance ( Vector3D, a, Vector3D, b ) : double
a Vector3D,
b Vector3D,
return double
Ejemplo n.º 1
0
        float IMyPathVertex <MyNavigationPrimitive> .EstimateDistanceTo(IMyPathVertex <MyNavigationPrimitive> other)
        {
            MyNavigationPrimitive primitive = other as MyNavigationPrimitive;

            return(!ReferenceEquals(this.Group, primitive.Group) ? ((float)Vector3D.Distance(this.WorldPosition, primitive.WorldPosition)) : Vector3.Distance(this.Position, primitive.Position));
        }
Ejemplo n.º 2
0
        internal void MyStaticInfo()
        {
            ClosestStaticSqr  = double.MaxValue;
            StaticGridInRange = false;
            MyEntity closestEnt     = null;
            var      closestCenter  = Vector3D.Zero;
            double   closestDistSqr = double.MaxValue;

            CanShoot = true;
            for (int i = 0; i < StaticsInRange.Count; i++)
            {
                var ent = StaticsInRange[i];
                if (ent == null)
                {
                    continue;
                }
                if (ent.MarkedForClose)
                {
                    continue;
                }
                var safeZone = ent as MySafeZone;


                var staticCenter = ent.PositionComp.WorldAABB.Center;
                if (ent is MyCubeGrid)
                {
                    StaticGridInRange = true;
                }

                double distSqr;
                Vector3D.DistanceSquared(ref staticCenter, ref ScanVolume.Center, out distSqr);
                if (distSqr < closestDistSqr)
                {
                    closestDistSqr = distSqr;
                    closestEnt     = ent;
                    closestCenter  = staticCenter;
                }

                if (CanShoot && safeZone != null && safeZone.Enabled)
                {
                    if (safeZone.PositionComp.WorldVolume.Contains(MyGrid.PositionComp.WorldVolume) != ContainmentType.Disjoint && ((Session.SafeZoneAction)safeZone.AllowedActions & Session.SafeZoneAction.Shooting) == 0)
                    {
                        CanShoot = !TouchingSafeZone(safeZone);
                    }
                }
            }

            if (closestEnt != null)
            {
                var dist = Vector3D.Distance(ScanVolume.Center, closestCenter);
                dist -= closestEnt.PositionComp.LocalVolume.Radius;
                dist -= ScanVolume.Radius;
                if (dist < 0)
                {
                    dist = 0;
                }

                var distSqr = dist * dist;
                if (ClosestPlanetSqr < distSqr)
                {
                    distSqr = ClosestPlanetSqr;
                }

                ClosestStaticSqr = distSqr;
            }
            else if (ClosestPlanetSqr < ClosestStaticSqr)
            {
                ClosestStaticSqr = ClosestPlanetSqr;
            }
        }
        public override void ActiveUpdate()
        {
            if (MyAPIGateway.Session.Player == null)
            {
                return;
            }

            //if (Vector3D.Distance(MyAPIGateway.Session.Camera.Position, m_source.PositionComp.GetPosition()) > 50f)
            if (Vector3D.Distance(MyAPIGateway.Session.Player.GetPosition(), m_source.PositionComp.GetPosition()) > 50f)
            {
                return;
            }

            for (int s = m_activeBolts.Count - 1; s >= 0; s--)
            {
                var activeItem = m_activeBolts[s];

                activeItem.Position++;
                if (activeItem.Position >= activeItem.MaxPosition)
                {
                    m_activeBolts.Remove(activeItem);
                    m_globalBolts--;
                    continue;
                }
            }

            if (m_activeBolts.Count < m_maxBolts && m_globalBolts < m_globalMaxBolts)
            {
                int numAdd = Math.Min(2, m_maxBolts - m_activeBolts.Count);
                for (int r = 0; r < numAdd; r++)
                {
                    var bolt     = m_boltPool[MyUtils.GetRandomInt(0, m_boltPool.Count)];
                    var boltPath = m_boltPathPool[MyUtils.GetRandomInt(0, m_boltPathPool.Count)];
                    var boltItem = new LightningBoltInstance(bolt, boltPath, 60 + MyUtils.GetRandomInt(-10, 15));
                    m_activeBolts.Add(boltItem);
                    m_globalBolts++;
                }
            }

            for (int s = 0; s < m_activeBolts.Count; s++)
            {
                var activeItem = m_activeBolts[s];

                Vector3D sourceBolt      = new Vector3D(0f, 4f, 0f);
                Vector3D startBoltPoint  = activeItem.Path.Start - new Vector3D(0f, 1.5f, 0f);
                Vector3D endBoltPoint    = activeItem.Path.End - new Vector3D(0f, 1.5f, 0f);
                Vector3D endDiff         = endBoltPoint - startBoltPoint;
                Vector3D endBoltPosition = startBoltPoint + Vector3D.Normalize(endDiff) * (endDiff.Length() * ((float)activeItem.Position / (float)activeItem.MaxPosition));

                Quaternion rot = sourceBolt.CreateQuaternionFromVector(endBoltPosition);

                int startPos      = 0;
                int maxPos        = activeItem.Bolt.Points.Count;
                var previousPoint = activeItem.Bolt.Points[startPos];
                var color         = activeItem.Path.Color;
                for (int r = startPos + 1; r < maxPos; r++)
                {
                    var currentPoint = activeItem.Bolt.Points[startPos + r];

                    if (previousPoint.Length() > endBoltPosition.Length())
                    {
                        break;
                    }

                    // Spin the bolt on the Y axis
                    var startPoint = Vector3D.Transform(currentPoint, MatrixD.CreateRotationY(MathHelper.ToRadians((float)activeItem.Position * 5)));
                    // Rotate the bolt towards the endpoint
                    startPoint = Vector3D.Transform(startPoint, rot);
                    // Move the bolt up to the center of the sphere
                    startPoint += new Vector3D(0f, 1.5f, 0f);
                    // Place it in the world properly
                    startPoint = Vector3D.Transform(startPoint, m_source.WorldMatrix);

                    var endPoint = Vector3D.Transform(previousPoint, MatrixD.CreateRotationY(MathHelper.ToRadians((float)activeItem.Position * 5)));
                    endPoint  = Vector3D.Transform(endPoint, rot);
                    endPoint += new Vector3(0f, 1.5f, 0f);
                    endPoint  = Vector3D.Transform(endPoint, m_source.WorldMatrix);

                    var dir    = Vector3D.Normalize(endPoint - startPoint);
                    var length = (endPoint - startPoint).Length() * 2f;

                    float pulse = MathExtensions.TrianglePulse((float)activeItem.Position, 1f, activeItem.MaxPosition / 2f) + 0.2f;
                    if (activeItem.Position < 10)
                    {
                        pulse = MathExtensions.TrianglePulse((float)activeItem.Position, 1f, 2.5f);
                    }

                    Vector4 diff      = color * pulse;
                    float   thickness = (0.0125f);

                    MyTransparentGeometry.AddLineBillboard(MyStringId.GetOrCompute("Testfly"), diff, startPoint, dir, (float)length, (float)thickness);
                    previousPoint = currentPoint;
                }
            }
        }
Ejemplo n.º 4
0
        internal void DeferedVoxelCheck()
        {
            DeferedVoxels.ApplyAdditions();
            for (int i = 0; i < DeferedVoxels.Count; i++)
            {
                var p      = DeferedVoxels[i].Projectile;
                var branch = DeferedVoxels[i].Branch;
                var voxel  = DeferedVoxels[i].Voxel;

                Vector3D?voxelHit = null;

                if (branch == VoxelIntersectBranch.DeferFullCheck)
                {
                    if (p.Beam.Length > 85)
                    {
                        IHitInfo hit;
                        p.Info.System.Session.Physics.CastLongRay(p.Beam.From, p.Beam.To, out hit, false);
                        if (hit?.HitEntity is MyVoxelBase)
                        {
                            voxelHit = hit.Position;
                        }
                    }
                    else
                    {
                        using (voxel.Pin()) {
                            if (!voxel.GetIntersectionWithLine(ref p.Beam, out voxelHit, true, IntersectionFlags.DIRECT_TRIANGLES) && VoxelIntersect.PointInsideVoxel(voxel, p.Info.System.Session.TmpStorage, p.Beam.From))
                            {
                                voxelHit = p.Beam.From;
                            }
                        }
                    }

                    if (voxelHit.HasValue && p.Info.IsShrapnel && p.Info.Age == 0)
                    {
                        if (!VoxelIntersect.PointInsideVoxel(voxel, p.Info.System.Session.TmpStorage, voxelHit.Value + (p.Beam.Direction * 1.25f)))
                        {
                            voxelHit = null;
                        }
                    }
                }
                else if (branch == VoxelIntersectBranch.DeferedMissUpdate)
                {
                    using (voxel.Pin()) {
                        if (!voxel.GetIntersectionWithLine(ref p.Beam, out voxelHit, true, IntersectionFlags.DIRECT_TRIANGLES) && VoxelIntersect.PointInsideVoxel(voxel, p.Info.System.Session.TmpStorage, p.Beam.From))
                        {
                            voxelHit = p.Beam.From;
                        }
                    }
                }
                else
                {
                    Log.Line($"impossible");
                }

                if (!voxelHit.HasValue)
                {
                    if (p.Info.VoxelCache.MissSphere.Contains(p.Beam.To) == ContainmentType.Disjoint)
                    {
                        p.Info.VoxelCache.MissSphere.Center = p.Beam.To;
                    }
                    continue;
                }

                p.Info.VoxelCache.Update(voxel, ref voxelHit, p.Info.System.Session.Tick);

                if (voxelHit == null)
                {
                    continue;
                }
                if (!p.FinalizeIntersection)
                {
                    p.FinalizeIntersection = true;
                    FinalHitCheck.Add(p);
                }
                var hitEntity = HitEntityPool.Get();
                var lineCheck = p.Info.AmmoDef.Const.CollisionIsLine && !p.Info.EwarAreaPulse;
                hitEntity.Info           = p.Info;
                hitEntity.Entity         = voxel;
                hitEntity.Intersection   = p.Beam;
                hitEntity.SphereCheck    = !lineCheck;
                hitEntity.PruneSphere    = p.PruneSphere;
                hitEntity.DamageOverTime = p.Info.AmmoDef.Const.AreaEffect == DotField;

                var hitPos = voxelHit.Value;
                hitEntity.HitPos = hitPos;

                double dist;
                Vector3D.Distance(ref p.Beam.From, ref hitPos, out dist);
                hitEntity.HitDist = dist;

                hitEntity.EventType = Voxel;
                p.Info.HitList.Add(hitEntity);
            }
            DeferedVoxels.ClearImmediate();
        }
Ejemplo n.º 5
0
        // states
        // 0 = init
        // 10 = powered hovering. No connections
        // 20 = landing gear locked.
        //

        void doModeHover()
        {
            StatusLog("clear", textPanelReport);
            Echo("Hover Mode:" + current_state);
            StatusLog(OurName + ":" + moduleName + ":Hover", textPanelReport);
            StatusLog("Planet Gravity: " + dGravity.ToString(velocityFormat) + " g", textPanelReport);
            double elevation = 0;

            ((IMyShipController)shipOrientationBlock).TryGetPlanetElevation(MyPlanetElevation.Surface, out elevation);
            StatusLog("Elevation: " + elevation.ToString("N0") + " Meters", textPanelReport);

            if (current_state == 0)
            {
                calculateBestGravityThrust();

                float fAtmoPower, fHydroPower, fIonPower;
                calculateHoverThrust(thrustOrbitalUpList, out fAtmoPower, out fHydroPower, out fIonPower);
                if (fAtmoPower > 0)
                {
                    powerDownThrusters(thrustAllList, thrustatmo);
                }
                if (fHydroPower > 0)
                {
                    powerDownThrusters(thrustAllList, thrusthydro);
                }
                if (fIonPower > 0)
                {
                    powerDownThrusters(thrustAllList, thrustion);
                }
                current_state = 10;
//                powerDownThrusters(thrustAllList, thrustAll); // turns ON thrusters
            }

            bool bGearsLocked         = anyGearIsLocked();
            bool bConnectorsConnected = AnyConnectorIsConnected();
            bool bConnectorIsLocked   = AnyConnectorIsLocked();
            bool bGearsReadyToLock    = anyGearReadyToLock();


            /*
             * Echo("Gears:");
             * foreach(var gear in gearList)
             * {
             *  Echo(gear.CustomName);
             * }
             */
            if (bGearsLocked)
            {
                if (current_state != 20)
                {
                    // gears just became locked
                    Echo("Force thrusters Off!");
                    powerDownThrusters(thrustAllList, thrustAll, true);
//                    blockApplyAction(thrustAllList, "OnOff_Off");

                    if ((craft_operation & CRAFT_MODE_NOTANK) == 0)
                    {
                        TanksStockpile(true);
                        GasGensEnable();
//                        blockApplyAction(tankList, "Stockpile_On");
//                        blockApplyAction(gasgenList, "OnOff_On");
                    }
                    current_state = 20;
                }
                landingDoMode(1);
            }
            else
            {
                if (current_state != 10)
                {
                    if ((craft_operation & CRAFT_MODE_NOTANK) == 0)
                    {
                        powerDownThrusters(thrustAllList); // turns ON all thusters
                        TanksStockpile(false);
//                        blockApplyAction(tankList, "Stockpile_Off");
                        //				blockApplyAction(gasgenList,"OnOff_On");
                    }

                    current_state = 10;
                }
                landingDoMode(0);
            }

            // add to delay time
            if (HoverCameraElapsedMs >= 0)
            {
                HoverCameraElapsedMs += Runtime.TimeSinceLastRun.TotalMilliseconds;
            }

            // check for delay
            if (HoverCameraElapsedMs > HoverCameraWaitMs || HoverCameraElapsedMs < 0) // it is time to scan..
            {
                if (doCameraScan(cameraOrbitalLandingList, elevation * 2))            // scan down 2x current alt
                {
                    HoverCameraElapsedMs = 0;
                    // we are able to do a scan
                    if (!lastDetectedInfo.IsEmpty())
                    { // we got something
                        double distance = Vector3D.Distance(lastCamera.GetPosition(), lastDetectedInfo.HitPosition.Value);
                        //			if (distance < elevation)
                        { // try to land on found thing below us.
                            Echo("Scan found:" + lastDetectedInfo.Name + " " + distance.ToString("N0") + "m below");
                            if (!bGearsLocked)
                            {
                                StatusLog("Hovering above: " + lastDetectedInfo.Name + " " + distance.ToString("N0") + "m below", textPanelReport);
                            }
                        }
                    }
                }
            }
            else
            {
                Echo("Camera Scan delay");
            }

            if (bGearsLocked)
            {
                StatusLog("Landing Gear(s) LOCKED!", textPanelReport);
                // we can turn off thrusters.. but that's about it..
                // stay in 'hover' iMode
            }
            else if (bGearsReadyToLock)
            {
                StatusLog("Landing Gear(s) Ready to lock.", textPanelReport);
            }
            if (bConnectorsConnected)
            {
                //prepareForSupported();
                StatusLog("Connector connected!\n   auto-prepare for launch", textPanelReport);
                setMode(MODE_LAUNCHPREP);
            }
            else
            {
                if (!bGearsLocked)
                {
                    //			blockApplyAction(thrustAllList, "OnOff_On");
                    //			if ((craft_operation & CRAFT_MODE_NOTANK) == 0) blockApplyAction(tankList,"Stockpile_On");
                }
                ConnectAnyConnectors(false, true);// "OnOff_On");
            }

            if (bConnectorIsLocked)
            {
                StatusLog("Connector Locked!", textPanelReport);
            }

            if (bConnectorIsLocked || bGearsLocked)
            {
                Echo("Stable");
                landingDoMode(1); // landing mode
                gyrosOff();
            }
            else
            {
                if ((craft_operation & CRAFT_MODE_NOAUTOGYRO) > 0)
                {
                    gyrosOff();
                    StatusLog("Wico Gravity Alignment OFF", textPanelReport);
                }
                else
                {
                    StatusLog("Gravity Alignment Operational", textPanelReport);

                    /*
                     * string sOrientation = "";
                     * if ((craft_operation & CRAFT_MODE_ROCKET) > 0)
                     *  sOrientation = "rocket";
                     */
                    bool bAimed = GyroMain(sOrbitalUpDirection);
//                    if (bAimed)
                    bWantMedium = true;
//                    else  bWantFast = true;
                }
            }

            //	StatusLog("Car:" + progressBar(cargopcent), textPanelReport);

// done in premodes	        batteryCheck(0, false);//,textPanelReport);
            //	if (bValidExtraInfo)
            {
                if (batteryPercentage >= 0)
                {
                    StatusLog("Bat:" + progressBar(batteryPercentage), textPanelReport);
                }
                if (oxyPercent >= 0)
                {
                    StatusLog("O2:" + progressBar(oxyPercent * 100), textPanelReport);
                    //Echo("O:" + oxyPercent.ToString("000.0%"));
                }
                else
                {
                    Echo("No Oxygen Tanks");
                }

                if (hydroPercent >= 0)
                {
                    StatusLog("Hyd:" + progressBar(hydroPercent * 100), textPanelReport);
                    //                   Echo("H:" + (hydroPercent*100).ToString("0.0") + "%");
                    if (hydroPercent < 0.20f)
                    {
                        StatusLog(" WARNING: Low Hydrogen Supplies", textPanelReport);
                    }
                }
                else
                {
                    Echo("No Hydrogen Tanks");
                }
                if (batteryPercentage >= 0 && batteryPercentage < batterypctlow)
                {
                    StatusLog(" WARNING: Low Battery Power", textPanelReport);
                }

                //		if (iOxygenTanks > 0) StatusLog("O2:" + progressBar(tanksFill(iTankOxygen)), textPanelReport);
                //		if (iHydroTanks > 0) StatusLog("Hyd:" + progressBar(tanksFill(iTankHydro)), textPanelReport);
            }

            if (dGravity <= 0)
            {
                setMode(MODE_INSPACE);
                gyrosOff();
                StatusLog("clear", textPanelReport);
            }
        }
Ejemplo n.º 6
0
        internal bool GetTargetState(Session s)
        {
            var ai            = s.TrackingAi;
            var validFocus    = false;
            var maxNameLength = 18;

            if (s.Tick - MasterUpdateTick > 300 || MasterUpdateTick < 300 && _masterTargets.Count == 0)
            {
                BuildMasterCollections(ai);
            }

            for (int i = 0; i < ai.Construct.Data.Repo.FocusData.Target.Length; i++)
            {
                var targetId = ai.Construct.Data.Repo.FocusData.Target[i];
                MyTuple <float, TargetControl> targetInfo;
                MyEntity target;
                if (targetId <= 0 || !MyEntities.TryGetEntityById(targetId, out target) || !_masterTargets.TryGetValue(target, out targetInfo) || ai.NoTargetLos.ContainsKey(target))
                {
                    continue;
                }
                validFocus = true;
                if (!s.Tick20)
                {
                    continue;
                }
                var    grid      = target as MyCubeGrid;
                var    partCount = 1;
                var    largeGrid = false;
                GridAi targetAi  = null;
                if (grid != null)
                {
                    largeGrid = grid.GridSizeEnum == MyCubeSize.Large;
                    GridMap gridMap;
                    if (s.GridToMasterAi.TryGetValue(grid, out targetAi))
                    {
                        partCount = targetAi.Construct.BlockCount;
                    }
                    else if (s.GridToInfoMap.TryGetValue(grid, out gridMap))
                    {
                        partCount = gridMap.MostBlocks;
                    }
                }

                var state = ai.TargetState[i];

                state.Aware = targetAi != null?AggressionState(ai, targetAi) : TargetStatus.Awareness.WONDERING;

                var displayName = target.DisplayName;

                var combinedName = TargetControllerNames[(int)targetInfo.Item2] + displayName;
                var name         = string.IsNullOrEmpty(combinedName) ? string.Empty : combinedName.Length <= maxNameLength ? combinedName : combinedName.Substring(0, maxNameLength);
                var targetVel    = target.Physics?.LinearVelocity ?? Vector3.Zero;
                if (MyUtils.IsZero(targetVel, 1E-01F))
                {
                    targetVel = Vector3.Zero;
                }
                var targetDir    = Vector3D.Normalize(targetVel);
                var targetRevDir = -targetDir;
                var targetPos    = target.PositionComp.WorldAABB.Center;
                var myPos        = ai.MyGrid.PositionComp.WorldAABB.Center;
                var myHeading    = Vector3D.Normalize(myPos - targetPos);

                var intercept = MathFuncs.IsDotProductWithinTolerance(ref targetDir, ref myHeading, s.ApproachDegrees);
                var retreat   = MathFuncs.IsDotProductWithinTolerance(ref targetRevDir, ref myHeading, s.ApproachDegrees);

                var distanceFromCenters = Vector3D.Distance(ai.MyGrid.PositionComp.WorldAABB.Center, target.PositionComp.WorldAABB.Center);
                distanceFromCenters -= ai.MyGrid.PositionComp.LocalVolume.Radius;
                distanceFromCenters -= target.PositionComp.LocalVolume.Radius;
                distanceFromCenters  = distanceFromCenters <= 0 ? 0 : distanceFromCenters;

                var speed = (float)Math.Round(target.Physics?.Speed ?? 0, 1);

                state.Name = name;

                state.RealDistance = distanceFromCenters;

                state.SizeExtended = (float)Math.Round(partCount / (largeGrid ? 100f : 500f), 1);

                state.Speed = speed;

                if (intercept)
                {
                    state.Engagement = 0;
                }
                else if (retreat)
                {
                    state.Engagement = 1;
                }
                else
                {
                    state.Engagement = 2;
                }

                MyTuple <bool, bool, float, float, float, int> shieldInfo = new MyTuple <bool, bool, float, float, float, int>();
                if (s.ShieldApiLoaded)
                {
                    shieldInfo = s.SApi.GetShieldInfo(target);
                }
                if (shieldInfo.Item1)
                {
                    var modInfo  = s.SApi.GetModulationInfo(target);
                    var modValue = MyUtils.IsEqual(modInfo.Item3, modInfo.Item4) ? 0 : modInfo.Item3 > modInfo.Item4 ? modInfo.Item3 : -modInfo.Item4;
                    var faceInfo = s.SApi.GetFacesFast(target);
                    state.ShieldFaces  = faceInfo.Item1 ? faceInfo.Item2 : Vector3I.Zero;
                    state.ShieldHeat   = shieldInfo.Item6 / 10;
                    state.ShieldMod    = modValue;
                    state.ShieldHealth = (float)Math.Round(shieldInfo.Item5);
                }
                else
                {
                    state.ShieldHeat   = 0;
                    state.ShieldMod    = 0;
                    state.ShieldHealth = -1;
                    state.ShieldFaces  = Vector3I.Zero;
                }

                var friend = false;
                if (grid != null && grid.BigOwners.Count != 0)
                {
                    var relation = MyIDModule.GetRelationPlayerBlock(ai.AiOwner, grid.BigOwners[0], MyOwnershipShareModeEnum.Faction);
                    if (relation == MyRelationsBetweenPlayerAndBlock.FactionShare || relation == MyRelationsBetweenPlayerAndBlock.Owner || relation == MyRelationsBetweenPlayerAndBlock.Friends)
                    {
                        friend = true;
                    }
                }

                if (friend)
                {
                    state.ThreatLvl = -1;
                }
                else
                {
                    int shieldBonus = 0;
                    if (s.ShieldApiLoaded)
                    {
                        var myShieldInfo = s.SApi.GetShieldInfo(ai.MyGrid);
                        if (shieldInfo.Item1 && myShieldInfo.Item1)
                        {
                            shieldBonus = shieldInfo.Item5 > myShieldInfo.Item5 ? 1 : -1;
                        }
                        else if (shieldInfo.Item1)
                        {
                            shieldBonus = 1;
                        }
                        else if (myShieldInfo.Item1)
                        {
                            shieldBonus = -1;
                        }
                    }

                    if (targetInfo.Item1 > 5)
                    {
                        state.ThreatLvl = shieldBonus < 0 ? 8 : 9;
                    }
                    else if (targetInfo.Item1 > 4)
                    {
                        state.ThreatLvl = 8 + shieldBonus;
                    }
                    else if (targetInfo.Item1 > 3)
                    {
                        state.ThreatLvl = 7 + shieldBonus;
                    }
                    else if (targetInfo.Item1 > 2)
                    {
                        state.ThreatLvl = 6 + shieldBonus;
                    }
                    else if (targetInfo.Item1 > 1)
                    {
                        state.ThreatLvl = 5 + shieldBonus;
                    }
                    else if (targetInfo.Item1 > 0.5)
                    {
                        state.ThreatLvl = 4 + shieldBonus;
                    }
                    else if (targetInfo.Item1 > 0.25)
                    {
                        state.ThreatLvl = 3 + shieldBonus;
                    }
                    else if (targetInfo.Item1 > 0.125)
                    {
                        state.ThreatLvl = 2 + shieldBonus;
                    }
                    else if (targetInfo.Item1 > 0.0625)
                    {
                        state.ThreatLvl = 1 + shieldBonus;
                    }
                    else if (targetInfo.Item1 > 0)
                    {
                        state.ThreatLvl = shieldBonus > 0 ? 1 : 0;
                    }
                    else
                    {
                        state.ThreatLvl = -1;
                    }
                }
            }
            return(validFocus);
        }
Ejemplo n.º 7
0
 bool NearDest(RoboticArm arm, Vector3D dest)
 => Vector3D.Distance(arm.Tip.GetPosition(), dest) < 0.3;
        // /admin movefrom x y z x y z radius
        public override bool HandleCommand(ulong userId, string command)
        {
            string[] words = command.Split(' ');
            if (words.Count( ) < 2)
            {
                Communication.SendPrivateInformation(userId, GetHelp());
                return(true);
            }

            string sourceName = words[0];
            float  distance   = 50f;

            // TODO Allow quotes so we can do distance?
            bool parse = false;

            if (words.Count() > 2)
            {
                parse = float.TryParse(words[words.Count() - 1], out distance);
            }

            string targetName;

            if (parse)
            {
                targetName = string.Join(" ", words.Skip(1).Take(words.Count() - 2).ToArray());
            }
            else
            {
                targetName = string.Join(" ", words.Skip(1).ToArray());
            }

            IMyEntity entity = Player.FindControlledEntity(targetName);

            if (entity == null)
            {
                entity = CubeGrids.Find(targetName);
                if (entity == null)
                {
                    Communication.SendPrivateInformation(userId, string.Format("Can not find user or grid with the name: {0}", targetName));
                    return(true);
                }
            }

            Vector3D position = entity.GetPosition();

            Communication.SendPrivateInformation(userId, string.Format("Trying to move {0} to within {1}m of {2}.  This may take about 20 seconds.", sourceName, distance, targetName));
            Vector3D startPosition = MathUtility.RandomPositionFromPoint((Vector3)position, distance);

            if (!Player.Move(sourceName, startPosition))
            {
                Communication.SendPrivateInformation(userId, string.Format("Can not move user: {0} (Is user in a cockpit or not in game?)", sourceName));
                return(true);
            }

            Communication.SendPrivateInformation(userId, string.Format("Moved {0} to within {1}m of {2}", sourceName, (int)Math.Round(Vector3D.Distance(startPosition, position)), targetName));
            return(true);
        }
 public static float DistanceVector3D(Vector3D posA, Vector3D posB)
 {
     return((float)Vector3D.Distance(posA, posB));
 }
Ejemplo n.º 10
0
        public double Distance(Vector3D point)
        {
            var clamp = Vector3D.Clamp(point, Min, Max);

            return(Vector3D.Distance(clamp, point));
        }
Ejemplo n.º 11
0
 private float Heuristic(MyNavigationPrimitive primitive)
 {
     return((float)Vector3D.Distance(primitive.WorldPosition, m_destinationCenter));
 }
Ejemplo n.º 12
0
        public static bool GetSpawnCoords(ImprovedSpawnGroup spawnGroup, Vector3D startCoords, out Vector3D spawnCoords)
        {
            spawnCoords = Vector3D.Zero;
            SpawnResources.RefreshEntityLists();
            MyPlanet planet = SpawnResources.GetNearestPlanet(spawnCoords);

            for (int i = 0; i < Settings.RandomEncounters.SpawnAttempts; i++)
            {
                var spawnDir        = Vector3D.Normalize(MyUtils.GetRandomVector3D());
                var randDist        = (double)SpawnResources.rnd.Next((int)Settings.RandomEncounters.MinSpawnDistanceFromPlayer, (int)Settings.RandomEncounters.MaxSpawnDistanceFromPlayer);
                var tempSpawnCoords = spawnDir * randDist + startCoords;

                if (SpawnResources.IsPositionInGravity(tempSpawnCoords, planet) == true)
                {
                    spawnDir       *= -1;
                    tempSpawnCoords = spawnDir * randDist + startCoords;

                    if (SpawnResources.IsPositionInGravity(tempSpawnCoords, planet) == true)
                    {
                        continue;
                    }
                }

                var tempMatrix = MatrixD.CreateWorld(tempSpawnCoords);
                var badPath    = false;

                foreach (var prefab in spawnGroup.SpawnGroup.Prefabs)
                {
                    var prefabCoords = Vector3D.Transform((Vector3D)prefab.Position, tempMatrix);
                    planet = SpawnResources.GetNearestPlanet(prefabCoords);

                    foreach (var entity in SpawnResources.EntityList)
                    {
                        if (Vector3D.Distance(entity.GetPosition(), prefabCoords) < Settings.RandomEncounters.MinDistanceFromOtherEntities)
                        {
                            badPath = true;
                            break;
                        }
                    }

                    if (SpawnResources.IsPositionInSafeZone(prefabCoords) == true || SpawnResources.IsPositionInGravity(prefabCoords, planet) == true)
                    {
                        badPath = true;
                        break;
                    }

                    if (badPath == true)
                    {
                        break;
                    }
                }

                if (badPath == true)
                {
                    continue;
                }

                spawnCoords = tempSpawnCoords;
                return(true);
            }

            return(false);
        }
Ejemplo n.º 13
0
        private void PathClear(ref Vector3D destination, byte runId, bool isAlternate, bool slowDown)
        {
            if (runId == m_runId)
            {
                if (isAlternate)
                {
                    LineSegment line = new LineSegment()
                    {
                        From = destination, To = m_destination
                    };
                    float distToWaypoint = (float)Vector3D.Distance(m_navBlock.WorldPosition, destination);
                    float pathValue      = m_pathChecker.distanceCanTravel(line) + distToWaypoint * WaypointDistanceBias;
                    m_logger.debugLog("for point: " + line.From + ", waypoint distance: " + (float)Vector3D.Distance(m_navBlock.WorldPosition, destination) + ", path value: " + pathValue + ", required: " + m_altPath_PathValue, Logger.severity.TRACE);

                    if (!AddAlternatePath(pathValue, ref destination))
                    {
                        m_logger.debugLog("throwing out: " + line.From + ", path value: " + pathValue + ", required: " + m_altPath_PathValue, Logger.severity.TRACE);
                    }

                    return;
                }
                if (slowDown)
                {
                    //m_logger.debugLog("Removing speed limit", "PathClear()");
                    m_navSet.Settings_Task_NavWay.SpeedMaxRelative = float.MaxValue;
                    m_navSet.Settings_Task_NavWay.SpeedTarget      = float.MaxValue;
                    return;
                }
                m_logger.debugLog("path clear, throwing out search", Logger.severity.DEBUG, condition: m_pathLow.Count != 0);
                MoveObstruction = null;
                m_pathState     = PathState.No_Obstruction;
                m_pathLow.Clear();
            }
            else
            {
                m_logger.debugLog("destination changed, abort", Logger.severity.DEBUG);
            }
            return;
        }
Ejemplo n.º 14
0
        private void CalculateNextCue()
        {
            if (MySession.Static == null || MySession.Static.LocalCharacter == null)
            {
                return;
            }
            m_noMusicTimer = m_random.Next(DEFAULT_NO_MUSIC_TIME_MIN, DEFAULT_NO_MUSIC_TIME_MAX);

            //planet or space
            Vector3D pos    = MySession.Static.LocalCharacter.PositionComp.GetPosition();
            MyPlanet planet = MyGravityProviderSystem.GetNearestPlanet(pos);

            if (planet != null && Vector3D.Distance(pos, planet.PositionComp.GetPosition()) <= planet.GravityLimit * 0.65f)
            {
                if (planet != m_lastVisitedPlanet)
                {
                    m_lastVisitedPlanet = planet;
                    if (planet.Generator.MusicCategories != null && planet.Generator.MusicCategories.Count > 0)
                    {
                        m_actualMusicOptions.Clear();
                        foreach (var option in planet.Generator.MusicCategories)
                        {
                            m_actualMusicOptions.Add(new MusicOption(option.Category, option.Frequency));
                        }
                    }
                    else
                    {
                        m_actualMusicOptions = m_defaultPlanetCategory;
                    }
                }
            }
            else
            {
                m_lastVisitedPlanet  = null;
                m_actualMusicOptions = m_defaultSpaceCategories;
            }

            //choose category based on frequency
            float sum = 0f;

            foreach (var option in m_actualMusicOptions)
            {
                sum += Math.Max(option.Frequency, 0f);
            }
            float      r        = (float)m_random.NextDouble() * sum;
            MyStringId selected = m_actualMusicOptions[0].Category;

            for (int i = 0; i < m_actualMusicOptions.Count; i++)
            {
                if (r <= m_actualMusicOptions[i].Frequency)
                {
                    selected = m_actualMusicOptions[i].Category;
                    break;
                }
                else
                {
                    r -= m_actualMusicOptions[i].Frequency;
                }
            }

            //pick from cue list and play
            CueIdPlaying    = SelectCueFromCategory(selected);
            CategoryPlaying = selected;

            if (CueIdPlaying == m_cueEmpty)
            {
                return;
            }

            PlayMusic(CueIdPlaying, MyStringHash.NullOrEmpty);
            m_currentMusicCategory = MusicCategory.location;
        }
Ejemplo n.º 15
0
        public void Wormholetransferout(string name, string sendto, double xgate, double ygate, double zgate)
        {
            Vector3D        gatepoint = new Vector3D(xgate, ygate, zgate);
            BoundingSphereD gate      = new BoundingSphereD(gatepoint, Config.RadiusGate);

            foreach (var entity in MyAPIGateway.Entities.GetTopMostEntitiesInSphere(ref gate))
            {
                var grid = (entity as IMyCubeGrid);
                if (grid != null)
                {
                    var WormholeDrives = new List <IMyJumpDrive>();
                    Log.Warn("test a");
                    var gts = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(grid);
                    gts.GetBlocksOfType(WormholeDrives);
                    if (WormholeDrives.Count > 0)
                    {
                        foreach (var WormholeDrive in WormholeDrives)
                        {
                            if (Config.JumpDriveSubid.Split(',').Any(s => s.Trim() == WormholeDrive.BlockDefinition.SubtypeId) || Config.WorkWithAllJD)
                            {
                                Request request = null;
                                try
                                {
                                    request = MyAPIGateway.Utilities.SerializeFromXML <Request>(WormholeDrive.CustomData);
                                }
                                catch { }
                                string pickeddestination = null;
                                if (request != null)
                                {
                                    if (request.PluginRequest)
                                    {
                                        if (request.Destination != null)
                                        {
                                            if (sendto.Split(',').Any(s => s.Trim() == request.Destination.Trim()))
                                            {
                                                pickeddestination = request.Destination.Trim();
                                            }
                                        }
                                        Request reply = new Request
                                        {
                                            PluginRequest = false,
                                            Destination   = null,
                                            Destinations  = sendto.Split(',').Select(s => s.Trim()).ToArray()
                                        };
                                        WormholeDrive.CustomData = MyAPIGateway.Utilities.SerializeToXML <Request>(reply);
                                    }
                                }
                                else
                                {
                                    Request reply = new Request
                                    {
                                        PluginRequest = false,
                                        Destination   = null,
                                        Destinations  = sendto.Split(',').Select(s => s.Trim()).ToArray()
                                    };
                                    WormholeDrive.CustomData = MyAPIGateway.Utilities.SerializeToXML <Request>(reply);
                                }
                                if (Config.AutoSend && sendto.Split(',').Length == 1)
                                {
                                    pickeddestination = sendto.Split(',')[0].Trim();
                                }
                                if (pickeddestination != null)
                                {
                                    if (WormholeDrive.IsWorking && WormholeDrive.CurrentStoredPower == WormholeDrive.MaxStoredPower)
                                    {
                                        var playerInCharge = MyAPIGateway.Players.GetPlayerControllingEntity(entity);
                                        if (playerInCharge != null && HasRightToMove(playerInCharge, entity as MyCubeGrid))
                                        {
                                            WormholeDrive.CurrentStoredPower = 0;
                                            foreach (var DisablingWormholeDrive in WormholeDrives)
                                            {
                                                if (Config.JumpDriveSubid.Split(',').Any(s => s.Trim() == DisablingWormholeDrive.BlockDefinition.SubtypeId) || Config.WorkWithAllJD)
                                                {
                                                    DisablingWormholeDrive.Enabled = false;
                                                }
                                            }
                                            List <MyCubeGrid> grids = GridFinder.FindGridList(grid.EntityId.ToString(), playerInCharge as MyCharacter, Config.IncludeConnectedGrids);
                                            if (grids == null)
                                            {
                                                return;
                                            }
                                            if (grids.Count == 0)
                                            {
                                                return;
                                            }
                                            Sandbox.Game.MyVisualScriptLogicProvider.CreateLightning(gatepoint);

                                            //NEED TO DROP ENEMY GRIDS
                                            if (Config.WormholeGates.Any(s => s.Name.Trim() == pickeddestination.Split(':')[0]))
                                            {
                                                foreach (WormholeGate internalwormhole in Config.WormholeGates)
                                                {
                                                    if (internalwormhole.Name.Trim() == pickeddestination.Split(':')[0].Trim())
                                                    {
                                                        var box         = WormholeDrive.GetTopMostParent().WorldAABB;
                                                        var togatepoint = new Vector3D(internalwormhole.X, internalwormhole.Y, internalwormhole.Z);
                                                        var togate      = new BoundingSphereD(togatepoint, Config.RadiusGate);
                                                        Utilities.UpdateGridsPositionAndStopLive(WormholeDrive.GetTopMostParent(), Utilities.FindFreePos(togate, (float)(Vector3D.Distance(box.Center, box.Max) + 50)));
                                                        Sandbox.Game.MyVisualScriptLogicProvider.CreateLightning(togatepoint);
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                var destination = pickeddestination.Split(':');
                                                var filename    = destination[0] + "_" + playerInCharge.SteamUserId.ToString() + "_" + LegalCharOnly(playerInCharge.DisplayName) + "_" + LegalCharOnly(grid.DisplayName) + "_" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss");

                                                List <MyObjectBuilder_CubeGrid> objectBuilders = new List <MyObjectBuilder_CubeGrid>();
                                                foreach (MyCubeGrid mygrid in grids)
                                                {
                                                    if (!(grid.GetObjectBuilder(true) is MyObjectBuilder_CubeGrid objectBuilder))
                                                    {
                                                        throw new ArgumentException(mygrid + " has a ObjectBuilder thats not for a CubeGrid");
                                                    }
                                                    objectBuilders.Add(objectBuilder);
                                                }
                                                MyObjectBuilder_ShipBlueprintDefinition definition = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ShipBlueprintDefinition>();
                                                definition.Id        = new MyDefinitionId(new MyObjectBuilderType(typeof(MyObjectBuilder_ShipBlueprintDefinition)), filename);
                                                definition.CubeGrids = objectBuilders.Select(x => (MyObjectBuilder_CubeGrid)x.Clone()).ToArray();
                                                List <ulong> playerIds = new List <ulong>();
                                                foreach (MyObjectBuilder_CubeGrid cubeGrid in definition.CubeGrids)
                                                {
                                                    foreach (MyObjectBuilder_CubeBlock cubeBlock in cubeGrid.CubeBlocks)
                                                    {
                                                        if (!Config.KeepOriginalOwner)
                                                        {
                                                            cubeBlock.Owner   = 0L;
                                                            cubeBlock.BuiltBy = 0L;
                                                        }
                                                        if (!Config.ExportProjectorBlueprints)
                                                        {
                                                            if (cubeBlock is MyObjectBuilder_ProjectorBase projector)
                                                            {
                                                                projector.ProjectedGrids = null;
                                                            }
                                                        }
                                                        if (cubeBlock is MyObjectBuilder_Cockpit cockpit)
                                                        {
                                                            if (cockpit.Pilot != null)
                                                            {
                                                                var playersteam = cockpit.Pilot.PlayerSteamId;
                                                                var player      = PlayerUtils.GetIdentityByNameOrId(playersteam.ToString());
                                                                playerIds.Add(playersteam);
                                                                ModCommunication.SendMessageTo(new JoinServerMessage(destination[1] + ":" + destination[2]), playersteam);
                                                            }
                                                        }
                                                    }
                                                }

                                                MyObjectBuilder_Definitions builderDefinition = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Definitions>();
                                                builderDefinition.ShipBlueprints = new MyObjectBuilder_ShipBlueprintDefinition[] { definition };
                                                foreach (var playerId in playerIds)
                                                {
                                                    var player = PlayerUtils.GetIdentityByNameOrId(playerId.ToString());
                                                    player.Character.EnableBag(false);
                                                    Sandbox.Game.MyVisualScriptLogicProvider.SetPlayersHealth(player.IdentityId, 0);
                                                    player.Character.Close();
                                                }
                                                if (MyObjectBuilderSerializer.SerializeXML(CreatePath(Config.Folder + "/" + admingatesfolder, filename), false, builderDefinition))
                                                {
                                                    foreach (var delgrid in grids)
                                                    {
                                                        delgrid.Close();
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        public EnvironmentEvaluation(Vector3D coords) : base()
        {
            //Non Planet Checks
            DistanceFromWorldCenter  = Vector3D.Distance(Vector3D.Zero, coords);
            DirectionFromWorldCenter = Vector3D.Normalize(coords);

            InsideTerritories       = new List <string>();
            InsideStrictTerritories = new List <string>();

            //Planet Checks
            NearestPlanet = SpawnResources.GetNearestPlanet(coords, true);

            if (NearestPlanet == null || !MyAPIGateway.Entities.Exist(NearestPlanet))
            {
                return;
            }

            AltitudeAtPosition = Vector3D.Distance(NearestPlanet.GetClosestSurfacePointGlobal(coords), coords);
            NearestPlanetName  = NearestPlanet.Generator.Id.SubtypeName;
            PlanetDiameter     = NearestPlanet.AverageRadius * 2;

            var planetEntity    = NearestPlanet as IMyEntity;
            var gravityProvider = planetEntity.Components.Get <MyGravityProviderComponent>();

            if (gravityProvider != null)
            {
                if (gravityProvider.IsPositionInRange(coords) == true)
                {
                    IsOnPlanet = true;
                }
            }

            if (!IsOnPlanet)
            {
                return;
            }

            //On Planet Checks
            GravityAtPosition    = gravityProvider.GetGravityMultiplier(coords);
            AtmosphereAtPosition = NearestPlanet.GetAirDensity(coords);
            OxygenAtPosition     = NearestPlanet.GetOxygenForPosition(coords);
            IsNight           = MyVisualScriptLogicProvider.IsOnDarkSide(NearestPlanet, coords);
            WeatherAtPosition = MyVisualScriptLogicProvider.GetWeather(coords) ?? "";

            //Terrain Material Checks
            var upDir         = Vector3D.Normalize(coords - NearestPlanet.PositionComp.WorldAABB.Center);
            var downDir       = upDir * -1;
            var forward       = Vector3D.CalculatePerpendicularVector(upDir);
            var matrix        = MatrixD.CreateWorld(coords, forward, upDir);
            var directionList = new List <Vector3D>();

            directionList.Add(matrix.Forward);
            directionList.Add(matrix.Backward);
            directionList.Add(matrix.Left);
            directionList.Add(matrix.Right);

            var terrainTypes = new Dictionary <string, int>();

            for (int i = 1; i < 12; i++)
            {
                foreach (var direction in directionList)
                {
                    try {
                        var checkCoordsRough   = direction * (i * 15) + coords;
                        var checkSurfaceCoords = NearestPlanet.GetClosestSurfacePointGlobal(checkCoordsRough);
                        var checkMaterial      = NearestPlanet.GetMaterialAt(ref checkSurfaceCoords);

                        if (checkMaterial == null)
                        {
                            continue;
                        }

                        if (terrainTypes.ContainsKey(checkMaterial.MaterialTypeName))
                        {
                            terrainTypes[checkMaterial.MaterialTypeName]++;
                        }
                        else
                        {
                            terrainTypes.Add(checkMaterial.MaterialTypeName, 1);
                        }
                    } catch (Exception e) {
                        Logger.AddMsg("Caught Exception Trying To Determine Terrain Material", true);
                        Logger.AddMsg(e.ToString(), true);
                    }
                }
            }

            string highestCountName   = "";
            int    highestCountNumber = 0;

            foreach (var material in terrainTypes.Keys)
            {
                if (string.IsNullOrWhiteSpace(highestCountName) || terrainTypes[material] > highestCountNumber)
                {
                    highestCountName   = material;
                    highestCountNumber = terrainTypes[material];
                }
            }

            if (!string.IsNullOrWhiteSpace(highestCountName))
            {
                CommonTerrainAtPosition = highestCountName;
            }
        }
Ejemplo n.º 17
0
 public void Set()
 {
     Length = (float)Vector3D.Distance(From, To);
     DirectionNormalized = Vector3.Normalize(To - From);
 }
Ejemplo n.º 18
0
        //  Draw the projectile but only if desired polyline trail distance can fit in the trajectory (otherwise we will see polyline growing from the origin and it's ugly).
        //  Or draw if this is last draw of this projectile (useful for short-distance shots).
        public void Draw()
        {
            const float PROJECTILE_POLYLINE_DESIRED_LENGTH = 120;

            //var velPerFrame = m_velocity * VRage.Game.MyEngineConstants.PHYSICS_STEP_SIZE_IN_SECONDS;
            //for (int i = 0; i < 70; i += 5)
            //{
            //    Color col = new Color(255, 0, i * 5, 255);
            //    VRageRender.MyRenderProxy.DebugDrawLine3D(m_position + i * velPerFrame, m_position + i * velPerFrame + 5 * velPerFrame, col, Color.Yellow, false);
            //}

            double trajectoryLength = Vector3D.Distance(m_position, m_origin);

            if ((trajectoryLength > 0) || (m_state == MyProjectileStateEnum.KILLED))
            {
                if (m_state == MyProjectileStateEnum.KILLED)
                {
                    m_state = MyProjectileStateEnum.KILLED_AND_DRAWN;
                }

                if (!m_positionChecked)
                {
                    return;
                }

                //  If we calculate previous position using normalized direction (insted of velocity), projectile trails will
                //  look like coming from cannon, and that is desired. Even during fast movement, acceleration, rotation or changes in movement directions.
                //Vector3 previousPosition = m_position - m_directionNormalized * projectileTrailLength * 1.05f;
                Vector3D previousPosition = m_position - m_directionNormalized * PROJECTILE_POLYLINE_DESIRED_LENGTH * VRage.Game.MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS;
                //Vector3 previousPosition = m_previousPosition;
                //Vector3 previousPosition = m_initialSunWindPosition - MyMwcUtils.Normalize(m_desiredVelocity) * projectileTrailLength;

                Vector3D direction = Vector3D.Normalize(m_position - previousPosition);

                double projectileTrailLength = LengthMultiplier * m_projectileAmmoDefinition.ProjectileTrailScale;// PROJECTILE_POLYLINE_DESIRED_LENGTH;

                projectileTrailLength *= MyUtils.GetRandomFloat(0.6f, 0.8f);

                if (trajectoryLength < projectileTrailLength)
                {
                    projectileTrailLength = trajectoryLength;
                }

                previousPosition = m_position - projectileTrailLength * direction;


                //float color = MyMwcUtils.GetRandomFloat(1, 2);
                float color     = MyUtils.GetRandomFloat(1, 2);
                float thickness = MyUtils.GetRandomFloat(0.2f, 0.3f) * m_projectileAmmoDefinition.ProjectileTrailScale;

                //  Line particles (polyline) don't look good in distance. Start and end aren't rounded anymore and they just
                //  look like a pieces of paper. Especially when zoom-in.
                thickness *= MathHelper.Lerp(0.2f, 0.8f, MySector.MainCamera.Zoom.GetZoomLevel());

                float alphaCone = 1;

                if (projectileTrailLength > 0)
                {
                    if (m_projectileAmmoDefinition.ProjectileTrailMaterial != null)
                    {
                        MyTransparentGeometry.AddLineBillboard(m_projectileAmmoDefinition.ProjectileTrailMaterial, new Vector4(m_projectileAmmoDefinition.ProjectileTrailColor, 1),
                                                               previousPosition, direction, (float)projectileTrailLength, thickness);
                    }
                    else
                    {
                        MyTransparentGeometry.AddLineBillboard("ProjectileTrailLine", new Vector4(m_projectileAmmoDefinition.ProjectileTrailColor * color, 1) * alphaCone,
                                                               previousPosition, direction, (float)projectileTrailLength, thickness);
                    }
                }
            }
        }
Ejemplo n.º 19
0
 public bool CheckReceivedCoordinates(ref Vector3D pos)
 {
     if (m_jumpTimeLeft > 20)
     {
         return(true);
     }
     if (Vector3D.DistanceSquared(m_grid.PositionComp.GetPosition(), pos) > 10000 * 10000)
     {
         //most likely comes from packet created before jump
         MySandboxGame.Log.WriteLine(string.Format("Wrong position packet received, dist={0}, T={1})", Vector3D.Distance(m_grid.PositionComp.GetPosition(), pos), m_jumpTimeLeft));
         return(false);
     }
     return(true);
 }
Ejemplo n.º 20
0
        private bool affectEnemyBlocks()
        {
            bool done = true;

            scanArea = scanRange.TransformSlow(thisBlock.WorldMatrix);
            List <IMyEntity> entityList = null;

            lock (MyAPIGateway.Entities) {  // Scan for nearby entities (grids)
                entityList = MyAPIGateway.Entities.GetElementsInBox(ref scanArea);
            }

            if (entityList != null)
            {
                List <IMySlimBlock> gridBlocks = new List <IMySlimBlock>();
                foreach (IMyEntity entity in entityList)
                {
                    try {
                        if (entity is IMyCubeGrid)
                        {
                            IMyCubeGrid grid = entity as IMyCubeGrid;
                            if (isEnemyGrid(grid))
                            {
                                gridBlocks.Clear();
                                grid.GetBlocks(gridBlocks, b => b.FatBlock is IMyTerminalBlock && (b.FatBlock as IMyTerminalBlock).IsWorking && isEnemyBlock(b.FatBlock));
                                //MyAPIGateway.Utilities.ShowNotification("Found grid #"+i+" named "+grid.Name+" & "+grid.GetFriendlyName()+", ID="+grid.EntityId+"; size = "+grid.GridSizeEnum+", owners = "+grid.SmallOwners.ToString()+", grid elements = "+gridBlocks.ToString(), 5000, MyFontEnum.Red);
                                foreach (IMySlimBlock slim in gridBlocks)
                                {
                                    IMyTerminalBlock block    = slim.FatBlock as IMyTerminalBlock;
                                    EMPReaction      reaction = Configuration.getEMPReaction(block);
                                    if (reaction != null)
                                    {
                                        bool share = thisGrid == grid;
                                        if (rand.Next(100) >= (share ? reaction.ResistanceSameGrid : reaction.Resistance))
                                        {
                                            bool   inRange  = reaction.InfRangeSharedGrid;
                                            double distance = reaction.InfRangeSharedGrid ? 0 : Vector3D.Distance(thisBlock.GetPosition(), block.GetPosition());
                                            if (!inRange)
                                            {
                                                double d = reaction.MaxDistance;
                                                if (share)
                                                {
                                                    //MyAPIGateway.Utilities.ShowNotification("boosting range (from "+d+" by "+reaction.SameGridBoost+"x) due to grid sharing ("+emp_grid.EntityId+"/"+emp_grid.GridSizeEnum+" & "+grid.EntityId+"/"+grid.GridSizeEnum+") for block "+block.CustomName+" @ "+distance, 5000, MyFontEnum.Red);
                                                    d *= reaction.SameGridBoost;
                                                }
                                                else
                                                {
                                                    //MyAPIGateway.Utilities.ShowNotification("Not boosting range (from "+d+", using native "+distanceMultiplier+"x instead); no grid sharing ("+emp_grid.EntityId+"/"+emp_grid.GridSizeEnum+" & "+grid.EntityId+"/"+grid.GridSizeEnum+") for block "+block.CustomName+" @ "+distance, 5000, MyFontEnum.Red);
                                                    d *= distanceMultiplier;
                                                }
                                                inRange = distance < d;
                                            }
                                            if (inRange)
                                            {
                                                done &= empBlock(slim, block, distance, share, reaction, !(block is IMyFunctionalBlock), false);
                                            }
                                            else
                                            {
                                                //MyAPIGateway.Utilities.ShowNotification("Not EMPing block "+block.CustomName+" @ "+distance+"; out of range", 5000, MyFontEnum.Red);
                                            }
                                        }
                                        else if (reaction.Resistance < 100)
                                        {
                                            done = false;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex) {
                        //MyAPIGateway.Utilities.ShowNotification("Could not run EMP cycle: "+ex.ToString(), 5000, MyFontEnum.Red);
                        IO.log("Could not run EMP cycle: " + ex.ToString());
                    }
                }
            }
            return(done);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Draws location marker on screen.
        /// </summary>
        public void DrawLocationMarker(int styleHandle, Vector3D position, MyHudEntityParams hudParams, float targetDamageRatio, float targetArmorRatio, float alphaMultiplifier = 1f)
        {
            if (MySession.Static.ControlledEntity == null)
            {
                return;
            }

            //  Transform point to camera space, so Z = -1 is always forward and then do projective transformation
            Vector3D transformedPoint = Vector3D.Transform(position, MySector.MainCamera.ViewMatrix);
            Vector4D projectedPoint   = Vector4D.Transform(transformedPoint, MySector.MainCamera.ProjectionMatrix);

            //  If point is behind camera we swap X and Y (this is mirror-like transformation)
            if (transformedPoint.Z > 0)
            {
                projectedPoint.X *= -1;
                projectedPoint.Y *= -1;
            }

            if (projectedPoint.W == 0)
            {
                return;
            }

            MyMarkerStyle markerStyle = m_markerStyles[styleHandle];

            double distance         = Vector3D.Distance(position, MySession.Static.ControlledEntity.Entity.WorldMatrix.Translation);
            float  maxDistance      = hudParams.MaxDistance;
            byte   colorAlphaInByte = 255;
            var    hudColor         = MyFakes.SHOW_FACTIONS_GUI ? markerStyle.Color : Color.White;

            hudColor.A = (byte)(colorAlphaInByte * alphaMultiplifier);

            //  Calculate centered coordinates in range <0..1>
            Vector2 projectedPoint2D = new Vector2((float)(projectedPoint.X / projectedPoint.W / 2.0f) + 0.5f, (float)(-projectedPoint.Y / projectedPoint.W) / 2.0f + 0.5f);

            if (MyVideoSettingsManager.IsTripleHead())
            {
                projectedPoint2D.X = (projectedPoint2D.X - (1.0f / 3.0f)) / (1.0f / 3.0f);
            }

            float objectNameYOffset = 0.0f; //offset to direction indicator

            //  This will bound the rectangle in circle, although it isn't real circle because we work in [1,1] dimensions,
            //  but number of horizontal pixels is bigger, so at the end it's more elypse
            //  It must be done when point is out of circle or behind the camera
            Vector2 direction = projectedPoint2D - MyHudConstants.DIRECTION_INDICATOR_SCREEN_CENTER;

            if ((direction.Length() > MyHudConstants.DIRECTION_INDICATOR_MAX_SCREEN_DISTANCE) || (transformedPoint.Z > 0))
            {
                if ((hudParams.FlagsEnum & MyHudIndicatorFlagsEnum.SHOW_BORDER_INDICATORS) == 0)
                {
                    return;
                }

                if (direction.LengthSquared() > MyMathConstants.EPSILON_SQUARED)
                {
                    direction.Normalize();
                }
                else
                {
                    direction = new Vector2(1f, 0f);
                }
                projectedPoint2D = MyHudConstants.DIRECTION_INDICATOR_SCREEN_CENTER + direction * MyHudConstants.DIRECTION_INDICATOR_MAX_SCREEN_DISTANCE;

                //  Fix vertical scale
                projectedPoint2D.Y *= MyGuiManager.GetHudSize().Y;

                AddTexturedQuad(markerStyle.TextureDirectionIndicator, projectedPoint2D + direction * MyHudConstants.HUD_DIRECTION_INDICATOR_SIZE * 2.5f, direction,
                                hudColor, MyHudConstants.HUD_DIRECTION_INDICATOR_SIZE * 1.2f, MyHudConstants.HUD_DIRECTION_INDICATOR_SIZE * 0.8f);
            }
            else
            {
                //  Fix vertical scale
                projectedPoint2D.Y *= MyGuiManager.GetHudSize().Y;

                Color rectangleColor = Color.White;
                rectangleColor.A = colorAlphaInByte;

                if ((hudParams.FlagsEnum & MyHudIndicatorFlagsEnum.SHOW_FOCUS_MARK) > 0)
                {
                    Vector2 upVector = new Vector2(0, -1);
                    if (markerStyle.TextureTargetRotationSpeed != 0)
                    {
                        upVector = new Vector2((float)Math.Cos(MySandboxGame.TotalGamePlayTimeInMilliseconds / 1000f * markerStyle.TextureTargetRotationSpeed * MathHelper.Pi),
                                               (float)Math.Sin(MySandboxGame.TotalGamePlayTimeInMilliseconds / 1000f * markerStyle.TextureTargetRotationSpeed * MathHelper.Pi));
                    }

                    AddTexturedQuad(markerStyle.TextureTarget, projectedPoint2D, upVector, hudColor, MyHudConstants.HUD_DIRECTION_INDICATOR_SIZE * markerStyle.TextureTargetScale, MyHudConstants.HUD_DIRECTION_INDICATOR_SIZE * markerStyle.TextureTargetScale);
                }

                objectNameYOffset = -MyHudConstants.HUD_TEXTS_OFFSET;
            }

            if (hudParams.Text != null && hudParams.Text.Length > 0 && (hudParams.FlagsEnum & MyHudIndicatorFlagsEnum.SHOW_TEXT) != 0)
            {
                //  Add object's name
                MyHudText objectName = m_hudScreen.AllocateText();
                if (objectName != null)
                {
                    objectName.Start(markerStyle.Font, projectedPoint2D + new Vector2(0, hudParams.OffsetText ? objectNameYOffset : 0),
                                     hudColor, 0.8f, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER);
                    objectName.Append(hudParams.Text);
                }
            }

            // display hud icon
            if (hudParams.Icon != null && (hudParams.FlagsEnum & MyHudIndicatorFlagsEnum.SHOW_ICON) != 0)
            {
                Color iconColor = hudParams.IconColor.HasValue && MyFakes.SHOW_FACTIONS_GUI ? hudParams.IconColor.Value : Color.White;
                iconColor.A = (byte)(colorAlphaInByte * alphaMultiplifier);

                AddTexturedQuad(hudParams.Icon.Value, projectedPoint2D + hudParams.IconOffset, new Vector2(0, -1), iconColor, hudParams.IconSize.X / 2f, hudParams.IconSize.Y / 2f);
            }

            if (MyFakes.SHOW_HUD_DISTANCES && (hudParams.FlagsEnum & MyHudIndicatorFlagsEnum.SHOW_DISTANCE) != 0)
            {
                //  Add distance to object
                MyHudText objectDistance = m_hudScreen.AllocateText();
                if (objectDistance != null)
                {
                    objectDistance.Start(markerStyle.Font, projectedPoint2D + new Vector2(0, MyHudConstants.HUD_TEXTS_OFFSET),
                                         hudColor, 0.8f, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER);

                    // Create a string builder with the distance in metres, kilometres, light seconds or light years
                    if (distance > LY_METRES)
                    {
                        objectDistance.Append(Math.Round(distance / LY_METRES, 2).ToString());
                        objectDistance.Append("ly");
                    }
                    else if (distance > LS_METRES)
                    {
                        objectDistance.Append(Math.Round(distance / LS_METRES, 2).ToString());
                        objectDistance.Append("ls");
                    }
                    else if (distance > 1000)
                    {
                        objectDistance.Append(Math.Round(distance / 1000, 2).ToString());
                        objectDistance.Append("km");
                    }
                    else
                    {
                        objectDistance.Append(Math.Round(distance, 2).ToString());
                        objectDistance.Append("m");
                    }
                }
            }
        }
Ejemplo n.º 22
0
            public void DebugDraw()
            {
                //if (m_lodIndex > 5)
                //    return;


                //            if (m_lodIndex == 1)
                //            {
                //                float sizeInMetres = MyVoxelCoordSystems.RenderCellSizeInMeters(m_lodIndex);

                //                //var start = localFarCameraBox.Min;
                //                //var end = localFarCameraBox.Max;
                //                var start = m_localNearCameraBox.Min;
                //                var end = m_localNearCameraBox.Max;
                //                Vector3I coord = start;

                //                Color nearColor = Color.Yellow;
                //                Color farColor = Color.White;

                //                var startF = m_localFarCameraBox.Min;
                //                var endF = m_localFarCameraBox.Max;
                //                Vector3I coordF = startF;

                ////                for (var it = new Vector3I_RangeIterator(ref startF, ref endF);
                ////it.IsValid(); it.GetNext(out coordF))
                ////                {
                ////                    Vector3D min = Vector3D.Transform((Vector3D)(sizeInMetres * coordF), m_parent.m_worldMatrix);
                ////                    Vector3D max = Vector3D.Transform((Vector3D)(sizeInMetres * coordF + new Vector3(sizeInMetres)), m_parent.m_worldMatrix);

                ////                    BoundingBoxD aabb = new BoundingBoxD(min, max);
                ////                    MyRenderProxy.DebugDrawAABB(aabb, farColor, 1, 1, false);

                ////                    if (Vector3D.Distance(CameraFrustumGetter().Matrix.Translation, aabb.Center) < 200)
                ////                        MyRenderProxy.DebugDrawText3D(aabb.Center, coordF.ToString(), farColor, 0.5f, false);
                ////                }


                //                for (var it = new Vector3I_RangeIterator(ref start, ref end);
                //it.IsValid(); it.GetNext(out coord))
                //                {
                //                    Vector3D min = Vector3D.Transform((Vector3D)(sizeInMetres * coord), m_clipmap.m_worldMatrix);
                //                    Vector3D max = Vector3D.Transform((Vector3D)(sizeInMetres * coord + new Vector3(sizeInMetres)), m_clipmap.m_worldMatrix);

                //                    BoundingBoxD aabb = new BoundingBoxD(min, max);
                //                    MyRenderProxy.DebugDrawAABB(aabb, nearColor, 1, 1, false);
                //                }


                //                Vector3D center = Vector3D.Transform(m_localPosition, m_clipmap.m_worldMatrix);

                //                MyRenderProxy.DebugDrawSphere(center, m_nearDistance, nearColor, 1, false);
                //                MyRenderProxy.DebugDrawSphere(center, m_farDistance, farColor, 1, false);

                //            }

                var camera = m_clipmap.LastCameraPosition;

                //if (m_lodIndex < 6)
                {
                    float sizeInMetres = MyVoxelCoordSystems.RenderCellSizeInMeters(m_lodIndex);
                    Color color        = LOD_COLORS[m_lodIndex] + new Vector4(0.2f);


                    foreach (var cell in m_storedCellData)
                    {
                        if (!cell.Value.InScene)
                        {
                            continue;
                        }

                        MyCellCoord cellStr = new MyCellCoord();
                        cellStr.SetUnpack(cell.Key);
                        var coordF = cellStr.CoordInLod;

                        Vector3D min = Vector3D.Transform((Vector3D)(sizeInMetres * coordF), m_clipmap.m_worldMatrix);
                        Vector3D max = Vector3D.Transform((Vector3D)(sizeInMetres * coordF + new Vector3(sizeInMetres)), m_clipmap.m_worldMatrix);

                        BoundingBoxD aabb     = new BoundingBoxD(min, max);
                        double       distance = Vector3D.Distance(camera, aabb.Center);
                        //if (distance < sizeInMetres * 4)
                        MyRenderProxy.DebugDrawAABB(aabb, color, 1, 1, true);
                        if (distance < sizeInMetres * 2)
                        {
                            MyRenderProxy.DebugDrawText3D(aabb.Center, String.Format("{0}:{1}", m_lodIndex, coordF.ToString()), color, 0.7f, false);
                        }
                    }

                    if (m_storedCellData.Count > 0)
                    {
                        Vector3D center = Vector3D.Transform(m_localPosition, m_clipmap.m_worldMatrix);
                        //MyRenderProxy.DebugDrawSphere(center, m_farDistance, color, 1, false);
                    }
                }
            }
Ejemplo n.º 23
0
        void doTechnikerCalcsandDisplay()
        {
            double stoppingDistance = calculateStoppingDistance(thrustBackwardList, velocityShip, 0);

            StringBuilder sb          = new StringBuilder();
            double        targetRange = 0; // no target

            //    StatusLog("clear", textPanelReport);
            StatusLog(OurName + " Control", textPanelReport);

            string output = "";

            output += "Velocity: " + velocityShip.ToString("N0") + "m/s";

            Echo(output);
            StatusLog(output, textPanelReport);

            if (bCreative)
            {
                Echo("Creative!");
            }
            //           Echo("Cargomult=" + cargoMult);

            sb.Clear();
            sb.AppendLine();


            if (bLongRange)
            {
                sb.Append("Long Range Scan Active");
            }
            else
            {
                sb.Append("Normal Range Scan Active");
            }
            sb.AppendLine();

            string s = "";

            if (lastDetectedInfo.IsEmpty())
            {
                sb.Append("No Target Found");
                sb.AppendLine();

                sb.Append("Next scanner Range: " + currentScan.ToString("N0") + " m");
                sb.AppendLine();

                StatusLog("clear", textRangeReport);
                StatusLog("No Target found", textRangeReport);
            }
            else
            {
                Echo("EntityID: " + lastDetectedInfo.EntityId);
                Echo("Name: " + lastDetectedInfo.Name);
                sb.Append("Name: " + lastDetectedInfo.Name);
                //sb.AppendLine();
                sb.Append(" - ");
                sb.Append("Type: " + lastDetectedInfo.Type);
                sb.AppendLine();
                sb.Append("Relationship: " + lastDetectedInfo.Relationship);
                if (lastDetectedInfo.HitPosition.HasValue && lastCamera != null)
                {
                    sb.AppendLine();
                    double distance = Vector3D.Distance(lastCamera.GetPosition(), lastDetectedInfo.HitPosition.Value);
                    if (lastDetectedInfo.Name == "Asteroid")
                    {
                        // calculate range to outter edge of boudning box of asteroid.
                        targetRange  = Vector3D.Distance(lastCamera.GetPosition(), lastDetectedInfo.Position);
                        targetRange -= lastDetectedInfo.BoundingBox.Size.X / 2; // half of bounding box.
                        Echo("adjTargetRange=" + targetRange.ToString("0.0"));
                    }
                    else
                    {
                        targetRange = distance;
                    }

                    if (distance > 1000)
                    {
                        s += (distance / 1000).ToString("RANGE:   0000.0km");
                    }
                    else
                    {
                        s += (distance).ToString("RANGE:     00000m ");
                    }


                    StatusLog("clear", textRangeReport);
                    StatusLog(s, textRangeReport);

                    sb.Append("Distance: " + niceDoubleMeters(distance));
                    sb.AppendLine();

                    sb.Append("Safe Range: " + niceDoubleMeters(targetRange));
                    sb.AppendLine();
                }
                //		sb.AppendLine();
                //		sb.Append("TimeStamp: " + lastDetectedInfo.TimeStamp.ToString());
            }
            s = "";
            if (stoppingDistance > 1000)
            {
                s += (stoppingDistance / 1000).ToString("STOP DIST: 000.0km");
            }
            else
            {
                s += (stoppingDistance).ToString("STOP DIST: 00000m ");
            }
            StatusLog(s, textRangeReport);

            double maxRange = findMaxCameraRange(cameraForwardList);

            if (maxRange < currentScan)
            {
                sb.AppendLine();
                sb.Append("Awaiting Available Range");
                sb.AppendLine();

                sb.Append(progressBar(maxRange / currentScan * 100));
                sb.AppendLine();
            }

            sb.AppendLine();
            sb.Append(detectedEntities.Count.ToString() + " detected items");


            if (dGravity > 0)
            {
                StatusLog("GRAVITY WELL", textPanelReport);
            }

            if (AnyConnectorIsConnected())
            {
                StatusLog("Docked!", textPanelReport);
            }
            else
            {
                StatusLog(doEStopCheck(targetRange, stoppingDistance), textPanelReport);
            }

            // rotor status code for Techniker
            output = "";
            IMyMotorStator drillrotor;

            drillrotor = (IMyMotorStator)GridTerminalSystem.GetBlockWithName("Advanced Rotor L Drills");

            if (drillrotor != null)
            {
                output += "\nDrill Arm -";
                double angle = MathHelper.ToDegrees(drillrotor.Angle);
                if (angle > 178)
                {
                    output += " Stowed";
                }
                else if (angle < 1)
                {
                    output += " Deployed";
                }
                else
                {
                    output += " Moving";
                }

                /*
                 * if (drillrotor.SafetyLock)
                 *  output += " - (Locked)";
                 * else
                 *  output += " - Unlocked";
                 */
            }

            IMyMotorStator toolrotor;

            toolrotor = (IMyMotorStator)GridTerminalSystem.GetBlockWithName("Advanced Rotor R Tools");
            if (toolrotor != null)
            {
                output += "\nTool Arm -";
                double angle = MathHelper.ToDegrees(toolrotor.Angle);
                if (angle > 178)
                {
                    output += " Deployed";
                }
                else if (angle < 1)
                {
                    output += " Stowed";
                }
                else
                {
                    output += " Moving";
                }

                /*
                 * if (toolrotor.SafetyLock)
                 *  output += " - (Locked)";
                 * else
                 *  output += " - Unlocked";
                 */
            }
            //	output = "Drill rotor=" + angle.ToString("0.0");

            if (output != "")
            {
                Echo(output);
                StatusLog(output, textPanelReport);
            }

            // output main status.
            StatusLog(sb.ToString(), textPanelReport);
            //	Echo(sb.ToString());

            sb.Clear();
        }
Ejemplo n.º 24
0
        internal void InitialHitCheck()
        {
            var vhCount  = ValidateHits.Count;
            var minCount = Session.Settings.Enforcement.ServerOptimizations ? 96 : 99999;
            var stride   = vhCount < minCount ? 100000 : 48;

            MyAPIGateway.Parallel.For(0, ValidateHits.Count, x => {
                var p = ValidateHits[x];

                var shieldByPass       = p.Info.AmmoDef.DamageScales.Shields.Type == ShieldDef.ShieldType.Bypass;
                var shieldFullBypass   = shieldByPass && p.Info.AmmoDef.Const.ShieldBypassMod >= 1;
                var genericFields      = p.Info.EwarActive && (p.Info.AmmoDef.Const.AreaEffect == DotField || p.Info.AmmoDef.Const.AreaEffect == PushField || p.Info.AmmoDef.Const.AreaEffect == PullField);
                p.FinalizeIntersection = false;
                var lineCheck          = p.Info.AmmoDef.Const.CollisionIsLine && !p.Info.EwarAreaPulse;
                var ewarProjectile     = (p.Info.EwarActive || p.Info.AmmoDef.Const.EwarEffect);

                bool projetileInShield = false;
                var tick = p.Info.System.Session.Tick;

                var useEntityCollection = p.CheckType != Projectile.CheckTypes.Ray;
                var entityCollection    = p.UseEntityCache ? p.Info.Ai.NearByEntityCache : p.MyEntityList;
                var collectionCount     = !useEntityCollection ? p.MySegmentList.Count : entityCollection.Count;
                var ray    = new RayD(ref p.Beam.From, ref p.Beam.Direction);
                var myGrid = p.Info.Target.FiringCube.CubeGrid;

                Water water = null;
                if (Session.WaterApiLoaded && p.Info.MyPlanet != null)
                {
                    Session.WaterMap.TryGetValue(p.Info.MyPlanet, out water);
                }

                for (int i = 0; i < collectionCount; i++)
                {
                    var ent = !useEntityCollection ? p.MySegmentList[i].Element : entityCollection[i];

                    var grid      = ent as MyCubeGrid;
                    var entIsSelf = grid != null && (grid == myGrid || myGrid.IsSameConstructAs(grid));

                    if (entIsSelf && p.SmartsOn || ent.MarkedForClose || !ent.InScene || ent == p.Info.MyShield)
                    {
                        continue;
                    }

                    var character = ent as IMyCharacter;
                    if (p.Info.EwarActive && character != null && !genericFields)
                    {
                        continue;
                    }

                    var entSphere = ent.PositionComp.WorldVolume;
                    if (useEntityCollection)
                    {
                        if (p.CheckType == Projectile.CheckTypes.CachedRay)
                        {
                            var dist = ray.Intersects(entSphere);
                            if (!dist.HasValue || dist > p.Beam.Length)
                            {
                                continue;
                            }
                        }
                        else if (p.CheckType == Projectile.CheckTypes.CachedSphere && p.PruneSphere.Contains(entSphere) == ContainmentType.Disjoint)
                        {
                            continue;
                        }
                    }

                    if (grid != null || character != null)
                    {
                        var extBeam   = new LineD(p.Beam.From - p.Beam.Direction * (entSphere.Radius * 2), p.Beam.To);
                        var transform = ent.PositionComp.WorldMatrixRef;
                        var box       = ent.PositionComp.LocalAABB;
                        var obb       = new MyOrientedBoundingBoxD(box, transform);
                        if (lineCheck && obb.Intersects(ref extBeam) == null || !lineCheck && !obb.Intersects(ref p.PruneSphere))
                        {
                            continue;
                        }
                    }
                    var safeZone = ent as MySafeZone;
                    if (safeZone != null && safeZone.Enabled)
                    {
                        var action = (Session.SafeZoneAction)safeZone.AllowedActions;
                        if ((action & Session.SafeZoneAction.Damage) == 0)
                        {
                            bool intersects;
                            if (safeZone.Shape == MySafeZoneShape.Sphere)
                            {
                                var sphere = new BoundingSphereD(safeZone.PositionComp.WorldVolume.Center, safeZone.Radius);
                                var dist   = ray.Intersects(sphere);
                                intersects = dist != null && dist <= p.Beam.Length;
                            }
                            else
                            {
                                intersects = new MyOrientedBoundingBoxD(safeZone.PositionComp.LocalAABB, safeZone.PositionComp.WorldMatrixRef).Intersects(ref p.Beam) != null;
                            }

                            if (intersects)
                            {
                                p.State    = Projectile.ProjectileState.Depleted;
                                p.EarlyEnd = true;

                                if (p.EnableAv)
                                {
                                    p.Info.AvShot.ForceHitParticle = true;
                                }
                                break;
                            }
                        }
                    }

                    HitEntity hitEntity = null;
                    var checkShield     = Session.ShieldApiLoaded && Session.ShieldHash == ent.DefinitionId?.SubtypeId && ent.Render.Visible;
                    MyTuple <IMyTerminalBlock, MyTuple <bool, bool, float, float, float, int>, MyTuple <MatrixD, MatrixD> >?shieldInfo = null;
                    if (checkShield && (!shieldFullBypass && !p.ShieldBypassed || p.Info.EwarActive && (p.Info.AmmoDef.Const.AreaEffect == DotField || p.Info.AmmoDef.Const.AreaEffect == EmpField)))
                    {
                        shieldInfo = p.Info.System.Session.SApi.MatchEntToShieldFastExt(ent, true);
                        if (shieldInfo != null && !myGrid.IsSameConstructAs(shieldInfo.Value.Item1.CubeGrid))
                        {
                            if (p.Info.IsShrapnel || Vector3D.Transform(p.Info.Origin, shieldInfo.Value.Item3.Item1).LengthSquared() > 1)
                            {
                                p.EntitiesNear = true;
                                var dist       = MathFuncs.IntersectEllipsoid(shieldInfo.Value.Item3.Item1, shieldInfo.Value.Item3.Item2, new RayD(p.Beam.From, p.Beam.Direction));
                                if (p.Info.Target.IsProjectile && Vector3D.Transform(p.Info.Target.Projectile.Position, shieldInfo.Value.Item3.Item1).LengthSquared() <= 1)
                                {
                                    projetileInShield = true;
                                }

                                if (dist != null && (dist.Value < p.Beam.Length || p.Info.EwarActive))
                                {
                                    if (shieldByPass)
                                    {
                                        p.ShieldBypassed = true;
                                    }
                                    hitEntity           = HitEntityPool.Get();
                                    hitEntity.EventType = Shield;
                                    hitEntity.HitPos    = p.Beam.From + (p.Beam.Direction * dist.Value);
                                    hitEntity.HitDist   = dist;
                                }
                                else
                                {
                                    continue;
                                }
                            }
                        }
                    }

                    var destroyable = ent as IMyDestroyableObject;
                    var voxel       = ent as MyVoxelBase;
                    if (voxel != null && voxel == voxel?.RootVoxel)
                    {
                        if (ent == p.Info.MyPlanet && !(p.LinePlanetCheck || p.DynamicGuidance || p.CachedPlanetHit))
                        {
                            continue;
                        }
                        VoxelIntersectBranch voxelState = VoxelIntersectBranch.None;
                        Vector3D?voxelHit = null;
                        if (tick - p.Info.VoxelCache.HitRefreshed < 60)
                        {
                            var cacheDist = ray.Intersects(p.Info.VoxelCache.HitSphere);
                            if (cacheDist.HasValue && cacheDist.Value <= p.Beam.Length)
                            {
                                voxelHit   = p.Beam.From + (p.Beam.Direction * cacheDist.Value);
                                voxelState = VoxelIntersectBranch.PseudoHit1;
                            }
                            else if (cacheDist.HasValue)
                            {
                                p.Info.VoxelCache.MissSphere.Center = p.Beam.To;
                            }
                        }

                        if (voxelState != VoxelIntersectBranch.PseudoHit1)
                        {
                            if (voxel == p.Info.MyPlanet && p.Info.VoxelCache.MissSphere.Contains(p.Beam.To) == ContainmentType.Disjoint)
                            {
                                if (p.LinePlanetCheck)
                                {
                                    if (water != null && !p.Info.AmmoDef.IgnoreWater)
                                    {
                                        var waterSphere = new BoundingSphereD(p.Info.MyPlanet.PositionComp.WorldAABB.Center, water.radius);
                                        var estiamtedSurfaceDistance = ray.Intersects(waterSphere);

                                        if (estiamtedSurfaceDistance.HasValue && estiamtedSurfaceDistance.Value <= p.Beam.Length)
                                        {
                                            var estimatedHit = ray.Position + (ray.Direction * estiamtedSurfaceDistance.Value);
                                            voxelHit         = estimatedHit;
                                            voxelState       = VoxelIntersectBranch.PseudoHit2;
                                        }
                                    }

                                    if (voxelState != VoxelIntersectBranch.PseudoHit2)
                                    {
                                        var surfacePos   = p.Info.MyPlanet.GetClosestSurfacePointGlobal(ref p.Position);
                                        var planetCenter = p.Info.MyPlanet.PositionComp.WorldAABB.Center;
                                        double surfaceToCenter;
                                        Vector3D.DistanceSquared(ref surfacePos, ref planetCenter, out surfaceToCenter);
                                        double endPointToCenter;
                                        Vector3D.DistanceSquared(ref p.Position, ref planetCenter, out endPointToCenter);
                                        double startPointToCenter;
                                        Vector3D.DistanceSquared(ref p.Info.Origin, ref planetCenter, out startPointToCenter);

                                        var prevEndPointToCenter = p.PrevEndPointToCenterSqr;
                                        Vector3D.DistanceSquared(ref surfacePos, ref p.Position, out p.PrevEndPointToCenterSqr);
                                        if (surfaceToCenter > endPointToCenter || p.PrevEndPointToCenterSqr <= (p.Beam.Length * p.Beam.Length) || endPointToCenter > startPointToCenter && prevEndPointToCenter > p.DistanceToTravelSqr || surfaceToCenter > Vector3D.DistanceSquared(planetCenter, p.LastPosition))
                                        {
                                            var estiamtedSurfaceDistance = ray.Intersects(p.Info.VoxelCache.PlanetSphere);
                                            var fullCheck = p.Info.VoxelCache.PlanetSphere.Contains(p.Info.Origin) != ContainmentType.Disjoint || !estiamtedSurfaceDistance.HasValue;

                                            if (!fullCheck && estiamtedSurfaceDistance.HasValue && (estiamtedSurfaceDistance.Value <= p.Beam.Length || p.Info.VoxelCache.PlanetSphere.Radius < 1))
                                            {
                                                double distSqr;
                                                var estimatedHit = ray.Position + (ray.Direction * estiamtedSurfaceDistance.Value);
                                                Vector3D.DistanceSquared(ref p.Info.VoxelCache.FirstPlanetHit, ref estimatedHit, out distSqr);

                                                if (distSqr > 625)
                                                {
                                                    fullCheck = true;
                                                }
                                                else
                                                {
                                                    voxelHit   = estimatedHit;
                                                    voxelState = VoxelIntersectBranch.PseudoHit2;
                                                }
                                            }

                                            if (fullCheck)
                                            {
                                                voxelState = VoxelIntersectBranch.DeferFullCheck;
                                            }

                                            if (voxelHit.HasValue && Vector3D.DistanceSquared(voxelHit.Value, p.Info.VoxelCache.PlanetSphere.Center) > p.Info.VoxelCache.PlanetSphere.Radius * p.Info.VoxelCache.PlanetSphere.Radius)
                                            {
                                                p.Info.VoxelCache.GrowPlanetCache(voxelHit.Value);
                                            }
                                        }
                                    }
                                }
                            }
                            else if (voxelHit == null && p.Info.VoxelCache.MissSphere.Contains(p.Beam.To) == ContainmentType.Disjoint)
                            {
                                voxelState = VoxelIntersectBranch.DeferedMissUpdate;
                            }
                        }

                        if (voxelState == VoxelIntersectBranch.PseudoHit1 || voxelState == VoxelIntersectBranch.PseudoHit2)
                        {
                            if (!voxelHit.HasValue)
                            {
                                if (p.Info.VoxelCache.MissSphere.Contains(p.Beam.To) == ContainmentType.Disjoint)
                                {
                                    p.Info.VoxelCache.MissSphere.Center = p.Beam.To;
                                }
                                continue;
                            }

                            hitEntity = HitEntityPool.Get();

                            var hitPos       = voxelHit.Value;
                            hitEntity.HitPos = hitPos;

                            double dist;
                            Vector3D.Distance(ref p.Beam.From, ref hitPos, out dist);
                            hitEntity.HitDist = dist;

                            hitEntity.EventType = Voxel;
                        }
                        else if (voxelState == VoxelIntersectBranch.DeferedMissUpdate || voxelState == VoxelIntersectBranch.DeferFullCheck)
                        {
                            DeferedVoxels.Add(new DeferedVoxels {
                                Projectile = p, Branch = voxelState, Voxel = voxel
                            });
                        }
                    }
                    else if (ent.Physics != null && !ent.Physics.IsPhantom && !ent.IsPreview && grid != null)
                    {
                        if (grid != null)
                        {
                            hitEntity = HitEntityPool.Get();
                            if (entIsSelf)
                            {
                                if (!p.Info.AmmoDef.Const.IsBeamWeapon && p.Beam.Length <= grid.GridSize * 2)
                                {
                                    MyCube cube;
                                    if (!(grid.TryGetCube(grid.WorldToGridInteger(p.Position), out cube) && cube.CubeBlock != p.Info.Target.FiringCube.SlimBlock || grid.TryGetCube(grid.WorldToGridInteger(p.LastPosition), out cube) && cube.CubeBlock != p.Info.Target.FiringCube.SlimBlock))
                                    {
                                        HitEntityPool.Return(hitEntity);
                                        continue;
                                    }
                                }

                                if (!p.Info.EwarAreaPulse)
                                {
                                    var forwardPos = p.Info.Age != 1 ? p.Beam.From : p.Beam.From + (p.Beam.Direction * Math.Min(grid.GridSizeHalf, p.Info.DistanceTraveled - p.Info.PrevDistanceTraveled));
                                    grid.RayCastCells(forwardPos, p.Beam.To, hitEntity.Vector3ICache, null, true, true);

                                    if (hitEntity.Vector3ICache.Count > 0)
                                    {
                                        IHitInfo hitInfo;
                                        p.Info.System.Session.Physics.CastRay(forwardPos, p.Beam.To, out hitInfo, CollisionLayers.DefaultCollisionLayer);
                                        var hitGrid = hitInfo?.HitEntity?.GetTopMostParent() as MyCubeGrid;
                                        if (hitGrid == null || !myGrid.IsSameConstructAs(hitGrid))
                                        {
                                            HitEntityPool.Return(hitEntity);
                                            continue;
                                        }

                                        hitEntity.HitPos = hitInfo.Position;
                                        hitEntity.Blocks.Add(grid.GetCubeBlock(hitEntity.Vector3ICache[0]));
                                    }
                                }
                            }
                            else
                            {
                                grid.RayCastCells(p.Beam.From, p.Beam.To, hitEntity.Vector3ICache, null, true, true);
                            }

                            if (!ewarProjectile)
                            {
                                hitEntity.EventType = Grid;
                            }
                            else if (!p.Info.EwarAreaPulse)
                            {
                                hitEntity.EventType = Effect;
                            }
                            else
                            {
                                hitEntity.EventType = Field;
                            }

                            p.EntitiesNear = true;
                        }
                    }
                    else if (destroyable != null)
                    {
                        hitEntity           = HitEntityPool.Get();
                        hitEntity.EventType = Destroyable;
                    }

                    if (hitEntity != null)
                    {
                        p.FinalizeIntersection   = true;
                        hitEntity.Info           = p.Info;
                        hitEntity.Entity         = hitEntity.EventType != Shield ? ent : (MyEntity)shieldInfo.Value.Item1;
                        hitEntity.Intersection   = p.Beam;
                        hitEntity.SphereCheck    = !lineCheck;
                        hitEntity.PruneSphere    = p.PruneSphere;
                        hitEntity.SelfHit        = entIsSelf;
                        hitEntity.DamageOverTime = p.Info.AmmoDef.Const.AreaEffect == DotField;

                        p.Info.HitList.Add(hitEntity);
                    }
                }

                if (p.Info.Target.IsProjectile && !p.Info.AmmoDef.Const.EwarEffect && !projetileInShield)
                {
                    var detonate     = p.State == Projectile.ProjectileState.Detonate;
                    var hitTolerance = detonate ? p.Info.AmmoDef.Const.DetonationRadius : p.Info.AmmoDef.Const.AreaEffectSize > p.Info.AmmoDef.Const.CollisionSize ? p.Info.AmmoDef.Const.AreaEffectSize : p.Info.AmmoDef.Const.CollisionSize;
                    var useLine      = p.Info.AmmoDef.Const.CollisionIsLine && !detonate && p.Info.AmmoDef.Const.AreaEffectSize <= 0;

                    var sphere = new BoundingSphereD(p.Info.Target.Projectile.Position, p.Info.Target.Projectile.Info.AmmoDef.Const.CollisionSize);
                    sphere.Include(new BoundingSphereD(p.Info.Target.Projectile.LastPosition, 1));
                    var rayCheck      = useLine && sphere.Intersects(new RayD(p.LastPosition, p.Info.Direction)) != null;
                    var testSphere    = p.PruneSphere;
                    testSphere.Radius = hitTolerance;

                    if (rayCheck || sphere.Intersects(testSphere))
                    {
                        ProjectileHit(p, p.Info.Target.Projectile, lineCheck, ref p.Beam);
                    }
                }

                if (!useEntityCollection)
                {
                    p.MySegmentList.Clear();
                }
                else if (p.CheckType == Projectile.CheckTypes.Sphere)
                {
                    entityCollection.Clear();
                }

                if (p.FinalizeIntersection)
                {
                    FinalHitCheck.Add(p);
                }
            }, stride);
            ValidateHits.ClearImmediate();
        }
Ejemplo n.º 25
0
        protected MyBehaviorTreeState GetTargetWithPriority([BTParam] float radius, [BTInOut] ref MyBBMemoryTarget outTarget, [BTInOut] ref MyBBMemoryInt priority)
        {
            var             myPosition = Bot.Navigation.PositionAndOrientation.Translation;
            BoundingSphereD bb         = new BoundingSphereD(myPosition, radius);

            if (priority == null)
            {
                priority = new MyBBMemoryInt();
            }
            int bestPriority = priority.IntValue;

            if (bestPriority <= 0)
            {
                bestPriority = int.MaxValue;
            }

            MyBehaviorTreeState retval = IsTargetValid(ref outTarget);

            if (retval == MyBehaviorTreeState.FAILURE)
            {
                bestPriority = 7;
                MyBBMemoryTarget.UnsetTarget(ref outTarget);
            }
            Vector3D?targetPosition = SpiderTarget.GetMemoryTargetPosition(outTarget);

            if (!targetPosition.HasValue || Vector3D.Distance(targetPosition.Value, Bot.AgentEntity.PositionComp.GetPosition()) > 400.0f)
            {
                bestPriority = 7;
                MyBBMemoryTarget.UnsetTarget(ref outTarget);
            }

            var myFaction = MySession.Static.Factions.GetPlayerFaction(Bot.AgentEntity.ControllerInfo.ControllingIdentityId);

            // Priorities are as follows:
            // 1st characters, 3rd turrets, 4th weapons, 5th non-armor blocks, 6th armor blocks
            var entityList = MyEntities.GetTopMostEntitiesInSphere(ref bb);

            entityList.ShuffleList(); // Prevent all spiders going for the same player
            foreach (var entity in entityList)
            {
                if (entity == Bot.AgentEntity)
                {
                    continue;
                }
                if (!SpiderTarget.IsEntityReachable(entity))
                {
                    continue;
                }

                int entityPriority = 6;
                var character      = entity as MyCharacter;
                var grid           = entity as MyCubeGrid;

                if (character != null)
                {
                    var faction = MySession.Static.Factions.GetPlayerFaction(character.ControllerInfo.ControllingIdentityId);
                    if (myFaction != null && faction == myFaction)
                    {
                        continue;
                    }
                    if (character.IsDead)
                    {
                        continue;
                    }

                    entityPriority = 1;

                    if (entityPriority < bestPriority)
                    {
                        retval       = MyBehaviorTreeState.SUCCESS;
                        bestPriority = entityPriority;
                        MyBBMemoryTarget.SetTargetEntity(ref outTarget, MyAiTargetEnum.CHARACTER, character.EntityId);
                        continue;
                    }
                }
                else if (grid != null && bestPriority > 3)
                {
                    Vector3D    spiderPosInGrid = grid.WorldToGridScaledLocal(myPosition);
                    double      closestDist     = double.MaxValue;
                    MySlimBlock closestBlock    = null;
                    foreach (var block in grid.CubeBlocks)
                    {
                        Vector3D blockLocalPos = new Vector3D(block.Min + block.Max);
                        blockLocalPos = blockLocalPos * 0.5;

                        double dist = Vector3D.RectangularDistance(ref blockLocalPos, ref spiderPosInGrid);
                        if (dist < closestDist)
                        {
                            closestBlock = block;
                            closestDist  = dist;
                        }
                    }

                    if (closestBlock != null)
                    {
                        retval       = MyBehaviorTreeState.SUCCESS;
                        bestPriority = 3;
                        MyBBMemoryTarget.SetTargetCube(ref outTarget, (closestBlock.Min + closestBlock.Max) / 2, grid.EntityId);
                    }
                }
            }
            entityList.Clear();

            /*var players = Sync.Players.GetOnlinePlayers();
             * MyCharacter closestCharacter = null;
             * double closestDistanceSq = float.MaxValue;
             * foreach (var player in players)
             * {
             *  if (player.Id.SerialId != 0)
             *  {
             *      var bot = MyAIComponent.Static.Bots.TryGetBot<MyHumanoidBot>(player.Id.SerialId);
             *      if (bot == null || bot.BotDefinition.BehaviorType == "Barbarian")
             *          continue;
             *  }
             *
             *  if (!(player.Character is MyCharacter) || !AiTargetBase.IsEntityReachable(player.Character))
             *  {
             *      continue;
             *  }
             *
             *  if (player.Character.IsDead)
             *      continue;
             *
             *  var distanceSq = Vector3D.DistanceSquared(player.Character.PositionComp.GetPosition(), myPosition);
             *  if (distanceSq < radius * radius && distanceSq < closestDistanceSq)
             *  {
             *      closestCharacter = player.Character;
             *      closestDistanceSq = distanceSq;
             *  }
             * }*/

            //return closestCharacter;

            priority.IntValue = bestPriority;

            // CH: TODO: This is temporary. Remove it!
            if (outTarget.TargetType == MyAiTargetEnum.CUBE)
            {
                MyEntity outGrid;
                MyEntities.TryGetEntityById(outTarget.EntityId.Value, out outGrid);
                Debug.Assert(outGrid != null);
                var         grid  = outGrid as MyCubeGrid;
                MySlimBlock block = grid.GetCubeBlock(outTarget.BlockPosition);
                Debug.Assert(block != null);

                //MyTrace.Send(TraceWindow.Ai, "TARGETTING CUBE: " + grid.ToString() + " " + block.ToString());
            }

            return(retval);
        }
Ejemplo n.º 26
0
        internal int GetEntityCompareDist(HitEntity x, HitEntity y, ProInfo info)
        {
            var xDist        = double.MaxValue;
            var yDist        = double.MaxValue;
            var beam         = x.Intersection;
            var count        = y != null ? 2 : 1;
            var eWarPulse    = info.AmmoDef.Const.Ewar && info.AmmoDef.Const.Pulse;
            var triggerEvent = eWarPulse && !info.EwarAreaPulse && info.AmmoDef.Const.EwarTriggerRange > 0;

            for (int i = 0; i < count; i++)
            {
                var isX = i == 0;

                MyEntity  ent;
                HitEntity hitEnt;
                HitEntity otherHit;
                if (isX)
                {
                    hitEnt   = x;
                    otherHit = y;
                    ent      = hitEnt.Entity;
                }
                else
                {
                    hitEnt   = y;
                    otherHit = x;
                    ent      = hitEnt.Entity;
                }

                var dist   = double.MaxValue;
                var shield = ent as IMyTerminalBlock;
                var grid   = ent as MyCubeGrid;
                var voxel  = ent as MyVoxelBase;

                if (triggerEvent && (info.Ai.Targets.ContainsKey(ent) || shield != null))
                {
                    hitEnt.PulseTrigger = true;
                }
                else if (hitEnt.Projectile != null)
                {
                    dist = hitEnt.HitDist.Value;
                }
                else if (shield != null)
                {
                    hitEnt.Hit = true;
                    dist       = hitEnt.HitDist.Value;
                }
                else if (grid != null)
                {
                    /*
                     * var otherGrid = otherHit?.Entity as MyCubeGrid;
                     * if (otherGrid != null && otherGrid.IsInSameLogicalGroupAs(grid))
                     *  hitEnt.SubGrids.Add(otherHit);
                     */

                    if (hitEnt.Hit)
                    {
                        dist           = Vector3D.Distance(hitEnt.Intersection.From, hitEnt.HitPos.Value);
                        hitEnt.HitDist = dist;
                    }
                    else if (hitEnt.HitPos != null)
                    {
                        dist           = Vector3D.Distance(hitEnt.Intersection.From, hitEnt.HitPos.Value);
                        hitEnt.HitDist = dist;
                        hitEnt.Hit     = true;
                    }
                    else
                    {
                        if (hitEnt.SphereCheck || info.EwarActive && eWarPulse)
                        {
                            var ewarActive = hitEnt.EventType == Field || hitEnt.EventType == Effect;

                            var hitPos = !ewarActive ? hitEnt.PruneSphere.Center + (hitEnt.Intersection.Direction * hitEnt.PruneSphere.Radius) : hitEnt.PruneSphere.Center;
                            if (hitEnt.SelfHit && Vector3D.DistanceSquared(hitPos, hitEnt.Info.Origin) <= grid.GridSize * grid.GridSize)
                            {
                                continue;
                            }

                            if (!ewarActive)
                            {
                                GetAndSortBlocksInSphere(hitEnt.Info.AmmoDef, hitEnt.Info.System, grid, hitEnt.PruneSphere, false, hitEnt.Blocks);
                            }

                            if (hitEnt.Blocks.Count > 0 || ewarActive)
                            {
                                dist           = 0;
                                hitEnt.HitDist = dist;
                                hitEnt.Hit     = true;
                                hitEnt.HitPos  = hitPos;
                            }
                        }
                        else
                        {
                            var closestBlockFound = false;
                            for (int j = 0; j < hitEnt.Vector3ICache.Count; j++)
                            {
                                var     firstBlock = grid.GetCubeBlock(hitEnt.Vector3ICache[j]) as IMySlimBlock;
                                MatrixD transform  = grid.WorldMatrix;
                                if (firstBlock != null && !firstBlock.IsDestroyed && firstBlock != hitEnt.Info.Target.FiringCube.SlimBlock)
                                {
                                    hitEnt.Blocks.Add(firstBlock);
                                    if (closestBlockFound)
                                    {
                                        continue;
                                    }
                                    MyOrientedBoundingBoxD obb;
                                    var fat = firstBlock.FatBlock;
                                    if (fat != null)
                                    {
                                        obb = new MyOrientedBoundingBoxD(fat.Model.BoundingBox, fat.PositionComp.WorldMatrixRef);
                                    }
                                    else
                                    {
                                        Vector3 halfExt;
                                        firstBlock.ComputeScaledHalfExtents(out halfExt);
                                        var blockBox = new BoundingBoxD(-halfExt, halfExt);
                                        transform.Translation = grid.GridIntegerToWorld(firstBlock.Position);
                                        obb = new MyOrientedBoundingBoxD(blockBox, transform);
                                    }

                                    var hitDist = obb.Intersects(ref beam) ?? Vector3D.Distance(beam.From, obb.Center);
                                    var hitPos  = beam.From + (beam.Direction * hitDist);

                                    if (hitEnt.SelfHit)
                                    {
                                        if (Vector3D.DistanceSquared(hitPos, hitEnt.Info.Origin) <= grid.GridSize * 3)
                                        {
                                            hitEnt.Blocks.Clear();
                                        }
                                        else
                                        {
                                            dist           = hitDist;
                                            hitEnt.HitDist = dist;
                                            hitEnt.Hit     = true;
                                            hitEnt.HitPos  = hitPos;
                                        }
                                        break;
                                    }

                                    dist              = hitDist;
                                    hitEnt.HitDist    = dist;
                                    hitEnt.Hit        = true;
                                    hitEnt.HitPos     = hitPos;
                                    closestBlockFound = true;
                                }
                            }
                        }
                    }
                }
                else if (voxel != null)
                {
                    hitEnt.Hit     = true;
                    dist           = hitEnt.HitDist.Value;
                    hitEnt.HitDist = dist;
                }
                else if (ent is IMyDestroyableObject)
                {
                    if (hitEnt.Hit)
                    {
                        dist = Vector3D.Distance(hitEnt.Intersection.From, hitEnt.HitPos.Value);
                    }
                    else
                    {
                        if (hitEnt.SphereCheck || info.EwarActive && eWarPulse)
                        {
                            var ewarActive = hitEnt.EventType == Field || hitEnt.EventType == Effect;
                            dist           = 0;
                            hitEnt.HitDist = dist;
                            hitEnt.Hit     = true;
                            var hitPos = !ewarActive ? hitEnt.PruneSphere.Center + (hitEnt.Intersection.Direction * hitEnt.PruneSphere.Radius) : hitEnt.PruneSphere.Center;
                            hitEnt.HitPos = hitPos;
                        }
                        else
                        {
                            var transform = ent.PositionComp.WorldMatrixRef;
                            var box       = ent.PositionComp.LocalAABB;
                            var obb       = new MyOrientedBoundingBoxD(box, transform);
                            dist = obb.Intersects(ref beam) ?? double.MaxValue;
                            if (dist < double.MaxValue)
                            {
                                hitEnt.Hit     = true;
                                hitEnt.HitPos  = beam.From + (beam.Direction * dist);
                                hitEnt.HitDist = dist;
                            }
                        }
                    }
                }

                if (isX)
                {
                    xDist = dist;
                }
                else
                {
                    yDist = dist;
                }
            }
            return(xDist.CompareTo(yDist));
        }
Ejemplo n.º 27
0
        public override void MainBehavior()
        {
            if (RAI_SessionCore.IsServer == false)
            {
                return;
            }

            base.MainBehavior();

            //Logger.MsgDebug(Mode.ToString(), DebugTypeEnum.General);

            if (Mode != BehaviorMode.Retreat && Despawn.DoRetreat == true)
            {
                ChangeCoreBehaviorMode(BehaviorMode.Retreat);
                AutoPilot.ActivateAutoPilot(this.RemoteControl.GetPosition(), NewAutoPilotMode.RotateToWaypoint | NewAutoPilotMode.ThrustForward | NewAutoPilotMode.PlanetaryPathing | AutoPilot.UserCustomMode);
            }

            if (Mode == BehaviorMode.Init)
            {
                if (!AutoPilot.Targeting.HasTarget())
                {
                    ChangeCoreBehaviorMode(BehaviorMode.WaitingForTarget);
                }
                else
                {
                    ChangeCoreBehaviorMode(BehaviorMode.ApproachTarget);
                    AutoPilot.ActivateAutoPilot(this.RemoteControl.GetPosition(), NewAutoPilotMode.RotateToWaypoint | NewAutoPilotMode.ThrustForward | NewAutoPilotMode.PlanetaryPathing | NewAutoPilotMode.WaypointFromTarget | AutoPilot.UserCustomMode);
                }
            }

            if (Mode == BehaviorMode.WaitingForTarget)
            {
                if (AutoPilot.CurrentMode != AutoPilot.UserCustomModeIdle)
                {
                    AutoPilot.ActivateAutoPilot(this.RemoteControl.GetPosition(), AutoPilot.UserCustomModeIdle);
                }

                if (AutoPilot.Targeting.HasTarget())
                {
                    ChangeCoreBehaviorMode(BehaviorMode.ApproachTarget);
                    AutoPilot.ActivateAutoPilot(this.RemoteControl.GetPosition(), NewAutoPilotMode.RotateToWaypoint | NewAutoPilotMode.ThrustForward | NewAutoPilotMode.PlanetaryPathing | NewAutoPilotMode.WaypointFromTarget | AutoPilot.UserCustomMode);
                }
                else if (Despawn.NoTargetExpire == true)
                {
                    Despawn.Retreat();
                }
            }

            if (!AutoPilot.Targeting.HasTarget() && Mode != BehaviorMode.Retreat && Mode != BehaviorMode.WaitingForTarget)
            {
                ChangeCoreBehaviorMode(BehaviorMode.WaitingForTarget);
                AutoPilot.ActivateAutoPilot(this.RemoteControl.GetPosition(), AutoPilot.UserCustomModeIdle);
            }

            //Approach
            if (Mode == BehaviorMode.ApproachTarget)
            {
                var targetDist = Vector3D.Distance(RemoteControl.GetPosition(), AutoPilot.Targeting.TargetLastKnownCoords);

                if (targetDist < MaxDistanceFromTarget)
                {
                    if (AutoPilot.Data.PadDistanceFromTarget > 0 && targetDist > AutoPilot.Data.PadDistanceFromTarget)
                    {
                        //Nothing
                    }
                    else
                    {
                        BehaviorTriggerA = true;
                        ChangeCoreBehaviorMode(BehaviorMode.WaitAtWaypoint);
                        AutoPilot.ActivateAutoPilot(this.RemoteControl.GetPosition(), (RotateToTargetWithinRange ? NewAutoPilotMode.RotateToWaypoint : NewAutoPilotMode.None) | NewAutoPilotMode.WaypointFromTarget | AutoPilot.UserCustomMode);
                    }
                }
            }

            //Engage
            if (Mode == BehaviorMode.WaitAtWaypoint)
            {
                var targetDist = Vector3D.Distance(RemoteControl.GetPosition(), AutoPilot.Targeting.TargetLastKnownCoords);

                if (AutoPilot.Data.PadDistanceFromTarget > 0 && targetDist > AutoPilot.Data.PadDistanceFromTarget)
                {
                    BehaviorTriggerC = true;
                    ChangeCoreBehaviorMode(BehaviorMode.ApproachTarget);
                    AutoPilot.ActivateAutoPilot(this.RemoteControl.GetPosition(), NewAutoPilotMode.RotateToWaypoint | NewAutoPilotMode.ThrustForward | NewAutoPilotMode.PlanetaryPathing | NewAutoPilotMode.WaypointFromTarget | AutoPilot.UserCustomMode);
                }
                else if (targetDist > MaxDistanceFromTarget)
                {
                    BehaviorTriggerB = true;
                    ChangeCoreBehaviorMode(BehaviorMode.WaitAtWaypoint);
                    AutoPilot.ActivateAutoPilot(this.RemoteControl.GetPosition(), NewAutoPilotMode.RotateToWaypoint | NewAutoPilotMode.ThrustForward | NewAutoPilotMode.PlanetaryPathing | NewAutoPilotMode.WaypointFromTarget | AutoPilot.UserCustomMode);
                }
            }

            //Retreat
            if (Mode == BehaviorMode.Retreat)
            {
                if (Despawn.NearestPlayer?.Controller?.ControlledEntity?.Entity != null)
                {
                    //Logger.AddMsg("DespawnCoordsCreated", true);
                    AutoPilot.SetInitialWaypoint(VectorHelper.GetDirectionAwayFromTarget(this.RemoteControl.GetPosition(), Despawn.NearestPlayer.GetPosition()) * 1000 + this.RemoteControl.GetPosition());
                }
            }
        }
Ejemplo n.º 28
0
        private bool TryFindEdge(out FindEdgeResult result)
        {
            result = default;

            var prevEdgeReal = _prevEdge?.GetEdge(_graph);
            var position     = Entity.PositionComp.WorldMatrix.Translation;

            result.Score = Definition.DetachDistance + TotalBias;
            using (var e = _graph.Edges.SortedByDistance(position))
                while (e.MoveNext())
                {
                    if (Math.Sqrt(e.Current.DistanceSquared) - TotalBias > result.Score)
                    {
                        break;
                    }
                    var edge = (Edge)e.Current.UserData;
                    if (edge.Curve == null)
                    {
                        continue;
                    }
                    var edgeSegment = RailSegmentFor(edge);
                    var edgeCaps    = edgeSegment?.Definition.CapabilitiesFor(edge.Owner.Entity.GetBuildRatio());
                    if (edgeSegment == null || !edgeCaps.HasValue)
                    {
                        continue; // no capabilities at this stage
                    }
                    if (!CanUseEdge(prevEdgeReal, edge))
                    {
                        continue;
                    }

                    float t0 = 0, t1 = 1;
                    CurveExtensions.NearestPoint(edge.Curve, position, 16, ref t0, ref t1);
                    var p0     = edge.Curve.Sample(t0);
                    var p1     = edge.Curve.Sample(t1);
                    var dir    = p1 - p0;
                    var factor = (float)MathHelper.Clamp(dir.Dot(position - p0) / dir.LengthSquared(), 0, 1);
                    var t      = t0 + (t1 - t0) * factor;
                    var pos    = edge.Curve.Sample(t);
                    var score  = Vector3D.Distance(pos, position);
                    if (score - TotalBias > result.Score)
                    {
                        continue;
                    }
                    var tangent = (Vector3)edge.Curve.SampleDerivative(t);
                    tangent.Normalize();

                    const float switchingEpsilon = 0.25f;
                    var         switched         = false;
                    if (t < switchingEpsilon)
                    {
                        switched = edge.From.IsSwitchedTo(edge.To);
                    }
                    else if (t >= 1 - switchingEpsilon)
                    {
                        switched = edge.To.IsSwitchedTo(edge.From);
                    }
                    var forwardDotTangent = Entity.PositionComp.WorldMatrix.Forward.Dot(tangent);
                    if (forwardDotTangent < 0)
                    {
                        forwardDotTangent = -forwardDotTangent;
                        tangent           = -tangent;
                    }

                    if (switched)
                    {
                        score -= SwitchingDistanceBias + AlignmentTangentBias;
                    }
                    else
                    {
                        score -= AlignmentTangentBias * forwardDotTangent;
                    }

                    if (RailConstants.Debug.DrawBogieEdges)
                    {
                        edge.Draw(0, 1, switched ? new Vector4(0, 1, 0, 1) : new Vector4(1, 0, 1, 1), 2);
                    }

                    // ReSharper disable once InvertIf
                    if (score < result.Score)
                    {
                        result.Score       = score;
                        result.Tangent     = tangent;
                        result.Edge        = edge;
                        result.SegmentCaps = edgeCaps.Value;
                        result.EdgeFactor  = t;
                    }
                }

            if (result.Edge == null || result.Score > Definition.DetachDistance)
            {
                return(false);
            }
            result.Up = (Vector3)Vector3D.Lerp(result.Edge.From.Up, result.Edge.To.Up, result.EdgeFactor);
            // Not aligned vertically, abort
            if (Entity.PositionComp.WorldMatrix.Up.Dot(result.Up) < 0.5)
            {
                return(false);
            }

            result.Position = result.Edge.Curve.Sample(result.EdgeFactor) + result.Up * Definition.VerticalOffset;
            result.Normal   = Vector3.Cross(result.Tangent, result.Up);
            result.Normal.Normalize();

            result.Up = Vector3.Cross(result.Normal, result.Tangent);
            result.Up.Normalize();
            return(true);
        }
Ejemplo n.º 29
0
 //  Distance from camera to position of entity.
 public double GetDistanceBetweenCameraAndPosition()
 {
     return(Vector3D.Distance(MySector.MainCamera.Position, this.PositionComp.GetPosition()));
 }
Ejemplo n.º 30
0
		public void Distance()
		{
			var vector = new Vector3D(3, 4, 2);
			Assert.AreEqual(0, vector.Distance(vector));
			Assert.AreEqual(3, new Vector3D(1, 2, 3).Distance(vector));
			Assert.AreEqual(9, new Vector3D(1, 2, 3).DistanceSquared(vector));
		}
Ejemplo n.º 31
0
        public void ProcessTriggerWatchers()
        {
            var timeDifference = MyAPIGateway.Session.GameDateTime - LastTriggerRun;

            if (timeDifference.TotalMilliseconds < 500)
            {
                //Logger.MsgDebug("Triggers Not Ready (total ms elapsed: "+ timeDifference.TotalMilliseconds.ToString() + "), Handing Off to Next Action", DebugTypeEnum.Dev);
                //OnComplete?.Invoke();
                return;
            }

            //Logger.MsgDebug("Checking Triggers", DebugTypeEnum.Dev);
            LastTriggerRun = MyAPIGateway.Session.GameDateTime;

            for (int i = 0; i < Triggers.Count; i++)
            {
                var trigger = Triggers[i];

                if (!trigger.UseTrigger)
                {
                    continue;
                }

                //Timer
                if (trigger.Type == "Timer")
                {
                    //Logger.MsgDebug("Checking Timer Trigger: " + trigger.ProfileSubtypeId, DebugTypeEnum.Trigger);
                    if (trigger.UseTrigger == true)
                    {
                        trigger.ActivateTrigger();
                    }

                    continue;
                }

                //PlayerNear
                if (trigger.Type == "PlayerNear")
                {
                    //Logger.MsgDebug("Checking PlayerNear Trigger: " + trigger.ProfileSubtypeId, DebugTypeEnum.Trigger);
                    if (trigger.UseTrigger == true)
                    {
                        if (IsPlayerNearby(trigger))
                        {
                            trigger.ActivateTrigger();
                        }
                    }

                    continue;
                }

                //PlayerFar
                if (trigger.Type == "PlayerFar")
                {
                    //Logger.MsgDebug("Checking PlayerNear Trigger: " + trigger.ProfileSubtypeId, DebugTypeEnum.Trigger);
                    if (trigger.UseTrigger == true)
                    {
                        if (IsPlayerNearby(trigger, true))
                        {
                            trigger.ActivateTrigger();
                        }
                    }

                    continue;
                }

                //TargetNear
                if (trigger.Type == "TargetNear")
                {
                    //Logger.MsgDebug("Checking PlayerNear Trigger: " + trigger.ProfileSubtypeId, DebugTypeEnum.Trigger);
                    if (trigger.UseTrigger == true)
                    {
                        if (_behavior.AutoPilot.Targeting.HasTarget() && Vector3D.Distance(RemoteControl.GetPosition(), _behavior.AutoPilot.Targeting.TargetLastKnownCoords) < trigger.TargetDistance)
                        {
                            trigger.ActivateTrigger();
                        }
                    }

                    continue;
                }

                //TargetFar
                if (trigger.Type == "TargetFar")
                {
                    //Logger.MsgDebug("Checking PlayerNear Trigger: " + trigger.ProfileSubtypeId, DebugTypeEnum.Trigger);
                    if (trigger.UseTrigger == true)
                    {
                        if (_behavior.AutoPilot.Targeting.HasTarget() && Vector3D.Distance(RemoteControl.GetPosition(), _behavior.AutoPilot.Targeting.TargetLastKnownCoords) > trigger.TargetDistance)
                        {
                            trigger.ActivateTrigger();
                        }
                    }

                    continue;
                }

                //DespawnNear
                if (trigger.Type == "DespawnNear")
                {
                    //Logger.MsgDebug("Checking DespawnNear Trigger: " + trigger.ProfileSubtypeId, DebugTypeEnum.Trigger);
                    if (trigger.UseTrigger == true)
                    {
                        if (_behavior.Settings.DespawnCoords != Vector3D.Zero && Vector3D.Distance(RemoteControl.GetPosition(), _behavior.Settings.DespawnCoords) < trigger.TargetDistance)
                        {
                            trigger.ActivateTrigger();
                        }
                    }

                    continue;
                }

                //DespawnFar
                if (trigger.Type == "DespawnFar")
                {
                    //Logger.MsgDebug("Checking DespawnFar Trigger: " + trigger.ProfileSubtypeId, DebugTypeEnum.Trigger);
                    if (trigger.UseTrigger == true)
                    {
                        if (_behavior.Settings.DespawnCoords != Vector3D.Zero && Vector3D.Distance(RemoteControl.GetPosition(), _behavior.Settings.DespawnCoords) > trigger.TargetDistance)
                        {
                            trigger.ActivateTrigger();
                        }
                    }

                    continue;
                }

                //TurretTarget
                if (trigger.Type == "TurretTarget")
                {
                    //Logger.MsgDebug("Checking TurretTarget Trigger: " + trigger.ProfileSubtypeId, DebugTypeEnum.Trigger);
                    if (trigger.UseTrigger == true)
                    {
                        var turretTarget = _autopilot.Weapons.GetTurretTarget();

                        if (turretTarget != 0)
                        {
                            trigger.ActivateTrigger();

                            if (trigger.Triggered == true)
                            {
                                trigger.DetectedEntityId = turretTarget;
                            }
                        }
                    }

                    continue;
                }

                //NoWeapon
                if (trigger.Type == "NoWeapon")
                {
                    //Logger.MsgDebug("Checking NoWeapon Trigger: " + trigger.ProfileSubtypeId, DebugTypeEnum.Trigger);
                    if (trigger.UseTrigger && !_autopilot.Weapons.HasWorkingWeapons())
                    {
                        trigger.ActivateTrigger();
                    }

                    continue;
                }

                //NoTarget
                if (trigger.Type == "NoTarget")
                {
                    //Logger.MsgDebug("Checking NoTarget Trigger: " + trigger.ProfileSubtypeId, DebugTypeEnum.Trigger);
                    if (trigger.UseTrigger)
                    {
                        if (!_autopilot.Targeting.HasTarget())
                        {
                            trigger.ActivateTrigger();
                        }
                    }

                    continue;
                }

                //HasTarget
                if (trigger.Type == "HasTarget")
                {
                    //Logger.MsgDebug("Checking HasTarget Trigger: " + trigger.ProfileSubtypeId, DebugTypeEnum.Trigger);
                    if (trigger.UseTrigger)
                    {
                        if (_autopilot.Targeting.HasTarget())
                        {
                            trigger.ActivateTrigger();
                        }
                    }

                    continue;
                }

                //AcquiredTarget
                if (trigger.Type == "AcquiredTarget")
                {
                    //Logger.MsgDebug("Checking NoTarget Trigger: " + trigger.ProfileSubtypeId, DebugTypeEnum.Trigger);
                    if (trigger.UseTrigger)
                    {
                        if (_autopilot.Targeting.TargetAcquired)
                        {
                            _autopilot.Targeting.TargetAcquired = false;
                            trigger.ActivateTrigger();
                        }
                    }

                    continue;
                }

                //LostTarget
                if (trigger.Type == "LostTarget")
                {
                    //Logger.MsgDebug("Checking HasTarget Trigger: " + trigger.ProfileSubtypeId, DebugTypeEnum.Trigger);
                    if (trigger.UseTrigger)
                    {
                        if (_autopilot.Targeting.TargetLost)
                        {
                            _autopilot.Targeting.TargetLost = false;
                            trigger.ActivateTrigger();
                        }
                    }

                    continue;
                }

                //TargetInSafezone
                if (trigger.Type == "TargetInSafezone")
                {
                    //Logger.MsgDebug("Checking TargetInSafezone Trigger: " + trigger.ProfileSubtypeId, DebugTypeEnum.Trigger);
                    if (trigger.UseTrigger == true)
                    {
                        if (_autopilot.Targeting.HasTarget() && _autopilot.Targeting.Target.InSafeZone())
                        {
                            trigger.ActivateTrigger();
                        }
                    }

                    continue;
                }

                //Grounded
                if (trigger.Type == "Grounded")
                {
                    if (trigger.UseTrigger == true)
                    {
                        //Check if Grounded
                        trigger.ActivateTrigger();
                    }

                    continue;
                }

                //BehaviorTriggerA
                if (trigger.Type == "BehaviorTriggerA")
                {
                    if (trigger.UseTrigger == true && _behavior.BehaviorTriggerA)
                    {
                        trigger.ActivateTrigger();
                    }

                    continue;
                }

                //BehaviorTriggerB
                if (trigger.Type == "BehaviorTriggerB")
                {
                    if (trigger.UseTrigger == true && _behavior.BehaviorTriggerB)
                    {
                        trigger.ActivateTrigger();
                    }

                    continue;
                }

                //BehaviorTriggerC
                if (trigger.Type == "BehaviorTriggerC")
                {
                    if (trigger.UseTrigger == true && _behavior.BehaviorTriggerC)
                    {
                        trigger.ActivateTrigger();
                    }

                    continue;
                }

                //BehaviorTriggerD
                if (trigger.Type == "BehaviorTriggerD")
                {
                    if (trigger.UseTrigger == true && _behavior.BehaviorTriggerD)
                    {
                        trigger.ActivateTrigger();
                    }

                    continue;
                }

                //BehaviorTriggerE
                if (trigger.Type == "BehaviorTriggerE")
                {
                    if (trigger.UseTrigger == true && _behavior.BehaviorTriggerE)
                    {
                        trigger.ActivateTrigger();
                    }

                    continue;
                }

                //BehaviorTriggerF
                if (trigger.Type == "BehaviorTriggerF")
                {
                    if (trigger.UseTrigger == true && _behavior.BehaviorTriggerF)
                    {
                        trigger.ActivateTrigger();
                    }

                    continue;
                }

                //BehaviorTriggerG
                if (trigger.Type == "BehaviorTriggerG")
                {
                    if (trigger.UseTrigger == true && _behavior.BehaviorTriggerG)
                    {
                        trigger.ActivateTrigger();
                    }

                    continue;
                }

                //PaymentSuccess
                if (trigger.Type == "PaymentSuccess")
                {
                    if (trigger.UseTrigger == true && PaymentSuccessTriggered)
                    {
                        trigger.ActivateTrigger();
                    }

                    continue;
                }

                //PaymentFailure
                if (trigger.Type == "PaymentFailure")
                {
                    if (trigger.UseTrigger == true && PaymentFailureTriggered)
                    {
                        trigger.ActivateTrigger();
                    }

                    continue;
                }

                //PlayerKnownLocation
                if (trigger.Type == "PlayerKnownLocation")
                {
                    if (MESApi.MESApiReady)
                    {
                        if (trigger.UseTrigger == true && MESApi.IsPositionInKnownPlayerLocation(RemoteControl.GetPosition(), true, _behavior.Owner.Faction?.Tag))
                        {
                            trigger.ActivateTrigger();
                        }
                    }

                    continue;
                }

                //SensorActive
                if (trigger.Type == "SensorActive")
                {
                    if (_behavior.Grid.SensorCheck(trigger.SensorName))
                    {
                        trigger.ActivateTrigger();
                    }

                    continue;
                }

                //SensorActive
                if (trigger.Type == "SensorIdle")
                {
                    if (_behavior.Grid.SensorCheck(trigger.SensorName, false))
                    {
                        trigger.ActivateTrigger();
                    }

                    continue;
                }
            }

            _behavior.BehaviorTriggerA = false;
            _behavior.BehaviorTriggerB = false;
            _behavior.BehaviorTriggerC = false;
            _behavior.BehaviorTriggerD = false;
            _behavior.BehaviorTriggerE = false;
            _behavior.BehaviorTriggerF = false;
            _behavior.BehaviorTriggerG = false;
            PaymentSuccessTriggered    = false;
            PaymentFailureTriggered    = false;
            TimedTriggersProcessed     = true;
        }