Inheritance: DbContext
Exemple #1
0
        private void DrawTarget()
        {
            var s     = _session;
            var focus = s.TrackingAi.Construct.Data.Repo.FocusData;

            for (int i = 0; i < s.TrackingAi.TargetState.Length; i++)
            {
                if (focus.Target[i] <= 0)
                {
                    continue;
                }
                var lockMode = focus.Locked[i];

                var targetState  = s.TrackingAi.TargetState[i];
                var displayCount = 0;

                foreach (var icon in _targetIcons.Keys)
                {
                    int iconLevel;
                    if (!IconStatus(icon, targetState, out iconLevel))
                    {
                        continue;
                    }

                    Vector3D   offset;
                    float      scale;
                    MyStringId textureName;
                    var        iconInfo = _targetIcons[icon][iconLevel];
                    iconInfo.GetTextureInfo(i, displayCount, s, out textureName, out scale, out offset);

                    var color = Color.White;

                    switch (lockMode)
                    {
                    case FocusData.LockModes.None:
                        color = Color.White;
                        break;

                    case FocusData.LockModes.Locked:
                        color = s.Count < 60 ? Color.White : new Color(255, 255, 255, 64);
                        break;

                    case FocusData.LockModes.ExclusiveLock:
                        color = s.SCount < 30 ? Color.White : new Color(255, 255, 255, 64);
                        break;
                    }

                    var skipSize = !s.Settings.ClientConfig.ShowHudTargetSizes && icon.Equals("size");

                    if (!skipSize)
                    {
                        MyTransparentGeometry.AddBillboardOriented(textureName, color, offset, s.CameraMatrix.Left, s.CameraMatrix.Up, scale, BlendTypeEnum.PostPP);
                    }

                    if (focus.ActiveId == i && displayCount == 0)
                    {
                        if (!skipSize)
                        {
                            var focusTexture = focus.ActiveId == 0 ? _focus : _focusSecondary;
                            MyTransparentGeometry.AddBillboardOriented(focusTexture, color, offset, s.CameraMatrix.Left, s.CameraMatrix.Up, scale, BlendTypeEnum.PostPP);
                        }
                        else
                        {
                            var     focusColor = focus.ActiveId == 0 ? Color.Red : Color.LightBlue;
                            MyQuadD quad;
                            var     up   = (Vector3)s.CameraMatrix.Up;
                            var     left = (Vector3)s.CameraMatrix.Left;

                            MyUtils.GetBillboardQuadOriented(out quad, ref offset, 0.002f, 0.002f, ref left, ref up);
                            MyTransparentGeometry.AddTriangleBillboard(quad.Point0, quad.Point1, quad.Point2, Vector3.Zero, Vector3.Zero, Vector3.Zero, FocusTextureMap.P0, FocusTextureMap.P1, FocusTextureMap.P3, FocusTextureMap.Material, 0, offset, focusColor, BlendTypeEnum.PostPP);
                            MyTransparentGeometry.AddTriangleBillboard(quad.Point0, quad.Point3, quad.Point2, Vector3.Zero, Vector3.Zero, Vector3.Zero, FocusTextureMap.P0, FocusTextureMap.P2, FocusTextureMap.P3, FocusTextureMap.Material, 0, offset, focusColor, BlendTypeEnum.PostPP);
                        }
                    }

                    displayCount++;
                }

                MyEntity target;
                if (i == focus.ActiveId && MyEntities.TryGetEntityById(focus.Target[focus.ActiveId], out target))
                {
                    var targetSphere = target.PositionComp.WorldVolume;
                    var targetCenter = targetSphere.Center;
                    var screenPos    = s.Camera.WorldToScreen(ref targetCenter);
                    var screenScale  = 0.1 * s.ScaleFov;

                    if (Vector3D.Transform(targetCenter, s.Camera.ViewMatrix).Z > 0)
                    {
                        screenPos.X *= -1;
                        screenPos.Y  = -1;
                    }

                    var dotpos = new Vector2D(MathHelper.Clamp(screenPos.X, -0.98, 0.98), MathHelper.Clamp(screenPos.Y, -0.98, 0.98));

                    dotpos.X *= (float)(screenScale * _session.AspectRatio);
                    dotpos.Y *= (float)screenScale;
                    screenPos = Vector3D.Transform(new Vector3D(dotpos.X, dotpos.Y, -0.1), s.CameraMatrix);
                    MyTransparentGeometry.AddBillboardOriented(_active, Color.White, screenPos, s.CameraMatrix.Left, s.CameraMatrix.Up, (float)screenScale * 0.075f, BlendTypeEnum.PostPP);

                    if (s.Tick20)
                    {
                        s.HudUi.AddText(text: $"TargetSize: {targetState.SizeExtended}", x: i == 0 ? 0f : -0.345f, y: 0.83f, name: Hud.ElementNames.Test1, ttl: 18, color: i == 0 ? Color.OrangeRed : Color.MediumOrchid, justify: Hud.Justify.Center, fontType: Hud.FontType.Shadow, fontSize: 5, heightScale: 0.75f);
                    }
                }
            }
        }
Exemple #2
0
        /// <summary>
        /// Every object must have this method, but not every phys object must necessarily have something to cleanup
        /// <remarks>
        /// </remarks>
        /// </summary>
        public void Delete()
        {
            Close();
            BeforeDelete();
            GameLogic.Close();
            //doesnt work in parallel update
            //Debug.Assert(MySandboxGame.IsMainThread(), "Entity.Close() called not from Main Thread!");
            Debug.Assert(MyEntities.UpdateInProgress == false, "Do not close entities directly in Update*, use MarkForClose() instead");
            Debug.Assert(MyEntities.CloseAllowed == true, "Use MarkForClose()");
            Debug.Assert(!Closed, "Close() called twice!");

            //Children has to be cleared after close notification is send
            while (Hierarchy.Children.Count > 0)
            {
                MyHierarchyComponentBase compToRemove = Hierarchy.Children[Hierarchy.Children.Count - 1];
                Debug.Assert(compToRemove.Parent != null, "Entity has no parent but is part of children collection");

                compToRemove.Container.Entity.Delete();

                Hierarchy.Children.Remove(compToRemove);
            }

            //OnPositionChanged = null;

            CallAndClearOnClosing();

            MyDecals.RemoveModelDecals(this);
            MyEntities.RemoveName(this);
            MyEntities.RemoveFromClosedEntities(this);

            if (m_physics != null)
            {
                m_physics.Close();
                Physics = null;

                RaisePhysicsChanged();
            }

            MyEntities.UnregisterForUpdate(this, true);


            if (Parent == null) //only root objects are in entities list
            {
                MyEntities.Remove(this);
            }
            else
            {
                Parent.Hierarchy.Children.Remove(this.Hierarchy);

                //remove children first
                if (Parent.InScene)
                {
                    OnRemovedFromScene(this);
                }

                MyEntities.RaiseEntityRemove(this);
            }

            if (this.EntityId != 0)
            {
                MyEntityIdentifier.RemoveEntity(this.EntityId);
            }

            //this.EntityId = 0;
            Debug.Assert(this.Hierarchy.Children.Count == 0);

            CallAndClearOnClose();

            Components.Clear();

            ClearDebugRenderComponents();

            Closed = true;
        }
        internal bool UpdateLocalAiAndCockpit()
        {
            InGridAiBlock      = false;
            ActiveControlBlock = ControlledEntity as MyCubeBlock;
            ActiveCockPit      = ControlledEntity as MyCockpit;
            long oldBlockId;
            var  activeBlock = ActiveCockPit ?? ActiveControlBlock;

            if (activeBlock != null && ActiveControlBlock != null && GridToMasterAi.TryGetValue(activeBlock.CubeGrid, out TrackingAi))
            {
                InGridAiBlock = true;
                TrackingAi.Data.Repo.ControllingPlayers.TryGetValue(PlayerId, out oldBlockId);

                if (IsServer)
                {
                    TrackingAi.Construct.UpdateConstructsPlayers(ActiveControlBlock, PlayerId, true);
                }
                if (HandlesInput && oldBlockId != ActiveControlBlock.EntityId)
                {
                    SendActiveControlUpdate(TrackingAi, activeBlock, true);
                }
            }
            else
            {
                if (TrackingAi != null)
                {
                    TrackingAi.Construct.Focus.ClientIsFocused(TrackingAi);

                    MyCubeBlock oldBlock;
                    if (TrackingAi.Data.Repo.ControllingPlayers.TryGetValue(PlayerId, out oldBlockId) && MyEntities.TryGetEntityById(oldBlockId, out oldBlock, true))
                    {
                        if (IsServer)
                        {
                            TrackingAi.Construct.UpdateConstructsPlayers(ActiveControlBlock, PlayerId, false);
                        }
                        if (HandlesInput)
                        {
                            SendActiveControlUpdate(TrackingAi, oldBlock, false);
                        }
                    }
                }

                TrackingAi         = null;
                ActiveCockPit      = null;
                ActiveControlBlock = null;
            }
            return(InGridAiBlock);
        }
Exemple #4
0
        private MyCubeGrid DetectTouchingGrid(MySlimBlock block)
        {
            if (MyCubeBuilder.Static.DynamicMode)
            {
                return(null);
            }

            if (block == null)
            {
                return(null);
            }

            if (block.FatBlock is MyCompoundCubeBlock)
            {
                foreach (var blockInCompound in (block.FatBlock as MyCompoundCubeBlock).GetBlocks())
                {
                    MyCubeGrid touchingGrid = DetectTouchingGrid(blockInCompound);
                    if (touchingGrid != null)
                    {
                        return(touchingGrid);
                    }
                }

                return(null);
            }

            ProfilerShort.Begin("MultiBlockClipboard: DetectMerge");

            float        gridSize = block.CubeGrid.GridSize;
            BoundingBoxD aabb;

            block.GetWorldBoundingBox(out aabb);
            // Inflate by half cube, so it will intersect for sure when there's anything
            aabb.Inflate(gridSize / 2);

            m_tmpNearEntities.Clear();
            MyEntities.GetElementsInBox(ref aabb, m_tmpNearEntities);

            var mountPoints = block.BlockDefinition.GetBuildProgressModelMountPoints(block.BuildLevelRatio);

            try
            {
                for (int i = 0; i < m_tmpNearEntities.Count; i++)
                {
                    var grid = m_tmpNearEntities[i] as MyCubeGrid;
                    if (grid != null && grid != block.CubeGrid && grid.Physics != null && grid.Physics.Enabled && grid.IsStatic && grid.GridSizeEnum == block.CubeGrid.GridSizeEnum)
                    {
                        Vector3I gridOffset = grid.WorldToGridInteger(m_pastePosition);
                        if (!grid.CanMergeCubes(block.CubeGrid, gridOffset))
                        {
                            continue;
                        }

                        MatrixI transform = grid.CalculateMergeTransform(block.CubeGrid, gridOffset);
                        Base6Directions.Direction forward        = transform.GetDirection(block.Orientation.Forward);
                        Base6Directions.Direction up             = transform.GetDirection(block.Orientation.Up);
                        MyBlockOrientation        newOrientation = new MyBlockOrientation(forward, up);
                        Quaternion newRotation;
                        newOrientation.GetQuaternion(out newRotation);
                        Vector3I newPosition = Vector3I.Transform(block.Position, transform);

                        if (!MyCubeGrid.CheckConnectivity(grid, block.BlockDefinition, mountPoints, ref newRotation, ref newPosition))
                        {
                            continue;
                        }

                        return(grid);
                    }
                }
            }
            finally
            {
                m_tmpNearEntities.Clear();
                ProfilerShort.End();
            }

            return(null);
        }
