Inheritance: MonoBehaviour
Ejemplo n.º 1
0
 public override bool Update(MyPlayer player, MyEntity me)
 {
     if (me!=null)
         if (Vector3D.DistanceSquared(me.PositionComp.GetPosition(), TargetPos) > m_maxDistance2)
             m_IsTrue = true;
     return IsTrue;
 }
        public bool Update(MyPlayer player, MyEntity entity) //returns if lost
        {
            //MySessionComponentMission.Static.TryCreateFromDefault(Id);

            //if (IsLocal(player.Id))
            //    UpdateLocal(player.Id);

            if (!Sync.IsServer)
                return false;

            MyMissionTriggers mtrig;
            if (!MissionTriggers.TryGetValue(player.Id, out mtrig))
            {
                //Debug.Assert(false,"Bad ID for update in missionTriggers");
                mtrig = TryCreateFromDefault(player.Id, false);
            }
            mtrig.UpdateWin(player, entity);
            if (!mtrig.Won)
                mtrig.UpdateLose(player, entity);
            else
            {
                m_someoneWon = true;
                MyAnalyticsHelper.ReportTutorialEnd();
                MyTutorialHelper.MissionSuccess();
            }
            return mtrig.Lost;
        }
        public static void Init()
        {
            if ( !PluginSettings.Instance.PlayerBlockEnforcementEnabled )
                return;

            if (_init)
                return;

            _init = true;

            MyEntities.OnEntityAdd += MyEntities_OnEntityAdd;

            HashSet<MyEntity> allEntities = new HashSet<MyEntity>();
            Wrapper.GameAction( () => allEntities = MyEntities.GetEntities() );

            MyEntity[] entitiesCopy = new MyEntity[allEntities.Count];
            allEntities.CopyTo( entitiesCopy );

            Parallel.ForEach( entitiesCopy, ( entity ) =>
                                            {
                                                var grid = entity as MyCubeGrid;
                                                if ( grid == null )
                                                    return;

                                                InitGrid( grid );
                                            } );
            Essentials.Log.Info( "Initialized player block enforcement." );
            ProcessEnforcement();
        }
Ejemplo n.º 4
0
 private void on_entity_deleted(MyEntity entity)
 {
     //log_event("on_entity_deleted", entity);
     var cube_grid = entity as MyCubeGrid;
     if (cube_grid != null)
         grid_manager.remove_grid(cube_grid);
 }
Ejemplo n.º 5
0
 public override bool Update(MyPlayer player, MyEntity me)
 {
     if (MySession.Static.IsScenario)
         if (m_limit <= DateTime.UtcNow - MyScenarioSystem.Static.ServerStartGameTime)
             m_IsTrue = true;
     return IsTrue;
 }
 public MyCharacterPhysicsStateGroup(MyEntity entity, IMyReplicable ownerReplicable)
     : base(entity, ownerReplicable)
 {
     // This is 9 bits per component which is more than enough (512 discrete values per-axis)
     m_lowPrecisionOrientation = true;
     FindSupportDelegate = () => MySupportHelper.FindSupportForCharacter(Entity);
 }
 override protected bool IsMoving(MyEntity entity)
 {
     // Never know if somebody is moving entity when physics is null
     return Entity.Physics == null
         || Vector3.IsZero(entity.Physics.LinearVelocity, PRECISION) == false
         || Entity.RotationSpeed > 0.0f;
 }
Ejemplo n.º 8
0
 public MyRadioBroadcaster(MyEntity parent, float broadcastRadius = 100)
 {
     SyncObject = new MySyncRadioBroadcaster(this);
     Parent = parent;
     m_broadcastRadius = broadcastRadius;
     parent.OnClose += parent_OnClose;
 }
 public MyBasicObstacle(MyEntity entity)
 {
     m_entity = entity;
     m_entity.OnClosing += OnEntityClosing;
     Update();
     m_valid = true;
 }
Ejemplo n.º 10
0
 public virtual void Init(Vector3 offset, MyEntity parentObject, MyModelsEnum model)
 {
     base.Init(null, model, null, parentObject, null, null);
     LocalMatrix = Matrix.CreateTranslation(offset);
     RotationSpeed = 0;
     Save = false;
 }
 public override ChangeInfo Update(MyEntity owner, long playerID = 0)
 {
     if (MyCubeBuilder.Static==null)
         return ChangeInfo.None;
     var blockDefinition = MyCubeBuilder.Static.IsActivated ? MyCubeBuilder.Static.ToolbarBlockDefinition : null;
     if ((MyCubeBuilder.Static.BlockCreationIsActivated || MyCubeBuilder.Static.MultiBlockCreationIsActivated) && blockDefinition != null && (!MyFakes.ENABLE_BATTLE_SYSTEM || !MySession.Static.Battle))
     {
         var blockDef = (this.Definition as Sandbox.Definitions.MyCubeBlockDefinition);
         if (blockDefinition.BlockPairName == blockDef.BlockPairName)
         {
             WantsToBeSelected = true;
         }
         else if (blockDef.BlockStages != null && blockDef.BlockStages.Contains(blockDefinition.Id))
         {
             WantsToBeSelected = true;
         }
         else
         {
             WantsToBeSelected = false;
         }
     }
     else
     {
         WantsToBeSelected = false;
     }
     return ChangeInfo.None;
 }
Ejemplo n.º 12
0
 protected virtual bool IsMoving(MyEntity entity)
 {
     // Never know if somebody is moving entity when physics is null
     return entity.Physics == null
         || Vector3.IsZero(entity.Physics.LinearVelocity, PRECISION) == false
         || Vector3.IsZero(entity.Physics.AngularVelocity, PRECISION) == false;
 }
Ejemplo n.º 13
0
        public static void Add(MyEntity entity)
        {
            Debug.Assert(entity.Parent == null || (entity.Flags & EntityFlags.IsGamePrunningStructureObject) != 0, "Only topmost entities");

            if (entity.TopMostPruningProxyId != MyVRageConstants.PRUNING_PROXY_ID_UNITIALIZED) return;  // already inserted

            BoundingBoxD bbox = GetEntityAABB(entity);
            if (bbox.Size == Vector3D.Zero) return;  // don't add entities with zero bounding boxes


            if (IsEntityStatic(entity))
            {
                entity.TopMostPruningProxyId = m_staticObjectsTree.AddProxy(ref bbox, entity, 0);
                entity.StaticForPruningStructure = true;
            }
            else
            {
                entity.TopMostPruningProxyId = m_dynamicObjectsTree.AddProxy(ref bbox, entity, 0);
                entity.StaticForPruningStructure = false;
            }

            var voxelMap = entity as MyVoxelBase;
            if (voxelMap != null)
            {
                voxelMap.VoxelMapPruningProxyId = m_voxelMapsTree.AddProxy(ref bbox, entity, 0);
            }
        }
