Exemplo n.º 1
0
    public static void Test()
    {
        var entities = new MyEntities();
        var entity1  = new MyEntity1();

        entities.Add(entity1);
        var entity2 = new MyEntity2();

        entities.Add(entity1);
    }
    public static void Test()
    {
        var entities = new MyEntities();
        var entityA1 = new MyEntityA1();

        entities.Add(entityA1);
        var entityA2 = new MyEntityA2();

        entities.Add(entityA2);
        var entityB1 = new MyEntityB1();

        entities.Add(entityB1);
    }
        // Spawn empty entity
        private void SpawnEntityClicked(MyGuiControlButton myGuiControlButton)
        {
            string   newEntityName;
            MyEntity e;

            do
            {
                newEntityName = ENTITY_NAME_PREFIX + m_entityCounter++;
            } while(MyEntities.TryGetEntityByName(newEntityName, out e));

            var entity = new MyEntity
            {
                WorldMatrix = MyAPIGateway.Session.Camera.WorldMatrix,
                EntityId    = MyEntityIdentifier.AllocateId(),
                DisplayName = "Entity",
                Name        = newEntityName
            };

            // Place the entity 2m in the front
            entity.PositionComp.SetPosition(MyAPIGateway.Session.Camera.Position + MyAPIGateway.Session.Camera.WorldMatrix.Forward * 2);
            entity.Components.Remove <MyPhysicsComponentBase>();

            MyEntities.Add(entity);
            MyEntities.SetEntityName(entity, true);

            m_transformSys.SetControlledEntity(entity);
        }
        static void SpawnAsteroid(SpawnAsteroidInfo asteroidInfo)
        {
            if (MySession.Static.CreativeMode || MyEventContext.Current.IsLocallyInvoked || MySession.Static.HasPlayerAdminRights(MyEventContext.Current.Sender.Value))
            {
                MyStorageBase storage;
                string        storageName;
                using (MyRandom.Instance.PushSeed(asteroidInfo.RandomSeed))
                {
                    if (!asteroidInfo.IsProcedural)
                    {
                        var storageNameBase = asteroidInfo.Asteroid + "-" + asteroidInfo.RandomSeed;
                        storageName = MakeStorageName(storageNameBase);
                        storage     = CreateAsteroidStorage(asteroidInfo.Asteroid, asteroidInfo.RandomSeed);
                    }
                    else
                    {
                        var storageNameBase = "ProcAsteroid" + "-" + asteroidInfo.RandomSeed + "r" + asteroidInfo.ProceduralRadius;
                        storageName = MakeStorageName(storageNameBase);
                        storage     = CreateProceduralAsteroidStorage(asteroidInfo.RandomSeed, asteroidInfo.ProceduralRadius, 0.03f);
                    }
                }

                var pastedVoxelMap = new MyVoxelMap();
                pastedVoxelMap.CreatedByUser = true;
                pastedVoxelMap.Save          = true;
                pastedVoxelMap.AsteroidName  = asteroidInfo.Asteroid;
                pastedVoxelMap.Init(storageName, storage, asteroidInfo.Position - storage.Size * 0.5f);
                MyEntities.Add(pastedVoxelMap);
                MyEntities.RaiseEntityCreated(pastedVoxelMap);
            }
        }
Exemplo n.º 5
0
        static void SpawnAsteroidConfirmedSuccess(ref SpawnAsteroidConfirmedMsg msg, MyNetworkClient sender)
        {
            MyStorageBase    storage;
            SpawnAsteroidMsg asteroid = msg.AsteroidDetails;

            string storageName;

            using (MyRandom.Instance.PushSeed(asteroid.RandomSeed))
            {
                if (!asteroid.IsProcedural)
                {
                    var storageNameBase = asteroid.StorageName ?? (asteroid.Asteroid + "-" + asteroid.RandomSeed);
                    storageName = MakeStorageName(storageNameBase);
                    storage     = CreateAsteroidStorage(asteroid.Asteroid, asteroid.RandomSeed);
                }
                else
                {
                    var storageNameBase = asteroid.StorageName ?? "ProcAsteroid" + "-" + asteroid.RandomSeed + "r" + asteroid.ProceduralRadius;
                    storageName = MakeStorageName(storageNameBase);
                    storage     = CreateProceduralAsteroidStorage(asteroid.RandomSeed, asteroid.ProceduralRadius, 0.03f);
                }
            }

            var pastedVoxelMap = new MyVoxelMap();

            pastedVoxelMap.EntityId = msg.EntityId;
            pastedVoxelMap.Init(storageName, storage, asteroid.Position - storage.Size * 0.5f);
            MyEntities.Add(pastedVoxelMap);
        }