Exemple #5
0
        private bool LoadShipBlueprint(MyObjectBuilder_ShipBlueprintDefinition shipBlueprint,
                                       Vector3D playerPosition, bool keepOriginalLocation, Chat chat, Hangar Plugin, bool force = false)
        {
            var grids = shipBlueprint.CubeGrids;

            if (grids == null || grids.Length == 0)
            {
                Hangar.Debug("No grids in blueprint!");
                chat.Respond("No grids in blueprint!");

                return(false);
            }

            try
            {
                MyIdentity IDentity = MySession.Static.Players.TryGetPlayerIdentity(new MyPlayer.PlayerId(SteamID));

                if (Plugin.GridBackup != null)
                {
                    Plugin.GridBackup.GetType().GetMethod("BackupGridsManuallyWithBuilders", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, null, new Type[2] {
                        typeof(List <MyObjectBuilder_CubeGrid>), typeof(long)
                    }, null).Invoke(Plugin.GridBackup, new object[] { grids.ToList(), IDentity.IdentityId });
                    Log.Warn("Successfully BackedUp grid!");
                }
            }
            catch (Exception e)
            {
                Log.Fatal(e);
            }


            bool LoadNearPosition = false;
            //For loading in the same location

            ParallelSpawner Spawner  = new ParallelSpawner(grids);
            var             position = grids[0].PositionAndOrientation.Value;

            if (keepOriginalLocation)
            {
                var sphere = FindBoundingSphere(grids);



                sphere.Center = position.Position;

                List <MyEntity> entities = new List <MyEntity>();
                MyGamePruningStructure.GetAllTopMostEntitiesInSphere(ref sphere, entities);

                foreach (var entity in entities)
                {
                    if (entity is MyCubeGrid)
                    {
                        chat.Respond("There are potentially other grids in the way. Loading near the original point.");

                        LoadNearPosition = true;
                    }
                }

                if (!LoadNearPosition)
                {
                    /* Remapping to prevent any key problems upon paste. */
                    MyEntities.RemapObjectBuilderCollection(grids);

                    Spawner.Start();

                    return(true);
                }
            }



            /*
             *  Everything else is loading for near player
             *
             *
             *
             */



            /* Where do we want to paste the grids? Lets find out. */
            var pos = FindPastePosition(grids, position.Position);

            if (pos == null)
            {
                Hangar.Debug("No free Space found!");
                chat.Respond("No free space available!");

                return(false);
            }

            var newPosition = pos.Value;

            /* Update GridsPosition if that doesnt work get out of here. */
            if (!UpdateGridsPosition(grids, newPosition))
            {
                chat.Respond("The File to be imported does not seem to be compatible with the server!");

                return(false);
            }


            MyEntities.RemapObjectBuilderCollection(grids);
            Spawner.Start();
            return(true);
        }
Exemple #6
0
        void ThreadProc()
        {
            Thread.CurrentThread.Name = "Entity creation thread";
            HkBaseSystem.InitThread("Entity creation thread");
            ProfilerShort.Autocommit = false;
            MyEntityIdentifier.InitPerThreadStorage(2048);
            Item item;

            while (!m_exitting)
            {
                if (ConsumeWork(out item))
                {
                    if (item.ObjectBuilder != null)
                    {
                        if (item.Result == null)
                        {
                            item.Result = MyEntities.CreateFromObjectBuilderNoinit(item.ObjectBuilder);
                        }
                        item.InScene = (item.ObjectBuilder.PersistentFlags & MyPersistentEntityFlags2.InScene) == MyPersistentEntityFlags2.InScene;
                        item.ObjectBuilder.PersistentFlags &= ~MyPersistentEntityFlags2.InScene;
                        item.Result.DebugAsyncLoading       = true;
                        MyEntities.InitEntity(item.ObjectBuilder, ref item.Result);
                        if (item.Result != null)
                        {
                            if (item.SubgridBuilders != null)
                            {
                                item.SubGrids = new List <MyEntity>();
                                foreach (var subGridbulider in item.SubgridBuilders)
                                {
                                    MyEntity subGrid = MyEntities.CreateFromObjectBuilderNoinit(subGridbulider);
                                    subGridbulider.PersistentFlags &= ~MyPersistentEntityFlags2.InScene;
                                    item.Result.DebugAsyncLoading   = true;

                                    MyEntities.InitEntity(subGridbulider, ref subGrid);
                                    item.SubGrids.Add(subGrid);
                                }
                                item.SubgridBuilders.Clear();
                                item.SubgridBuilders = null;
                            }

                            item.EntityIds = new List <IMyEntity>();
                            MyEntityIdentifier.GetPerThreadEntities(item.EntityIds);
                            MyEntityIdentifier.ClearPerThreadEntities();
                            m_resultQueue.Enqueue(item);
                        }
                    }
                    else
                    {
                        if (item.Result != null)
                        {
                            item.Result.DebugAsyncLoading = true;
                        }

                        // This is ok, just invoking action asynchronously
                        m_resultQueue.Enqueue(item);
                    }
                }
                ProfilerShort.Commit();
            }
            MyEntityIdentifier.DestroyPerThreadStorage();
            HkBaseSystem.QuitThread();
            ProfilerShort.DestroyThread();
        }
Exemple #7
0
        // Creates prefab, but won't add into scene
        // WorldMatrix is the matrix of the first grid in the prefab. The others will be transformed to keep their relative positions
        private void CreateGridsFromPrefab(List <MyCubeGrid> results, string prefabName, MatrixD worldMatrix, bool spawnAtOrigin = false, bool ignoreMemoryLimits = true, long factionId = 0)
        {
            var prefabDefinition = MyDefinitionManager.Static.GetPrefabDefinition(prefabName);

            Debug.Assert(prefabDefinition != null, "Could not spawn prefab named " + prefabName);
            if (prefabDefinition == null)
            {
                return;
            }

            MyObjectBuilder_CubeGrid[] gridObs = prefabDefinition.CubeGrids;

            Debug.Assert(gridObs.Length != 0);

            if (gridObs.Length == 0)
            {
                return;
            }

            MyEntities.RemapObjectBuilderCollection(gridObs);

            MatrixD translateToOriginMatrix;

            if (spawnAtOrigin)
            {
                Vector3D translation = Vector3D.Zero;
                if (prefabDefinition.CubeGrids[0].PositionAndOrientation.HasValue)
                {
                    translation = prefabDefinition.CubeGrids[0].PositionAndOrientation.Value.Position;
                }
                translateToOriginMatrix = MatrixD.CreateWorld(-translation, Vector3D.Forward, Vector3D.Up);
            }
            else
            {
                translateToOriginMatrix = MatrixD.CreateWorld(-prefabDefinition.BoundingSphere.Center, Vector3D.Forward, Vector3D.Up);
            }

            Vector3D moveVector = new Vector3D();
            bool     ignoreMemoryLimitsPrevious = MyEntities.IgnoreMemoryLimits;

            MyEntities.IgnoreMemoryLimits = ignoreMemoryLimits;
            IMyFaction faction = MySession.Static.Factions.TryGetFactionById(factionId);

            for (int i = 0; i < gridObs.Length; ++i)
            {
                // Set faction defined in the operation
                if (faction != null)
                {
                    foreach (var cubeBlock in gridObs[i].CubeBlocks)
                    {
                        cubeBlock.Owner     = faction.FounderId;
                        cubeBlock.ShareMode = MyOwnershipShareModeEnum.Faction;
                    }
                }

                MyEntity entity = MyEntities.CreateFromObjectBuilder(gridObs[i]);
                MyEntities.Add(entity);
                MyCubeGrid cubeGrid = entity as MyCubeGrid;

                Debug.Assert(cubeGrid != null, "Could not create grid prefab!");
                if (cubeGrid != null)
                {
                    MatrixD originalGridMatrix = gridObs[i].PositionAndOrientation.HasValue ? gridObs[i].PositionAndOrientation.Value.GetMatrix() : MatrixD.Identity;
                    MatrixD newWorldMatrix;
                    newWorldMatrix = MatrixD.Multiply(originalGridMatrix, MatrixD.Multiply(translateToOriginMatrix, worldMatrix));

                    if (cubeGrid.IsStatic)
                    {
                        Vector3 rounded = default(Vector3I);
                        if (MyCubeBuilder.CubeBuilderDefinition.BuildingSettings.StaticGridAlignToCenter)
                        {
                            rounded = Vector3I.Round(newWorldMatrix.Translation / cubeGrid.GridSize) * cubeGrid.GridSize;
                        }
                        else
                        {
                            rounded = Vector3I.Round(newWorldMatrix.Translation / cubeGrid.GridSize + 0.5f) * cubeGrid.GridSize - 0.5f * cubeGrid.GridSize;
                        }
                        moveVector = new Vector3D(rounded - newWorldMatrix.Translation);
                        newWorldMatrix.Translation = rounded;
                        cubeGrid.PositionComp.SetWorldMatrix(newWorldMatrix, forceUpdate: true);

                        if (MyPerGameSettings.Destruction)
                        {
                            Debug.Assert(cubeGrid.Physics != null && cubeGrid.Physics.Shape != null);
                            if (cubeGrid.Physics != null && cubeGrid.Physics.Shape != null)
                            {
                                cubeGrid.Physics.Shape.RecalculateConnectionsToWorld(cubeGrid.GetBlocks());
                            }
                        }
                    }
                    else
                    {
                        newWorldMatrix.Translation += moveVector;
                        cubeGrid.PositionComp.SetWorldMatrix(newWorldMatrix, forceUpdate: true);
                    }
                    //if some mods are missing prefab can have 0 blocks,
                    //we don't want to process this grid
                    if (cubeGrid.CubeBlocks.Count > 0)
                    {
                        results.Add(cubeGrid);
                    }
                }
            }
            MyEntities.IgnoreMemoryLimits = ignoreMemoryLimitsPrevious;
        }