Ejemplo n.º 14
0
        public static MyEntity FindSupportForCharacterAABB(MyEntity entity)
        {
            BoundingBoxD characterBox = entity.PositionComp.WorldAABB;
            characterBox.Inflate(1.0);
            m_entities.Clear();

            MyEntities.GetTopMostEntitiesInBox(ref characterBox, m_entities);

            float maxRadius = 0;
            MyCubeGrid biggestGrid = null;
            MyEntity voxel = null;
            foreach(var parent in m_entities)
            {
                MyCubeGrid grid =  parent as MyCubeGrid;
                if(parent is MyVoxelBase)
                {
                    voxel = (parent as MyVoxelBase).RootVoxel;
                }
                if(grid != null)
                {
                    var rad = grid.PositionComp.LocalVolume.Radius;
                    if (rad > maxRadius || (rad == maxRadius && (biggestGrid == null || grid.EntityId > biggestGrid.EntityId)))
                    {
                        maxRadius = rad;
                        biggestGrid = grid;
                    }
                }
            }

            if (biggestGrid == null)
            {
                 return voxel;
            }
            return biggestGrid;
        }
Ejemplo n.º 15
0
        //  Not used apparently
        public static void AddShotgun(MyProjectileAmmoDefinition ammoDefinition, MyEntity ignorePhysObject, Vector3 origin, Vector3 initialVelocity, Vector3 directionNormalized, bool groupStart, float thicknessMultiplier, MyEntity weapon, float frontBillboardSize, MyEntity ownerEntity = null, float projectileCountMultiplier = 1)
        {
            MyProjectile newProjectile = m_projectiles.Allocate();
            if (newProjectile != null)
            {
                //newProjectile.Start(
                //    ammoDefinition,
                //    ignorePhysObject,
                //    origin,
                //    initialVelocity,
                //    directionNormalized,
                //    groupStart,
                //    thicknessMultiplier,
                //    1,
                //    weapon,
                //    projectileCountMultiplier
                //    );

            //    newProjectile.BlendByCameraDirection = true;
            //    newProjectile.FrontBillboardMaterial = "ShotgunParticle";
            //    newProjectile.LengthMultiplier = 2;
            //    newProjectile.FrontBillboardSize = frontBillboardSize;
             //   newProjectile.OwnerEntity = ownerEntity != null ? ownerEntity : ignorePhysObject;
            }
        }
Ejemplo n.º 16
0
 public void FirstIntoRowShouldReturnFirstRowIfMoreThanOneEntityUsed()
 {
     var first = new MyEntity() { Table = "x" };
     var second = new MyEntity() { Table = "y" };
     var query = new SqlQuery().From(first).From(second.Table, Alias.T1).Into(second);
     Assert.Equal(first, ((ISqlQueryExtensible)query).FirstIntoRow);
 }
        private void SectorOnContactPoint(int itemId, MyEntity other, ref MyPhysics.MyContactPointEvent e)
        {
            // if item is already disabled: puff
            // We get multiple contact points so this is for that
            if (m_sector.DataView.Items[itemId].ModelIndex < 0) return;

            var vel = Math.Abs(e.ContactPointEvent.SeparatingVelocity);

            if (other == null || other.Physics == null || other is MyFloatingObject) return;

            if (other is IMyHandheldGunObject<MyDeviceBase>) return;

            // Prevent debris from breaking trees.
            // Debris flies in unpredictable ways and this could cause out of sync tree destruction which would is bad.
            if (other.Physics.RigidBody != null && other.Physics.RigidBody.Layer == MyPhysics.CollisionLayers.DebrisCollisionLayer) return;

            // On objects held in manipulation tool, Havok returns high velocities, after this contact is fired by contraint solver.
            // Therefore we disable damage from objects connected by constraint to character
            if (MyManipulationTool.IsEntityManipulated(other))
                return;

            float otherMass = MyDestructionHelper.MassFromHavok(other.Physics.Mass);

            double impactEnergy = vel * vel * otherMass;

            // TODO: per item max impact energy
            if (impactEnergy > ItemResilience(itemId))
            {
                BreakAt(itemId, e.Position, e.ContactPointEvent.ContactPoint.Normal, impactEnergy);
            }

            // Meteor destroy always
            if (other is MyMeteor)
                m_sector.EnableItem(itemId, false);
        }
Ejemplo n.º 18
0
        public override void Init(StringBuilder displayName, Models.MyModelsEnum? modelLod0Enum, Models.MyModelsEnum? modelLod1Enum, MyEntity parentObject, float? scale, CommonLIB.AppCode.ObjectBuilders.MyMwcObjectBuilder_Base objectBuilder, Models.MyModelsEnum? modelCollision = null, Models.MyModelsEnum? modelLod2 = null)
        {
            base.Init(displayName, modelLod0Enum, modelLod1Enum, parentObject, scale, objectBuilder, modelCollision, modelLod2);

            switch (modelLod0Enum)
            {
                case Models.MyModelsEnum.Cockpit_SS_04:
                    Crosshair = HUD.MyHudTexturesEnum.crosshair_nazzi; 
                    break;
                case Models.MyModelsEnum.Cockpit_Razorclaw:
                    Crosshair = HUD.MyHudTexturesEnum.crosshair_templary;
                    break;
                case Models.MyModelsEnum.Cockpit_CN_03:
                    Crosshair = HUD.MyHudTexturesEnum.crosshair_russian;
                    break;
                case Models.MyModelsEnum.OmniCorp_EAC01_Cockpit:
                case Models.MyModelsEnum.OmniCorp01_Cockpit:
                case Models.MyModelsEnum.OmniCorp04_Cockpit:
                case Models.MyModelsEnum.OmniCorp03_Cockpit:
                    Crosshair = HUD.MyHudTexturesEnum.crosshair_omnicorp;
                    break;
                case Models.MyModelsEnum.EAC02_Cockpit:
                case Models.MyModelsEnum.EAC03_Cockpit:
                case Models.MyModelsEnum.EAC04_Cockpit:
                case Models.MyModelsEnum.EAC05_Cockpit:
                default:
                    Crosshair = HUD.MyHudTexturesEnum.Crosshair01;
                    break;
            }
            m_modelLod0.PreloadTextures(LoadingMode.Immediate, MaterialIndex);
        }
Ejemplo n.º 19
0
        //  This method realy initiates/starts the missile
        //  IMPORTANT: Direction vector must be normalized!
        public void Start(
            Vector3 position,
            Vector3 initialVelocity,
            Vector3 direction,
            float impulseMultiplier,
            MyEntity owner)
        {
            if (Physics.Static)
            {
                Physics.Static = false;
            }

            base.Start(position, initialVelocity, direction, impulseMultiplier, owner, MyTextsWrapper.Get(MyTextsWrapperEnum.RemoteCameraHud));

            Physics.AngularDamping = 1;
            Health = MaxHealth;
            m_directionAfterContact = null;

            var ownerShip = owner as MySmallShip;
            if (ownerShip != null)
            {
                ownerShip.Config.BackCamera.SetOn();
                ownerShip.AddRemoteCamera(this);
                ownerShip.SelectLastRemoteCamera();
            }
        }