Exemplo n.º 6
0
 public void Throw(MyObjectBuilder_CubeGrid grid, Vector3D position, Vector3D linearVelocity, float mass, MyCueId throwSound)
 {
     if (Sync.IsServer)
     {
         MyEntity entity = MyEntities.CreateFromObjectBuilder(grid, false);
         if (entity != null)
         {
             entity.PositionComp.SetPosition(position, null, false, true);
             entity.Physics.LinearVelocity = (Vector3)linearVelocity;
             if (mass > 0f)
             {
                 entity.Physics.RigidBody.Mass = mass;
             }
             MyEntities.Add(entity, true);
             if (!throwSound.IsNull)
             {
                 MyEntity3DSoundEmitter emitter = MyAudioComponent.TryGetSoundEmitter();
                 if (emitter != null)
                 {
                     emitter.SetPosition(new Vector3D?(position));
                     bool?nullable = null;
                     emitter.PlaySoundWithDistance(throwSound, false, false, false, true, false, false, nullable);
                 }
             }
         }
     }
 }
Exemplo n.º 7
0
        public static MyEntity Spawn(ref MyPhysicalInventoryItem item, Vector3 position, Vector3 speed)
        {
            var builder      = PrepareBuilder(ref item);
            var meteorEntity = MyEntities.CreateFromObjectBuilder(builder);

            Vector3 forward = -MySector.DirectionToSunNormalized;
            Vector3 up      = MyUtils.GetRandomVector3Normalized();

            while (forward == up)
            {
                up = MyUtils.GetRandomVector3Normalized();
            }

            Vector3 right = Vector3.Cross(forward, up);

            up = Vector3.Cross(right, forward);

            meteorEntity.WorldMatrix = Matrix.CreateWorld(position, forward, up);
            MyEntities.Add(meteorEntity);
            meteorEntity.Physics.RigidBody.MaxLinearVelocity = 500;
            meteorEntity.Physics.LinearVelocity  = speed;
            meteorEntity.Physics.AngularVelocity = MyUtils.GetRandomVector3Normalized() * MyUtils.GetRandomFloat(1.5f, 3);
            MySyncCreate.SendEntityCreated(meteorEntity.GetObjectBuilder());
            return(meteorEntity);
        }
Exemplo n.º 8
0
        static void OnCreateFracturePieceMessage(
            [Serialize(MyObjectFlags.Dynamic, DynamicSerializerType = typeof(MyObjectBuilderDynamicSerializer))] MyObjectBuilder_FracturedPiece fracturePiece)
        {
            var fracturedPiece = MyFracturedPiecesManager.Static.GetPieceFromPool(fracturePiece.EntityId, true);

            Debug.Assert(fracturePiece.EntityId != 0, "Fracture piece without ID");
            try
            {
                fracturedPiece.Init(fracturePiece);
                MyEntities.Add(fracturedPiece);
            }
            catch (Exception e)
            {
                MyLog.Default.WriteLine("Cannot add fracture piece: " + e.Message);
                if (fracturedPiece == null)
                {
                    return;
                }

                MyFracturedPiecesManager.Static.RemoveFracturePiece(fracturedPiece, 0, true, false);
                StringBuilder sb = new StringBuilder();
                foreach (var shape in fracturePiece.Shapes)
                {
                    sb.Append(shape.Name).Append(" ");
                }
                Debug.Fail("Recieved fracture piece not added");
                MyLog.Default.WriteLine("Received fracture piece not added, no shape found. Shapes: " + sb.ToString());
            }
        }
Exemplo n.º 9
0
        internal static MyEntity SpawnCamera(string name, out MyCameraBlock camera)
        {
            try
            {
                if (string.IsNullOrEmpty(name))
                {
                    camera = null;
                    return(null);
                }
                PrefabCamera.SubtypeName = name;
                PrefabBuilder.CubeBlocks.Clear(); // need no leftovers from previous spawns
                PrefabBuilder.CubeBlocks.Add(PrefabCamera);
                MyEntities.RemapObjectBuilder(PrefabBuilder);
                var ent = MyEntities.CreateFromObjectBuilder(PrefabBuilder, false);
                ent.Render.CastShadows = false;
                ent.Render.Visible     = false;
                ent.IsPreview          = true;
                ent.Save             = false;
                ent.SyncFlag         = false;
                ent.NeedsWorldMatrix = false;
                ent.Flags           |= EntityFlags.IsNotGamePrunningStructureObject;
                ent.Render.RemoveRenderObjects();
                MyEntities.Add(ent, false);
                var cameraSlim = ((IMyCubeGrid)ent).GetCubeBlock(Vector3I.Zero);
                var gId        = MyResourceDistributorComponent.ElectricityId;
                camera = (MyCameraBlock)cameraSlim.FatBlock;
                camera.ResourceSink.SetInputFromDistributor(gId, 0, true);
                camera.RefreshModels(null, null);
                return(ent);
            }
            catch (Exception ex) { Log.Line($"Exception in SpawnPrefab: {ex}"); }

            camera = null;
            return(null);
        }