Exemple #8
0
        public static void OnGlobalSpawnEvent(object senderEvent)
        {
            // Select a spawn group to spawn
            MySpawnGroupDefinition spawnGroup = PickRandomSpawnGroup();

            if (spawnGroup == null)
            {
                return;
            }

            spawnGroup.ReloadPrefabs();

            ProfilerShort.Begin("Generate position and direction");

            double   spawnDistance  = NEUTRAL_SHIP_SPAWN_DISTANCE;
            Vector3D playerPosition = Vector3D.Zero;
            bool     isWorldLimited = MyEntities.IsWorldLimited();
            int      numPlayers     = 0;

            if (isWorldLimited)
            {
                spawnDistance = Math.Min(spawnDistance, MyEntities.WorldSafeHalfExtent() - spawnGroup.SpawnRadius);
            }
            else
            {
                // In infinite worlds players can be thousands of kilometers away, so spawn ship around random player
                // so cargo ships will be spawned around every player at some time
                var players = MySession.Static.Players.GetOnlinePlayers();
                // In DS there can be no players connected
                numPlayers = Math.Max(0, players.Count - 1);
                int randomPlayerPosition = MyUtils.GetRandomInt(0, numPlayers);
                int i = 0;
                foreach (var player in players)
                {
                    if (i == randomPlayerPosition)
                    {
                        if (player.Character != null)
                        {
                            playerPosition = player.GetPosition();
                        }
                        break;
                    }
                    i++;
                }
            }
            if (spawnDistance < 0.0f)
            {
                MySandboxGame.Log.WriteLine("Not enough space in the world to spawn such a huge spawn group!");
                return;
            }

            double       forbiddenRadius = NEUTRAL_SHIP_FORBIDDEN_RADIUS;
            BoundingBoxD spawnBox;

            if (isWorldLimited)
            {
                spawnBox = new BoundingBoxD(new Vector3D(playerPosition - spawnDistance), new Vector3D(playerPosition + spawnDistance));
            }
            else
            {
                // We need to extend bouding box so cargo ships aren't spawned near other players
                GetSafeBoundingBoxForPlayers(playerPosition, spawnDistance, out spawnBox);
                // Forbidden radius is sphere around all players in box.
                // Bounding box is generated from players positions so their distance to center shall be same for all players
                forbiddenRadius += spawnBox.HalfExtents.Max() - NEUTRAL_SHIP_FORBIDDEN_RADIUS;
            }

            // Get the direction to the center and deviate it randomly
            Vector3D?origin = MyUtils.GetRandomBorderPosition(ref spawnBox);

            origin = MyEntities.TestPlaceInSpace(origin.Value, spawnGroup.SpawnRadius);
            if (!origin.HasValue)
            {
                if (++m_eventSpawnTry <= EVENT_SPAWN_TRY_MAX)
                {
                    MySandboxGame.Log.WriteLine("Could not spawn neutral ships - no free place found. Try " + m_eventSpawnTry + " of " + EVENT_SPAWN_TRY_MAX);

                    MyGlobalEvents.RescheduleEvent(senderEvent as MyGlobalEventBase, NEUTRAL_SHIP_RESCHEDULE_TIME);
                    ProfilerShort.End();
                    return;
                }
                else
                {
                    m_eventSpawnTry = 0;
                    return;
                }
            }
            m_eventSpawnTry = 0;

            // Radius in arc units of the forbidden sphere in the center, when viewed from origin
            float centerArcRadius = (float)Math.Atan(forbiddenRadius / (origin.Value - spawnBox.Center).Length());

            // Generate direction with elevation from centerArcRadius radians to (cAR + N_S_D_S) radians
            Vector3D direction = -Vector3D.Normalize(origin.Value);
            float    theta     = MyUtils.GetRandomFloat(centerArcRadius, centerArcRadius + NEUTRAL_SHIP_DIRECTION_SPREAD);
            float    phi       = MyUtils.GetRandomRadian();
            Vector3D cosVec    = Vector3D.CalculatePerpendicularVector(direction);
            Vector3D sinVec    = Vector3D.Cross(direction, cosVec);

            cosVec   *= (Math.Sin(theta) * Math.Cos(phi));
            sinVec   *= (Math.Sin(theta) * Math.Sin(phi));
            direction = direction * Math.Cos(theta) + cosVec + sinVec;

            Vector3D destination  = Vector3D.Zero;
            RayD     ray          = new RayD(origin.Value, direction);
            double?  intersection = ray.Intersects(spawnBox);
            Vector3D directionMult;

            if (!intersection.HasValue || intersection.Value < NEUTRAL_SHIP_MINIMAL_ROUTE_LENGTH)
            {
                directionMult = direction * NEUTRAL_SHIP_MINIMAL_ROUTE_LENGTH;
            }
            else
            {
                directionMult = direction * intersection.Value;
            }
            destination = origin.Value + directionMult;

            Vector3D upVector     = Vector3D.CalculatePerpendicularVector(direction);
            Vector3D rightVector  = Vector3D.Cross(direction, upVector);
            MatrixD  originMatrix = MatrixD.CreateWorld(origin.Value, direction, upVector);

            ProfilerShort.End();

            ProfilerShort.Begin("Check free space");

            // CH:TODO: Convex cast to detect collision
            // Check ships' path to avoid possible collisions. (TODO: But only if it is said in the definitions)
            m_raycastHits.Clear();
            foreach (var shipPrefab in spawnGroup.Prefabs)
            {
                var prefabDef = MyDefinitionManager.Static.GetPrefabDefinition(shipPrefab.SubtypeId);
                Debug.Assert(prefabDef != null);

                Vector3D shipPosition    = Vector3.Transform(shipPrefab.Position, originMatrix);
                Vector3D shipDestination = shipPosition + directionMult;
                float    radius          = prefabDef == null ? 10.0f : prefabDef.BoundingSphere.Radius;

                //these point checks could be done in the trajectory intersect, but checking points is faster than ray intersect
                if (MyGravityProviderSystem.IsPositionInNaturalGravity(shipPosition, spawnGroup.SpawnRadius))
                {
                    if (!MyFinalBuildConstants.IS_OFFICIAL)
                    {
                        MySandboxGame.Log.WriteLine("Could not spawn neutral ships: spawn point is inside gravity well");
                    }
                    MyGlobalEvents.RescheduleEvent(senderEvent as MyGlobalEventBase, NEUTRAL_SHIP_RESCHEDULE_TIME);
                    ProfilerShort.End();
                    return;
                }
                if (MyGravityProviderSystem.IsPositionInNaturalGravity(shipDestination, spawnGroup.SpawnRadius))
                {
                    if (!MyFinalBuildConstants.IS_OFFICIAL)
                    {
                        MySandboxGame.Log.WriteLine("Could not spawn neutral ships: destination point is inside gravity well");
                    }
                    MyGlobalEvents.RescheduleEvent(senderEvent as MyGlobalEventBase, NEUTRAL_SHIP_RESCHEDULE_TIME);
                    ProfilerShort.End();
                    return;
                }
                if (MyGravityProviderSystem.DoesTrajectoryIntersectNaturalGravity(shipPosition, shipDestination, spawnGroup.SpawnRadius + NEUTRAL_SHIP_SPAWN_OFFSET))
                {
                    if (!MyFinalBuildConstants.IS_OFFICIAL)
                    {
                        MySandboxGame.Log.WriteLine("Could not spawn neutral ships: flight path intersects gravity well");
                    }
                    MyGlobalEvents.RescheduleEvent(senderEvent as MyGlobalEventBase, NEUTRAL_SHIP_RESCHEDULE_TIME);
                    ProfilerShort.End();
                    return;
                }

                MyPhysics.CastRay(shipPosition, shipDestination, m_raycastHits, MyPhysics.CollisionLayers.ObjectDetectionCollisionLayer);
                if (m_raycastHits.Count > 0)
                {
                    if (!MyFinalBuildConstants.IS_OFFICIAL)
                    {
                        MySandboxGame.Log.WriteLine("Could not spawn neutral ships due to collision");
                    }
                    MyGlobalEvents.RescheduleEvent(senderEvent as MyGlobalEventBase, NEUTRAL_SHIP_RESCHEDULE_TIME);
                    ProfilerShort.End();
                    return;
                }

                for (int i = 0; i < 4; ++i)
                {
                    Vector3D shiftVector = upVector * m_upVecMultipliers[i] * radius + rightVector * m_rightVecMultipliers[i] * radius;
                    MyPhysics.CastRay(shipPosition + shiftVector, shipDestination + shiftVector, m_raycastHits, MyPhysics.CollisionLayers.ObjectDetectionCollisionLayer);

                    if (m_raycastHits.Count > 0)
                    {
                        if (!MyFinalBuildConstants.IS_OFFICIAL)
                        {
                            MySandboxGame.Log.WriteLine("Could not spawn neutral ships due to collision");
                        }
                        MyGlobalEvents.RescheduleEvent(senderEvent as MyGlobalEventBase, NEUTRAL_SHIP_RESCHEDULE_TIME);
                        ProfilerShort.End();
                        return;
                    }
                }
            }

            ProfilerShort.End();

            ProfilerShort.Begin("Spawn ships");

            long spawnGroupId = MyPirateAntennas.GetPiratesId();

            // The ships were collision-free. Now spawn them
            foreach (var shipPrefab in spawnGroup.Prefabs)
            {
                ProfilerShort.Begin(shipPrefab.BeaconText);

                // Yes, this could have been saved in the previous loop, but compared to (e.g.) raycasts, this does not take too much time to recalculate
                Vector3D shipPosition    = Vector3D.Transform((Vector3D)shipPrefab.Position, originMatrix);
                Vector3D shipDestination = shipPosition + directionMult;
                Vector3D up = Vector3D.CalculatePerpendicularVector(-direction);

                m_tmpGridList.Clear();

                // CH: We don't want a new identity for each ship anymore. We should handle that in a better way...

                /*if (shipPrefab.ResetOwnership)
                 * {
                 *  if (spawnGroupId == 0)
                 *  {
                 *      //This is not an NPC so that it doesn't show up in assign ownership drop down menu
                 *      MyIdentity spawnGroupIdentity = Sync.Players.CreateNewIdentity("Neutral NPC");
                 *      spawnGroupId = spawnGroupIdentity.IdentityId;
                 *  }
                 * }*/

                // Deploy ship
                ProfilerShort.Begin("Spawn cargo ship");
                MyPrefabManager.Static.SpawnPrefab(
                    resultList: m_tmpGridList,
                    prefabName: shipPrefab.SubtypeId,
                    position: shipPosition,
                    forward: direction,
                    up: up,
                    initialLinearVelocity: shipPrefab.Speed * direction,
                    beaconName: shipPrefab.BeaconText,
                    spawningOptions: VRage.Game.ModAPI.SpawningOptions.RotateFirstCockpitTowardsDirection |
                    VRage.Game.ModAPI.SpawningOptions.SpawnRandomCargo |
                    VRage.Game.ModAPI.SpawningOptions.DisableDampeners,
                    ownerId: shipPrefab.ResetOwnership ? spawnGroupId : 0,
                    updateSync: true);
                ProfilerShort.End();

                foreach (var grid in m_tmpGridList)
                {
                    var cockpit = grid.GetFirstBlockOfType <MyCockpit>();
                    if (cockpit != null)
                    {
                        MySimpleAutopilot ai = new MySimpleAutopilot(shipDestination, (Vector3)direction);
                        cockpit.AttachAutopilot(ai);
                        break;
                    }
                }

                m_tmpGridList.Clear();

                ProfilerShort.End();
            }

            ProfilerShort.End();
        }
        public bool TryNamingAnBlockOrFloatingObject()
        {
            var worldMatrix = MyAPIGateway.Session.Camera.WorldMatrix; // most accurate for player view.
            var position    = worldMatrix.Translation + worldMatrix.Forward * 0.5f;
            var ray         = new RayD(position, worldMatrix.Forward * 1000);

            var boundingSphere = new BoundingSphereD(worldMatrix.Translation, 30);
            var entites        = MyEntities.GetEntitiesInSphere(ref boundingSphere);

            List <MyPhysics.HitInfo> hits = new List <MyPhysics.HitInfo>();

            MyPhysics.CastRay(worldMatrix.Translation, worldMatrix.Translation + worldMatrix.Forward * 5, hits, 15);

            foreach (var hitInfo in hits)
            {
                var body = (MyPhysicsBody)hitInfo.HkHitInfo.Body.UserObject;
                if (body.Entity is MyFloatingObject)
                {
                    var rayEntity = (MyEntity)body.Entity;
                    NameDialog(rayEntity);
                    return(true);
                }
            }

            foreach (var entity in entites)
            {
                var cubeGrid = entity as MyCubeGrid;

                if (cubeGrid != null && ray.Intersects(entity.PositionComp.WorldAABB).HasValue)
                {
                    var hit = cubeGrid.RayCastBlocks(worldMatrix.Translation, worldMatrix.Translation + worldMatrix.Forward * 100);
                    if (hit.HasValue)
                    {
                        var block = cubeGrid.GetCubeBlock(hit.Value);

                        if (block.FatBlock != null)
                        {
                            var dialog = new ValueGetScreenWithCaption("Name block dialog: " + block.FatBlock.DefinitionDisplayNameText, block.FatBlock.Name ?? block.FatBlock.DefinitionDisplayNameText + " has no name.", delegate(string text)
                            {
                                MyEntity foundEntity;
                                if (MyEntities.TryGetEntityByName(text, out foundEntity))
                                {
                                    MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                                               buttonType: MyMessageBoxButtonsType.OK,
                                                               messageText: new StringBuilder("Entity with same name already exits, please enter different name."),
                                                               messageCaption: new StringBuilder("Naming error")));
                                }
                                else
                                {
                                    block.FatBlock.Name = text;
                                    MyEntities.SetEntityName(block.FatBlock, true);

                                    return(true);
                                }

                                return(false);
                            });
                            MyGuiSandbox.AddScreen(dialog);
                            entites.Clear();
                            return(true);
                        }
                    }
                }
            }

            entites.Clear();
            return(false);
        }