Ejemplo n.º 20
0
 public void SetAbsoluteTarget(Vector3 absoluteTarget)
 {
     m_mode = AimingMode.TARGET;
     m_aimTarget = null;
     m_relativeTarget = absoluteTarget;
     Update();
 }
Ejemplo n.º 21
0
 public void SetTarget(MyEntity entity, Vector3? relativeTarget = null)
 {
     m_mode = AimingMode.TARGET;
     m_aimTarget = entity;
     m_relativeTarget = relativeTarget;
     Update();
 }
 private void EntityRemoved(MyEntity entity)
 {
     var planet = entity as MyPlanet;
     if (planet != null)
     {
         m_planets.Remove(entity.EntityId);
     }
 }
 private void EntityAdded(MyEntity entity)
 {
     var planet = entity as MyPlanet;
     if (planet != null)
     {
         m_planets.Add(entity.EntityId, planet);
     }
 }
Ejemplo n.º 24
0
        public void Init(MyEntity parent)
        {
            base.Init(null, MyModelsEnum.HarvestingHead, null, parent, null, null);

            //  For performance optimizations, we don't check if this small objects are in a frustum and draw them directly
            m_frustumCheckBeforeDrawEnabled = false;
            Save = false;
        }
 override protected bool IsMoving(MyEntity entity)
 {
     // Never know if somebody is moving entity when physics is null
     return Entity.Physics == null
         || Vector3.IsZero(entity.Physics.LinearVelocity, PRECISION) == false
         || Vector2.IsZero(Entity.RotationIndicator, PRECISION) == false 
         || Math.Abs(Entity.RollIndicator - 0.0f) > 0.001f;
 }
Ejemplo n.º 26
0
        public void GetEntityName_returns_name_of_entity()
        {
            var entity = new MyEntity();

            var name = entity.GetEntityName();

            Assert.AreEqual("MyEntity", name);
        }
Ejemplo n.º 27
0
 public MyRadioBroadcaster(MyEntity parent, float broadcastRadius = 100, bool enabled = true)
 {
     SyncObject = new MySyncRadioBroadcaster(this);
     Parent = parent;
     m_broadcastRadius = broadcastRadius;
     parent.OnClose += parent_OnClose;
     Enabled = enabled;
 }
Ejemplo n.º 28
0
        public override void Init(StringBuilder displayName, Models.MyModelsEnum? modelLod0Enum, Models.MyModelsEnum? modelLod1Enum, MyEntity parentObject, float? scale, CommonLIB.AppCode.ObjectBuilders.MyMwcObjectBuilder_Base objectBuilder, Models.MyModelsEnum? modelCollision = null, Models.MyModelsEnum? modelLod2Enum = null)
        {
            // Some fake builder
            var builder = new MyMwcObjectBuilder_SmallShip_Weapon(MyMwcObjectBuilder_SmallShip_Weapon_TypesEnum.Drilling_Device_Crusher);

            base.Init(displayName, modelLod0Enum, modelLod1Enum, parentObject, scale, builder, modelCollision, modelLod2Enum);
            SetModel(MyModelsEnum.MysteriousBox_matt_5m);
        }
Ejemplo n.º 29
0
 void m_entity_OnClose(MyEntity obj)
 {
     if (m_shotSmoke != null)
     {
         MyParticlesManager.RemoveParticleEffect(m_shotSmoke);
         m_shotSmoke = null;
     }
 }
 public MyEntityPhysicsStateGroupWithSupport(MyEntity entity, IMyReplicable ownerReplicable)
     : base(entity, ownerReplicable)
 {
     m_onSupportMove = OnSupportMove;
     m_onSupportVelocityChanged = OnSupportVelocityChanged;
     if (Sync.IsServer)
         OnMoved += PhysicsStateGroup_OnMoved;
 }
Ejemplo n.º 31
0
 private void m_endEntity_OnClosing(MyEntity obj)
 {
     m_endEntity = null;
     IsValid     = false;
 }
 protected override bool IsUsed(MyEntity thrustEntity)
 {
     return(Enabled);
 }
Ejemplo n.º 33
0
 void collidedEntity_OnClose(MyEntity obj)
 {
     m_collidedEntity = null;
     obj.OnClose     -= m_collidedEntity_OnClose;
 }
 protected override void AddToGroup(MyEntity thrustEntity, MyEntityThrustComponent.MyConveyorConnectedGroup group)
 {
 }
        protected override void CustomClientRead(uint timeStamp, ref MyTimeStampValues serverPositionAndOrientation, VRage.Library.Collections.BitStream stream)
        {
            bool hasSupport = stream.ReadBool();

            if (hasSupport)
            {
                long entityId = stream.ReadInt64();

                Vector3D serverDelta      = stream.ReadVector3D();
                Vector3D serverSupportPos = stream.ReadVector3D();

                if (!MyEntities.EntityExists(entityId))
                {
                    return;
                }

                MyEntity support = MyEntities.GetEntityById(entityId);

                MyTimeStampValues?clientTransform = m_timestamp.GetTransform(timeStamp);

                Vector3D   clientDelta    = Vector3.Zero;
                Vector3D   clientVelocity = Vector3D.Zero;
                Quaternion rotationComp   = Quaternion.Identity;

                if (clientTransform != null)
                {
                    if (m_supportTimeStamp == null)
                    {
                        return;
                    }
                    MyTimeStampValues?supportTransform = m_supportTimeStamp.GetTransform(timeStamp);

                    Vector3D supportPosition = support.PositionComp.WorldMatrix.Translation;

                    if (supportTransform.HasValue)
                    {
                        supportPosition = supportTransform.Value.Transform.Position;

                        if (supportTransform.Value.EntityId != entityId)
                        {
                            supportPosition = serverSupportPos;
                            return;
                        }
                    }

                    clientDelta    = supportPosition - clientTransform.Value.Transform.Position;
                    clientVelocity = clientTransform.Value.LinearVelocity;
                    rotationComp   = Quaternion.Inverse(clientTransform.Value.Transform.Rotation);
                }
                else
                {
                    m_character.PositionComp.SetWorldMatrix(serverPositionAndOrientation.Transform.TransformMatrix, null, true);
                    return;
                }

                MyTimeStampValues delta = new MyTimeStampValues();

                Quaternion.Multiply(ref serverPositionAndOrientation.Transform.Rotation, ref rotationComp, out delta.Transform.Rotation);

                delta.Transform.Position = clientDelta - serverDelta;
                delta.LinearVelocity     = serverPositionAndOrientation.LinearVelocity - clientVelocity;

                double deltaL = delta.Transform.Position.Length();

                //if difference is more than
                if (deltaL < (MyGridPhysics.ShipMaxLinearVelocity() * Sync.RelativeSimulationRatio))
                {
                    delta.Transform.Position = delta.Transform.Position * 0.2;
                    delta.Transform.Rotation = Quaternion.Slerp(delta.Transform.Rotation, Quaternion.Identity, 0.2f);
                }


                Quaternion normalized = delta.Transform.Rotation;
                normalized.Normalize();
                delta.Transform.Rotation = normalized;
                normalized = serverPositionAndOrientation.Transform.Rotation;
                normalized.Normalize();
                serverPositionAndOrientation.Transform.Rotation = normalized;

                Quaternion clientNormalized = clientTransform.Value.Transform.Rotation;
                clientNormalized.Normalize();

                double eps        = 0.001;
                bool   hasJetpack = m_character.JetpackComp != null;
                if (hasJetpack && m_character.JetpackComp.TurnedOn && m_character.IsDead == false)
                {
                    if (Math.Abs(Quaternion.Dot(serverPositionAndOrientation.Transform.Rotation, clientNormalized)) < 1 - eps)
                    {
                        Quaternion currentOrientation = Quaternion.CreateFromForwardUp(m_character.WorldMatrix.Forward, m_character.WorldMatrix.Up);
                        Quaternion.Multiply(ref delta.Transform.Rotation, ref currentOrientation, out currentOrientation);

                        MatrixD matrix        = MatrixD.CreateFromQuaternion(currentOrientation);
                        MatrixD currentMatrix = m_character.PositionComp.WorldMatrix;
                        currentMatrix.Translation = Vector3D.Zero;

                        if (currentMatrix.EqualsFast(ref matrix) == false)
                        {
                            if (m_character.Physics.CharacterProxy != null)
                            {
                                m_character.Physics.CharacterProxy.Forward = matrix.Forward;
                                m_character.Physics.CharacterProxy.Up      = matrix.Up;
                            }
                        }
                    }
                }

                if (deltaL > (MyGridPhysics.ShipMaxLinearVelocity() * Sync.RelativeSimulationRatio))
                {
                    m_character.PositionComp.SetPosition(serverPositionAndOrientation.Transform.Position);
                    m_character.Physics.LinearVelocity = serverPositionAndOrientation.LinearVelocity;
                    m_timestamp.OverwriteServerPosition(timeStamp, ref serverPositionAndOrientation);
                    return;
                }
                else if (deltaL > 5.0f * MyTimestampHelper.POSITION_TOLERANCE)
                {
                    m_character.CacheMoveDelta(ref delta.Transform.Position);
                }

                m_character.Physics.LinearVelocity += delta.LinearVelocity;

                m_timestamp.UpdateDeltaPosition(timeStamp, ref delta);
            }
            else
            {
                base.CustomClientRead(timeStamp, ref serverPositionAndOrientation, stream);
            }
        }