Exemplo n.º 10
0
        public static IMyVoxelMap SpawnAsteroid(MyPositionAndOrientation pos, CompositeShapeProviderBuilder provider)
        {
            var       storage     = new OctreeStorageBuilder(provider, MyVoxelCoordSystems.FindBestOctreeSize(provider.Size));
            var       storageName = $"proc_astr_{provider.Seed}_{provider.Size}_{(long) pos.Position.X}_{(long) pos.Position.Y}_{(long) pos.Position.Z}";
            var       entityID    = GetAsteroidEntityId(storageName);
            IMyEntity currEntity;

            if (MyAPIGateway.Entities.TryGetEntityById(entityID, out currEntity))
            {
                return(currEntity as IMyVoxelMap);
            }
            var data = storage.GetCompressedData();

            var storageInstance = MyAPIGateway.Session.VoxelMaps.CreateStorage(data);
            var entity          = MyAPIGateway.Session.VoxelMaps.CreateVoxelMap(storageName, storageInstance, pos.Position, entityID);

            entity.Save = false;
            var realEntity = entity as MyEntity;

            if (realEntity == null)
            {
                return(entity);
            }
            MyEntities.RaiseEntityCreated(realEntity);
            MyEntities.Add(realEntity);
            return(entity);
        }
Exemplo n.º 11
0
        private IMyHandheldGunObject <MyDeviceBase> CreateWeapon(MyDefinitionId?weaponDefinition, int lastMomentUpdateIndex)
        {
            var builder = MyObjectBuilderSerializer.CreateNewObject(weaponDefinition.Value.TypeId);
            MyObjectBuilder_EntityBase weaponEntityBuilder = builder as MyObjectBuilder_EntityBase;

            if (weaponEntityBuilder != null)
            {
                weaponEntityBuilder.SubtypeName = weaponDefinition.Value.SubtypeId.String;
                var gun = MyCharacter.CreateGun(weaponEntityBuilder);
                //EquipWeapon(gun);
                MyEntity gunEntity = (MyEntity)gun;
                gunEntity.Render.CastShadows            = true;
                gunEntity.Render.NeedsResolveCastShadow = false;
                gunEntity.Render.LastMomentUpdateIndex  = lastMomentUpdateIndex;
                gunEntity.Save     = false;
                gunEntity.OnClose += gunEntity_OnClose;
                MyEntities.Add(gunEntity);

                if (gunEntity.Model != null)
                {
                    gunEntity.InitBoxPhysics(MyMaterialType.METAL, gunEntity.Model, 10,
                                             MyPerGameSettings.DefaultAngularDamping, MyPhysics.CollisionLayers.DefaultCollisionLayer,
                                             RigidBodyFlag.RBF_KINEMATIC);
                    gunEntity.Physics.Enabled = true;
                }
                return(gun);
            }
            else
            {
                Debug.Fail("Couldn't create builder for weapon! typeID: " + weaponDefinition.Value.TypeId.ToString());
            }
            return(null);
        }
Exemplo n.º 12
0
        static void OnCreateFracturePieceMessage(ref CreateFracturePieceMsg msg, MyNetworkClient sender)
        {
            Debug.Assert(!Sync.IsServer);

            var fracturedPiece = MyFracturedPiecesManager.Static.GetPieceFromPool(msg.FracturePiece.EntityId, true);

            Debug.Assert(msg.FracturePiece.EntityId != 0, "Fracture piece without ID");
            try
            {
                fracturedPiece.Init(msg.FracturePiece);
                MyEntities.Add(fracturedPiece);
            }
            catch (Exception e)
            {
                MyLog.Default.WriteLine("Cannot add fracture piece: " + e.Message);
                if (fracturedPiece == null)
                {
                    return;
                }

                MyFracturedPiecesManager.Static.RemoveFracturePiece(fracturedPiece, 0, true, false);
                StringBuilder sb = new StringBuilder();
                foreach (var shape in msg.FracturePiece.Shapes)
                {
                    sb.Append(shape.Name).Append(" ");
                }
                Debug.Fail("Recieved fracture piece not added");
                MyLog.Default.WriteLine("Received fracture piece not added, no shape found. Shapes: " + sb.ToString());
            }
        }
        private void ChangeClipboardPreview(bool visible)
        {
            if (m_copiedFloatingObjects.Count == 0 || !visible)
            {
                foreach (var grid in m_previewFloatingObjects)
                {
                    MyEntities.EnableEntityBoundingBoxDraw(grid, false);
                    grid.Close();
                }
                m_previewFloatingObjects.Clear();
                m_visible = false;
                return;
            }

            MyEntities.RemapObjectBuilderCollection(m_copiedFloatingObjects);

            foreach (var gridBuilder in m_copiedFloatingObjects)
            {
                var previewFloatingObject = MyEntities.CreateFromObjectBuilder(gridBuilder) as MyFloatingObject;
                if (previewFloatingObject == null)
                {
                    ChangeClipboardPreview(false);
                    return;// Not enough memory to create preview grid or there was some error.
                }

                MakeTransparent(previewFloatingObject);
                IsActive  = visible;
                m_visible = visible;
                MyEntities.Add(previewFloatingObject);

                previewFloatingObject.Save = false;
                DisablePhysicsRecursively(previewFloatingObject);
                m_previewFloatingObjects.Add(previewFloatingObject);
            }
        }