Exemple #10
0
        private static void OnConsumeItem(ref ConsumeItemMsg msg, MyNetworkClient sender)
        {
            if (!MyEntities.EntityExists(msg.OwnerEntityId) || (msg.ConsumerEntityId != 0 && !MyEntities.EntityExists(msg.ConsumerEntityId)))
            {
                return;
            }

            var entity = MyEntities.GetEntityById(msg.OwnerEntityId);

            if (entity == null)
            {
                return;
            }

            var inventoryOwner = entity as IMyInventoryOwner;

            if (inventoryOwner == null)
            {
                return;
            }

            var inventory = inventoryOwner.GetInventory(msg.InventoryId);

            if (inventory == null)
            {
                return;
            }

            if (Sync.IsServer)
            {
                var existingAmount = inventory.GetItemAmount(msg.ItemId);
                if (existingAmount < msg.Amount)
                {
                    msg.Amount = existingAmount;
                }
            }

            if (msg.ConsumerEntityId != 0)
            {
                entity = MyEntities.GetEntityById(msg.ConsumerEntityId);
                if (entity == null)
                {
                    return;
                }
            }

            if (entity.Components != null)
            {
                var statComp = entity.Components.Get <MyEntityStatComponent>() as MyCharacterStatComponent;
                if (statComp != null)
                {
                    var definition = MyDefinitionManager.Static.GetDefinition(msg.ItemId) as MyConsumableItemDefinition;
                    statComp.Consume(msg.Amount, definition);
                    var character = entity as MyCharacter;
                    if (character != null)
                    {
                        character.StartSecondarySound(definition.EatingSound, true);
                    }
                }
            }

            if (Sync.IsServer)
            {
                inventory.RemoveItemsOfType(msg.Amount, msg.ItemId);
                Sync.Layer.SendMessageToAll(ref msg);
            }
        }
Exemple #11
0
        public static void ReportPlayerDeath(bool isLocallyControlled, ulong playerSteamId)
        {
            if (MySandboxGame.IsDedicated)
            {
                return;
            }
            try
            {
                IMyAnalytics analytics = MyPerGameSettings.AnalyticsTracker;
                if (analytics == null)
                {
                    return;
                }

                if (!isLocallyControlled)
                {
                    return;
                }

                var deathCause = m_lastDamageInformation.Type.String;

                Debug.Assert(!string.IsNullOrEmpty(deathCause), "Analytics: Unknown death type. Please report what you were doing to the devs.");

                string deathType;
                bool   pvp           = false;
                bool   selfInflicted = false;
                if (m_lastDamageInformation.Type != MyStringHash.NullOrEmpty && m_lastDamageInformation.AttackerId != 0)
                {
                    MyEntity entity = null;
                    MyEntities.TryGetEntityById(m_lastDamageInformation.AttackerId, out entity);
                    var controllableEntity = entity as IMyControllableEntity;
                    if (controllableEntity != null)
                    {
                        // The attacker is controller by a character.
                        var controller = controllableEntity.ControllerInfo.Controller;
                        if (controller != null)
                        {
                            if (controller.Player.Id.SteamId != playerSteamId)
                            {
                                pvp = true;
                            }
                            else
                            {
                                selfInflicted = true;
                            }
                        }
                    }
                    else if (entity is IMyGunBaseUser || entity is IMyHandheldGunObject <MyToolBase> ||
                             entity is IMyHandheldGunObject <MyGunBase> )
                    {
                        pvp = true;
                    }
                }

                if (pvp)
                {
                    deathType = "pvp";
                }
                else if (selfInflicted)
                {
                    deathType = "self_inflicted";
                }
                else
                {
                    deathType = m_lastDamageInformation.Type == MyDamageType.Environment ? "environment" : "unknown";
                }

                MyPlanetNamesData planetData = GetPlanetNames(MySession.Static.LocalCharacter.PositionComp.GetPosition());
                analytics.ReportPlayerDeath(deathType, deathCause, planetData.planetName, planetData.planetType, MySession.Static.IsScenario);
            }
            catch (Exception exception)
            {
                MyLog.Default.WriteLine(exception);
            }
        }
Exemple #12
0
        static void OnTransferInventoryMsg(ref TransferInventoryMsg msg, MyNetworkClient sender)
        {
            MyEntity source      = MyEntities.GetEntityById(msg.SourceEntityID);
            MyEntity destination = MyEntities.GetEntityById(msg.DestinationEntityID);

            Debug.Assert(source != null && destination != null, "Entities weren't found!");
            if (source != null && destination != null)
            {
                var inventory          = source.Components.Get <MyInventoryBase>();
                var inventoryAggregate = inventory as MyInventoryAggregate;

                var destinationAggregate = destination.Components.Get <MyInventoryBase>() as MyInventoryAggregate;

                if (inventoryAggregate != null)
                {
                    inventory = inventoryAggregate.GetInventory(msg.InventoryId);
                    inventoryAggregate.ChildList.RemoveComponent(inventory);
                }
                else
                {
                    inventory.Container.Remove <MyInventoryBase>();
                }

                Debug.Assert(inventoryAggregate == null || (inventoryAggregate != null && inventoryAggregate.GetInventory(inventory.InventoryId) == null), "Source's entity inventory aggregate still contains inventory!");
                Debug.Assert(inventoryAggregate != null || (inventoryAggregate == null && !source.Components.Has <MyInventoryBase>()), "Inventory wasn't removed from it's source entity");

                if (source is MyCharacter)
                {
                    (source as MyCharacter).Inventory = null;
                }

                Debug.Assert(inventory.InventoryId.ToString() == msg.InventoryId.ToString(), "Inventory wasn't found!");

                if (destinationAggregate != null)
                {
                    destinationAggregate.ChildList.AddComponent(inventory);
                }
                else
                {
                    destination.Components.Add <MyInventoryBase>(inventory);
                }

                inventory.RemoveEntityOnEmpty = msg.RemoveEntityOnEmpty;

                // TODO (OM): Since we still have IMyInventoryOwner we need to keep the below, but remove it, when IMyInventoryOwner is no longer needed
                if (inventory is MyInventory)
                {
                    (inventory as MyInventory).RemoveOwner();
                }

                Debug.Assert(destinationAggregate == null || (destinationAggregate.GetInventory(inventory.InventoryId) != null), "The destination aggregate doesn't contain inserted inventory!");

                // Check whether the destination entity has the detector component
                MyUseObjectsComponent useObjectComponent = null;
                if (!destination.Components.Has <MyUseObjectsComponentBase>())
                {
                    useObjectComponent = new MyUseObjectsComponent();
                    destination.Components.Add <MyUseObjectsComponentBase>(useObjectComponent);
                }
                else
                {
                    useObjectComponent = destination.Components.Get <MyUseObjectsComponentBase>() as MyUseObjectsComponent;
                }
                Debug.Assert(useObjectComponent != null, "Detector is missing on the entity!");
                if (useObjectComponent != null && useObjectComponent.GetDetectors("inventory").Count == 0)
                {
                    var useObjectMat = Matrix.CreateScale(destination.PositionComp.LocalAABB.Size) * Matrix.CreateTranslation(destination.PositionComp.LocalAABB.Center);
                    useObjectComponent.AddDetector("inventory", useObjectMat);
                    useObjectComponent.RecreatePhysics();
                }
            }
        }