Ejemplo n.º 36
0
 public MySyncEntity(MyEntity entity)
 {
     Entity = entity;
     ResetUpdateTimer();
     UpdatesOnlyOnServer = false;
 }
Ejemplo n.º 37
0
 // 构造方法
 public MyQueryable(string connectionString)
 {
     _masterEntity     = MyEntityContainer.Get(typeof(T));
     _connectionString = connectionString;
 }
 public float GetPostModifier(float damage, MyStringHash damageSource, MyHitInfo?hitInfo, MyEntity attacker = null)
 {
     return(0);
 }
        public float GetMultiplier(float damage, MyStringHash damageSource, MyHitInfo?hitInfo, MyEntity attacker = null)
        {
            if (Definition == null)
            {
                return(1);
            }

            float reduction;

            return(Definition.DamageReduction.TryGetValue(damageSource, out reduction) ? 1 - reduction : 1);
        }
Ejemplo n.º 40
0
 public MyEntity3DSoundEmitter(MyEntity entity, MyEntity owner = null)
 {
     m_entity = entity;
     m_owner  = owner;
 }
Ejemplo n.º 41
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;
            }
        }
Ejemplo n.º 42
0
        public void RequestJump(string destinationName, Vector3D destination, long userId)
        {
            if (!Vector3.IsZero(MyGravityProviderSystem.CalculateNaturalGravityInPoint(m_grid.WorldMatrix.Translation)))
            {
                var notification = new MyHudNotification(MySpaceTexts.NotificationCannotJumpFromGravity, 1500);
                MyHud.Notifications.Add(notification);
                return;
            }
            if (!Vector3.IsZero(MyGravityProviderSystem.CalculateNaturalGravityInPoint(destination)))
            {
                var notification = new MyHudNotification(MySpaceTexts.NotificationCannotJumpIntoGravity, 1500);
                MyHud.Notifications.Add(notification);
                return;
            }

            if (!IsJumpValid(userId))
            {
                return;
            }

            if (MySession.Static.Settings.WorldSizeKm > 0 && destination.Length() > MySession.Static.Settings.WorldSizeKm * 500)
            {
                var notification = new MyHudNotification(MySpaceTexts.NotificationCannotJumpOutsideWorld, 1500);
                MyHud.Notifications.Add(notification);
                return;
            }

            m_selectedDestination = destination;
            double maxJumpDistance = GetMaxJumpDistance(userId);

            m_jumpDirection = destination - m_grid.WorldMatrix.Translation;
            double jumpDistance   = m_jumpDirection.Length();
            double actualDistance = jumpDistance;

            if (jumpDistance > maxJumpDistance)
            {
                double ratio = maxJumpDistance / jumpDistance;
                actualDistance   = maxJumpDistance;
                m_jumpDirection *= ratio;
            }

            //By Gregory: Check for obstacle not that fast but happens rarely(on Jump drive enable)
            //TODO: make compatible with GetMaxJumpDistance and refactor to much code checks for actual jump
            var direction = Vector3D.Normalize(destination - m_grid.WorldMatrix.Translation);
            var startPos  = m_grid.WorldMatrix.Translation + m_grid.PositionComp.LocalAABB.Extents.Max() * direction;
            var line      = new LineD(startPos, destination);


            var intersection = MyEntities.GetIntersectionWithLine(ref line, m_grid, null, ignoreObjectsWithoutPhysics: false);

            Vector3D newDestination = Vector3D.Zero;
            Vector3D newDirection   = Vector3D.Zero;

            if (intersection.HasValue)
            {
                MyEntity MyEntity = intersection.Value.Entity as MyEntity;

                var targetPos     = MyEntity.WorldMatrix.Translation;
                var obstaclePoint = MyUtils.GetClosestPointOnLine(ref startPos, ref destination, ref targetPos);

                MyPlanet MyEntityPlanet = intersection.Value.Entity as MyPlanet;
                if (MyEntityPlanet != null)
                {
                    var notification = new MyHudNotification(MySpaceTexts.NotificationCannotJumpIntoGravity, 1500);
                    MyHud.Notifications.Add(notification);
                    return;
                }

                //var Radius = MyEntityPlanet != null ? MyEntityPlanet.MaximumRadius : MyEntity.PositionComp.LocalAABB.Extents.Length();
                var Radius = MyEntity.PositionComp.LocalAABB.Extents.Length();

                destination           = obstaclePoint - direction * (Radius + m_grid.PositionComp.LocalAABB.HalfExtents.Length());
                m_selectedDestination = destination;
                m_jumpDirection       = m_selectedDestination - startPos;
                actualDistance        = m_jumpDirection.Length();
            }

            if (actualDistance < MIN_JUMP_DISTANCE)
            {
                MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                           buttonType: MyMessageBoxButtonsType.OK,
                                           messageText: GetWarningText(actualDistance, intersection.HasValue),
                                           messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionWarning)
                                           ));
            }
            else
            {
                MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                           buttonType : MyMessageBoxButtonsType.YES_NO,
                                           messageText : GetConfimationText(destinationName, jumpDistance, actualDistance, userId, intersection.HasValue),
                                           messageCaption : MyTexts.Get(MyCommonTexts.MessageBoxCaptionPleaseConfirm),
                                           size : new Vector2(0.839375f, 0.3675f), callback : delegate(MyGuiScreenMessageBox.ResultEnum result)
                {
                    if (result == MyGuiScreenMessageBox.ResultEnum.YES && IsJumpValid(userId))
                    {
                        RequestJump(m_selectedDestination, userId);
                    }
                    else
                    {
                        AbortJump();
                    }
                }
                                           ));
            }
        }