Exemplo n.º 14
0
        private MyVoxelPhysics CreateVoxelPhysics(ref Vector3I increment, ref Vector3I_RangeIterator it)
        {
            if (m_physicsShapes == null)
            {
                m_physicsShapes = new MyConcurrentDictionary <Vector3I, MyVoxelPhysics>();
            }

            MyVoxelPhysics voxelMap = null;

            if (!m_physicsShapes.TryGetValue(it.Current, out voxelMap))
            {
                Vector3I storageMin = it.Current * increment;
                Vector3I storageMax = storageMin + increment;

                BoundingBox check = new BoundingBox(storageMin, storageMax);

                if (Storage.Intersect(ref check, false) == ContainmentType.Intersects)
                {
                    voxelMap = new MyVoxelPhysics();

                    voxelMap.Init(m_storage,
                                  this.PositionLeftBottomCorner + storageMin * MyVoxelConstants.VOXEL_SIZE_IN_METRES, storageMin,
                                  storageMax, this);
                    voxelMap.Save = false;
                    MyEntities.Add(voxelMap);
                }

                m_physicsShapes.Add(it.Current, voxelMap);
            }
            return(voxelMap);
        }
        public void Throw(MyObjectBuilder_CubeGrid grid, Vector3D position, Vector3D linearVelocity, float mass, MyCueId throwSound)
        {
            if (!Sync.IsServer)
            {
                return;
            }

            var entity = MyEntities.CreateFromObjectBuilder(grid);

            if (entity == null)
            {
                return;
            }

            entity.PositionComp.SetPosition(position);
            entity.Physics.LinearVelocity = linearVelocity;

            if (mass > 0)
            {
                entity.Physics.RigidBody.Mass = mass;
            }

            MyEntities.Add(entity);

            if (!throwSound.IsNull)
            {
                var emitter = MyAudioComponent.TryGetSoundEmitter();
                if (emitter != null)
                {
                    emitter.SetPosition(position);
                    emitter.PlaySoundWithDistance(throwSound);
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="shape">Piece takes ownership of shape so clone it first</param>
        /// <param name="worldMatrix"></param>
        /// <param name="definition"> without definition the piece wont save</param>
        /// <returns></returns>
        public static MyFracturedPiece CreateFracturePiece(HkdBreakableShape shape, HkdWorld world, ref MatrixD worldMatrix, bool isStatic, MyDefinitionId?definition, bool sync)
        {
            System.Diagnostics.Debug.Assert(Sync.IsServer, "Only on server");
            var fracturedPiece = CreateFracturePiece(ref shape, world, ref worldMatrix, isStatic);

            if (definition.HasValue)
            {
                fracturedPiece.OriginalBlocks.Clear();
                fracturedPiece.OriginalBlocks.Add(definition.Value);

                MyPhysicalModelDefinition def;
                if (MyDefinitionManager.Static.TryGetDefinition <MyPhysicalModelDefinition>(definition.Value, out def))
                {
                    fracturedPiece.Physics.MaterialType = def.PhysicalMaterial.Id.SubtypeId;
                }
            }
            else
            {
                fracturedPiece.Save = false;
            }

            // Check valid shapes from block definitions.
            if (fracturedPiece.Save && MyFakes.ENABLE_FRACTURE_PIECE_SHAPE_CHECK)
            {
                fracturedPiece.DebugCheckValidShapes();
            }

            ProfilerShort.Begin("MyEntities.Add");
            MyEntities.RaiseEntityCreated(fracturedPiece);
            MyEntities.Add(fracturedPiece);
            ProfilerShort.End();

            return(fracturedPiece);
        }
        public static MyFracturedPiece CreateFracturePiece(MyFracturedBlock fracturedBlock, bool sync)
        {
            System.Diagnostics.Debug.Assert(Sync.IsServer, "Only on server");
            var m = fracturedBlock.CubeGrid.PositionComp.WorldMatrix;

            m.Translation = fracturedBlock.CubeGrid.GridIntegerToWorld(fracturedBlock.Position);
            var fp = CreateFracturePiece(ref fracturedBlock.Shape, fracturedBlock.CubeGrid.GetPhysicsBody().HavokWorld.DestructionWorld, ref m, false);

            fp.OriginalBlocks = fracturedBlock.OriginalBlocks;

            MyPhysicalModelDefinition def;

            if (MyDefinitionManager.Static.TryGetDefinition <MyPhysicalModelDefinition>(fp.OriginalBlocks[0], out def))
            {
                fp.Physics.MaterialType = def.PhysicalMaterial.Id.SubtypeId;
            }

            // Check valid shapes from block definitions.
            if (MyFakes.ENABLE_FRACTURE_PIECE_SHAPE_CHECK)
            {
                fp.DebugCheckValidShapes();
            }

            ProfilerShort.Begin("MyEntities.Add");
            MyEntities.RaiseEntityCreated(fp);
            MyEntities.Add(fp);
            ProfilerShort.End();

            return(fp);
        }
Exemplo n.º 18
0
        public static MyEntity SpawnEntity(Action <MyEntity> onEntity)
        {
            var dialog = new ValueGetScreenWithCaption("Spawn new Entity", "", delegate(string text)
            {
                var entity         = new MyEntity();
                entity.WorldMatrix = MyAPIGateway.Session.Camera.WorldMatrix;
                entity.PositionComp.SetPosition(MyAPIGateway.Session.Camera.Position);
                entity.EntityId = MyEntityIdentifier.AllocateId();
                entity.Components.Remove <MyPhysicsComponentBase>();
                entity.Components.Remove <MyRenderComponentBase>();
                entity.DisplayName = "EmptyEntity";
                MyEntities.Add(entity);
                entity.Name = text;
                MyEntities.SetEntityName(entity, true);

                if (onEntity != null)
                {
                    onEntity(entity);
                }

                return(true);
            });

            MyGuiSandbox.AddScreen(dialog);

            return(null);
        }
Exemplo n.º 19
0
        private static void UnpackMothership()
        {
            MyTrace.Send(TraceWindow.Saving, "Player unpacking mothership");
            MyInventoryItem item = MySession.Static.Inventory.GetInventoryItem(MyMwcObjectBuilderTypeEnum.PrefabContainer, null);

            if (item != null)
            {
                //place largeship
                //MyMwcObjectBuilder_LargeShip largeShipObjectBuilder = (MyMwcObjectBuilder_LargeShip)inventoryItems[0].GetObjectBuilder(true);
                MyMwcObjectBuilder_PrefabContainer containerObjectBuilder =
                    (MyMwcObjectBuilder_PrefabContainer)item.GetInventoryItemObjectBuilder(true);

                // We need to remove id's because mothership container could have same entity id in different sector
                containerObjectBuilder.RemapEntityIds(new MyEntityIdRemapContext());

                MyPrefabContainer container = new MyPrefabContainer();
                container.Init(null, containerObjectBuilder, FindMothershipPosition());

                MyEntities.Add(container);

                //CreateFromObjectBuilderAndAdd(null, largeShipObjectBuilder, Matrix.CreateTranslation(MySession.PlayerShip.GetPosition() + new Vector3(100,100,0)));
                MySession.Static.Inventory.RemoveInventoryItem(item);

                container.Link();

                MyTrace.Send(TraceWindow.Saving, "Player mothership found and unpacked");
            }
        }
        public static void AddPlanetPrefab(string prefabName, string name)
        {
            DictionaryValuesReader <MyDefinitionId, MyPlanetPrefabDefinition> planetDefinitions = MyDefinitionManager.Static.GetPlanetsPrefabsDefinitions();

            foreach (var planetPrebabDefinition in planetDefinitions)
            {
                if (planetPrebabDefinition.Id.SubtypeName == prefabName)
                {
                    var voxelMap = new MyPlanet();
                    var ob       = planetPrebabDefinition.PlanetBuilder;

                    string storageName = MyFileSystem.ContentPath + "\\VoxelMaps\\" + ob.StorageName + MyVoxelConstants.FILE_EXTENSION;
                    voxelMap.EntityId = ob.EntityId;

                    MyPlanetInitArguments planetInitArguments;
                    planetInitArguments.StorageName           = ob.StorageName;
                    planetInitArguments.Storage               = MyStorageBase.LoadFromFile(storageName);
                    planetInitArguments.PositionMinCorner     = ob.PositionAndOrientation.Value.Position;
                    planetInitArguments.AveragePlanetRadius   = ob.Radius;
                    planetInitArguments.AtmosphereRadius      = ob.AtmosphereRadius;
                    planetInitArguments.MaximumHillRadius     = ob.MaximumHillRadius;
                    planetInitArguments.MinimumSurfaceRadius  = ob.MinimumSurfaceRadius;
                    planetInitArguments.HasAtmosphere         = ob.HasAtmosphere;
                    planetInitArguments.AtmosphereWavelengths = ob.AtmosphereWavelengths;
                    planetInitArguments.MaxOxygen             = ob.MaximumOxygen;
                    planetInitArguments.GravityFalloff        = ob.GravityFalloff;
                    planetInitArguments.MarkAreaEmpty         = true;

                    voxelMap.Init(planetInitArguments);
                    MyEntities.Add(voxelMap);
                }
            }
        }
Exemplo n.º 21
0
        private MyVoxelPhysics CreatePhysicsShape(ref Vector3I increment, ref Vector3I.RangeIterator it)
        {
            if (m_physicsShapes == null)
            {
                m_physicsShapes = new Dictionary <Vector3I, MyVoxelPhysics>();
            }

            MyVoxelPhysics voxelMap = null;

            if (m_physicsShapes.TryGetValue(it.Current, out voxelMap) == false)
            {
                if (m_hasGeneratedTexture == false)
                {
                    m_storage.DataProvider.GenerateNoiseHelpTexture(m_storage.Size.X);
                    m_hasGeneratedTexture = true;
                }

                voxelMap = new MyVoxelPhysics();

                Vector3I storageMin = it.Current * increment;
                Vector3I storageMax = storageMin + increment;

                voxelMap.EntityId = 0;
                voxelMap.Init(m_storage, this.PositionLeftBottomCorner + storageMin * MyVoxelConstants.VOXEL_SIZE_IN_METRES, storageMin, storageMax, this);
                voxelMap.Save = false;
                m_physicsShapes.Add(it.Current, voxelMap);
                MyEntities.Add(voxelMap);
            }
            return(voxelMap);
        }
Exemplo n.º 22
0
        private static void AddToPos(MyEntity thrownEntity, Vector3D pos, MyPhysicsComponentBase motionInheritedFrom)
        {
            ProfilerShort.Begin("AddToPos");
            ProfilerShort.Begin("GetPos");
            Vector3 forward = MyUtils.GetRandomVector3Normalized();
            Vector3 up      = MyUtils.GetRandomVector3Normalized();

            while (forward == up)
            {
                up = MyUtils.GetRandomVector3Normalized();
            }

            Vector3 right = Vector3.Cross(forward, up);

            up = Vector3.Cross(right, forward);

            thrownEntity.WorldMatrix = MatrixD.CreateWorld(pos, forward, up);
            ProfilerShort.End();
            ProfilerShort.Begin("MyEntities.Add");
            MyEntities.Add(thrownEntity);
            ProfilerShort.BeginNextBlock("ApplyPhysics");
            ApplyPhysics(thrownEntity, motionInheritedFrom);
            ProfilerShort.End();
            ProfilerShort.End();
        }
        public MyEntity Spawn(MyFixedPoint amount, MatrixD worldMatrix, MyEntity owner = null)
        {
            if (Content is MyObjectBuilder_BlockItem)
            {
                Debug.Assert(MyFixedPoint.IsIntegral(amount), "Spawning fractional number of grids!");

                var blockItem = Content as MyObjectBuilder_BlockItem;
                var builder   = MyObjectBuilderSerializer.CreateNewObject(typeof(MyObjectBuilder_CubeGrid)) as MyObjectBuilder_CubeGrid;
                builder.GridSizeEnum           = MyCubeSize.Small;
                builder.IsStatic               = false;
                builder.PersistentFlags       |= MyPersistentEntityFlags2.InScene | MyPersistentEntityFlags2.Enabled;
                builder.PositionAndOrientation = new MyPositionAndOrientation(worldMatrix);

                var block = MyObjectBuilderSerializer.CreateNewObject(blockItem.BlockDefId) as MyObjectBuilder_CubeBlock;
                builder.CubeBlocks.Add(block);

                MyCubeGrid firstGrid = null;
                for (int i = 0; i < amount; ++i)
                {
                    builder.EntityId = MyEntityIdentifier.AllocateId();
                    block.EntityId   = MyEntityIdentifier.AllocateId();
                    MyCubeGrid newGrid = MyEntities.CreateFromObjectBuilder(builder) as MyCubeGrid;
                    firstGrid = firstGrid ?? newGrid;
                    MyEntities.Add(newGrid);
                    Sandbox.Game.Multiplayer.MySyncCreate.SendEntityCreated(builder);
                }
                return(firstGrid);
            }
            else
            {
                return(MyFloatingObjects.Spawn(new MyPhysicalInventoryItem(amount, Content), worldMatrix, owner != null ? owner.Physics : null));
            }
        }
Exemplo n.º 24
0
 void IMyEntities.AddEntity(IMyEntity entity, bool insertIntoScene)
 {
     if (entity is MyEntity)
     {
         MyEntities.Add(entity as MyEntity, insertIntoScene);
     }
 }
Exemplo n.º 25
0
            public virtual void Start(MatrixD position, Vector3D initialVelocity, float scale, bool randomRotation = true)
            {
                MyDebug.AssertDebug(!m_isStarted);
                m_createdTime = MySandboxGame.TotalGamePlayTimeInMilliseconds;
                Container.Entity.PositionComp.Scale = RandomScale * scale;
                Container.Entity.WorldMatrix        = position;
                (Container.Entity.Physics as MyDebrisPhysics).ScalePhysicsShape(ref m_massProperties);
                Container.Entity.Physics.Clear();
                Container.Entity.Physics.LinearVelocity = initialVelocity;
                //apply random rotation impulse
                if (randomRotation)
                {
                    Container.Entity.Physics.AngularVelocity = new Vector3(MyUtils.GetRandomRadian(),
                                                                           MyUtils.GetRandomRadian(),
                                                                           MyUtils.GetRandomRadian());
                }
                MyEntities.Add(m_entity);
                Container.Entity.Physics.Enabled = true;
                float    simulationRatio = Sync.IsServer ? 1.0f : Sync.RelativeSimulationRatio * Sync.RelativeSimulationRatio;
                Vector3D gravity         = simulationRatio * MyGravityProviderSystem.CalculateNaturalGravityInPoint(position.Translation);

                ((MyPhysicsBody)Container.Entity.Physics).RigidBody.Gravity = gravity;
                (Container.Entity.Physics as MyPhysicsBody).HavokWorld.ActiveRigidBodies.Add((Container.Entity.Physics as MyPhysicsBody).RigidBody);
                m_isStarted = true;
            }
Exemplo n.º 26
0
            public void OnGridsCreated(ParallelTasks.WorkData workData)
            {
                foreach (var entity in m_resultIDs)
                {
                    VRage.ModAPI.IMyEntity foundEntity;
                    MyEntityIdentifier.TryGetEntity(entity.EntityId, out foundEntity);
                    if (foundEntity == null)
                    {
                        MyEntityIdentifier.AddEntityWithId(entity);
                    }
                    else
                    {
                        Debug.Fail("Two threads added the same entity");
                    }
                }
                foreach (var grid in m_results)
                {
                    MyEntities.Add(grid);
                    grid.IsReadyForReplication = true;
                }

                while (m_callbacks.Count > 0)
                {
                    var callback = m_callbacks.Pop();
                    if (callback != null)
                    {
                        callback();
                    }
                }
            }
        private void CreateTopPart(out MyAttachableTopBlockBase topBlock, long builtBy, MyCubeBlockDefinitionGroup topGroup, bool smallToLarge)
        {
            Debug.Assert(Sync.IsServer, "Server only method.");
            if (topGroup == null)
            {
                topBlock = null;
                return;
            }

            var gridSize = CubeGrid.GridSizeEnum;

            if (smallToLarge && gridSize == MyCubeSize.Large)   //If we have pressed the Attach Small Rotor Head button on large grid take the small grid definition from pair
            {
                gridSize = MyCubeSize.Small;
            }
            var matrix = GetTopGridMatrix();

            var definition = topGroup[gridSize];

            Debug.Assert(definition != null);

            var block = MyCubeGrid.CreateBlockObjectBuilder(definition, Vector3I.Zero, MyBlockOrientation.Identity, MyEntityIdentifier.AllocateId(), OwnerId, fullyBuilt: MySession.Static.CreativeMode);

            matrix.Translation = Vector3D.Transform(-definition.Center * CubeGrid.GridSize, matrix);

            var gridBuilder = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_CubeGrid>();

            gridBuilder.GridSizeEnum           = gridSize;
            gridBuilder.IsStatic               = false;
            gridBuilder.PositionAndOrientation = new MyPositionAndOrientation(matrix);
            gridBuilder.CubeBlocks.Add(block);

            var grid = MyEntityFactory.CreateEntity <MyCubeGrid>(gridBuilder);

            grid.Init(gridBuilder);

            topBlock = (MyAttachableTopBlockBase)grid.GetCubeBlock(Vector3I.Zero).FatBlock;

            if (!CanPlaceTop(topBlock, builtBy))
            {
                topBlock = null;
                grid.Close();
                return;
            }
            grid.PositionComp.SetPosition(grid.WorldMatrix.Translation - (Vector3D.Transform(topBlock.DummyPosLoc, grid.WorldMatrix) - grid.WorldMatrix.Translation));

            MyEntities.Add(grid);
            if (MyFakes.ENABLE_SENT_GROUP_AT_ONCE)
            {
                MyMultiplayer.ReplicateImmediatelly(MyExternalReplicable.FindByObject(grid), MyExternalReplicable.FindByObject(CubeGrid));
            }

            MatrixD masterToSlave = topBlock.CubeGrid.WorldMatrix * MatrixD.Invert(WorldMatrix);

            m_connectionState.Value = new State()
            {
                TopBlockId = topBlock.EntityId, MasterToSlave = masterToSlave
            };
        }
Exemplo n.º 28
0
        protected void CreateRotorGrid(out MyCubeGrid rotorGrid, out MyAttachableTopBlockBase rotorBlock, long builtBy, MyCubeBlockDefinitionGroup rotorGroup)
        {
            Debug.Assert(Sync.IsServer, "Rotor grid can be created only on server");
            if (rotorGroup == null)
            {
                rotorGrid  = null;
                rotorBlock = null;
                return;
            }

            var gridSize = CubeGrid.GridSizeEnum;

            float size       = MyDefinitionManager.Static.GetCubeSize(gridSize);
            var   matrix     = MatrixD.CreateWorld(Vector3D.Transform(DummyPosition, CubeGrid.WorldMatrix), WorldMatrix.Forward, WorldMatrix.Up);
            var   definition = rotorGroup[gridSize];

            Debug.Assert(definition != null);

            var block = MyCubeGrid.CreateBlockObjectBuilder(definition, Vector3I.Zero, MyBlockOrientation.Identity, MyEntityIdentifier.AllocateId(), OwnerId, fullyBuilt: MySession.Static.CreativeMode);

            var gridBuilder = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_CubeGrid>();

            gridBuilder.GridSizeEnum           = gridSize;
            gridBuilder.IsStatic               = false;
            gridBuilder.PositionAndOrientation = new MyPositionAndOrientation(matrix);
            gridBuilder.CubeBlocks.Add(block);

            var grid = MyEntityFactory.CreateEntity <MyCubeGrid>(gridBuilder);

            grid.Init(gridBuilder);

            rotorGrid = grid;
            MyMotorRotor rotor = (MyMotorRotor)rotorGrid.GetCubeBlock(Vector3I.Zero).FatBlock;

            rotorBlock = rotor;
            rotorGrid.PositionComp.SetPosition(rotorGrid.WorldMatrix.Translation - (Vector3D.Transform(rotor.DummyPosLoc, rotorGrid.WorldMatrix) - rotorGrid.WorldMatrix.Translation));

            if (!CanPlaceRotor(rotorBlock, builtBy))
            {
                rotorGrid  = null;
                rotorBlock = null;
                grid.Close();
                return;
            }

            MyEntities.Add(grid);

            if (MyFakes.ENABLE_SENT_GROUP_AT_ONCE)
            {
                MyMultiplayer.ReplicateImmediatelly(MyExternalReplicable.FindByObject(grid), MyExternalReplicable.FindByObject(CubeGrid));
            }

            MatrixD masterToSlave = rotorBlock.CubeGrid.WorldMatrix * MatrixD.Invert(WorldMatrix);

            m_connectionState.Value = new State()
            {
                TopBlockId = rotorBlock.EntityId, MasterToSlave = masterToSlave
            };
        }
Exemplo n.º 29
0
        protected override void OnLoad(BitStream stream, Action <T> loadingDoneHandler)
        {
            var builder = VRage.Serialization.MySerializer.CreateAndRead <MyObjectBuilder_EntityBase>(stream, MyObjectBuilderSerializer.Dynamic);
            T   entity  = (T)MyEntities.CreateFromObjectBuilder(builder);

            MyEntities.Add(entity);
            loadingDoneHandler(entity);
        }
Exemplo n.º 30
0
        public static MyVoxelMap AddVoxelMap(string storageName, MyStorageBase storage, Vector3 positionMinCorner, long entityId = 0)
        {
            var voxelMap = new MyVoxelMap();

            voxelMap.EntityId = entityId;
            voxelMap.Init(storageName, storage, positionMinCorner);
            MyEntities.Add(voxelMap);
            return(voxelMap);
        }