Exemple #13
0
        // Creates prefab, but won't add into scene
        // WorldMatrix is the matrix of the first grid in the prefab. The others will be transformed to keep their relative positions
        private void CreateGridsFromPrefab(List <MyCubeGrid> results, string prefabName, MatrixD worldMatrix, bool spawnAtOrigin, bool ignoreMemoryLimits, long factionId, Stack <Action> callbacks)
        {
            var prefabDefinition = MyDefinitionManager.Static.GetPrefabDefinition(prefabName);

            Debug.Assert(prefabDefinition != null, "Could not spawn prefab named " + prefabName);
            if (prefabDefinition == null)
            {
                return;
            }

            MyObjectBuilder_CubeGrid[] gridObs = new MyObjectBuilder_CubeGrid[prefabDefinition.CubeGrids.Length];

            Debug.Assert(gridObs.Length != 0);

            if (gridObs.Length == 0)
            {
                return;
            }

            for (int i = 0; i < gridObs.Length; i++)
            {
                gridObs[i] = (MyObjectBuilder_CubeGrid)prefabDefinition.CubeGrids[i].Clone();
            }

            MyEntities.RemapObjectBuilderCollection(gridObs);

            MatrixD translateToOriginMatrix;

            if (spawnAtOrigin)
            {
                Vector3D translation = Vector3D.Zero;
                if (prefabDefinition.CubeGrids[0].PositionAndOrientation.HasValue)
                {
                    translation = prefabDefinition.CubeGrids[0].PositionAndOrientation.Value.Position;
                }
                translateToOriginMatrix = MatrixD.CreateWorld(-translation, Vector3D.Forward, Vector3D.Up);
            }
            else
            {
                translateToOriginMatrix = MatrixD.CreateWorld(-prefabDefinition.BoundingSphere.Center, Vector3D.Forward, Vector3D.Up);
            }

            //Vector3D moveVector=new Vector3D();
            bool ignoreMemoryLimitsPrevious = MyEntities.IgnoreMemoryLimits;

            MyEntities.IgnoreMemoryLimits = ignoreMemoryLimits;
            IMyFaction faction = MySession.Static.Factions.TryGetFactionById(factionId);

            for (int i = 0; i < gridObs.Length; ++i)
            {
                // Set faction defined in the operation
                if (faction != null)
                {
                    foreach (var cubeBlock in gridObs[i].CubeBlocks)
                    {
                        cubeBlock.Owner     = faction.FounderId;
                        cubeBlock.ShareMode = MyOwnershipShareModeEnum.Faction;
                    }
                }

                MatrixD originalGridMatrix = gridObs[i].PositionAndOrientation.HasValue ? gridObs[i].PositionAndOrientation.Value.GetMatrix() : MatrixD.Identity;
                MatrixD newWorldMatrix;
                newWorldMatrix = MatrixD.Multiply(originalGridMatrix, MatrixD.Multiply(translateToOriginMatrix, worldMatrix));

                MyEntity   entity   = MyEntities.CreateFromObjectBuilder(gridObs[i], false);
                MyCubeGrid cubeGrid = entity as MyCubeGrid;


                Debug.Assert(cubeGrid != null, "Could not create grid prefab!");
                if (cubeGrid != null)
                {
                    //if some mods are missing prefab can have 0 blocks,
                    //we don't want to process this grid
                    if (cubeGrid.CubeBlocks.Count > 0)
                    {
                        results.Add(cubeGrid);
                        callbacks.Push(delegate() { SetPrefabPosition(entity, newWorldMatrix); });
                    }
                }
            }
            MyEntities.IgnoreMemoryLimits = ignoreMemoryLimitsPrevious;
        }
Exemple #14
0
        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)
                {
                    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;
                if (Math.Abs(Quaternion.Dot(serverPositionAndOrientation.Transform.Rotation, clientNormalized)) < 1 - eps && m_character.IsDead == false)
                {
                    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);
            }
        }
        // No network logic involved. highlighs the object.
        private void MakeLocalHighlightChange(MyHighlightData data)
        {
            if (data.Thickness > -1)
            {
                // Highlight On
                m_highlightedIds.Add(data.EntityId);
            }
            else
            {
                // Highlight Off
                m_highlightedIds.Remove(data.EntityId);
            }

            MyEntity entity;

            if (!MyEntities.TryGetEntityById(data.EntityId, out entity))
            {
                //Debug.Fail("Highlight system: Entity was not found.");
                return;
            }

            if (!data.IgnoreUseObjectData)
            {
                var useObject = entity as IMyUseObject;
                var useComp   = entity.Components.Get <MyUseObjectsComponentBase>();
                // Entities can derive from IMyUseObject or have useObject component.
                if (useObject != null || useComp != null)
                {
                    if (useComp != null)
                    {
                        // Has UseObjectComp
                        List <IMyUseObject> useObjectTmpList = new List <IMyUseObject>();
                        useComp.GetInteractiveObjects(useObjectTmpList);

                        for (var index = 0; index < useObjectTmpList.Count; index++)
                        {
                            HighlightUseObject(useObjectTmpList[index], data);
                        }

                        if (useObjectTmpList.Count > 0)
                        {
                            if (HighlightAccepted != null)
                            {
                                HighlightAccepted(data);
                            }

                            return;
                        }
                    }
                    else
                    {
                        // Is useObject
                        HighlightUseObject(useObject, data);
                        if (HighlightAccepted != null)
                        {
                            HighlightAccepted(data);
                        }

                        return;
                    }
                }
            }

            // Collect subPart indicies
            m_subPartIndicies.Clear();
            CollectSubPartIndicies(entity);

            // No use object just use the model for highlight
            MyRenderProxy.UpdateModelHighlight(
                (uint)entity.Render.GetRenderObjectID(),
                null,
                m_subPartIndicies.ToArray(),
                data.OutlineColor,
                data.Thickness,
                data.PulseTimeInFrames);

            if (HighlightAccepted != null)
            {
                HighlightAccepted(data);
            }
        }
        private void AfterDamageApplied(object target, MyDamageInformation info)
        {
            MyCharacter targetCharacter = target as MyCharacter;

            if (targetCharacter == null || targetCharacter.IsDead)
            {
                return;
            }

            MyEntity entity = null;

            MyEntities.TryGetEntityById(info.AttackerId, out entity);

            MyPlayer     attackerPlayer = null;
            MyStringHash hitCue         = MyStringHash.NullOrEmpty;

            // Because damage system is retarded...
            if (entity is MyCharacter || entity is MyCubeGrid || entity is MyCubeBlock)
            {
                attackerPlayer = Sync.Players.GetControllingPlayer(entity);
                if (attackerPlayer == null)
                {
                    return;
                }
            }
            else
            {
                var gunBaseUser = entity as IMyGunBaseUser;
                if (gunBaseUser == null)
                {
                    return;
                }
                if (gunBaseUser.Owner == null)
                {
                    return;
                }
                attackerPlayer = Sync.Players.GetControllingPlayer(gunBaseUser.Owner);

                if (MyPerGameSettings.Game == GameEnum.ME_GAME)
                {
                    //hitCue = MyStringHash.GetOrCompute("ToolCrossbHitBody");//this causes to play the hit sound at full volume regardless of distance
                }
            }

            if (attackerPlayer == null || attackerPlayer.Client == null || attackerPlayer.IsBot)
            {
                return;
            }
            if (targetCharacter.ControllerInfo.Controller != null && targetCharacter.ControllerInfo.Controller.Player == attackerPlayer)
            {
                return;
            }

            if (MyPerGameSettings.Game == GameEnum.ME_GAME)
            {
                MyMultiplayer.RaiseStaticEvent(s => AfterDamageAppliedClient, hitCue, new EndpointId(attackerPlayer.Client.SteamUserId));
            }
            else if (MyPerGameSettings.Game == GameEnum.SE_GAME)
            {
                MyMultiplayer.RaiseStaticEvent(s => AfterDamageAppliedClient, hitCue, new EndpointId(attackerPlayer.Client.SteamUserId));
            }
        }