Ejemplo n.º 43
0
        private void TakeMaterialsFromBuilder(MyEntity builder)
        {
            if (builder == null)
            {
                return;
            }
            var inventory = GetBuilderInventory(builder);

            if (inventory == null)
            {
                return;
            }
            MyInventory shipInventory = null;
            MyCockpit   cockpit       = null;
            long        identityId    = long.MaxValue;

            if (builder is MyCharacter)
            {//construction cockpit?
                cockpit = (builder as MyCharacter).IsUsing as MyCockpit;
                if (cockpit != null)
                {
                    shipInventory = cockpit.GetInventory();
                    identityId    = cockpit.ControllerInfo.ControllingIdentityId;
                }
                else
                if ((builder as MyCharacter).ControllerInfo != null)
                {
                    identityId = (builder as MyCharacter).ControllerInfo.ControllingIdentityId;
                }
                else
                {
                    Debug.Fail("failed to get identityId");
                }
            }

            VRage.MyFixedPoint hasAmount, hasAmountCockpit;

            foreach (var entry in m_materialList.RequiredMaterials)
            {
                VRage.MyFixedPoint toRemove = entry.Value;
                hasAmount = GetItemAmountCombined(inventory, entry.Key);
                if (hasAmount > entry.Value)
                {
                    RemoveItemsCombined(inventory, (int)toRemove, entry.Key);
                    continue;
                }
                if (hasAmount > 0)
                {
                    RemoveItemsCombined(inventory, (int)hasAmount, entry.Key);
                    toRemove -= hasAmount;
                }
                if (shipInventory != null)
                {
                    hasAmountCockpit = GetItemAmountCombined(shipInventory, entry.Key);
                    if (hasAmountCockpit >= toRemove)
                    {
                        RemoveItemsCombined(shipInventory, (int)toRemove, entry.Key);
                        continue;
                    }
                    if (hasAmountCockpit > 0)
                    {
                        RemoveItemsCombined(shipInventory, (int)hasAmountCockpit, entry.Key);
                        toRemove -= hasAmountCockpit;
                    }
                    var transferred = MyGridConveyorSystem.ItemPullRequest(cockpit, shipInventory, identityId, entry.Key, toRemove, true);
                    Debug.Assert(transferred == toRemove, "Cannot pull enough materials to build, " + transferred + "!=" + toRemove);
                }
                else
                {
                    Debug.Assert(toRemove == 0, "Needs more materials and ship inventory is null");
                }
            }
        }
Ejemplo n.º 44
0
 private void DroneMainEntityOnClosing(MyEntity entity)
 {
     UnregisterDrone(entity);
 }
Ejemplo n.º 45
0
        /// <summary>
        /// Adjusts input for the autopilot's velocity and entity's velocity.
        /// </summary>
        /// <param name="input">Original TestInput with Direction as the desired direction of travel and Length as the distance to the destination.</param>
        /// <param name="adjusted">Offset will be zero, Direction and Length will be modified from input for the velocity of autopilot and entity.</param>
        /// <param name="entity">The potential obstruction, if null, assumes a static entity</param>
        public void AdjustForCurrentVelocity(ref TestInput input, out TestInput adjusted, MyEntity entity, bool destination)
        {
            Vector3 autopilotVelocity = AutopilotGrid.Physics.LinearVelocity;
            Vector3 relativeVelocity;

            if (entity == null)
            {
                relativeVelocity = autopilotVelocity;
            }
            else
            {
                MyPhysicsComponentBase physics = entity.GetTopMostParent().Physics;
                if (physics == null || physics.IsStatic)
                {
                    relativeVelocity = autopilotVelocity;
                }
                else
                {
                    Vector3 entityVelocity = physics.LinearVelocity;
                    Vector3.Subtract(ref autopilotVelocity, ref entityVelocity, out relativeVelocity);
                }
            }

            Vector3.Add(ref relativeVelocity, ref input.Direction, out adjusted.Direction);
            adjusted.Offset = Vector3D.Zero;
            if (adjusted.Direction == Vector3.Zero)
            {
                adjusted.Length = 0f;
            }
            else
            {
                adjusted.Length = 20f + adjusted.Direction.Normalize() * Pathfinder.SpeedFactor;
                if (destination && input.Length < adjusted.Length)
                {
                    adjusted.Length = input.Length;
                }
            }
        }
 protected override bool IsThrustEntityType(MyEntity thrustEntity)
 {
     return(thrustEntity is MyCharacter);
 }
Ejemplo n.º 47
0
 private void character_OnClosing(MyEntity obj)
 {
     Character.OnClosing -= character_OnClosing;
     Character            = null;
 }
 protected override float MinPowerConsumption(MyEntity thrustEntity)
 {
     return(Jetpack.MinPowerConsumption);
 }
