internal static MyEntity Spawn(MyPhysicalInventoryItem item, BoundingBoxD box, MyPhysicsComponentBase motionInheritedFrom = null) { var floatingBuilder = PrepareBuilder(ref item); var thrownEntity = MyEntities.CreateFromObjectBuilder(floatingBuilder); System.Diagnostics.Debug.Assert(thrownEntity != null); if (thrownEntity != null) { var size = thrownEntity.PositionComp.LocalVolume.Radius; var halfSize = box.Size / 2 - new Vector3(size); halfSize = Vector3.Max(halfSize, Vector3.Zero); box = new BoundingBoxD(box.Center - halfSize, box.Center + halfSize); var pos = MyUtils.GetRandomPosition(ref box); AddToPos(thrownEntity, pos, motionInheritedFrom); thrownEntity.Physics.ForceActivate(); //Visual scripting action if (MyVisualScriptLogicProvider.ItemSpawned != null) { MyVisualScriptLogicProvider.ItemSpawned(item.Content.TypeId.ToString(), item.Content.SubtypeName, thrownEntity.EntityId, item.Amount.ToIntSafe(), pos); } } return(thrownEntity); }
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); } } }
public static MyEntity Spawn(MyPhysicalInventoryItem item, BoundingSphereD sphere, MyPhysicsComponentBase motionInheritedFrom = null, MyVoxelMaterialDefinition voxelMaterial = null) { ProfilerShort.Begin("MyFloatingObjects.Spawn"); var floatingBuilder = PrepareBuilder(ref item); ProfilerShort.Begin("Create"); var thrownEntity = MyEntities.CreateFromObjectBuilder(floatingBuilder); ProfilerShort.End(); ((MyFloatingObject)thrownEntity).VoxelMaterial = voxelMaterial; var size = thrownEntity.PositionComp.LocalVolume.Radius; var sphereSize = sphere.Radius - size; sphereSize = Math.Max(sphereSize, 0); sphere = new BoundingSphereD(sphere.Center, sphereSize); var pos = MyUtils.GetRandomBorderPosition(ref sphere); AddToPos(thrownEntity, pos, motionInheritedFrom); ProfilerShort.End(); //Visual scripting action if (thrownEntity != null && MyVisualScriptLogicProvider.ItemSpawned != null) { MyVisualScriptLogicProvider.ItemSpawned(item.Content.TypeId.ToString(), item.Content.SubtypeName, thrownEntity.EntityId, item.Amount.ToIntSafe(), pos); } return(thrownEntity); }
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)); } }
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); } } } } }
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); }
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); }
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); } }
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); }
private void CreateHolo(LastSeen seen) { if (!(seen.Entity is IMyCubeGrid)) { return; } SeenHolo sh; if (m_holoEntities.TryGetValue(seen.Entity.EntityId, out sh)) { sh.Seen = seen; return; } if (!CanDisplay(seen)) { return; } Profiler.StartProfileBlock("CreateHolo.GetObjectBuilder"); MyObjectBuilder_CubeGrid builder = (MyObjectBuilder_CubeGrid)seen.Entity.GetObjectBuilder(); Profiler.EndProfileBlock(); MyEntities.RemapObjectBuilder(builder); builder.IsStatic = false; builder.CreatePhysics = false; builder.EnableSmallToLargeConnections = false; Profiler.StartProfileBlock("CreateHolo.CreateFromObjectBuilder"); MyCubeGrid holo = (MyCubeGrid)MyEntities.CreateFromObjectBuilder(builder); Profiler.EndProfileBlock(); Profiler.StartProfileBlock("CreateHolo.SetupProjection"); SetupProjection(holo); Profiler.EndProfileBlock(); Profiler.StartProfileBlock("CreateHolo.AddEntity"); MyAPIGateway.Entities.AddEntity(holo); Profiler.EndProfileBlock(); Log.DebugLog("created holo for " + seen.Entity.nameWithId() + ", holo: " + holo.nameWithId()); m_holoEntities.Add(seen.Entity.EntityId, new SeenHolo() { Seen = seen, Holo = holo }); MyCubeGrid actual = (MyCubeGrid)seen.Entity; actual.OnBlockAdded += Actual_OnBlockAdded; actual.OnBlockRemoved += Actual_OnBlockRemoved; actual.OnBlockIntegrityChanged += OnBlockIntegrityChanged; }
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); if (entity != null) { entity.SentFromServer = true; entity.DebugCreatedBy = DebugCreatedBy.FromServer; MyEntities.Add(entity); } loadingDoneHandler(entity); }
/// <summary> /// Creates new entity based on its object builder /// </summary> /// <param name="hudLabelText"></param> /// <param name="objectBuilder"></param> /// <returns></returns> protected virtual MyEntity CreateEntity(string hudLabelText, MyMwcObjectBuilder_Base objectBuilder, Matrix matrix, Vector2?screenPosition) { MyEntity entity = null; if (objectBuilder is MyMwcObjectBuilder_PrefabBase) { //When creating prefabs, it will never happen that active container does not exist entity = m_activeContainer.CreateAndAddPrefab(hudLabelText, objectBuilder as MyMwcObjectBuilder_PrefabBase); } else { entity = MyEntities.CreateFromObjectBuilder(hudLabelText, objectBuilder, matrix); } return(entity); }
/// <summary> /// Converts grid builder with fractured blocks to builder with fractured components. Grid entity is created for conversion so it is not light weight. /// Result builder can have remapped entity ids. /// </summary> public static MyObjectBuilder_CubeGrid ConvertFracturedBlocksToComponents(MyObjectBuilder_CubeGrid gridBuilder) { bool foundFracturedBlock = false; foreach (var block in gridBuilder.CubeBlocks) { if (block is MyObjectBuilder_FracturedBlock) { foundFracturedBlock = true; break; } } if (!foundFracturedBlock) { return(gridBuilder); } bool origEnableSmallToLargeConnections = gridBuilder.EnableSmallToLargeConnections; gridBuilder.EnableSmallToLargeConnections = false; bool origCreatePhysics = gridBuilder.CreatePhysics; gridBuilder.CreatePhysics = true; var tempGrid = MyEntities.CreateFromObjectBuilder(gridBuilder) as MyCubeGrid; tempGrid.ConvertFracturedBlocksToComponents(); var convertedBuilder = (MyObjectBuilder_CubeGrid)tempGrid.GetObjectBuilder(); gridBuilder.EnableSmallToLargeConnections = origEnableSmallToLargeConnections; convertedBuilder.EnableSmallToLargeConnections = origEnableSmallToLargeConnections; gridBuilder.CreatePhysics = origCreatePhysics; convertedBuilder.CreatePhysics = origCreatePhysics; tempGrid.Close(); MyEntities.RemapObjectBuilder(convertedBuilder); return(convertedBuilder); }
internal static MyEntity Spawn(MyPhysicalInventoryItem item, BoundingBoxD box, MyPhysicsComponentBase motionInheritedFrom = null) { MyEntity thrownEntity = MyEntities.CreateFromObjectBuilder(PrepareBuilder(ref item), false); if (thrownEntity != null) { float radius = thrownEntity.PositionComp.LocalVolume.Radius; Vector3D vectord = Vector3.Max(((Vector3)(box.Size / 2.0)) - new Vector3(radius), Vector3.Zero); box = new BoundingBoxD(box.Center - vectord, box.Center + vectord); Vector3D randomPosition = MyUtils.GetRandomPosition(ref box); AddToPos(thrownEntity, randomPosition, motionInheritedFrom); thrownEntity.Physics.ForceActivate(); if (MyVisualScriptLogicProvider.ItemSpawned != null) { MyVisualScriptLogicProvider.ItemSpawned(item.Content.TypeId.ToString(), item.Content.SubtypeName, thrownEntity.EntityId, item.Amount.ToIntSafe(), randomPosition); } } return(thrownEntity); }
internal static MyEntity Spawn(MyPhysicalInventoryItem item, BoundingBoxD box, MyPhysicsComponentBase motionInheritedFrom = null) { var floatingBuilder = PrepareBuilder(ref item); var thrownEntity = MyEntities.CreateFromObjectBuilder(floatingBuilder); System.Diagnostics.Debug.Assert(thrownEntity != null); if (thrownEntity != null) { var size = thrownEntity.PositionComp.LocalVolume.Radius; var halfSize = box.Size / 2 - new Vector3(size); halfSize = Vector3.Max(halfSize, Vector3.Zero); box = new BoundingBoxD(box.Center - halfSize, box.Center + halfSize); var pos = MyUtils.GetRandomPosition(ref box); AddToPos(thrownEntity, pos, motionInheritedFrom); thrownEntity.Physics.ForceActivate(); } return(thrownEntity); }
private MySmallShipBot CreateBotFromBuilder(MyMwcObjectBuilder_SmallShip_Bot bldr, Vector3 position) { //hax bldr.ArmorHealth = MyGameplayConstants.HEALTH_BASIC; bldr.ShipMaxHealth = MyGameplayConstants.HEALTH_BASIC; bldr.Fuel = float.MaxValue; bldr.Oxygen = float.MaxValue; bldr.OwnerId = this.EntityId.Value.NumericValue; if (bldr.ShipTemplateID != null) { var shipTemplate = MySmallShipTemplates.GetTemplateForSpawn(bldr.ShipTemplateID.Value); Debug.Assert(shipTemplate != null, string.Format("ShipTemplate {0} was not found!", bldr.ShipTemplateID.Value)); if (shipTemplate != null) { shipTemplate.ApplyToSmallShipBuilder(bldr); } } bldr.Faction = this.Faction; MySmallShipBot bot = (MySmallShipBot)MyEntities.CreateFromObjectBuilder(null, bldr, Matrix.CreateWorld(position, Vector3.Backward, Vector3.Up)); return(bot); }
internal static T CreateNewComponent <T>(MyObjectBuilder_FunctionalBlock prefab) where T : VRage.Game.Components.MyComponentBase { try { PrefabBuilder.CubeBlocks.Clear(); // need no leftovers from previous spawns PrefabBuilder.CubeBlocks.Add(prefab); MyEntities.RemapObjectBuilder(PrefabBuilder); var ent = MyEntities.CreateFromObjectBuilder(PrefabBuilder, false); Log.Line("259"); 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); Log.Line("269"); var grid = (IMyCubeGrid)ent; var blocks = new List <IMySlimBlock>(); grid.GetBlocks(blocks); var blockSlim = blocks.FirstOrDefault(); Log.Line("271"); var blockFat = blockSlim.FatBlock; Log.Line("273"); Log.Line("275"); var component = blockFat.Components.Get <T>(); blockFat.Components.Remove <T>(); ent.Delete(); return(component); } catch (Exception ex) { Log.Error(ex); } return(null); }
public static MyEntity Spawn(MyPhysicalInventoryItem item, BoundingSphereD sphere, MyPhysicsComponentBase motionInheritedFrom = null, MyVoxelMaterialDefinition voxelMaterial = null) { ProfilerShort.Begin("MyFloatingObjects.Spawn"); var floatingBuilder = PrepareBuilder(ref item); ProfilerShort.Begin("Create"); var thrownEntity = MyEntities.CreateFromObjectBuilder(floatingBuilder); ProfilerShort.End(); ((MyFloatingObject)thrownEntity).VoxelMaterial = voxelMaterial; var size = thrownEntity.PositionComp.LocalVolume.Radius; var sphereSize = sphere.Radius - size; sphereSize = Math.Max(sphereSize, 0); sphere = new BoundingSphereD(sphere.Center, sphereSize); var pos = MyUtils.GetRandomBorderPosition(ref sphere); AddToPos(thrownEntity, pos, motionInheritedFrom); ProfilerShort.End(); return(thrownEntity); }
public MyEntity Spawn(MyFixedPoint amount, MatrixD worldMatrix, MyEntity owner = null) { if (Content is MyObjectBuilder_BlockItem) { var blockItem = Content as MyObjectBuilder_BlockItem; var builder = Sandbox.Common.ObjectBuilders.Serializer.MyObjectBuilderSerializer.CreateNewObject(typeof(MyObjectBuilder_CubeGrid)) as MyObjectBuilder_CubeGrid; builder.EntityId = MyEntityIdentifier.AllocateId(); builder.GridSizeEnum = MyCubeSize.Small; builder.IsStatic = false; builder.PersistentFlags |= MyPersistentEntityFlags2.InScene | MyPersistentEntityFlags2.Enabled; builder.PositionAndOrientation = new MyPositionAndOrientation(worldMatrix); var block = Sandbox.Common.ObjectBuilders.Serializer.MyObjectBuilderSerializer.CreateNewObject(blockItem.BlockDefId) as MyObjectBuilder_CubeBlock; builder.CubeBlocks.Add(block); var newGrid = MyEntities.CreateFromObjectBuilder(builder) as MyCubeGrid; MyEntities.Add(newGrid); Sandbox.Game.Multiplayer.MySyncCreate.SendEntityCreated(builder); return(newGrid); } else { return(MyFloatingObjects.Spawn(new MyInventoryItem(amount, Content), worldMatrix, owner != null ? owner.Physics : null)); } }
public static MyEntity Spawn(this MyPhysicalInventoryItem thisItem, MyFixedPoint amount, MatrixD worldMatrix, MyEntity owner = null) { if (amount < 0) { return(null); } if (thisItem.Content == null) { Debug.Fail("Can not spawn item with null content!"); return(null); } if (thisItem.Content is MyObjectBuilder_BlockItem) { Debug.Assert(MyFixedPoint.IsIntegral(amount), "Spawning fractional number of grids!"); bool isBlock = typeof(MyObjectBuilder_CubeBlock).IsAssignableFrom(thisItem.Content.GetObjectId().TypeId); Debug.Assert(isBlock, "Block item does not contain block!?!?@&*#%!"); if (!isBlock) { return(null); } var blockItem = thisItem.Content as MyObjectBuilder_BlockItem; MyCubeBlockDefinition blockDefinition; MyDefinitionManager.Static.TryGetCubeBlockDefinition(blockItem.BlockDefId, out blockDefinition); Debug.Assert(blockDefinition != null, "Block definition not found"); if (blockDefinition == null) { return(null); } var builder = MyObjectBuilderSerializer.CreateNewObject(typeof(MyObjectBuilder_CubeGrid)) as MyObjectBuilder_CubeGrid; builder.GridSizeEnum = blockDefinition.CubeSize; builder.IsStatic = false; builder.PersistentFlags |= MyPersistentEntityFlags2.InScene | MyPersistentEntityFlags2.Enabled; builder.PositionAndOrientation = new MyPositionAndOrientation(worldMatrix); var block = MyObjectBuilderSerializer.CreateNewObject(blockItem.BlockDefId) as MyObjectBuilder_CubeBlock; System.Diagnostics.Debug.Assert(block != null, "Block couldn't been created, maybe wrong definition id? DefID: " + blockItem.BlockDefId); if (block != null) { block.Min = blockDefinition.Size / 2 - blockDefinition.Size + Vector3I.One; 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); } return(firstGrid); } return(null); } else { MyPhysicalItemDefinition itemDefinition = null; if (MyDefinitionManager.Static.TryGetPhysicalItemDefinition(thisItem.Content.GetObjectId(), out itemDefinition)) { return(MyFloatingObjects.Spawn(new MyPhysicalInventoryItem(amount, thisItem.Content), worldMatrix, owner != null ? owner.Physics : null)); } return(null); } }
internal static MyEntity SpawnPrefab(string name, out IMyTextPanel lcd, bool isDisplay = false) { try { if (string.IsNullOrEmpty(name)) { lcd = null; return(null); } PrefabBuilder.CubeBlocks.Clear(); // need no leftovers from previous spawns if (isDisplay) { PrefabTextPanel.SubtypeName = name; PrefabTextPanel.FontColor = new Vector4(1, 1, 1, 1); PrefabTextPanel.BackgroundColor = new Vector4(0, 0, 0, 0); PrefabTextPanel.FontSize = DISPLAY_FONT_SIZE; PrefabBuilder.CubeBlocks.Add(PrefabTextPanel); var def = MyDefinitionManager.Static.GetCubeBlockDefinition(new MyDefinitionId(typeof(MyObjectBuilder_TextPanel), name)) as MyTextPanelDefinition; if (def != null) { def.TextureResolution = 256; } } else { PrefabCubeBlock.SubtypeName = name; PrefabBuilder.CubeBlocks.Add(PrefabCubeBlock); } MyEntities.RemapObjectBuilder(PrefabBuilder); var ent = MyEntities.CreateFromObjectBuilder(PrefabBuilder, true); ent.IsPreview = true; // don't sync on MP ent.SyncFlag = false; // don't sync on MP ent.Save = false; // don't save this entity MyEntities.Add(ent, true); var lcdSlim = ((IMyCubeGrid)ent).GetCubeBlock(Vector3I.Zero); lcd = lcdSlim.FatBlock as IMyTextPanel; //lcd.Render.CastShadows = false; //lcd.Render.Transparency = 0.5f; //lcd.Render.NeedsResolveCastShadow = false; //lcd.Render.EnableColorMaskHsv = false; //lcd.Render.DrawInAllCascades = false; //lcd.Render.UpdateRenderObject(false, true); //lcd.Render.UpdateRenderObject(true, true); //lcd.Render.RemoveRenderObjects(); //lcd.Render.AddRenderObjects(); lcd.SetEmissiveParts("ScreenArea", Color.White, 1f); lcd.SetEmissiveParts("Edges", Color.Teal, 0.5f); lcd.ContentType = ContentType.TEXT_AND_IMAGE; return(ent); } catch (Exception ex) { Log.Line($"Exception in SpawnPrefab: {ex}"); } lcd = null; return(null); }
// 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) { var prefabDefinition = MyDefinitionManager.Static.GetPrefabDefinition(prefabName); Debug.Assert(prefabDefinition != null, "Could not spawn prefab named " + prefabName); if (prefabDefinition == null) { return; } if (prefabDefinition.CubeGrids == null) { MyDefinitionManager.Static.ReloadPrefabsFromFile(prefabDefinition.PrefabPath); prefabDefinition = MyDefinitionManager.Static.GetPrefabDefinition(prefabName); } MyObjectBuilder_CubeGrid[] gridObs = prefabDefinition.CubeGrids; Debug.Assert(gridObs.Count() != 0); if (gridObs.Count() == 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); } List <MyCubeGrid> gridsToMove = new List <MyCubeGrid>(); bool needMove = true; Vector3D moveVector = new Vector3D(); bool ignoreMemoryLimitsPrevious = MyEntities.IgnoreMemoryLimits; MyEntities.IgnoreMemoryLimits = ignoreMemoryLimits; for (int i = 0; i < gridObs.Count(); ++i) { MyEntity entity = MyEntities.CreateFromObjectBuilder(gridObs[i]); 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)); Sandbox.Game.Gui.MyCestmirDebugInputComponent.AddDebugPoint(newWorldMatrix.Translation, Color.Red); if (cubeGrid.IsStatic) { Debug.Assert(Vector3.IsZero(newWorldMatrix.Forward - Vector3.Forward, 0.001f), "Creating a static grid with orientation that is not identity"); Debug.Assert(Vector3.IsZero(newWorldMatrix.Up - Vector3.Up, 0.001f), "Creating a static grid with orientation that is not identity"); Vector3 rounded = default(Vector3I); if (MyPerGameSettings.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.WorldMatrix = newWorldMatrix; needMove = false; 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.WorldMatrix = newWorldMatrix; if (needMove) { gridsToMove.Add(cubeGrid); } } //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); } } } foreach (var grid in gridsToMove) { MatrixD wmatrix = grid.WorldMatrix; wmatrix.Translation += moveVector; } MyEntities.IgnoreMemoryLimits = ignoreMemoryLimitsPrevious; }
public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid) { base.Init(objectBuilder, cubeGrid); PostBaseInit(); //MyDebug.AssertDebug(objectBuilder.TypeId == typeof(MyObjectBuilder_Cockpit)); var def = MyDefinitionManager.Static.GetCubeBlockDefinition(objectBuilder.GetId()); m_isLargeCockpit = (def.CubeSize == MyCubeSize.Large); m_cockpitInteriorModel = BlockDefinition.InteriorModel; m_cockpitGlassModel = BlockDefinition.GlassModel; NeedsUpdate = MyEntityUpdateEnum.EACH_100TH_FRAME; MyObjectBuilder_Cockpit cockpitOb = (MyObjectBuilder_Cockpit)objectBuilder; if (cockpitOb.Pilot != null) { MyEntity pilotEntity; MyCharacter pilot = null; if (MyEntities.TryGetEntityById(cockpitOb.Pilot.EntityId, out pilotEntity)) { //Pilot already exists, can be the case after cube grid split pilot = (MyCharacter)pilotEntity; if (pilot.IsUsing is MyShipController && pilot.IsUsing != this) { System.Diagnostics.Debug.Assert(false, "Pilot already sits on another place!"); pilot = null; } } else { pilot = (MyCharacter)MyEntities.CreateFromObjectBuilder(cockpitOb.Pilot); } if (pilot != null) { AttachPilot(pilot, storeOriginalPilotWorld: false, calledFromInit: true); if (cockpitOb.PilotRelativeWorld.HasValue) { m_pilotRelativeWorld = cockpitOb.PilotRelativeWorld.Value.GetMatrix(); } else { m_pilotRelativeWorld = null; } m_singleWeaponMode = cockpitOb.UseSingleWeaponMode; } IsInFirstPersonView = cockpitOb.IsInFirstPersonView; } if (cockpitOb.Autopilot != null) { MyAutopilotBase autopilot = MyAutopilotFactory.CreateAutopilot(cockpitOb.Autopilot); autopilot.Init(cockpitOb.Autopilot); AttachAutopilot(autopilot, updateSync: false); } m_pilotGunDefinition = cockpitOb.PilotGunDefinition; // backward compatibility check for automatic rifle without subtype if (m_pilotGunDefinition.HasValue) { if (m_pilotGunDefinition.Value.TypeId == typeof(MyObjectBuilder_AutomaticRifle) && string.IsNullOrEmpty(m_pilotGunDefinition.Value.SubtypeName)) { m_pilotGunDefinition = new MyDefinitionId(typeof(MyObjectBuilder_AutomaticRifle), "RifleGun"); } } if (!string.IsNullOrEmpty(m_cockpitInteriorModel)) { if (MyModels.GetModelOnlyDummies(m_cockpitInteriorModel).Dummies.ContainsKey("head")) { m_headLocalPosition = MyModels.GetModelOnlyDummies(m_cockpitInteriorModel).Dummies["head"].Matrix.Translation; } } else { if (MyModels.GetModelOnlyDummies(BlockDefinition.Model).Dummies.ContainsKey("head")) { m_headLocalPosition = MyModels.GetModelOnlyDummies(BlockDefinition.Model).Dummies["head"].Matrix.Translation; } } AddDebugRenderComponent(new Components.MyDebugRenderComponentCockpit(this)); InitializeConveyorEndpoint(); AddDebugRenderComponent(new Components.MyDebugRenderComponentDrawConveyorEndpoint(m_conveyorEndpoint)); m_oxygenLevel = cockpitOb.OxygenLevel; }
public void InsertRequiredActors() { MyMwcLog.WriteLine("InsertRequiredActors - START"); foreach (MyActorEnum actor in RequiredActors) { switch (actor) { //Insert Madelyn case MyActorEnum.MADELYN: { if (!MyEntities.EntityExists("Madelyn")) { MyMwcLog.WriteLine("Insert Madelyne - START"); // Holds ids for remap IMyEntityIdRemapContext remapContext = new MyEntityIdRemapContext(); //MyMwcObjectBuilder_SectorObjectGroups groups = MySectorGenerator.LoadSectorGroups(MyTemplateGroups.GetGroupSector(MyTemplateGroupEnum.Madelyn)); MyMwcObjectBuilder_SectorObjectGroups groups = MySession.Static.LoadSectorGroups(MyTemplateGroups.GetGroupSector(MyTemplateGroupEnum.Madelyn)); System.Diagnostics.Debug.Assert(groups.Groups.Count > 0); MyMwcObjectBuilder_ObjectGroup madelynGroup = groups.Groups[0]; groups.RemapEntityIds(remapContext); IEnumerable <MyMwcObjectBuilder_Base> rootObjects = madelynGroup.GetRootBuilders(groups.Entities); List <MyMwcObjectBuilder_Base> clonedList = new List <MyMwcObjectBuilder_Base>(); foreach (MyMwcObjectBuilder_Base o in rootObjects) { // Clone var clone = o.Clone() as MyMwcObjectBuilder_Base; // we want Madelyn's prefab container as first builder if (clone is MyMwcObjectBuilder_PrefabContainer) { clonedList.Insert(0, clone); } else { clonedList.Add(clone); } } System.Diagnostics.Debug.Assert(clonedList.Count > 0 && clonedList[0] is MyMwcObjectBuilder_PrefabContainer); // create Madelyn's prefab container MyEntity madelynMothership = MyEntities.CreateFromObjectBuilder(MyTextsWrapper.Get(MyTextsWrapperEnum.Actor_Madelyn).ToString(), clonedList[0], ((MyMwcObjectBuilder_Object3dBase)clonedList[0]).PositionAndOrientation.GetMatrix()); madelynMothership.FindChild(MyMissionLocation.MADELYN_HANGAR).DisplayName = MyTextsWrapper.Get(MyTextsWrapperEnum.Sapho).ToString(); madelynMothership.SetName(MyActorConstants.GetActorName(MyActorEnum.MADELYN)); Matrix madelynMothershipWorldInv = Matrix.Invert(madelynMothership.WorldMatrix); List <MinerWars.AppCode.Game.Entities.WayPoints.MyWayPoint> waypoints = new List <Entities.WayPoints.MyWayPoint>(); // create other entities as children of Madelyn's prefab container for (int i = 1; i < clonedList.Count; i++) { System.Diagnostics.Debug.Assert(clonedList[i] is MyMwcObjectBuilder_Object3dBase); MyEntity childEntity = MyEntities.CreateFromObjectBuilder(null, clonedList[i], ((MyMwcObjectBuilder_Object3dBase)clonedList[i]).PositionAndOrientation.GetMatrix()); childEntity.SetLocalMatrix(childEntity.WorldMatrix * madelynMothershipWorldInv); madelynMothership.Children.Add(childEntity); if (childEntity is MinerWars.AppCode.Game.Entities.WayPoints.MyWayPoint) { waypoints.Add(childEntity as MinerWars.AppCode.Game.Entities.WayPoints.MyWayPoint); } } // connect waypoints of Madelyn's prefab container foreach (var waypoint in waypoints) { waypoint.ResolveLinks(); } // set correct Madelyn's position and add to scene madelynMothership.SetWorldMatrix(MyPlayer.FindMothershipPosition()); madelynMothership.Link(); MyEntities.Add(madelynMothership); MyMwcLog.WriteLine("Insert Madelyne - END"); } else { MyMwcLog.WriteLine("Insert Madelyne - Madelyne already loaded"); } MyWayPointGraph.RecreateWaypointsAroundMadelyn(); } break; //Insert Marcus case MyActorEnum.MARCUS: InsertFriend(MyActorEnum.MARCUS); break; //Insert RavenGirl case MyActorEnum.TARJA: InsertFriend(MyActorEnum.TARJA); break; //Insert RavenGuy case MyActorEnum.VALENTIN: InsertFriend(MyActorEnum.VALENTIN, MyMwcObjectBuilder_SmallShip_TypesEnum.HAMMER); break; default: System.Diagnostics.Debug.Assert(false, "Uknown actor to insert!"); break; } } MyMwcLog.WriteLine("InsertRequiredActors - END"); }
IMyEntity IMyEntities.CreateFromObjectBuilder(Common.ObjectBuilders.MyObjectBuilder_EntityBase objectBuilder) { return((IMyEntity)MyEntities.CreateFromObjectBuilder(objectBuilder)); }
// 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; }
// 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 (MyPerGameSettings.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; }