Exemple #17
0
        public bool ConsumeResult()
        {
            Item result;

            if (m_resultQueue.TryDequeue(out result))
            {
                if (result.Result != null)
                {
                    result.Result.DebugAsyncLoading = false;
                }
                bool conflictFound = false;
                if (result.EntityIds != null)
                {
                    while (MyEntities.HasEntitiesToDelete())
                    {
                        MyEntities.DeleteRememberedEntities();
                    }
                    foreach (var id in result.EntityIds)
                    {
                        IMyEntity entity;
                        if (MyEntityIdentifier.TryGetEntity(id.EntityId, out entity))
                        {
                            MyLog.Default.WriteLine("Entity found !  id : " + id.EntityId.ToString() + " existing : " + entity.ToString() + " adding: " + id.ToString());
                            conflictFound = true;
                            // Debug.Fail("double entity add !!");
                        }
                    }
                    if (conflictFound == false)
                    {
                        foreach (var id in result.EntityIds)
                        {
                            MyEntityIdentifier.AddEntityWithId(id);
                        }
                    }
                    result.EntityIds.Clear();
                }

                if (conflictFound == false)
                {
                    if (result.AddToScene)
                    {
                        MyEntities.Add(result.Result, result.InScene);
                        if (result.SubGrids != null)
                        {
                            foreach (var subGrid in result.SubGrids)
                            {
                                MyEntities.Add(subGrid, result.InScene);
                            }
                            result.SubGrids.Clear();
                            result.SubGrids = null;
                        }
                    }
                    if (result.DoneHandler != null)
                    {
                        result.DoneHandler(result.Result);
                    }
                }
                else
                {
                    if (result.DoneHandler != null)
                    {
                        result.DoneHandler(null);
                    }
                }
                return(true);
            }
            return(false);
        }
        public override bool Update(bool hasFocus)
        {
            /*if (m_respawnsTable.RowsCount == 0 && State != MyGuiScreenState.CLOSING && MySession.Static.LocalHumanPlayer != null)
             * {
             *  MyPlayerCollection.RespawnRequest(joinGame: true, newPlayer: true, medicalId: 0, shipPrefabId: null);
             *  CloseScreen();
             * }*/
            UpdateSpawnShipTimes();
            bool retval = base.Update(hasFocus);

            if (m_selectedRespawnShip != null)
            {
                var rc       = MySpaceRespawnComponent.Static;
                int cooldown = rc.GetRespawnCooldownSeconds(MySession.Static.LocalHumanPlayer.Id, m_selectedRespawnShip.Id.SubtypeName);
                if (rc.IsSynced && cooldown == 0)
                {
                    RespawnShipImmediately(m_selectedRespawnShip.Id.SubtypeName);
                }
            }

            if (m_respawnsTable.RowsCount == 0)
            {
                RefreshRespawnPoints();//because medical rooms are not powered when the map starts
            }

            if (m_respawnsTable.SelectedRow != null && MySession.Static.GetCameraControllerEnum() != MyCameraControllerEnum.Entity)
            {
                MyMedicalRoomInfo userData = m_respawnsTable.SelectedRow.UserData as MyMedicalRoomInfo;

                if (userData != null)
                {
                    m_respawnButton.Enabled = false;
                    MyMedicalRoom medicalRoom;
                    if (MyEntities.TryGetEntityById <MyMedicalRoom>(userData.MedicalRoomId, out medicalRoom))
                    {
                        m_respawnButton.Enabled = true;
                        Vector3D medRoomPosition         = (Vector3D)medicalRoom.PositionComp.GetPosition();
                        Vector3D preferredCameraPosition = medRoomPosition + medicalRoom.WorldMatrix.Up * 20 + medicalRoom.WorldMatrix.Right * 20 + medicalRoom.WorldMatrix.Forward * 20;
                        Vector3D?cameraPosition          = MyEntities.FindFreePlace(preferredCameraPosition, 1);

                        if (!cameraPosition.HasValue)
                        {
                            cameraPosition = preferredCameraPosition;
                        }

                        MySpectatorCameraController.Static.Target   = medRoomPosition;
                        MySpectatorCameraController.Static.Position = cameraPosition.Value;
                    }
                }
            }


            if (m_labelNoRespawn.Text == null)
            {
                m_labelNoRespawn.Visible = false;
            }
            else
            {
                m_labelNoRespawn.Visible = true;
            }

            return(retval);
        }
        public override void UpdateAfterSimulation()
        {
            base.UpdateAfterSimulation();

            var muzzlePosition = m_positionMuzzleInWorldSpace;

            muzzlePosition += NearFlag
                                     ? MySmallShipConstants.ALL_SMALL_SHIP_MODEL_SCALE * WorldMatrix.Forward
                                     : .5f * WorldMatrix.Forward;
            if (m_state == PressureState.Pushed && CurrentState == MyDrillStateEnum.Activated)
            {
                StartPressureIdleCue();
            }
            else
            {
                StopPressureIdleCue();
            }

            if ((MyMinerGame.TotalGamePlayTimeInMilliseconds - m_lastTimeStarted) >= MyPressureDrillDeviceConstants.SHOT_INTERVAL_IN_MILISECONDS)
            {
                StopDrillingCue();
                StopMovingCue();
                m_state = PressureState.Pushed;

                return;
            }

            if (m_pressureFireEffect != null && !m_pressureFireEffect.IsStopped)
            {
                m_pressureFireEffect.WorldMatrix = Matrix.CreateWorld(
                    muzzlePosition + 1.5f * WorldMatrix.Forward,
                    WorldMatrix.Forward,
                    WorldMatrix.Up);
            }

            switch (m_state)
            {
            case PressureState.Init:
                StartDrillChargingCue();
                m_state = PressureState.Charging;

                m_chargingPressureEffect             = MyParticlesManager.CreateParticleEffect((int)MyParticleEffectsIDEnum.Drill_Pressure_Charge);
                m_chargingPressureEffect.WorldMatrix = Matrix.CreateWorld(muzzlePosition, WorldMatrix.Forward, WorldMatrix.Up);
                break;

            case PressureState.Charging:
            {
                ((MySmallShip)Parent).IncreaseHeadShake(MyDrillDeviceConstants.SHAKE_DURING_ROTATION);

                if (m_chargingPressureEffect != null)
                {
                    m_chargingPressureEffect.WorldMatrix = Matrix.CreateWorld(muzzlePosition, WorldMatrix.Forward, WorldMatrix.Up);
                }

                if (m_drillChargingCue == null || !m_drillChargingCue.Value.IsPlaying)
                {
                    m_state = PressureState.Ready;
                }
            }
            break;

            case PressureState.Ready:
            {
                m_chargingPressureEffect.Stop();
                m_chargingPressureEffect = null;

                m_pressureFireEffect             = MyParticlesManager.CreateParticleEffect((int)MyParticleEffectsIDEnum.Drill_Pressure_Fire);
                m_pressureFireEffect.OnDelete   += OnPressureFireEffectDelete;
                m_pressureFireEffect.WorldMatrix = Matrix.CreateWorld(muzzlePosition, WorldMatrix.Forward, WorldMatrix.Up);

                //  Check for collision with drill and world
                MyLine line = new MyLine(GetPosition(), GetPosition() + 2 * m_radius * WorldMatrix.Forward, true);

                MyIntersectionResultLineTriangleEx?intersection = MyEntities.GetIntersectionWithLine(ref line, Parent, null);

                if (intersection != null && intersection.Value.Entity.Physics != null)
                {
                    var voxelMap = intersection.Value.Entity as MyVoxelMap;

                    StartDrillingCue(voxelMap != null);

                    if (voxelMap != null)
                    {
                        ((MySmallShip)Parent).IncreaseHeadShake(MyDrillDeviceConstants.SHAKE_DURING_IN_VOXELS);

                        //  We found voxel so lets make tunel into it
                        BoundingSphere bigSphereForTunnel = new BoundingSphere(GetPosition() + 20 * WorldMatrix.Forward, m_radius);

                        for (int i = 1; i < (int)m_radius; i++)
                        {
                            bigSphereForTunnel.Center = GetPosition() + (20 + i) * WorldMatrix.Forward;
                            bigSphereForTunnel.Radius = i * 2;

                            CutOutFromVoxel(voxelMap, ref bigSphereForTunnel);
                        }

                        CreateImpactEffect(intersection.Value.IntersectionPointInWorldSpace, intersection.Value.NormalInWorldSpace, MyParticleEffectsIDEnum.Drill_Pressure_Impact);
                        StartDrillBlastRockCue();
                    }
                    //  Display particles when we are in contact with voxel
                    else
                    {
                        ((MySmallShip)Parent).IncreaseHeadShake(MyDrillDeviceConstants.SHAKE_DURING_ROTATION);

                        CreateImpactEffect(intersection.Value.IntersectionPointInWorldSpace, intersection.Value.NormalInWorldSpace, MyParticleEffectsIDEnum.Drill_Pressure_Impact_Metal);

                        intersection.Value.Entity.DoDamage(0, m_damage, 0, MyDamageType.Drill, MyAmmoType.Explosive, Parent);

                        StartDrillBlastOtherCue();
                    }
                }
                else
                {
                    StartDrillBlastCue();
                }
                m_state = PressureState.Pushed;
            }
            break;

            case PressureState.Pushed:
            {
                StopDrillingBlastCue();
                StopMovingCue();
            }
            break;
            }
        }
 public static string GetEntityNameOrElse(long entityId, string defaultName)
 {
     return(MyEntities.TryGetEntityById(entityId, out var e) ? e.DisplayName : defaultName);
 }
 public List <Customer> GetAllCustomers()
 {
     using (var context = new MyEntities())
         return(context.Customers.ToList());
 }
Exemple #22
0
        /// <summary>
        /// Updates resource.
        /// </summary>
        public override void UpdateBeforeSimulation()
        {
            try
            {
                VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("MyMissile.UpdateBeforeSimulation");

                if (m_isExploded)
                {
                    if (Sandbox.Game.Multiplayer.Sync.IsServer)
                    {
                        //  Create explosion
                        float           radius          = m_missileAmmoDefinition.MissileExplosionRadius;
                        BoundingSphereD explosionSphere = new BoundingSphereD(m_collisionPoint.HasValue ? m_collisionPoint.Value : PositionComp.GetPosition(), radius);

                        MyEntity ownerEntity = null;
                        //MyEntities.TryGetEntityById(m_owner, out ownerEntity);
                        MyEntities.TryGetEntity(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       = 0.2f,
                            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 * 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.AutoDelete           = false;
                            m_smokeEffect.CalculateDeltaMatrix = true;
                        }
                    }
                }
                Physics.AngularVelocity = Vector3.Zero;

                if ((Vector3.Distance(PositionComp.GetPosition(), m_origin) >= m_maxTrajectory))
                {
                    Explode();
                    return;
                }
            }
            finally
            {
                VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();
            }
        }
        public MyPetaInputComponent()
        {
            AddShortcut(MyKeys.OemBackslash, true, true, false, false,
                        () => "Debug draw physics clusters: " + MyDebugDrawSettings.DEBUG_DRAW_PHYSICS_CLUSTERS,
                        delegate
            {
                MyDebugDrawSettings.DEBUG_DRAW_PHYSICS_CLUSTERS = !MyDebugDrawSettings.DEBUG_DRAW_PHYSICS_CLUSTERS;
                return(true);
            });

            AddShortcut(MyKeys.OemBackslash, false, false, false, false,
                        () => "Advance all moving entities",
                        delegate
            {
                foreach (var entity in MyEntities.GetEntities().ToList())
                {
                    if (entity.Physics != null)
                    {
                        Vector3D posDelta = entity.Physics.LinearVelocity * SI_DYNAMICS_MULTIPLIER;
                        MyPhysics.Clusters.EnsureClusterSpace(entity.PositionComp.WorldAABB + posDelta);

                        if (entity.Physics.LinearVelocity.Length() > 0.1f)
                        {
                            entity.PositionComp.SetPosition(entity.PositionComp.GetPosition() + posDelta);
                        }
                    }
                }
                return(true);
            });

            AddShortcut(MyKeys.S, true, true, false, false,
                        () => "Insert controllable sphere",
                        delegate
            {
                MyControllableSphere sphere = new MyControllableSphere();
                sphere.Init();
                MyEntities.Add(sphere);

                sphere.PositionComp.SetPosition(MySector.MainCamera.Position + 2 * MySector.MainCamera.ForwardVector);
                sphere.Physics.Enabled = false;

                MySession.LocalHumanPlayer.Controller.TakeControl(sphere);
                return(true);
            });

            AddShortcut(MyKeys.Back, true, true, false, false,
                        () => "Freeze gizmo: " + MyCubeBuilder.Static.FreezeGizmo,
                        delegate
            {
                MyCubeBuilder.Static.FreezeGizmo = !MyCubeBuilder.Static.FreezeGizmo;
                return(true);
            });

            AddShortcut(MyKeys.NumPad8, true, false, false, false,
                        () => "Wave to friend",
                        delegate
            {
                MySession.LocalCharacter.AddCommand(new MyAnimationCommand()
                {
                    AnimationSubtypeName = "Wave",
                    BlendTime            = 0.3f,
                    TimeScale            = 1,
                }, true);
                return(true);
            });

            AddShortcut(MyKeys.NumPad9, true, false, false, false,
                        () => "Dynamics multiplier: " + ((int)SI_DYNAMICS_MULTIPLIER).ToString(),
                        delegate
            {
                SI_DYNAMICS_MULTIPLIER *= 10;
                if (SI_DYNAMICS_MULTIPLIER > 10000)
                {
                    SI_DYNAMICS_MULTIPLIER = 1;
                }
                return(true);
            });

            AddShortcut(MyKeys.NumPad7, true, false, false, false,
                        () => "Use next ship",
                        delegate
            {
                MyCharacterInputComponent.UseNextShip();
                return(true);
            });

            AddShortcut(MyKeys.NumPad5, true, false, false, false,
                        () => "Insert tree",
                        delegate
            {
                InsertTree();
                return(true);
            });

            AddShortcut(MyKeys.NumPad6, true, false, false, false,
                        () => "SI Debug draw paths",
                        delegate
            {
                MyDebugDrawSettings.ENABLE_DEBUG_DRAW = !MyDebugDrawSettings.ENABLE_DEBUG_DRAW;
                if (MyDebugDrawSettings.ENABLE_DEBUG_DRAW)
                {
                    MyStructuralIntegrity.Enabled = true;
                    MyDebugDrawSettings.DEBUG_DRAW_STRUCTURAL_INTEGRITY = true;
                    DEBUG_DRAW_PATHS    = true;
                    DEBUG_DRAW_TENSIONS = false;
                }

                //foreach (var entity in MyEntities.GetEntities())
                //{
                //    if (entity.GetTopMostParent().Physics != null)
                //    {
                //        var body = entity.GetTopMostParent().Physics;
                //        if (body.RigidBody != null)
                //        {
                //            Vector3 newVel = body.Entity.Physics.LinearVelocity;
                //            float y = newVel.Y;
                //            newVel.Y = -newVel.Z;
                //            newVel.Z = y;
                //            body.RigidBody.ApplyLinearImpulse(newVel * body.Mass * 20);
                //        }
                //    }
                //}
                return(true);
            });

            AddShortcut(MyKeys.NumPad1, true, false, false, false,
                        () => "Reorder clusters",
                        delegate
            {
                if (MySession.ControlledEntity != null)
                {
                    MySession.ControlledEntity.Entity.GetTopMostParent().Physics.ReorderClusters();
                }
                return(true);
            });

            AddShortcut(MyKeys.NumPad3, true, false, false, false,
                        () => "SI Debug draw tensions",
                        delegate
            {
                MyDebugDrawSettings.ENABLE_DEBUG_DRAW = !MyDebugDrawSettings.ENABLE_DEBUG_DRAW;
                if (MyDebugDrawSettings.ENABLE_DEBUG_DRAW)
                {
                    MyStructuralIntegrity.Enabled = true;
                    MyDebugDrawSettings.DEBUG_DRAW_STRUCTURAL_INTEGRITY = true;
                    DEBUG_DRAW_PATHS    = false;
                    DEBUG_DRAW_TENSIONS = true;
                }
                //foreach (var entity in MyEntities.GetEntities())
                //{
                //    if (entity.GetTopMostParent().Physics != null)
                //    {
                //        var body = entity.GetTopMostParent().Physics;
                //        if (body.RigidBody != null)
                //        {
                //            Vector3 newVel = body.Entity.Physics.LinearVelocity;
                //            float x = newVel.X;
                //            newVel.X = -newVel.X;
                //            newVel.Z = x;
                //            body.RigidBody.ApplyLinearImpulse(newVel * body.Mass * 20);
                //        }
                //    }
                //}
                return(true);
            });

            AddShortcut(MyKeys.NumPad4, true, false, false, false,
                        () => "Enable SI destructions: " + ENABLE_SI_DESTRUCTIONS,
                        delegate
            {
                ENABLE_SI_DESTRUCTIONS = !ENABLE_SI_DESTRUCTIONS;
                return(true);
            });



            AddShortcut(MyKeys.Up, true, false, false, false,
                        () => "SI Selected cube up",
                        delegate
            {
                MyAdvancedStaticSimulator.SelectedCube = new Vector3I(MyAdvancedStaticSimulator.SelectedCube.X, MyAdvancedStaticSimulator.SelectedCube.Y + 1, MyAdvancedStaticSimulator.SelectedCube.Z);
                return(true);
            });
            AddShortcut(MyKeys.Down, true, false, false, false,
                        () => "SI Selected cube down",
                        delegate
            {
                MyAdvancedStaticSimulator.SelectedCube = new Vector3I(MyAdvancedStaticSimulator.SelectedCube.X, MyAdvancedStaticSimulator.SelectedCube.Y - 1, MyAdvancedStaticSimulator.SelectedCube.Z);
                return(true);
            });
            AddShortcut(MyKeys.Left, true, false, false, false,
                        () => "SI Selected cube left",
                        delegate
            {
                MyAdvancedStaticSimulator.SelectedCube = new Vector3I(MyAdvancedStaticSimulator.SelectedCube.X - 1, MyAdvancedStaticSimulator.SelectedCube.Y, MyAdvancedStaticSimulator.SelectedCube.Z);
                return(true);
            });
            AddShortcut(MyKeys.Right, true, false, false, false,
                        () => "SI Selected cube right",
                        delegate
            {
                MyAdvancedStaticSimulator.SelectedCube = new Vector3I(MyAdvancedStaticSimulator.SelectedCube.X + 1, MyAdvancedStaticSimulator.SelectedCube.Y, MyAdvancedStaticSimulator.SelectedCube.Z);
                return(true);
            });
            AddShortcut(MyKeys.Up, true, true, false, false,
                        () => "SI Selected cube forward",
                        delegate
            {
                MyAdvancedStaticSimulator.SelectedCube = new Vector3I(MyAdvancedStaticSimulator.SelectedCube.X, MyAdvancedStaticSimulator.SelectedCube.Y, MyAdvancedStaticSimulator.SelectedCube.Z - 1);
                return(true);
            });
            AddShortcut(MyKeys.Down, true, true, false, false,
                        () => "SI Selected cube back",
                        delegate
            {
                MyAdvancedStaticSimulator.SelectedCube = new Vector3I(MyAdvancedStaticSimulator.SelectedCube.X, MyAdvancedStaticSimulator.SelectedCube.Y, MyAdvancedStaticSimulator.SelectedCube.Z + 1);
                return(true);
            });

            AddShortcut(MyKeys.NumPad2, true, false, false, false,
                        () => "Spawn simple skinned object",
                        delegate
            {
                //MyDebugDrawSettings.ENABLE_DEBUG_DRAW = true;
                //MyDebugDrawSettings.DEBUG_DRAW_FRACTURED_PIECES = !MyDebugDrawSettings.DEBUG_DRAW_FRACTURED_PIECES;

                //foreach (var entity in MyEntities.GetEntities())
                //{
                //    if (entity is MyFracturedPiece)
                //    {
                //        foreach (var id in entity.Render.RenderObjectIDs)
                //        {
                //            VRageRender.MyRenderProxy.UpdateRenderObjectVisibility(id, !MyDebugDrawSettings.DEBUG_DRAW_FRACTURED_PIECES, false);
                //        }
                //    }
                //}

                SpawnSimpleSkinnedObject();

                return(true);
            });
        }