Ejemplo n.º 49
0
        /// <summary>
        /// Tests if a section of space can be travelled without hitting the specified entity.
        /// </summary>
        /// <param name="entity">The potential obstruction</param>
        /// <param name="ignoreBlock">Null or the block autopilot is trying to connect with.</param>
        /// <param name="input"><see cref="TestInput"/></param>
        /// <param name="result"><see cref="GridTestResult"/></param>
        /// <returns>True if the specified entity obstructs the path.</returns>
        public bool ObstructedBy(MyEntity entity, MyCubeBlock ignoreBlock, ref TestInput input, out GridTestResult result)
        {
            //Logger.DebugLog("checking: " + entity.getBestName() + ", offset: " + offset + ", rejection vector: " + rejectionVector + ", rejection distance: " + rejectionDistance);
#if DEBUG
            if (!input.Direction.IsValid() || Math.Abs(1f - input.Direction.LengthSquared()) > 0.01f)
            {
                throw new Exception("rejection vector is invalid. entity: " + entity.nameWithId() + ", input: " + input);
            }
#endif

            result          = GridTestResult.Default;
            result.Distance = input.Length;
            MyCubeGrid grid = entity as MyCubeGrid;
            if (grid != null)
            {
                // check for dangerous tools on grid
                CubeGridCache cache = CubeGridCache.GetFor(grid);
                if (cache == null)
                {
                    return(false);
                }
                Profiler.StartProfileBlock("Checking Tools");
                foreach (MyShipDrill drill in cache.BlocksOfType(typeof(MyObjectBuilder_Drill)))
                {
                    if (drill.IsShooting)
                    {
                        if (SphereTest(drill, ref input, ref result))
                        {
                            Profiler.EndProfileBlock();
                            return(true);
                        }
                    }
                }
                foreach (MyShipGrinder grinder in cache.BlocksOfType(typeof(MyObjectBuilder_ShipGrinder)))
                {
                    if (grinder.IsShooting)
                    {
                        if (SphereTest(grinder, ref input, ref result))
                        {
                            Profiler.EndProfileBlock();
                            return(true);
                        }
                    }
                }
                Profiler.EndProfileBlock();

                if (ExtensionsRelations.canConsiderFriendly(Controller.CubeBlock, grid) && EndangerGrid(grid, ref input, ref result))
                {
                    Logger.DebugLog("Movement would endanger: " + grid.getBestName());
                    return(true);
                }

                Profiler.StartProfileBlock("RejectionIntersects");
                if (RejectionIntersects(grid, ignoreBlock, ref input, ref result))
                {
                    Profiler.EndProfileBlock();
                    return(true);
                }
                Profiler.EndProfileBlock();
            }
            else
            {
                return(SphereTest(entity, ref input, ref result));
            }

            return(false);
        }
Ejemplo n.º 50
0
        /// <summary>
        /// Updates resource.
        /// </summary>
        public override void UpdateBeforeSimulation()
        {
            try
            {
                VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("MyMissile.UpdateBeforeSimulation");

                if (m_isExploded)
                {
                    Vector3D explosionPoint;
                    if (m_collisionPoint.HasValue)
                    {
                        explosionPoint = PlaceDecal();
                    }
                    else
                    {
                        // Can have no collision point when exploding from cascade explosions
                        explosionPoint = PositionComp.GetPosition();
                    }

                    if (Sandbox.Game.Multiplayer.Sync.IsServer)
                    {
                        //  Create explosion
                        float           radius          = m_missileAmmoDefinition.MissileExplosionRadius;
                        BoundingSphereD explosionSphere = new BoundingSphereD(explosionPoint, radius);

                        MyEntity ownerEntity = null;
                        var      ownerId     = Sync.Players.TryGetIdentity(m_owner);
                        if (ownerId != null)
                        {
                            ownerEntity = ownerId.Character;
                        }
                        //MyEntities.TryGetEntityById(m_owner, out ownerEntity);


                        //  Call main explosion starter
                        MyExplosionInfo info = new MyExplosionInfo()
                        {
                            PlayerDamage = 0,
                            //Damage = m_ammoProperties.Damage,
                            Damage              = MyFakes.ENABLE_VOLUMETRIC_EXPLOSION ? m_missileAmmoDefinition.MissileExplosionDamage : 200,
                            ExplosionType       = m_explosionType,
                            ExplosionSphere     = explosionSphere,
                            LifespanMiliseconds = MyExplosionsConstants.EXPLOSION_LIFESPAN,
                            CascadeLevel        = CascadedExplosionLevel,
                            HitEntity           = m_collidedEntity,
                            ParticleScale       = 1.0f,
                            OwnerEntity         = ownerEntity,

                            Direction            = WorldMatrix.Forward,
                            VoxelExplosionCenter = explosionSphere.Center + radius * WorldMatrix.Forward * 0.25f,

                            ExplosionFlags      = MyExplosionFlags.AFFECT_VOXELS | MyExplosionFlags.APPLY_FORCE_AND_DAMAGE | MyExplosionFlags.CREATE_DEBRIS | MyExplosionFlags.CREATE_DECALS | MyExplosionFlags.CREATE_SHRAPNELS | MyExplosionFlags.APPLY_DEFORMATION,
                            VoxelCutoutScale    = 0.3f,
                            PlaySound           = true,
                            ApplyForceAndDamage = true
                        };
                        if (!MarkedToDestroy)
                        {
                            info.ExplosionFlags |= MyExplosionFlags.CREATE_PARTICLE_EFFECT;
                        }
                        MyExplosions.AddExplosion(ref info);

                        if (m_collidedEntity != null && !(m_collidedEntity is MyAmmoBase))
                        {
                            if (!m_collidedEntity.Physics.IsStatic)
                            {
                                m_collidedEntity.Physics.AddForce(MyPhysicsForceType.APPLY_WORLD_IMPULSE_AND_WORLD_ANGULAR_IMPULSE,
                                                                  100 * Physics.LinearVelocity, m_collisionPoint, null);
                            }
                        }
                    }

                    Close();

                    return;
                }

                base.UpdateBeforeSimulation();

                if (m_missileAmmoDefinition.MissileSkipAcceleration)
                {
                    Physics.LinearVelocity = WorldMatrix.Forward * m_missileAmmoDefinition.DesiredSpeed * 0.7f;
                }
                else
                {
                    Physics.LinearVelocity += PositionComp.WorldMatrix.Forward * m_missileAmmoDefinition.MissileAcceleration * VRage.Game.MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS;
                }

                if (m_smokeEffect == null)
                {
                    // if (MyCamera.GetDistanceWithFOV(GetPosition()) < 150)
                    {
                        if (MyParticlesManager.TryCreateParticleEffect((int)MyParticleEffectsIDEnum.Smoke_Missile, out m_smokeEffect))
                        {
                            m_smokeEffect.UserScale = 0.3f;

                            var matrix = PositionComp.WorldMatrix;
                            matrix.Translation       -= matrix.Forward * m_smokeEffectOffsetMultiplier;
                            m_smokeEffect.WorldMatrix = matrix;
                            //m_smokeEffect.WorldMatrix = PositionComp.WorldMatrix;
                            m_smokeEffect.CalculateDeltaMatrix = true;
                        }
                    }
                }
                Physics.AngularVelocity = Vector3.Zero;

                if ((Vector3.Distance(PositionComp.GetPosition(), m_origin) >= m_maxTrajectory))
                {
                    Explode();
                    return;
                }
            }
            finally
            {
                VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();
            }
        }
 protected override MyDefinitionId FuelType(MyEntity thrustEntity)
 {
     return(Jetpack.FuelDefinition != null ? Jetpack.FuelDefinition.Id : MyResourceDistributorComponent.ElectricityId);
 }