Exemple #24
0
        protected virtual void InitSubBlocks()
        {
            if (!MyFakes.ENABLE_SUBBLOCKS)
            {
                return;
            }

            if (m_subBlocksInitialized)
            {
                return;
            }

            //  if (!Sync.IsServer)
            //    return;

            try
            {
                MyCubeBlockDefinition subBlockDefinition;
                MatrixD subBlockMatrix;
                Vector3 dummyPosition;

                var finalModel = Sandbox.Engine.Models.MyModels.GetModelOnlyDummies(BlockDefinition.Model);
                foreach (var dummy in finalModel.Dummies)
                {
                    if (!MyCubeBlock.GetSubBlockDataFromDummy(BlockDefinition, dummy.Key, dummy.Value, true, out subBlockDefinition, out subBlockMatrix, out dummyPosition))
                    {
                        continue;
                    }

                    string dummyName = dummy.Key.Substring(DUMMY_SUBBLOCK_ID.Length);

                    MySlimBlock        subblock = null;
                    MyCubeGrid         subgrid  = null;
                    MySubBlockLoadInfo subBlockLoadInfo;
                    if (m_subBlockIds.TryGetValue(dummyName, out subBlockLoadInfo))
                    {
                        MyEntity entity;
                        if (MyEntities.TryGetEntityById(subBlockLoadInfo.GridId, out entity))
                        {
                            subgrid = entity as MyCubeGrid;
                            if (subgrid != null)
                            {
                                subblock = subgrid.GetCubeBlock(subBlockLoadInfo.SubBlockPosition);
                                Debug.Assert(subblock != null, "Cannot find subblock in subgrid!");
                                if (subblock == null)
                                {
                                    continue;
                                }
                            }
                            else
                            {
                                Debug.Assert(false, "Loaded entity is not grid!");
                                continue;
                            }
                        }
                        else
                        {
                            Debug.Assert(false, "Cannot load subgrid!");
                            continue;
                        }
                    }

                    if (!m_subBlocksLoaded)
                    {
                        if (subgrid == null)
                        {
                            Debug.Assert(!subBlockMatrix.IsMirrored());
                            Matrix subGridWorldMatrix = subBlockMatrix * PositionComp.LocalMatrix * CubeGrid.WorldMatrix;

                            //TODO: Try to find better way how to sync entity ID of subblocks..
                            subgrid = MyCubeBuilder.SpawnDynamicGrid(subBlockDefinition, null, subGridWorldMatrix, EntityId + (SubBlocks.Count * 16) + 1);
                            if (subgrid != null)
                            {
                                subblock = subgrid.GetCubeBlock(Vector3I.Zero);
                            }
                        }

                        if (subgrid == null)
                        {
                            Debug.Assert(false, "SubGrid has not been set!");
                            continue;
                        }

                        if (subblock == null || subblock.FatBlock == null)
                        {
                            Debug.Assert(false, "Fatblock cannot be null for subblocks!");
                            continue;
                        }
                    }

                    if (subblock != null)
                    {
                        SubBlocks.Add(dummyName, subblock);
                        subblock.FatBlock.SubBlockName = dummyName;
                        subblock.FatBlock.OwnerBlock   = SlimBlock;
                        subblock.FatBlock.OnClosing   += SubBlock_OnClosing;
                        Debug.Assert(SlimBlock != null);
                    }
                }
            }
            finally
            {
                m_subBlockIds.Clear();

                m_subBlocksInitialized = true;
            }
        }
        public void AddGates(int type = 1, bool selfowned = false, long ownerid = 0L)
        {
            try
            {
                var entities = MyEntities.GetEntities();
                if (entities != null)
                {
                    entities.Where(b => b != null)
                    .OfType <MyCubeGrid>()
                    .Where(b => b.DisplayName.Contains("[NPC-IGNORE]_[Wormhole-Gate]"))
                    .ForEach(b => b.Close());
                }

                foreach (var server in Plugin.Config.WormholeGates)
                {
                    string prefab;
                    switch (type)
                    {
                    case 2:
                        prefab = "WORMHOLE_ROTATING";
                        break;

                    case 3:
                        prefab = "WORMHOLE_ROTATING_ADVANCED";
                        break;

                    case 4:
                        prefab = "WORMHOLE_53_BLOCKS";
                        break;

                    case 5:
                        prefab = "WORMHOLE_ROTATING_53_BLOCKS";
                        break;

                    case 6:
                        prefab = "WORMHOLE_ROTATING_ADVANCED_53_BLOCKS";
                        break;

                    default:
                        prefab = "WORMHOLE";
                        break;
                    }

                    MyObjectBuilder_CubeGrid[]        grids             = MyPrefabManager.Static.GetGridPrefab(prefab);
                    List <MyObjectBuilder_EntityBase> objectBuilderList = new List <MyObjectBuilder_EntityBase>();

                    foreach (var grid in grids)
                    {
                        foreach (MyObjectBuilder_CubeBlock cubeBlock in grid.CubeBlocks)
                        {
                            if (selfowned)
                            {
                                cubeBlock.Owner   = Context.Player.IdentityId;
                                cubeBlock.BuiltBy = Context.Player.IdentityId;
                            }
                            else
                            {
                                cubeBlock.Owner   = ownerid;
                                cubeBlock.BuiltBy = ownerid;
                            }
                        }

                        objectBuilderList.Add(grid);
                    }

                    bool   firstGrid = true;
                    double deltaX    = 0;
                    double deltaY    = 0;
                    double deltaZ    = 0;

                    foreach (var grid in grids)
                    {
                        var position        = grid.PositionAndOrientation;
                        var realPosition    = position.Value;
                        var currentPosition = realPosition.Position;

                        if (firstGrid)
                        {
                            deltaX = server.X - currentPosition.X;
                            deltaY = server.Y - currentPosition.Y;
                            deltaZ = server.Z - currentPosition.Z;

                            currentPosition.X = server.X;
                            currentPosition.Y = server.Y;
                            currentPosition.Z = server.Z;

                            firstGrid = false;
                        }
                        else
                        {
                            currentPosition.X += deltaX;
                            currentPosition.Y += deltaY;
                            currentPosition.Z += deltaZ;
                        }

                        realPosition.Position       = currentPosition;
                        grid.PositionAndOrientation = realPosition;
                    }

                    MyEntities.RemapObjectBuilderCollection(objectBuilderList);
                    MyEntities.Load(objectBuilderList, out _);
                }

                Context.Respond("Deleted all entities with '[NPC-IGNORE]_[Wormhole-Gate]' in them and readded Gates to each Wormhole");
            }
            catch {
                Context.Respond("Error: make sure you add the mod for the gates you are using");
            }
        }
Exemple #26
0
        internal bool GetTargetState(Session s)
        {
            var ai         = s.TrackingAi;
            var validFocus = false;
            var size0      = s.Settings.Enforcement.ShipSizes[0];
            var size1      = s.Settings.Enforcement.ShipSizes[1];
            var size2      = s.Settings.Enforcement.ShipSizes[2];
            var size3      = s.Settings.Enforcement.ShipSizes[3];
            var size4      = s.Settings.Enforcement.ShipSizes[4];
            var size5      = s.Settings.Enforcement.ShipSizes[5];
            var size6      = s.Settings.Enforcement.ShipSizes[6];

            if (s.Tick - MasterUpdateTick > 600 || MasterUpdateTick < 600 && _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];
                float    offenseRating;
                MyEntity target;
                if (targetId <= 0 || !MyEntities.TryGetEntityById(targetId, out target) || !_masterTargets.TryGetValue(target, out offenseRating))
                {
                    continue;
                }
                validFocus = true;
                if (!s.Tick20)
                {
                    continue;
                }
                var grid      = target as MyCubeGrid;
                var partCount = 1;
                var largeGrid = false;
                var smallGrid = false;
                if (grid != null)
                {
                    largeGrid = grid.GridSizeEnum == MyCubeSize.Large;
                    smallGrid = !largeGrid;
                    GridAi  targetAi;
                    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 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);

                if ((size6.LargeGrid && largeGrid || !size6.LargeGrid && smallGrid) && partCount > size6.BlockCount)
                {
                    ai.TargetState[i].Size = 6;
                }
                else if ((size5.LargeGrid && largeGrid || !size5.LargeGrid && smallGrid) && partCount > size5.BlockCount)
                {
                    ai.TargetState[i].Size = 5;
                }
                else if ((size4.LargeGrid && largeGrid || !size4.LargeGrid && smallGrid) && partCount > size4.BlockCount)
                {
                    ai.TargetState[i].Size = 4;
                }
                else if ((size3.LargeGrid && largeGrid || !size3.LargeGrid && smallGrid) && partCount > size3.BlockCount)
                {
                    ai.TargetState[i].Size = 3;
                }
                else if ((size2.LargeGrid && largeGrid || !size2.LargeGrid && smallGrid) && partCount > size2.BlockCount)
                {
                    ai.TargetState[i].Size = 2;
                }
                else if ((size1.LargeGrid && largeGrid || !size1.LargeGrid && smallGrid) && partCount > size1.BlockCount)
                {
                    ai.TargetState[i].Size = 1;
                }
                else
                {
                    ai.TargetState[i].Size = 0;
                }

                ai.TargetState[i].SizeExtended = partCount / (largeGrid ? 100f : 500f);

                var intercept = MathFuncs.IsDotProductWithinTolerance(ref targetDir, ref myHeading, s.ApproachDegrees);
                var retreat   = MathFuncs.IsDotProductWithinTolerance(ref targetRevDir, ref myHeading, s.ApproachDegrees);
                if (intercept)
                {
                    ai.TargetState[i].Engagement = 0;
                }
                else if (retreat)
                {
                    ai.TargetState[i].Engagement = 1;
                }
                else
                {
                    ai.TargetState[i].Engagement = 2;
                }

                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 distPercent = (distanceFromCenters / ai.MaxTargetingRange) * 100;
                if (distPercent > 95)
                {
                    ai.TargetState[i].Distance = 9;
                }
                else if (distPercent > 90)
                {
                    ai.TargetState[i].Distance = 8;
                }
                else if (distPercent > 80)
                {
                    ai.TargetState[i].Distance = 7;
                }
                else if (distPercent > 70)
                {
                    ai.TargetState[i].Distance = 6;
                }
                else if (distPercent > 60)
                {
                    ai.TargetState[i].Distance = 5;
                }
                else if (distPercent > 50)
                {
                    ai.TargetState[i].Distance = 4;
                }
                else if (distPercent > 40)
                {
                    ai.TargetState[i].Distance = 3;
                }
                else if (distPercent > 30)
                {
                    ai.TargetState[i].Distance = 2;
                }
                else if (distPercent > 20)
                {
                    ai.TargetState[i].Distance = 1;
                }
                else if (distPercent > 0)
                {
                    ai.TargetState[i].Distance = 0;
                }
                else
                {
                    ai.TargetState[i].Distance = -1;
                }

                var speed = Math.Round(target.Physics?.Speed ?? 0, 1);
                if (speed <= 0)
                {
                    ai.TargetState[i].Speed = -1;
                }
                else
                {
                    var speedPercent = (speed / s.MaxEntitySpeed) * 100;
                    if (speedPercent > 95)
                    {
                        ai.TargetState[i].Speed = 9;
                    }
                    else if (speedPercent > 90)
                    {
                        ai.TargetState[i].Speed = 8;
                    }
                    else if (speedPercent > 80)
                    {
                        ai.TargetState[i].Speed = 7;
                    }
                    else if (speedPercent > 70)
                    {
                        ai.TargetState[i].Speed = 6;
                    }
                    else if (speedPercent > 60)
                    {
                        ai.TargetState[i].Speed = 5;
                    }
                    else if (speedPercent > 50)
                    {
                        ai.TargetState[i].Speed = 4;
                    }
                    else if (speedPercent > 40)
                    {
                        ai.TargetState[i].Speed = 3;
                    }
                    else if (speedPercent > 30)
                    {
                        ai.TargetState[i].Speed = 2;
                    }
                    else if (speedPercent > 20)
                    {
                        ai.TargetState[i].Speed = 1;
                    }
                    else if (speedPercent > 0.3)
                    {
                        ai.TargetState[i].Speed = 0;
                    }
                    else
                    {
                        ai.TargetState[i].Speed = -1;
                    }
                }

                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 shieldPercent = shieldInfo.Item5;
                    if (shieldPercent > 95)
                    {
                        ai.TargetState[i].ShieldHealth = 9;
                    }
                    else if (shieldPercent > 90)
                    {
                        ai.TargetState[i].ShieldHealth = 8;
                    }
                    else if (shieldPercent > 80)
                    {
                        ai.TargetState[i].ShieldHealth = 7;
                    }
                    else if (shieldPercent > 70)
                    {
                        ai.TargetState[i].ShieldHealth = 6;
                    }
                    else if (shieldPercent > 60)
                    {
                        ai.TargetState[i].ShieldHealth = 5;
                    }
                    else if (shieldPercent > 50)
                    {
                        ai.TargetState[i].ShieldHealth = 4;
                    }
                    else if (shieldPercent > 40)
                    {
                        ai.TargetState[i].ShieldHealth = 3;
                    }
                    else if (shieldPercent > 30)
                    {
                        ai.TargetState[i].ShieldHealth = 2;
                    }
                    else if (shieldPercent > 20)
                    {
                        ai.TargetState[i].ShieldHealth = 1;
                    }
                    else if (shieldPercent > 0)
                    {
                        ai.TargetState[i].ShieldHealth = 0;
                    }
                    else
                    {
                        ai.TargetState[i].ShieldHealth = -1;
                    }
                }
                else
                {
                    ai.TargetState[i].ShieldHealth = -1;
                }

                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)
                {
                    ai.TargetState[i].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 (offenseRating > 5)
                    {
                        ai.TargetState[i].ThreatLvl = shieldBonus < 0 ? 8 : 9;
                    }
                    else if (offenseRating > 4)
                    {
                        ai.TargetState[i].ThreatLvl = 8 + shieldBonus;
                    }
                    else if (offenseRating > 3)
                    {
                        ai.TargetState[i].ThreatLvl = 7 + shieldBonus;
                    }
                    else if (offenseRating > 2)
                    {
                        ai.TargetState[i].ThreatLvl = 6 + shieldBonus;
                    }
                    else if (offenseRating > 1)
                    {
                        ai.TargetState[i].ThreatLvl = 5 + shieldBonus;
                    }
                    else if (offenseRating > 0.5)
                    {
                        ai.TargetState[i].ThreatLvl = 4 + shieldBonus;
                    }
                    else if (offenseRating > 0.25)
                    {
                        ai.TargetState[i].ThreatLvl = 3 + shieldBonus;
                    }

                    else if (offenseRating > 0.125)
                    {
                        ai.TargetState[i].ThreatLvl = 2 + shieldBonus;
                    }
                    else if (offenseRating > 0.0625)
                    {
                        ai.TargetState[i].ThreatLvl = 1 + shieldBonus;
                    }
                    else if (offenseRating > 0)
                    {
                        ai.TargetState[i].ThreatLvl = shieldBonus > 0 ? 1 : 0;
                    }
                    else
                    {
                        ai.TargetState[i].ThreatLvl = -1;
                    }
                }
            }
            return(validFocus);
        }
Exemple #27
0
 public static void AddEntity(MyObjectBuilder_EntityBase entityBuilder)
 {
     MyEntities.CreateFromObjectBuilderAndAdd(entityBuilder);
 }
Exemple #28
0
        public static void FindNext(MyEntityCyclingOrder order, ref float metric, ref long entityId, bool findLarger, CyclingOptions options)
        {
            Metric metric2 = new Metric {
                Value    = metric,
                EntityId = entityId
            };
            Metric metric3 = findLarger ? Metric.Max : Metric.Min;
            Metric metric4 = metric3;
            Metric metric5 = metric3;

            foreach (MyEntity entity in MyEntities.GetEntities())
            {
                if (options.Enabled)
                {
                    MyCubeGrid grid = entity as MyCubeGrid;
                    if (options.OnlyLargeGrids)
                    {
                        if (grid == null)
                        {
                            continue;
                        }
                        if (grid.GridSizeEnum != MyCubeSize.Large)
                        {
                            continue;
                        }
                    }
                    if (options.OnlySmallGrids && ((grid == null) || (grid.GridSizeEnum != MyCubeSize.Small)))
                    {
                        continue;
                    }
                }
                Metric metric7 = new Metric(GetMetric(order, entity), entity.EntityId);
                if (metric7.Value != 0f)
                {
                    if (findLarger)
                    {
                        if ((metric7 > metric2) && (metric7 < metric4))
                        {
                            metric4 = metric7;
                        }
                        if (metric7 < metric5)
                        {
                            metric5 = metric7;
                        }
                    }
                    else
                    {
                        if ((metric7 < metric2) && (metric7 > metric4))
                        {
                            metric4 = metric7;
                        }
                        if (metric7 > metric5)
                        {
                            metric5 = metric7;
                        }
                    }
                }
            }
            if (metric4 == metric3)
            {
                metric4 = metric5;
            }
            metric   = metric4.Value;
            entityId = metric4.EntityId;
        }