Ejemplo n.º 52
0
        internal bool SelectTarget(bool manualSelect = true)
        {
            var s  = _session;
            var ai = s.TrackingAi;

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

            if (!_cachedPointerPos)
            {
                InitPointerOffset(0.05);
            }
            if (!_cachedTargetPos)
            {
                InitTargetOffset();
            }
            var      cockPit = s.ActiveCockPit;
            Vector3D end;

            if (!s.UiInput.FirstPersonView)
            {
                var offetPosition = Vector3D.Transform(PointerOffset, s.CameraMatrix);
                AimPosition  = offetPosition;
                AimDirection = Vector3D.Normalize(AimPosition - s.CameraPos);
                end          = offetPosition + (AimDirection * ai.MaxTargetingRange);
            }
            else
            {
                if (!_session.UiInput.AltPressed)
                {
                    AimDirection = cockPit.PositionComp.WorldMatrixRef.Forward;
                    AimPosition  = cockPit.PositionComp.WorldAABB.Center;
                    end          = AimPosition + (AimDirection * s.TrackingAi.MaxTargetingRange);
                }
                else
                {
                    var offetPosition = Vector3D.Transform(PointerOffset, s.CameraMatrix);
                    AimPosition  = offetPosition;
                    AimDirection = Vector3D.Normalize(AimPosition - s.CameraPos);
                    end          = offetPosition + (AimDirection * ai.MaxTargetingRange);
                }
            }

            var foundTarget    = false;
            var rayOnlyHitSelf = false;
            var rayHitSelf     = false;

            MyEntity closestEnt = null;

            _session.Physics.CastRay(AimPosition, end, _hitInfo);

            for (int i = 0; i < _hitInfo.Count; i++)
            {
                var hit = _hitInfo[i];
                closestEnt = hit.HitEntity.GetTopMostParent() as MyEntity;

                var hitGrid = closestEnt as MyCubeGrid;

                if (hitGrid != null && hitGrid.IsSameConstructAs(ai.MyGrid))
                {
                    rayHitSelf     = true;
                    rayOnlyHitSelf = true;
                    continue;
                }

                if (rayOnlyHitSelf)
                {
                    rayOnlyHitSelf = false;
                }

                if (manualSelect)
                {
                    if (hitGrid == null || !_masterTargets.ContainsKey(hitGrid))
                    {
                        continue;
                    }

                    s.SetTarget(hitGrid, ai, _masterTargets);
                    return(true);
                }

                foundTarget = true;
                ai.Session.PlayerDummyTargets[ai.Session.PlayerId].Update(hit.Position, ai, closestEnt);
                break;
            }

            if (rayHitSelf)
            {
                ReticleOnSelfTick = s.Tick;
                ReticleAgeOnSelf++;
                if (rayOnlyHitSelf)
                {
                    ai.Session.PlayerDummyTargets[ai.Session.PlayerId].Update(end, ai);
                }
            }
            else
            {
                ReticleAgeOnSelf = 0;
            }

            Vector3D hitPos;
            bool     foundOther = false;

            if (!foundTarget && RayCheckTargets(AimPosition, AimDirection, out closestEnt, out hitPos, out foundOther, !manualSelect))
            {
                foundTarget = true;
                if (manualSelect)
                {
                    s.SetTarget(closestEnt, ai, _masterTargets);
                    return(true);
                }
                ai.Session.PlayerDummyTargets[ai.Session.PlayerId].Update(hitPos, ai, closestEnt);
            }

            if (!manualSelect)
            {
                var activeColor = closestEnt != null && !_masterTargets.ContainsKey(closestEnt) || foundOther ? Color.DeepSkyBlue : Color.Red;
                _reticleColor = closestEnt != null && !(closestEnt is MyVoxelBase) ? activeColor : Color.White;

                if (!foundTarget)
                {
                    ai.Session.PlayerDummyTargets[ai.Session.PlayerId].Update(end, ai);
                }
            }

            return(foundTarget || foundOther);
        }
 protected override float CalculateConsumptionMultiplier(MyEntity thrustEntity, float naturalGravityStrength)
 {
     return(1f + Jetpack.ConsumptionFactorPerG * (naturalGravityStrength / MyGravityProviderSystem.G));
 }
 /// <summary>
 /// Override to discard query results of your choice.
 /// </summary>
 /// <param name="entity"></param>
 /// <returns>True for valid entities.</returns>
 protected virtual bool QueryEvaluator(MyEntity entity)
 {
     return(true);
 }
 protected override float ForceMagnitude(MyEntity thrustEntity, float planetaryInfluence, bool inAtmosphere)
 {
     return(Jetpack.ForceMagnitude * CalculateForceMultiplier(thrustEntity, planetaryInfluence, inAtmosphere));
 }
Ejemplo n.º 56
0
        public static void TakeMaterialsFromBuilder(List <MyObjectBuilder_CubeGrid> blocksToBuild, MyEntity builder)
        {
            Debug.Assert(blocksToBuild.Count == 1);
            if (blocksToBuild.Count == 0)
            {
                return;
            }

            // Search for multiblock definition.
            var firstBlock = blocksToBuild[0].CubeBlocks.FirstOrDefault();

            Debug.Assert(firstBlock != null);
            if (firstBlock == null)
            {
                return;
            }

            MyDefinitionId multiBlockDefId;
            var            compound = firstBlock as MyObjectBuilder_CompoundCubeBlock;

            if (compound != null)
            {
                Debug.Assert(compound.Blocks != null && compound.Blocks.Length > 0 && compound.Blocks[0].MultiBlockDefinition != null);
                if (compound.Blocks == null || compound.Blocks.Length == 0 || compound.Blocks[0].MultiBlockDefinition == null)
                {
                    return;
                }

                multiBlockDefId = compound.Blocks[0].MultiBlockDefinition.Value;
            }
            else
            {
                Debug.Assert(firstBlock.MultiBlockDefinition != null);
                if (firstBlock.MultiBlockDefinition == null)
                {
                    return;
                }

                multiBlockDefId = firstBlock.MultiBlockDefinition.Value;
            }

            MyMultiBlockDefinition multiBlockDefinition = MyDefinitionManager.Static.TryGetMultiBlockDefinition(multiBlockDefId);

            Debug.Assert(multiBlockDefinition != null);
            if (multiBlockDefinition == null)
            {
                return;
            }

            MyCubeBuilder.BuildComponent.GetMultiBlockPlacementMaterials(multiBlockDefinition);
            MyCubeBuilder.BuildComponent.AfterSuccessfulBuild(builder, instantBuild: false);
        }
Ejemplo n.º 57
0
 public override void Init(MyEntity holder, MyHandItem item, MyHandItemBehaviorDefinition definition)
 {
     base.Init(holder, item, definition);
     _definition = (EquiMaterialHereBehaviorDefinition)definition;
 }
Ejemplo n.º 58
0
 public MySyncEntity(MyEntity entity)
 {
     Entity = entity;
 }
Ejemplo n.º 59
0
        internal bool CreateEntInfo(MyEntity entity, long gridOwner, out Sandbox.ModAPI.Ingame.MyDetectedEntityInfo entInfo)
        {
            try
            {
                MyRelationsBetweenPlayerAndBlock relationship = MyRelationsBetweenPlayerAndBlock.Neutral;
                if (entity == null)
                {
                    entInfo = new Sandbox.ModAPI.Ingame.MyDetectedEntityInfo();
                    return(false);
                }
                var grid = entity.GetTopMostParent() as MyCubeGrid;
                if (grid != null)
                {
                    if (!grid.DestructibleBlocks || grid.Immune || grid.GridGeneralDamageModifier <= 0)
                    {
                        entInfo = new Sandbox.ModAPI.Ingame.MyDetectedEntityInfo();
                        return(false);
                    }

                    var bigOwners = grid.BigOwners;
                    var topOwner  = bigOwners.Count > 0 ? bigOwners[0] : long.MaxValue;

                    relationship = topOwner != long.MaxValue ? MyIDModule.GetRelationPlayerBlock(gridOwner, topOwner, MyOwnershipShareModeEnum.Faction) : MyRelationsBetweenPlayerAndBlock.NoOwnership;

                    var type = grid.GridSizeEnum != MyCubeSize.Small ? Sandbox.ModAPI.Ingame.MyDetectedEntityType.LargeGrid : Sandbox.ModAPI.Ingame.MyDetectedEntityType.SmallGrid;
                    entInfo = new Sandbox.ModAPI.Ingame.MyDetectedEntityInfo(grid.EntityId, string.Empty, type, null, MatrixD.Zero, Vector3.Zero, relationship, new BoundingBoxD(), Session.Tick);
                    return(true);
                }

                var myCharacter = entity as IMyCharacter;
                if (myCharacter != null)
                {
                    var type = !myCharacter.IsPlayer ? Sandbox.ModAPI.Ingame.MyDetectedEntityType.CharacterOther : Sandbox.ModAPI.Ingame.MyDetectedEntityType.CharacterHuman;

                    var getComponentOwner = entity as IMyComponentOwner <MyIDModule>;

                    long       playerId;
                    MyIDModule targetIdModule;
                    if (getComponentOwner != null && getComponentOwner.GetComponent(out targetIdModule))
                    {
                        playerId = targetIdModule.Owner;
                    }
                    else
                    {
                        var controllingId = myCharacter.ControllerInfo?.ControllingIdentityId;
                        playerId = controllingId ?? 0;
                    }

                    relationship = MyIDModule.GetRelationPlayerBlock(gridOwner, playerId, MyOwnershipShareModeEnum.Faction);

                    entInfo = new Sandbox.ModAPI.Ingame.MyDetectedEntityInfo(entity.EntityId, string.Empty, type, null, MatrixD.Zero, Vector3.Zero, relationship, new BoundingBoxD(), Session.Tick);
                    return(!myCharacter.IsDead && myCharacter.Integrity > 0);
                }

                var myPlanet = entity as MyPlanet;

                if (myPlanet != null)
                {
                    const Sandbox.ModAPI.Ingame.MyDetectedEntityType type = Sandbox.ModAPI.Ingame.MyDetectedEntityType.Planet;
                    entInfo = new Sandbox.ModAPI.Ingame.MyDetectedEntityInfo(entity.EntityId, string.Empty, type, null, MatrixD.Zero, Vector3.Zero, relationship, new BoundingBoxD(), Session.Tick);
                    return(true);
                }
                if (entity is MyVoxelMap)
                {
                    const Sandbox.ModAPI.Ingame.MyDetectedEntityType type = Sandbox.ModAPI.Ingame.MyDetectedEntityType.Asteroid;
                    entInfo = new Sandbox.ModAPI.Ingame.MyDetectedEntityInfo(entity.EntityId, string.Empty, type, null, MatrixD.Zero, Vector3.Zero, relationship, new BoundingBoxD(), Session.Tick);
                    return(true);
                }
                if (entity is MyMeteor)
                {
                    const Sandbox.ModAPI.Ingame.MyDetectedEntityType type = Sandbox.ModAPI.Ingame.MyDetectedEntityType.Meteor;
                    entInfo = new Sandbox.ModAPI.Ingame.MyDetectedEntityInfo(entity.EntityId, string.Empty, type, null, MatrixD.Zero, Vector3.Zero, MyRelationsBetweenPlayerAndBlock.Enemies, new BoundingBoxD(), Session.Tick);
                    return(true);
                }
            }
            catch (Exception ex) { Log.Line($"Exception in CreateEntInfo: {ex}"); }

            entInfo = new Sandbox.ModAPI.Ingame.MyDetectedEntityInfo();
            return(false);
        }
Ejemplo n.º 60
0
        public static void LoadInventoryConfig(MyEntity toolEntity, MyAssetModifierComponent skinComponent)
        {
            if (toolEntity == null)
            {
                throw new ArgumentNullException("toolEntity");
            }
            if (skinComponent == null)
            {
                throw new ArgumentNullException("skinComponent");
            }
            if (MyGameService.IsActive)
            {
                MyObjectBuilder_SkinInventory inventory;
                string path = Path.Combine(MyFileSystem.SavesPath, activeInventoryFile);
                switch (inventory.Tools)
                {
                case ((!MyFileSystem.FileExists(path) || !MyObjectBuilderSerializer.DeserializeXML <MyObjectBuilder_SkinInventory>(path, out inventory)) || ((null) || (null))):
                    break;

                default:
                {
                    IMyHandheldGunObject <MyDeviceBase> obj2 = toolEntity as IMyHandheldGunObject <MyDeviceBase>;
                    MyPhysicalItemDefinition            physicalItemDefinition = obj2.PhysicalItemDefinition;
                    MyGameInventoryItemSlot             none = MyGameInventoryItemSlot.None;
                    if (obj2 is MyHandDrill)
                    {
                        none = MyGameInventoryItemSlot.Drill;
                    }
                    else if (obj2 is MyAutomaticRifleGun)
                    {
                        none = MyGameInventoryItemSlot.Rifle;
                    }
                    else if (obj2 is MyWelder)
                    {
                        none = MyGameInventoryItemSlot.Welder;
                    }
                    else if (obj2 is MyAngleGrinder)
                    {
                        none = MyGameInventoryItemSlot.Grinder;
                    }
                    if (none != MyGameInventoryItemSlot.None)
                    {
                        List <MyGameInventoryItem> items = new List <MyGameInventoryItem>();
                        using (List <ulong> .Enumerator enumerator = inventory.Tools.GetEnumerator())
                        {
                            while (enumerator.MoveNext())
                            {
                                MyGameInventoryItem item = MyGameService.InventoryItems.FirstOrDefault <MyGameInventoryItem>(delegate(MyGameInventoryItem i) {
                                        ulong itemId;
                                        return(i.ID == itemId);
                                    });
                                if ((item != null) && ((physicalItemDefinition != null) && ((physicalItemDefinition == null) || (item.ItemDefinition.ItemSlot == none))))
                                {
                                    item.IsInUse = true;
                                    items.Add(item);
                                }
                            }
                        }
                        MyGameService.GetItemsCheckData(items, checkDataResult => skinComponent.TryAddAssetModifier(checkDataResult));
                    }
                    break;
                }
                }
            }
        }