private void TryRegisterSessionComponent(Type type, bool modAssembly) { try { MyDefinitionId?definition = default(MyDefinitionId?); if (MyFakes.ENABLE_LOAD_NEEDED_SESSION_COMPONENTS) { var component = (MySessionComponentBase)Activator.CreateInstance(type); Debug.Assert(component != null, "Session component is cannot be created by activator"); if (component.IsRequiredByGame) { RegisterComponent(component, component.UpdateOrder, component.Priority); GetComponentInfo(type, out definition); component.Definition = definition; } } else if (modAssembly || GetComponentInfo(type, out definition)) { var component = (MySessionComponentBase)Activator.CreateInstance(type); Debug.Assert(component != null, "Session component is cannot be created by activator"); RegisterComponent(component, component.UpdateOrder, component.Priority); component.Definition = definition; } } catch (Exception) { MySandboxGame.Log.WriteLine("Exception during loading of type : " + type.Name); } }
protected override void Init(MyObjectBuilder_DefinitionBase builder) { MyDefinitionId id; base.Init(builder); MyObjectBuilder_MotorSuspensionDefinition definition = (MyObjectBuilder_MotorSuspensionDefinition)builder; this.MaxSteer = definition.MaxSteer; this.SteeringSpeed = definition.SteeringSpeed; this.PropulsionForce = definition.PropulsionForce; this.MinHeight = definition.MinHeight; this.MaxHeight = definition.MaxHeight; this.AxleFriction = definition.AxleFriction; this.AirShockMinSpeed = definition.AirShockMinSpeed; this.AirShockMaxSpeed = definition.AirShockMaxSpeed; this.AirShockActivationDelay = definition.AirShockActivationDelay; this.RequiredIdlePowerInput = (definition.RequiredIdlePowerInput != 0f) ? definition.RequiredIdlePowerInput : definition.RequiredPowerInput; if ((definition.SoundDefinitionId == null) || !MyDefinitionId.TryParse(definition.SoundDefinitionId.DefinitionTypeName, definition.SoundDefinitionId.DefinitionSubtypeName, out id)) { this.SoundDefinitionId = null; } else { this.SoundDefinitionId = new MyDefinitionId?(id); } }
private void ModifyCurrentList(ref List <MyGuiControlListbox.Item> list, bool Add) { this.m_allowCurrentListUpdate = false; if (list != null) { foreach (MyGuiControlListbox.Item item in list) { MyDefinitionId?userData = item.UserData as MyDefinitionId?; if (userData != null) { this.ChangeListId(userData.Value, Add); continue; } byte?nullable2 = item.UserData as byte?; if (nullable2 != null) { this.ChangeListType(nullable2.Value, Add); } } } this.m_allowCurrentListUpdate = true; currentList.UpdateVisual(); addToSelectionButton.UpdateVisual(); removeFromSelectionButton.UpdateVisual(); }
private void modifyCurrentList(ref List <MyGuiControlListbox.Item> list, bool Add) { Debug.Assert(list != null, "Adding NULL from list"); m_allowCurrentListUpdate = false; if (list != null) { foreach (var val in list) { Debug.Assert(val.UserData != null, "User data is null"); MyDefinitionId?id = val.UserData as MyDefinitionId?; if (id != null) { ChangeListId((MyDefinitionId)id, Add); continue; } byte?b = val.UserData as byte?; if (b == null) { Debug.Assert(false, "Should not be here"); continue; } ChangeListType((byte)b, Add); } } m_allowCurrentListUpdate = true; currentList.UpdateVisual(); addToSelectionButton.UpdateVisual(); removeFromSelectionButton.UpdateVisual(); }
public void UpdateBlockDefinitionStages(MyDefinitionId?id) { if (!id.HasValue || CurrentBlockDefinition == null) { return; } MyDefinitionId defBlockId = id.Value; if (CurrentBlockDefinitionStages.Count > 1) { defBlockId = CurrentBlockDefinitionStages[0].Id; } if (CurrentBlockDefinitionStages.Count <= 1) { return; } int lastStage; if (StageIndexByDefinitionHash.TryGetValue(defBlockId, out lastStage)) { if (lastStage >= 0 && lastStage < CurrentBlockDefinitionStages.Count) { CurrentBlockDefinition = CurrentBlockDefinitionStages[lastStage]; } } }
protected override void Init(MyObjectBuilder_DefinitionBase builder) { base.Init(builder); MyObjectBuilder_PhysicalItemDefinition definition = builder as MyObjectBuilder_PhysicalItemDefinition; this.Size = definition.Size; this.Mass = definition.Mass; this.Model = definition.Model; this.Models = definition.Models; this.Volume = (definition.Volume != null) ? (definition.Volume.Value / 1000f) : definition.Size.Volume; this.ModelVolume = (definition.ModelVolume != null) ? (definition.ModelVolume.Value / 1000f) : this.Volume; this.IconSymbol = !string.IsNullOrEmpty(definition.IconSymbol) ? new MyStringId?(MyStringId.GetOrCompute(definition.IconSymbol)) : null; this.PhysicalMaterial = MyStringHash.GetOrCompute(definition.PhysicalMaterial); this.VoxelMaterial = MyStringHash.GetOrCompute(definition.VoxelMaterial); this.CanSpawnFromScreen = definition.CanSpawnFromScreen; this.RotateOnSpawnX = definition.RotateOnSpawnX; this.RotateOnSpawnY = definition.RotateOnSpawnY; this.RotateOnSpawnZ = definition.RotateOnSpawnZ; this.Health = definition.Health; if (definition.DestroyedPieceId != null) { this.DestroyedPieceId = new MyDefinitionId?(definition.DestroyedPieceId.Value); } this.DestroyedPieces = definition.DestroyedPieces; this.ExtraInventoryTooltipLine = (definition.ExtraInventoryTooltipLine == null) ? new StringBuilder() : new StringBuilder().Append(MyEnvironment.NewLine).Append(definition.ExtraInventoryTooltipLine); this.MaxStackAmount = definition.MaxStackAmount; }
protected override void Init(MyObjectBuilder_DefinitionBase builder) { base.Init(builder); var ob = builder as MyObjectBuilder_PhysicalItemDefinition; MyDebug.AssertDebug(ob != null); this.Size = ob.Size; this.Mass = ob.Mass; this.Model = ob.Model; this.Models = ob.Models; this.Volume = ob.Volume.HasValue? ob.Volume.Value / 1000f : ob.Size.Volume; if (string.IsNullOrEmpty(ob.IconSymbol)) this.IconSymbol = null; else this.IconSymbol = MyStringId.GetOrCompute(ob.IconSymbol); PhysicalMaterial = MyStringHash.GetOrCompute(ob.PhysicalMaterial); VoxelMaterial = MyStringHash.GetOrCompute(ob.VoxelMaterial); CanSpawnFromScreen = ob.CanSpawnFromScreen; RotateOnSpawnX = ob.RotateOnSpawnX; RotateOnSpawnY = ob.RotateOnSpawnY; RotateOnSpawnZ = ob.RotateOnSpawnZ; Health = ob.Health; if (ob.DestroyedPieceId.HasValue) { DestroyedPieceId = ob.DestroyedPieceId.Value; } DestroyedPieces = ob.DestroyedPieces; if (ob.ExtraInventoryTooltipLine != null) ExtraInventoryTooltipLine = new StringBuilder().Append(Environment.NewLine).Append(ob.ExtraInventoryTooltipLine); else ExtraInventoryTooltipLine = new StringBuilder(); }
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); }
public bool EquipAny(MyDefinitionId?itemRemoved = null) { foreach (Tool t in tools) { if (t.Equip(itemRemoved)) { return(true); } } return(false); }
internal void SwitchTo(MyDefinitionId?gunId, bool useSingle = false) { //if (m_gunType == gunType) // return; m_gunId = gunId; m_useSingleGun = useSingle; if (m_currentGuns != null) { foreach (var gun in m_currentGuns) { gun.OnControlReleased(); } } if (!gunId.HasValue) { m_currentGuns.Clear(); return; } m_currentGuns.Clear(); if (useSingle) { var gun = WeaponSystem.GetGunWithAmmo(gunId.Value, m_shipController.OwnerId); if (gun != null) { m_currentGuns.Add(gun); } } else { var guns = WeaponSystem.GetGunsById(gunId.Value); if (guns != null) { foreach (var gun in guns) { if (gun != null) { m_currentGuns.Add(gun); } } } } foreach (var gun in m_currentGuns) { gun.OnControlAcquired(m_shipController.Pilot); } }
public virtual void Init(MyObjectBuilder_EntityBase objectBuilder) { ProfilerShort.Begin("MyEntity.Init(objectBuilder)"); MarkedForClose = false; Closed = false; this.Render.PersistentFlags = MyPersistentEntityFlags2.CastShadows; if (objectBuilder != null) { if (objectBuilder.EntityDefinitionId.HasValue) { DefinitionId = objectBuilder.EntityDefinitionId; InitFromDefinition(objectBuilder, DefinitionId.Value); } if (objectBuilder.PositionAndOrientation.HasValue) { var posAndOrient = objectBuilder.PositionAndOrientation.Value; MatrixD matrix = MatrixD.CreateWorld(posAndOrient.Position, posAndOrient.Forward, posAndOrient.Up); MyUtils.AssertIsValid(matrix); PositionComp.SetWorldMatrix((MatrixD)matrix); if (MyPerGameSettings.LimitedWorld) { ClampToWorld(); } } // Do not copy EntityID if it gets overwritten later. It might // belong to some existing entity that we're making copy of. if (objectBuilder.EntityId != 0) { this.EntityId = objectBuilder.EntityId; } this.Name = objectBuilder.Name; this.Render.PersistentFlags = objectBuilder.PersistentFlags; this.Components.Deserialize(objectBuilder.ComponentContainer); } AllocateEntityID(); this.InScene = false; MyEntities.SetEntityName(this, false); if (SyncFlag) { CreateSync(); } GameLogic.Init(objectBuilder); ProfilerShort.End(); }
public void UpdateCubeBlockDefinition(MyDefinitionId?id, MatrixD localMatrixAdd) { if (!id.HasValue) { return; } if (CurrentBlockDefinition != null) { var cubeBlockDefGroup = MyDefinitionManager.Static.GetDefinitionGroup(CurrentBlockDefinition.BlockPairName); if (CurrentBlockDefinitionStages.Count > 1) { cubeBlockDefGroup = MyDefinitionManager.Static.GetDefinitionGroup(CurrentBlockDefinitionStages[0].BlockPairName); if (cubeBlockDefGroup.Small != null) { StageIndexByDefinitionHash[cubeBlockDefGroup.Small.Id] = CurrentBlockDefinitionStages.IndexOf(CurrentBlockDefinition); } if (cubeBlockDefGroup.Large != null) { StageIndexByDefinitionHash[cubeBlockDefGroup.Large.Id] = CurrentBlockDefinitionStages.IndexOf(CurrentBlockDefinition); } } var rotation = Quaternion.CreateFromRotationMatrix(localMatrixAdd); if (cubeBlockDefGroup.Small != null) { RotationsByDefinitionHash[cubeBlockDefGroup.Small.Id] = rotation; } if (cubeBlockDefGroup.Large != null) { RotationsByDefinitionHash[cubeBlockDefGroup.Large.Id] = rotation; } } var tmpDef = MyDefinitionManager.Static.GetCubeBlockDefinition(id.Value); if (tmpDef.Public || MyFakes.ENABLE_NON_PUBLIC_BLOCKS) { CurrentBlockDefinition = tmpDef; } else { CurrentBlockDefinition = tmpDef.CubeSize == MyCubeSize.Large ? MyDefinitionManager.Static.GetDefinitionGroup(tmpDef.BlockPairName).Small : MyDefinitionManager.Static.GetDefinitionGroup(tmpDef.BlockPairName).Large; } StartBlockDefinition = CurrentBlockDefinition; }
public void UpdateBlockDefinitionStages(MyDefinitionId?id) { if ((id != null) && (this.CurrentBlockDefinition != null)) { int num; MyDefinitionId key = id.Value; if (this.CurrentBlockDefinitionStages.Count > 1) { key = this.CurrentBlockDefinitionStages[0].Id; } if ((this.CurrentBlockDefinitionStages.Count > 1) && ((this.StageIndexByDefinitionHash.TryGetValue(key, out num) && (num >= 0)) && (num < this.CurrentBlockDefinitionStages.Count))) { this.CurrentBlockDefinition = this.CurrentBlockDefinitionStages[num]; } } }
public void RequestSwitchToWeapon(MyDefinitionId?weapon, MyObjectBuilder_EntityBase weaponObjectBuilder, long weaponEntityId) { if (!Sync.IsServer) { m_switchWeaponCounter++; } var msg = new SwitchToWeaponMsg(); msg.ControlledEntityId = SyncedEntityId; msg.Weapon = weapon; msg.WeaponObjectBuilder = weaponObjectBuilder; msg.WeaponEntityId = weaponEntityId; Sync.Layer.SendMessageToServer(ref msg); }
public void InitFromDefinition(MyObjectBuilder_EntityBase entityBuilder, MyDefinitionId definitionId) { Debug.Assert(entityBuilder != null, "Invalid arguments!"); MyPhysicalItemDefinition entityDefinition; if (!MyDefinitionManager.Static.TryGetDefinition(definitionId, out entityDefinition)) { Debug.Fail("Definition: " + DefinitionId.ToString() + " was not found!"); return; } DefinitionId = definitionId; Flags |= EntityFlags.Visible | EntityFlags.NeedsDraw | EntityFlags.Sync | EntityFlags.InvalidateOnMove; StringBuilder name = new StringBuilder(entityDefinition.DisplayNameText); Init(name, entityDefinition.Model, null, null, null); CreateSync(); if (entityBuilder.PositionAndOrientation.HasValue) { MatrixD worldMatrix = MatrixD.CreateWorld( (Vector3D)entityBuilder.PositionAndOrientation.Value.Position, (Vector3)entityBuilder.PositionAndOrientation.Value.Forward, (Vector3)entityBuilder.PositionAndOrientation.Value.Up); PositionComp.SetWorldMatrix(worldMatrix); } Name = name.Append("_(").Append(entityBuilder.EntityId).Append(")").ToString(); Render.UpdateRenderObject(true); Physics = new Engine.Physics.MyPhysicsBody(this, RigidBodyFlag.RBF_DEFAULT); if (ModelCollision != null && ModelCollision.HavokCollisionShapes.Length >= 1) { HkMassProperties massProperties = HkInertiaTensorComputer.ComputeBoxVolumeMassProperties(entityDefinition.Size / 2, (MyPerGameSettings.Destruction ? MyDestructionHelper.MassToHavok(entityDefinition.Mass) : entityDefinition.Mass));; Physics.CreateFromCollisionObject(ModelCollision.HavokCollisionShapes[0], Vector3.Zero, WorldMatrix, massProperties); Physics.RigidBody.AngularDamping = 2; Physics.RigidBody.LinearDamping = 1; } Physics.Enabled = true; EntityId = entityBuilder.EntityId; }
private bool EquipBest(MyDefinitionId?itemRemoved = null) { MyDefinitionId handId; if (GetBestId(out handId, itemRemoved)) { // An item exists in the inventory SetToolSlot(handId); EquipSlot(); return(true); } else { // No items exist in the inventory return(false); } }
public int this[MyItemType type] { get { return(DesiredStock[type]); } set { if (!Blueprints.ContainsKey(type)) { MyDefinitionId?bp = CreateBlueprint(type.SubtypeId); if (!bp.HasValue) { throw new ArgumentException($"Failed to create blueprint for {type.ToString()}"); } Blueprints[type] = bp.Value; InverseBlueprints[bp.Value] = type; } DesiredStock[type] = value; } }
public void ApplySettings(Settings.MapSettings config) { float modifier = config.ComponentCostModifier; Dictionary <MyDefinitionId, int> newDict; if (modifier != 1) { newDict = new Dictionary <MyDefinitionId, int>(comps.Count); foreach (KeyValuePair <MyDefinitionId, int> kv in comps) { int newCost = (int)Math.Round(kv.Value * modifier); if (newCost > 0) { newDict.Add(kv.Key, newCost); } } } else { newDict = comps; } MyDefinitionId?extraComp = config.ExtraComponent; if (extraComp.HasValue) { MyDefinitionId id = extraComp.Value; int count; if (!newDict.TryGetValue(id, out count)) { count = 0; } int numExtraComps = (int)Math.Round(BlockCount * config.ExtraCompCost); if (numExtraComps <= 0) { numExtraComps = 1; } newDict[id] = count + numExtraComps; } comps = newDict; }
protected override void Init(MyObjectBuilder_DefinitionBase builder) { base.Init(builder); var ob = builder as MyObjectBuilder_PhysicalItemDefinition; MyDebug.AssertDebug(ob != null); this.Size = ob.Size; this.Mass = ob.Mass; this.Model = ob.Model; this.Models = ob.Models; this.Volume = ob.Volume.HasValue ? ob.Volume.Value / 1000f : ob.Size.Volume; this.ModelVolume = ob.ModelVolume.HasValue ? ob.ModelVolume.Value / 1000f : this.Volume; if (string.IsNullOrEmpty(ob.IconSymbol)) { this.IconSymbol = null; } else { this.IconSymbol = MyStringId.GetOrCompute(ob.IconSymbol); } PhysicalMaterial = MyStringHash.GetOrCompute(ob.PhysicalMaterial); VoxelMaterial = MyStringHash.GetOrCompute(ob.VoxelMaterial); CanSpawnFromScreen = ob.CanSpawnFromScreen; RotateOnSpawnX = ob.RotateOnSpawnX; RotateOnSpawnY = ob.RotateOnSpawnY; RotateOnSpawnZ = ob.RotateOnSpawnZ; Health = ob.Health; if (ob.DestroyedPieceId.HasValue) { DestroyedPieceId = ob.DestroyedPieceId.Value; } DestroyedPieces = ob.DestroyedPieces; if (ob.ExtraInventoryTooltipLine != null) { ExtraInventoryTooltipLine = new StringBuilder().Append(Environment.NewLine).Append(ob.ExtraInventoryTooltipLine); } else { ExtraInventoryTooltipLine = new StringBuilder(); } this.MaxStackAmount = ob.MaxStackAmount; }
public bool Equip(MyDefinitionId?itemRemoved = null) { if (!Enabled) { return(false); } MyDefinitionId handId; if (!itemRemoved.HasValue && GetHandId(out handId)) { // Something is in the hand int index; if (GetIndex(handId, out index)) { // The item in the hand is correct type if (MakeBest(ref handId, index)) { // The item needs to be upgraded SetToolSlot(handId); EquipSlot(); return(true); } else { // The item in the hand is already the best SelectPage(); return(true); } } else { // The item in the hand is not correct type return(EquipBest()); } } else { // Nothing in the hand return(EquipBest(itemRemoved)); } }
public void UpdateCubeBlockDefinition(MyDefinitionId?id, MatrixD localMatrixAdd) { if (id != null) { if (this.CurrentBlockDefinition != null) { MyCubeBlockDefinitionGroup definitionGroup = MyDefinitionManager.Static.GetDefinitionGroup(this.CurrentBlockDefinition.BlockPairName); if (this.CurrentBlockDefinitionStages.Count > 1) { definitionGroup = MyDefinitionManager.Static.GetDefinitionGroup(this.CurrentBlockDefinitionStages[0].BlockPairName); if (definitionGroup.Small != null) { this.StageIndexByDefinitionHash[definitionGroup.Small.Id] = this.CurrentBlockDefinitionStages.IndexOf(this.CurrentBlockDefinition); } if (definitionGroup.Large != null) { this.StageIndexByDefinitionHash[definitionGroup.Large.Id] = this.CurrentBlockDefinitionStages.IndexOf(this.CurrentBlockDefinition); } } Quaternion quaternion = Quaternion.CreateFromRotationMatrix(localMatrixAdd); if (definitionGroup.Small != null) { this.RotationsByDefinitionHash[definitionGroup.Small.Id] = quaternion; } if (definitionGroup.Large != null) { this.RotationsByDefinitionHash[definitionGroup.Large.Id] = quaternion; } } MyCubeBlockDefinition cubeBlockDefinition = MyDefinitionManager.Static.GetCubeBlockDefinition(id.Value); if (cubeBlockDefinition.Public || MyFakes.ENABLE_NON_PUBLIC_BLOCKS) { this.CurrentBlockDefinition = cubeBlockDefinition; } else { this.CurrentBlockDefinition = (cubeBlockDefinition.CubeSize == MyCubeSize.Large) ? MyDefinitionManager.Static.GetDefinitionGroup(cubeBlockDefinition.BlockPairName).Small : MyDefinitionManager.Static.GetDefinitionGroup(cubeBlockDefinition.BlockPairName).Large; } this.StartBlockDefinition = this.CurrentBlockDefinition; } }
public ProceduralConstructionSeed(ProceduralFactionSeed faction, Vector3D location, Ob_ProceduralConstructionSeed ob) { Faction = faction; Location = location; Name = ob.Name; Orientation = ob.Orientation; Population = ob.Population; Seed = ob.Seed; Speciality = ob.Speciality; SpecialityExport = ob.SpecialityExport; m_blockCountRequirements = new Dictionary <SupportedBlockTypes, BlockRequirement>(); foreach (var k in ob.BlockCountRequirements) { m_blockCountRequirements[k.Type] = new BlockRequirement(k.Count, k.ErrorMultiplier); } m_imports = TradeReqToDictionary(ob.Imports); m_exports = TradeReqToDictionary(ob.Exports); m_localStorage = TradeReqToDictionary(ob.Local); ComputeStorageVolumeMass(out StorageVolume, out StorageMass); }
private bool GetComponentInfo(Type type, out MyDefinitionId?definition) { string name = null; if (m_componentsToLoad.Contains(type.Name)) { name = type.Name; } else if (m_componentsToLoad.Contains(type.FullName)) { name = type.FullName; } if (name != null) { GameDefinition.SessionComponents.TryGetValue(name, out definition); return(true); } definition = default(MyDefinitionId?); return(false); }
/// <summary> /// Finds the best available id. /// Returns true if an id was found. /// </summary> /// <param name="itemRemoved">The item to ignore when checking inventory.</param> private bool GetBestId(out MyDefinitionId id, MyDefinitionId?itemRemoved = null) { if (MyAPIGateway.Session.CreativeMode) { id = Ids[EquipIndex]; return(true); } IMyInventory inv = p.Character.GetInventory(); MyFixedPoint one = 1; for (int i = Ids.Length - 1; i >= 0; i--) { MyDefinitionId temp = Ids[i]; if ((!itemRemoved.HasValue || itemRemoved.Value != temp) && inv.ContainItems(one, temp)) { id = temp; return(true); } } id = new MyDefinitionId(); return(false); }
internal void SwitchTo(MyDefinitionId? gunId, bool useSingle = false) { //if (m_gunType == gunType) // return; m_gunId = gunId; m_useSingleGun = useSingle; if (m_currentGuns != null) foreach (var gun in m_currentGuns) gun.OnControlReleased(); if (!gunId.HasValue) { m_currentGuns.Clear(); return; } m_currentGuns.Clear(); if (useSingle) { var gun = WeaponSystem.GetGunWithAmmo(gunId.Value, m_shipController.OwnerId); if (gun != null) m_currentGuns.Add(gun); } else { var guns = WeaponSystem.GetGunsById(gunId.Value); if (guns != null) { foreach (var gun in guns) { if (gun != null) m_currentGuns.Add(gun); } } } foreach (var gun in m_currentGuns) gun.OnControlAcquired(m_shipController.Pilot); }
public bool RemovePilot() { if (m_pilot == null) return true; MyAnalyticsHelper.ReportActivityEnd(m_pilot, "Cockpit"); System.Diagnostics.Debug.Assert(m_pilot.Physics != null); if (m_pilot.Physics == null) { //probably already closed pilot left in cockpit m_pilot = null; return true; } StopLoopSound(); m_pilot.OnMarkForClose -= m_pilotClosedHandler; if(MyVisualScriptLogicProvider.PlayerLeftCockpit != null) MyVisualScriptLogicProvider.PlayerLeftCockpit(Name, m_pilot.GetPlayerIdentityId(), CubeGrid.Name); Hierarchy.RemoveChild(m_pilot); if (m_pilot.IsDead) { if (this.ControllerInfo.Controller != null) this.SwitchControl(m_pilot); MyEntities.Add(m_pilot); m_pilot.WorldMatrix = WorldMatrix; m_pilotGunDefinition = null; m_rechargeSocket.Unplug(); m_pilot.SuitBattery.ResourceSink.TemporaryConnectedEntity = null; m_pilot = null; return true; } bool usePilotOriginalWorld = false; MatrixD placementMatrix = MatrixD.Identity; if (m_pilotRelativeWorld.Value.HasValue) { Vector3D cockpitWorldPos = Vector3D.Transform(Position * CubeGrid.GridSize, CubeGrid.WorldMatrix); placementMatrix = MatrixD.Multiply((MatrixD)m_pilotRelativeWorld.Value.Value, this.WorldMatrix); var hi = MyPhysics.CastRay(placementMatrix.Translation, cockpitWorldPos, MyPhysics.CollisionLayers.DefaultCollisionLayer); if (hi != null && hi.HasValue) { var ent = hi.Value.HkHitInfo.GetHitEntity(); if (CubeGrid.Equals(ent)) if (m_pilot.CanPlaceCharacter(ref placementMatrix)) usePilotOriginalWorld = true; } } Vector3D? allowedPosition = null; if (!usePilotOriginalWorld) { allowedPosition = FindFreeNeighbourPosition(); if (!allowedPosition.HasValue) allowedPosition = PositionComp.GetPosition(); } RemovePilotFromSeat(m_pilot); EndShootAll(); if (usePilotOriginalWorld || allowedPosition.HasValue) { Hierarchy.RemoveChild(m_pilot); MyEntities.Add(m_pilot); m_pilot.Physics.Enabled = true; m_rechargeSocket.Unplug(); m_pilot.SuitBattery.ResourceSink.TemporaryConnectedEntity = null; m_pilot.Stand(); // allowedPosition is in center of character MatrixD placeMatrix = (usePilotOriginalWorld) ? placementMatrix : MatrixD.CreateWorld(allowedPosition.Value - WorldMatrix.Up, WorldMatrix.Forward, WorldMatrix.Up); if (m_pilot.Physics.CharacterProxy != null) m_pilot.Physics.CharacterProxy.ImmediateSetWorldTransform = true; if (!MyEntities.CloseAllowed) { m_pilot.PositionComp.SetWorldMatrix(placeMatrix, this); } if (m_pilot.Physics.CharacterProxy != null) m_pilot.Physics.CharacterProxy.ImmediateSetWorldTransform = false; if (m_pilotJetpackEnabledBackup.HasValue && m_pilot.JetpackComp != null) m_pilot.JetpackComp.TurnOnJetpack(m_pilotJetpackEnabledBackup.Value); if (Parent != null && Parent.Physics != null) // Cockpit could be removing the pilot after it no longer belongs to any grid (e.g. during a split) { m_pilot.Physics.LinearVelocity = Parent.Physics.LinearVelocity; if (Parent.Physics.LinearVelocity.LengthSquared() > 100 * Sync.RelativeSimulationRatio) { var jetpack = m_pilot.JetpackComp; if (jetpack != null) { jetpack.EnableDampeners(false); jetpack.TurnOnJetpack(true); } } } if (this.ControllerInfo.Controller != null) { this.SwitchControl(m_pilot); } if (m_pilotGunDefinition != null) m_pilot.SwitchToWeapon(m_pilotGunDefinition); else m_pilot.SwitchToWeapon(null); var pilot = m_pilot; m_pilot = null; if (MySession.Static.CameraController == this && pilot == MySession.Static.LocalCharacter) { bool isInFirstPerson = IsInFirstPersonView; MySession.Static.SetCameraController(MyCameraControllerEnum.Entity, pilot); } pilot.IsInFirstPersonView = m_pilotFirstPerson; return true; } else { //System.Diagnostics.Debug.Assert(false, "There is no place where to put astronaut. Kill him!"); } return false; }
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; 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) { Debug.Assert(false, "Pilot already sits on another place!"); pilot = null; } } else { pilot = (MyCharacter)MyEntities.CreateFromObjectBuilder(cockpitOb.Pilot); } if (pilot != null) { m_savedPilot = pilot; if (cockpitOb.PilotRelativeWorld.HasValue) m_pilotRelativeWorld.Value = cockpitOb.PilotRelativeWorld.Value.GetMatrix(); else m_pilotRelativeWorld.Value = 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 (VRage.Game.Models.MyModels.GetModelOnlyDummies(m_cockpitInteriorModel).Dummies.ContainsKey("head")) m_headLocalPosition = VRage.Game.Models.MyModels.GetModelOnlyDummies(m_cockpitInteriorModel).Dummies["head"].Matrix.Translation; } else { if (VRage.Game.Models.MyModels.GetModelOnlyDummies(BlockDefinition.Model).Dummies.ContainsKey("head")) m_headLocalPosition = VRage.Game.Models.MyModels.GetModelOnlyDummies(BlockDefinition.Model).Dummies["head"].Matrix.Translation; } AddDebugRenderComponent(new Components.MyDebugRenderComponentCockpit(this)); InitializeConveyorEndpoint(); AddDebugRenderComponent(new Components.MyDebugRenderComponentDrawConveyorEndpoint(m_conveyorEndpoint)); OxygenFillLevel = cockpitOb.OxygenLevel; var sinkDataList = new List<MyResourceSinkInfo> { new MyResourceSinkInfo {ResourceTypeId = MyResourceDistributorComponent.ElectricityId, MaxRequiredInput = 0, RequiredInputFunc = CalculateRequiredPowerInput }, new MyResourceSinkInfo {ResourceTypeId = MyCharacterOxygenComponent.OxygenId, MaxRequiredInput = BlockDefinition.OxygenCapacity, RequiredInputFunc = ComputeRequiredGas}, }; ResourceSink.Init(MyStringHash.GetOrCompute("Utility"), sinkDataList); ResourceSink.CurrentInputChanged += Sink_CurrentInputChanged; m_lastGasInputUpdateTick = MySession.Static.ElapsedGameTime.Ticks; if (cockpitOb.AttachedPlayerId.HasValue == false && cockpitOb.Pilot != null && m_pilot!=null) { m_attachedCharacterIdSaved = m_pilot.EntityId; } else { m_attachedCharacterIdSaved = cockpitOb.AttachedPlayerId; } if (this.GetInventory() == null) { Vector3 inv = Vector3.One*1.0f; MyInventory inventory = new MyInventory(inv.Volume, inv, MyInventoryFlags.CanSend | MyInventoryFlags.CanReceive); Components.Add<MyInventoryBase>(inventory); } m_defferAttach = true; }
public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid) { SyncFlag = true; base.Init(objectBuilder, cubeGrid); //MyDebug.AssertDebug(objectBuilder.TypeId == typeof(MyObjectBuilder_ShipController)); var def = MyDefinitionManager.Static.GetCubeBlockDefinition(objectBuilder.GetId()); m_enableFirstPerson = BlockDefinition.EnableFirstPerson || MySession.Static.Settings.Enable3rdPersonView == false; m_enableShipControl = BlockDefinition.EnableShipControl; m_enableBuilderCockpit = BlockDefinition.EnableBuilderCockpit; m_rechargeSocket = new MyRechargeSocket(); MyObjectBuilder_ShipController shipControllerOb = (MyObjectBuilder_ShipController)objectBuilder; // No need for backward compatibility of selected weapon, we just leave it alone // m_selectedGunType = shipControllerOb.SelectedGunType; m_selectedGunId = shipControllerOb.SelectedGunId; ControlThrusters = shipControllerOb.ControlThrusters; ControlWheels = shipControllerOb.ControlWheels; if (shipControllerOb.IsMainCockpit) { IsMainCockpit = true; } HorizonIndicatorEnabled = shipControllerOb.HorizonIndicatorEnabled; m_toolbar = new MyToolbar(ToolbarType); m_toolbar.Init(shipControllerOb.Toolbar, this); m_toolbar.ItemChanged += Toolbar_ItemChanged; m_buildToolbar = new MyToolbar(MyToolbarType.BuildCockpit); m_buildToolbar.Init(shipControllerOb.BuildToolbar, this); SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged; // TODO: Seems like overkill if (Sync.IsServer && false) { //Because of simulating thrusts NeedsUpdate |= MyEntityUpdateEnum.EACH_FRAME; } NeedsUpdate |= MyEntityUpdateEnum.EACH_100TH_FRAME; m_baseIdleSound = BlockDefinition.PrimarySound; CubeGrid.OnGridSplit += CubeGrid_OnGridSplit; Components.ComponentAdded += OnComponentAdded; Components.ComponentRemoved += OnComponentRemoved; if(EntityThrustComponent != null) { m_dampenersEnabled.Value = EntityThrustComponent.Enabled; } UpdateShipInfo(); if (BlockDefinition.GetInSound != null && BlockDefinition.GetInSound.Length > 0) GetInCockpitSound = new MySoundPair(BlockDefinition.GetInSound); if (BlockDefinition.GetOutSound != null && BlockDefinition.GetOutSound.Length > 0) GetOutOfCockpitSound = new MySoundPair(BlockDefinition.GetOutSound); }
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 override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid) { SyncFlag = true; base.Init(objectBuilder, cubeGrid); //MyDebug.AssertDebug(objectBuilder.TypeId == typeof(MyObjectBuilder_ShipController)); var def = MyDefinitionManager.Static.GetCubeBlockDefinition(objectBuilder.GetId()); m_enableFirstPerson = BlockDefinition.EnableFirstPerson || MySession.Static.Settings.Enable3rdPersonView == false; m_enableShipControl = BlockDefinition.EnableShipControl; m_rechargeSocket = new MyRechargeSocket(); MyObjectBuilder_ShipController shipControllerOb = (MyObjectBuilder_ShipController)objectBuilder; // No need for backward compatibility of selected weapon, we just leave it alone // m_selectedGunType = shipControllerOb.SelectedGunType; m_selectedGunId = shipControllerOb.SelectedGunId; m_controlThrusters = shipControllerOb.ControlThrusters; m_controlWheels = shipControllerOb.ControlWheels; if (shipControllerOb.IsMainCockpit) { IsMainCockpit = true; } Toolbar = new MyToolbar(ToolbarType); Toolbar.Init(shipControllerOb.Toolbar, this); SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged; // TODO: Seems like overkill if (Sync.IsServer && false) { //Because of simulating thrusts NeedsUpdate |= MyEntityUpdateEnum.EACH_FRAME; } CubeGrid.OnGridSplit += CubeGrid_OnGridSplit; }
void SwitchToWeaponInternal(MyDefinitionId? weapon, bool updateSync) { if (updateSync) { SyncObject.RequestSwitchToWeapon(weapon, null, 0); return; } StopCurrentWeaponShooting(); if (weapon.HasValue) { // var gun = GetWeaponType(weapon.Value.TypeId); SwitchToWeaponInternal(weapon); } else { m_selectedGunId = null; GridSelectionSystem.SwitchTo(null); } }
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 virtual void Init(MyObjectBuilder_EntityBase objectBuilder) { ProfilerShort.Begin("MyEntity.Init(objectBuilder)"); MarkedForClose = false; Closed = false; this.Render.PersistentFlags = MyPersistentEntityFlags2.CastShadows; if (objectBuilder != null) { if (objectBuilder.EntityId != 0) this.EntityId = objectBuilder.EntityId; else AllocateEntityID(); DefinitionId = objectBuilder.GetId(); if (objectBuilder.EntityDefinitionId != null) // backward compatibility { Debug.Assert(objectBuilder.SubtypeName == null || objectBuilder.SubtypeName == objectBuilder.EntityDefinitionId.Value.SubtypeName); DefinitionId = objectBuilder.EntityDefinitionId.Value; } if (objectBuilder.PositionAndOrientation.HasValue) { var posAndOrient = objectBuilder.PositionAndOrientation.Value; //GR: Check for NaN values and remove them (otherwise there will be problems wilth clusters) if (posAndOrient.Position.x.IsValid() == false) { posAndOrient.Position.x = 0.0f; } if (posAndOrient.Position.y.IsValid() == false) { posAndOrient.Position.y = 0.0f; } if (posAndOrient.Position.z.IsValid() == false) { posAndOrient.Position.z = 0.0f; } MatrixD matrix = MatrixD.CreateWorld(posAndOrient.Position, posAndOrient.Forward, posAndOrient.Up); //if (matrix.IsValid()) // MatrixD.Rescale(ref matrix, scale); MyUtils.AssertIsValid(matrix); PositionComp.SetWorldMatrix((MatrixD)matrix); ClampToWorld(); } this.Name = objectBuilder.Name; this.Render.PersistentFlags = objectBuilder.PersistentFlags & ~VRage.ObjectBuilders.MyPersistentEntityFlags2.InScene; // This needs to be called after Entity has it's valid EntityID so components when are initiliazed or added to container, they get valid EntityID InitComponentsExtCallback(this.Components, DefinitionId.Value.TypeId, DefinitionId.Value.SubtypeId, objectBuilder.ComponentContainer); } else { AllocateEntityID(); } Debug.Assert(!this.InScene, "Entity is in scene after creation!"); MyEntitiesInterface.SetEntityName(this, false); if (SyncFlag) { CreateSync(); } GameLogic.Init(objectBuilder); ProfilerShort.End(); }
public void AttachPilot(MyCharacter pilot, bool storeOriginalPilotWorld = true, bool calledFromInit = false) { System.Diagnostics.Debug.Assert(pilot != null); System.Diagnostics.Debug.Assert(m_pilot == null); m_pilot = pilot; m_pilot.OnMarkForClose += m_pilotClosedHandler; m_pilot.IsUsing = this; //m_soundEmitter.OwnedBy = m_pilot; if (MyFakes.ENABLE_NEW_SOUNDS) StartLoopSound(); if (storeOriginalPilotWorld) { m_pilotRelativeWorld = (Matrix)MatrixD.Multiply(pilot.WorldMatrix, this.PositionComp.GetWorldMatrixNormalizedInv()); if (Sync.IsServer) { var relativeEntry = new MyPositionAndOrientation(m_pilotRelativeWorld.Value); SyncObject.SendPilotRelativeEntryUpdate(ref relativeEntry); } } if (pilot.InScene) MyEntities.Remove(pilot); m_pilot.Physics.Enabled = false; m_pilot.PositionComp.SetWorldMatrix(WorldMatrix); m_pilot.Physics.Clear(); //m_pilot.SetPosition(GetPosition() - WorldMatrix.Forward * 0.5f); Hierarchy.AddChild(m_pilot, true, true); var gunEntity = m_pilot.CurrentWeapon as MyEntity; if (gunEntity != null) { var ob = gunEntity.GetObjectBuilder(); m_pilotGunDefinition = ob.GetId(); } else m_pilotGunDefinition = null; MyAnimationDefinition animationDefinition; MyDefinitionId id = new MyDefinitionId(typeof(MyObjectBuilder_AnimationDefinition), BlockDefinition.CharacterAnimation); if (!MyDefinitionManager.Static.TryGetDefinition(id, out animationDefinition) && !MyFileSystem.FileExists(BlockDefinition.CharacterAnimation)) { BlockDefinition.CharacterAnimation = null; } PlacePilotInSeat(pilot); m_rechargeSocket.PlugIn(m_pilot.SuitBattery); // Control should be handled elsewhere if we initialize the grid in the Init(...) if (!calledFromInit) GiveControlToPilot(); m_pilot.SwitchToWeapon(null); }
protected override void Init(MyObjectBuilder_DefinitionBase objectBuilder) { var builder = (MyObjectBuilder_CharacterDefinition)objectBuilder; Name = builder.Name; Model = builder.Model; ReflectorTexture = builder.ReflectorTexture; LeftGlare = builder.LeftGlare; RightGlare = builder.RightGlare; LeftLightBone = builder.LeftLightBone; RightLightBone = builder.RightLightBone; LightGlareSize = builder.LightGlareSize; HeadBone = builder.HeadBone; Camera3rdBone = builder.Camera3rdBone; LeftHandIKStartBone = builder.LeftHandIKStartBone; LeftHandIKEndBone= builder.LeftHandIKEndBone; RightHandIKStartBone= builder.RightHandIKStartBone; RightHandIKEndBone= builder.RightHandIKEndBone; WeaponBone = builder.WeaponBone; LeftHandItemBone = builder.LeftHandItemBone; RighHandItemBone = builder.RightHandItemBone; Skeleton = builder.Skeleton; LeftForearmBone = builder.LeftForearmBone; LeftUpperarmBone = builder.LeftUpperarmBone; RightForearmBone = builder.RightForearmBone; RightUpperarmBone = builder.RightUpperarmBone; SpineBone = builder.SpineBone; BendMultiplier1st = builder.BendMultiplier1st; BendMultiplier3rd = builder.BendMultiplier3rd; MaterialsDisabledIn1st = builder.MaterialsDisabledIn1st; Stats = builder.Stats; FeetIKEnabled = builder.FeetIKEnabled; ModelRootBoneName = builder.ModelRootBoneName; LeftHipBoneName = builder.LeftHipBoneName; LeftKneeBoneName = builder.LeftKneeBoneName; LeftAnkleBoneName = builder.LeftAnkleBoneName; RightHipBoneName = builder.RightHipBoneName; RightKneeBoneName = builder.RightKneeBoneName; RightAnkleBoneName = builder.RightAnkleBoneName; NeedsOxygen = builder.NeedsOxygen; OxygenConsumption = builder.OxygenConsumption; PressureLevelForLowDamage = builder.PressureLevelForLowDamage; DamageAmountAtZeroPressure = builder.DamageAmountAtZeroPressure; RagdollDataFile = builder.RagdollDataFile; HelmetVariation = builder.HelmetVariation; DeathSoundName = builder.DeathSoundName; VisibleOnHud = builder.VisibleOnHud; RagdollRootBody = builder.RagdollRootBody; FeetIKSettings = new Dictionary<MyCharacterMovementEnum,MyFeetIKSettings>(); if (builder.IKSettings != null) { foreach (var feetSettings in builder.IKSettings) { string[] states = feetSettings.MovementState.Split(','); foreach (string stateSet in states) { string stateDef = stateSet.Trim(); if (stateDef != "") { Debug.Assert(Enum.GetNames(typeof(MyCharacterMovementEnum)).Contains(stateDef), "State " + stateDef + " is not defined in Character Movement States"); MyCharacterMovementEnum state; if (Enum.TryParse(stateDef, true, out state)) { MyFeetIKSettings fSettings = new MyFeetIKSettings(); fSettings.Enabled = feetSettings.Enabled; fSettings.AboveReachableDistance = feetSettings.AboveReachableDistance; fSettings.BelowReachableDistance = feetSettings.BelowReachableDistance; fSettings.VerticalShiftDownGain = feetSettings.VerticalShiftDownGain; fSettings.VerticalShiftUpGain = feetSettings.VerticalShiftUpGain; fSettings.FootSize = new Vector3(feetSettings.FootWidth, feetSettings.AnkleHeight, feetSettings.FootLenght); FeetIKSettings.Add(state, fSettings); } } } } } JetpackAvailable = builder.JetpackAvailable; JetpackSlowdown = builder.JetpackSlowdown; if (builder.Thrusts != null) Thrusts = builder.Thrusts; if (builder.BoneSets != null) { BoneSets = builder.BoneSets.ToDictionary(x => x.Name, x => x.Bones.Split(' ')); } if (builder.AnimationMappings != null) { AnimationNameToSubtypeName = builder.AnimationMappings.ToDictionary(mapping => mapping.Name, mapping => mapping.AnimationSubtypeName); } if (builder.RagdollBonesMappings != null) { RagdollBonesMappings = builder.RagdollBonesMappings.ToDictionary(x => x.Name, x => x.Bones.Split(' ')); } if (builder.RagdollPartialSimulations != null) { RagdollPartialSimulations = builder.RagdollPartialSimulations.ToDictionary(x => x.Name, x => x.Bones.Split(' ')); } Mass = builder.Mass; MaxHealth = builder.MaxHealth; OxygenCapacity = builder.OxygenCapacity; VerticalPositionFlyingOnly = builder.VerticalPositionFlyingOnly; UseOnlyWalking = builder.UseOnlyWalking; MaxSlope = builder.MaxSlope; MaxSprintSpeed = builder.MaxSprintSpeed; MaxRunSpeed = builder.MaxRunSpeed; MaxBackrunSpeed = builder.MaxBackrunSpeed; MaxRunStrafingSpeed = builder.MaxRunStrafingSpeed; MaxWalkSpeed = builder.MaxWalkSpeed; MaxBackwalkSpeed = builder.MaxBackwalkSpeed; MaxWalkStrafingSpeed = builder.MaxWalkStrafingSpeed; MaxCrouchWalkSpeed = builder.MaxCrouchWalkSpeed; MaxCrouchBackwalkSpeed = builder.MaxCrouchBackwalkSpeed; MaxCrouchStrafingSpeed = builder.MaxCrouchStrafingSpeed; CharacterHeadSize = builder.CharacterHeadSize; CharacterHeadHeight = builder.CharacterHeadHeight; CharacterCollisionScale = builder.CharacterCollisionScale; CharacterWidth = builder.CharacterWidth; CharacterHeight = builder.CharacterHeight; CharacterLength = builder.CharacterLength; if (builder.Inventory == null) { InventoryDefinition = new MyObjectBuilder_InventoryDefinition(); } else { InventoryDefinition = builder.Inventory; } EnabledComponents = builder.EnabledComponents.Split(' ').ToList(); EnableSpawnInventoryAsContainer = builder.EnableSpawnInventoryAsContainer; if (EnableSpawnInventoryAsContainer) { Debug.Assert(builder.InventorySpawnContainerId.HasValue, "Enabled spawning inventory as container, but type id is null"); if (builder.InventorySpawnContainerId.HasValue) { InventorySpawnContainerId = builder.InventorySpawnContainerId.Value; } } }
public void InitFromDefinition(MyObjectBuilder_EntityBase entityBuilder, MyDefinitionId definitionId) { Debug.Assert(entityBuilder != null, "Invalid arguments!"); MyPhysicalItemDefinition entityDefinition; if (!MyDefinitionManager.Static.TryGetDefinition(definitionId, out entityDefinition)) { Debug.Fail("Definition: " + DefinitionId.ToString() + " was not found!"); return; } DefinitionId = definitionId; Flags |= EntityFlags.Visible | EntityFlags.NeedsDraw | EntityFlags.Sync | EntityFlags.InvalidateOnMove; StringBuilder name = new StringBuilder(entityDefinition.DisplayNameText); Init(name, entityDefinition.Model, null, null, null); CreateSync(); if (entityBuilder.PositionAndOrientation.HasValue) { MatrixD worldMatrix = MatrixD.CreateWorld( (Vector3D)entityBuilder.PositionAndOrientation.Value.Position, (Vector3)entityBuilder.PositionAndOrientation.Value.Forward, (Vector3)entityBuilder.PositionAndOrientation.Value.Up); PositionComp.SetWorldMatrix(worldMatrix); } Name = name.Append("_(").Append(entityBuilder.EntityId).Append(")").ToString(); Render.UpdateRenderObject(true); Physics = new Engine.Physics.MyPhysicsBody(this, RigidBodyFlag.RBF_DEFAULT); if (ModelCollision != null && ModelCollision.HavokCollisionShapes.Length >= 1) { HkMassProperties massProperties = HkInertiaTensorComputer.ComputeBoxVolumeMassProperties(entityDefinition.Size / 2, (MyPerGameSettings.Destruction ? MyDestructionHelper.MassToHavok(entityDefinition.Mass) : entityDefinition.Mass)); ; Physics.CreateFromCollisionObject(ModelCollision.HavokCollisionShapes[0], Vector3.Zero, WorldMatrix, massProperties); Physics.RigidBody.AngularDamping = 2; Physics.RigidBody.LinearDamping = 1; } Physics.Enabled = true; EntityId = entityBuilder.EntityId; }
protected override void Init(MyObjectBuilder_DefinitionBase builder) { base.Init(builder); var ob = builder as MyObjectBuilder_PlanetGeneratorDefinition; if (ob.InheritFrom != null && ob.InheritFrom.Length > 0) { InheritFrom(ob.InheritFrom); } if (ob.Environment.HasValue) { EnvironmentId = ob.Environment.Value; } else { m_pgob = ob; } if (ob.PlanetMaps.HasValue) PlanetMaps = ob.PlanetMaps.Value; if (ob.HasAtmosphere.HasValue) HasAtmosphere = ob.HasAtmosphere.Value; if (ob.CloudLayers != null) CloudLayers = ob.CloudLayers; if (ob.SoundRules != null) { SoundRules = new MyPlanetEnvironmentalSoundRule[ob.SoundRules.Length]; for (int ruleIndex = 0; ruleIndex < ob.SoundRules.Length; ++ruleIndex) { MyPlanetEnvironmentalSoundRule sr; sr = new MyPlanetEnvironmentalSoundRule() { Latitude = ob.SoundRules[ruleIndex].Latitude, Height = ob.SoundRules[ruleIndex].Height, SunAngleFromZenith = ob.SoundRules[ruleIndex].SunAngleFromZenith, EnvironmentSound = MyStringHash.GetOrCompute(ob.SoundRules[ruleIndex].EnvironmentSound) }; sr.Latitude.ConvertToSine(); sr.SunAngleFromZenith.ConvertToCosine(); SoundRules[ruleIndex] = sr; } } if (ob.MusicCategories != null) MusicCategories = ob.MusicCategories; if (ob.HillParams.HasValue) HillParams = ob.HillParams.Value; if (ob.Atmosphere != null) Atmosphere = ob.Atmosphere; if (ob.GravityFalloffPower.HasValue) GravityFalloffPower = ob.GravityFalloffPower.Value; if (ob.HostileAtmosphereColorShift != null) HostileAtmosphereColorShift = ob.HostileAtmosphereColorShift; if (ob.MaterialsMaxDepth.HasValue) MaterialsMaxDepth = ob.MaterialsMaxDepth.Value; if (ob.MaterialsMinDepth.HasValue) MaterialsMinDepth = ob.MaterialsMinDepth.Value; if (ob.CustomMaterialTable != null && ob.CustomMaterialTable.Length > 0) { SurfaceMaterialTable = new MyPlanetMaterialDefinition[ob.CustomMaterialTable.Length]; for (int i = 0; i < SurfaceMaterialTable.Length; i++) { SurfaceMaterialTable[i] = ob.CustomMaterialTable[i].Clone() as MyPlanetMaterialDefinition; if (SurfaceMaterialTable[i].Material == null && !SurfaceMaterialTable[i].HasLayers) { MyLog.Default.WriteLine("Custom material does not contain any material ids."); } else if (SurfaceMaterialTable[i].HasLayers) { // Make the depth cumulative so we don't have to calculate it later. // If we want we can even binary search it. float depth = SurfaceMaterialTable[i].Layers[0].Depth; for (int j = 1; j < SurfaceMaterialTable[i].Layers.Length; j++) { SurfaceMaterialTable[i].Layers[j].Depth += depth; depth = SurfaceMaterialTable[i].Layers[j].Depth; } } } } if (ob.DistortionTable != null && ob.DistortionTable.Length > 0) { DistortionTable = ob.DistortionTable; } if (ob.DefaultSurfaceMaterial != null) DefaultSurfaceMaterial = ob.DefaultSurfaceMaterial; if (ob.DefaultSubSurfaceMaterial != null) DefaultSubSurfaceMaterial = ob.DefaultSubSurfaceMaterial; if (ob.SurfaceGravity.HasValue) SurfaceGravity = ob.SurfaceGravity.Value; if (ob.AtmosphereSettings != null) AtmosphereSettings = ob.AtmosphereSettings; // Folder name is not inherited to avoid weirdness. FolderName = ob.FolderName != null ? ob.FolderName : ob.Id.SubtypeName; if (ob.ComplexMaterials != null && ob.ComplexMaterials.Length > 0) { MaterialGroups = new MyPlanetMaterialGroup[ob.ComplexMaterials.Length]; for (int k = 0; k < ob.ComplexMaterials.Length; k++) { MaterialGroups[k] = ob.ComplexMaterials[k].Clone() as MyPlanetMaterialGroup; var group = MaterialGroups[k]; var matRules = group.MaterialRules; List<int> badMaterials = new List<int>(); for (int i = 0; i < matRules.Length; i++) { if (matRules[i].Material == null && (matRules[i].Layers == null || matRules[i].Layers.Length == 0)) { MyLog.Default.WriteLine("Material rule does not contain any material ids."); badMaterials.Add(i); continue; } else if (matRules[i].Layers != null && matRules[i].Layers.Length != 0) { // Make the depth cumulative so we don't have to calculate it later. // If we want we can even binary search it. float depth = matRules[i].Layers[0].Depth; for (int j = 1; j < matRules[i].Layers.Length; j++) { matRules[i].Layers[j].Depth += depth; depth = matRules[i].Layers[j].Depth; } } // We use the cosine later so we precompute it here. matRules[i].Slope.ConvertToCosine(); matRules[i].Latitude.ConvertToSine(); matRules[i].Longitude.ConvertToCosineLongitude(); } if (badMaterials.Count > 0) { matRules = matRules.RemoveIndices(badMaterials); } group.MaterialRules = matRules; } } /*if (ob.EnvironmentItems != null && ob.EnvironmentItems.Length > 0) { MaterialEnvironmentMappings = new Dictionary<int, Dictionary<string, List<MyPlanetEnvironmentMapping>>>(); for (int i = 0; i < ob.EnvironmentItems.Length; i++) { PlanetEnvironmentItemMapping map = ob.EnvironmentItems[i]; if (map.Rule != null) map.Rule = map.Rule.Clone() as MyPlanetSurfaceRule; else map.Rule = new MyPlanetSurfaceRule(); map.Rule.Slope.ConvertToCosine(); map.Rule.Latitude.ConvertToSine(); map.Rule.Longitude.ConvertToCosineLongitude(); // If the mapping does not assign a material it is ignored if (map.Materials == null) break; if (map.Biomes == null) map.Biomes = m_arrayOfZero; foreach (var biome in map.Biomes) { Dictionary<string, List<MyPlanetEnvironmentMapping>> matmap; if (MaterialEnvironmentMappings.ContainsKey(biome)) { matmap = MaterialEnvironmentMappings[biome]; } else { matmap = new Dictionary<string, List<MyPlanetEnvironmentMapping>>(); MaterialEnvironmentMappings.Add(biome, matmap); } foreach (var material in map.Materials) { if (!matmap.ContainsKey(material)) matmap.Add(material, new List<MyPlanetEnvironmentMapping>()); matmap[material].Add(new MyPlanetEnvironmentMapping(map)); } } } }*/ if (ob.OreMappings != null) { OreMappings = ob.OreMappings; } if (ob.MaterialBlending.HasValue) { MaterialBlending = ob.MaterialBlending.Value; } if (ob.SurfaceDetail != null) { Detail = ob.SurfaceDetail; } if (ob.AnimalSpawnInfo != null) { AnimalSpawnInfo = ob.AnimalSpawnInfo; } if (ob.NightAnimalSpawnInfo != null) { NightAnimalSpawnInfo = ob.NightAnimalSpawnInfo; } if (ob.SectorDensity.HasValue) { SectorDensity = ob.SectorDensity.Value; } }
public bool RemovePilot() { if (m_pilot == null) { return(true); } System.Diagnostics.Debug.Assert(m_pilot.Physics != null); if (m_pilot.Physics == null) { //probably already closed pilot left in cockpit m_pilot = null; return(true); } //m_soundEmitter.OwnedBy = null; if (MyFakes.ENABLE_NEW_SOUNDS) { StopLoopSound(); } m_pilot.OnMarkForClose -= m_pilotClosedHandler; if (m_pilot.IsDead) { if (this.ControllerInfo.Controller != null) { this.SwitchControl(m_pilot); } Hierarchy.RemoveChild(m_pilot); MyEntities.Add(m_pilot); m_pilot.WorldMatrix = WorldMatrix; m_pilotGunDefinition = null; m_rechargeSocket.Unplug(); m_pilot = null; return(true); } bool usePilotOriginalWorld = false; MatrixD placementMatrix = MatrixD.Identity; if (m_pilotRelativeWorld.HasValue) { placementMatrix = MatrixD.Multiply((MatrixD)m_pilotRelativeWorld.Value, this.WorldMatrix); if (m_pilot.CanPlaceCharacter(ref placementMatrix)) { usePilotOriginalWorld = true; } } Vector3D?allowedPosition = null; if (!usePilotOriginalWorld) { allowedPosition = FindFreeNeighbourPosition(); if (!allowedPosition.HasValue) { allowedPosition = PositionComp.GetPosition(); } } RemovePilotFromSeat(m_pilot); EndShootAll(); if (usePilotOriginalWorld || allowedPosition.HasValue) { Hierarchy.RemoveChild(m_pilot); MyEntities.Add(m_pilot); m_pilot.Physics.Enabled = true; m_rechargeSocket.Unplug(); m_pilot.Stand(); // allowedPosition is in center of character MatrixD placeMatrix = (usePilotOriginalWorld) ? placementMatrix : MatrixD.CreateWorld(allowedPosition.Value - WorldMatrix.Up, WorldMatrix.Forward, WorldMatrix.Up); if (m_pilot.Physics.CharacterProxy != null) { m_pilot.Physics.CharacterProxy.ImmediateSetWorldTransform = true; } if (!MyEntities.CloseAllowed) { m_pilot.PositionComp.SetWorldMatrix(placeMatrix); } if (m_pilot.Physics.CharacterProxy != null) { m_pilot.Physics.CharacterProxy.ImmediateSetWorldTransform = false; } if (Parent != null) // Cockpit could be removing the pilot after it no longer belongs to any grid (e.g. during a split) { m_pilot.Physics.LinearVelocity = Parent.Physics.LinearVelocity; if (Parent.Physics.LinearVelocity.LengthSquared() > 100) { m_pilot.EnableDampeners(false); m_pilot.EnableJetpack(true); } } if (this.ControllerInfo.Controller != null) { this.SwitchControl(m_pilot); } if (m_pilotGunDefinition != null) { m_pilot.SwitchToWeapon(m_pilotGunDefinition); } else { m_pilot.SwitchToWeapon(null); } var pilot = m_pilot; m_pilot = null; if (MySession.Static.CameraController == this) { MySession.SetCameraController(MyCameraControllerEnum.Entity, pilot); } return(true); } else { //System.Diagnostics.Debug.Assert(false, "There is no place where to put astronaut. Kill him!"); } return(false); }
protected override void Init(MyObjectBuilder_DefinitionBase objectBuilder) { base.Init(objectBuilder); var builder = (MyObjectBuilder_CharacterDefinition)objectBuilder; Name = builder.Name; Model = builder.Model; ReflectorTexture = builder.ReflectorTexture; LeftGlare = builder.LeftGlare; RightGlare = builder.RightGlare; LeftLightBone = builder.LeftLightBone; RightLightBone = builder.RightLightBone; LightOffset = builder.LightOffset; LightGlareSize = builder.LightGlareSize; HeadBone = builder.HeadBone; Camera3rdBone = builder.Camera3rdBone; LeftHandIKStartBone = builder.LeftHandIKStartBone; LeftHandIKEndBone= builder.LeftHandIKEndBone; RightHandIKStartBone= builder.RightHandIKStartBone; RightHandIKEndBone= builder.RightHandIKEndBone; WeaponBone = builder.WeaponBone; LeftHandItemBone = builder.LeftHandItemBone; RighHandItemBone = builder.RightHandItemBone; Skeleton = builder.Skeleton; LeftForearmBone = builder.LeftForearmBone; LeftUpperarmBone = builder.LeftUpperarmBone; RightForearmBone = builder.RightForearmBone; RightUpperarmBone = builder.RightUpperarmBone; SpineBone = builder.SpineBone; BendMultiplier1st = builder.BendMultiplier1st; BendMultiplier3rd = builder.BendMultiplier3rd; MaterialsDisabledIn1st = builder.MaterialsDisabledIn1st; FeetIKEnabled = builder.FeetIKEnabled; ModelRootBoneName = builder.ModelRootBoneName; LeftHipBoneName = builder.LeftHipBoneName; LeftKneeBoneName = builder.LeftKneeBoneName; LeftAnkleBoneName = builder.LeftAnkleBoneName; RightHipBoneName = builder.RightHipBoneName; RightKneeBoneName = builder.RightKneeBoneName; RightAnkleBoneName = builder.RightAnkleBoneName; UsesAtmosphereDetector = builder.UsesAtmosphereDetector; NeedsOxygen = builder.NeedsOxygen; OxygenConsumptionMultiplier = builder.OxygenConsumptionMultiplier; OxygenConsumption = builder.OxygenConsumption; PressureLevelForLowDamage = builder.PressureLevelForLowDamage; DamageAmountAtZeroPressure = builder.DamageAmountAtZeroPressure; RagdollDataFile = builder.RagdollDataFile; //HelmetVariation = builder.HelmetVariation; JumpSoundName = builder.JumpSoundName; JetpackIdleSoundName = builder.JetpackIdleSoundName; JetpackRunSoundName = builder.JetpackRunSoundName; CrouchDownSoundName = builder.CrouchDownSoundName; CrouchUpSoundName = builder.CrouchUpSoundName; PainSoundName = builder.PainSoundName; SuffocateSoundName = builder.SuffocateSoundName; DeathSoundName = builder.DeathSoundName; DeathBySuffocationSoundName = builder.DeathBySuffocationSoundName; IronsightActSoundName = builder.IronsightActSoundName; IronsightDeactSoundName = builder.IronsightDeactSoundName; FastFlySoundName = builder.FastFlySoundName; HelmetOxygenNormalSoundName = builder.HelmetOxygenNormalSoundName; HelmetOxygenLowSoundName = builder.HelmetOxygenLowSoundName; HelmetOxygenCriticalSoundName = builder.HelmetOxygenCriticalSoundName; HelmetOxygenNoneSoundName = builder.HelmetOxygenNoneSoundName; LoopingFootsteps = builder.LoopingFootsteps; VisibleOnHud = builder.VisibleOnHud; UsableByPlayer = builder.UsableByPlayer; RagdollRootBody = builder.RagdollRootBody; InitialAnimation = builder.InitialAnimation; PhysicalMaterial = builder.PhysicalMaterial; JumpForce = builder.JumpForce; FeetIKSettings = new Dictionary<MyCharacterMovementEnum,MyFeetIKSettings>(); if (builder.IKSettings != null) { foreach (var feetSettings in builder.IKSettings) { string[] states = feetSettings.MovementState.Split(','); foreach (string stateSet in states) { string stateDef = stateSet.Trim(); if (stateDef != "") { Debug.Assert(Enum.GetNames(typeof(MyCharacterMovementEnum)).Contains(stateDef), "State " + stateDef + " is not defined in Character Movement States"); MyCharacterMovementEnum state; if (Enum.TryParse(stateDef, true, out state)) { MyFeetIKSettings fSettings = new MyFeetIKSettings(); fSettings.Enabled = feetSettings.Enabled; fSettings.AboveReachableDistance = feetSettings.AboveReachableDistance; fSettings.BelowReachableDistance = feetSettings.BelowReachableDistance; fSettings.VerticalShiftDownGain = feetSettings.VerticalShiftDownGain; fSettings.VerticalShiftUpGain = feetSettings.VerticalShiftUpGain; fSettings.FootSize = new Vector3(feetSettings.FootWidth, feetSettings.AnkleHeight, feetSettings.FootLenght); FeetIKSettings.Add(state, fSettings); } } } } } SuitResourceStorage = builder.SuitResourceStorage; Jetpack = builder.Jetpack; if (builder.BoneSets != null) { BoneSets = builder.BoneSets.ToDictionary(x => x.Name, x => x.Bones.Split(' ')); } if (builder.BoneLODs != null) { BoneLODs = builder.BoneLODs.ToDictionary(x => Convert.ToSingle(x.Name), x => x.Bones.Split(' ')); } if (builder.AnimationMappings != null) { AnimationNameToSubtypeName = builder.AnimationMappings.ToDictionary(mapping => mapping.Name, mapping => mapping.AnimationSubtypeName); } if (builder.RagdollBonesMappings != null) { RagdollBonesMappings = builder.RagdollBonesMappings.ToDictionary(x => x.Name, x => new RagdollBoneSet(x.Bones, x.CollisionRadius)); } if (builder.RagdollPartialSimulations != null) { RagdollPartialSimulations = builder.RagdollPartialSimulations.ToDictionary(x => x.Name, x => x.Bones.Split(' ')); } Mass = builder.Mass; ImpulseLimit = builder.ImpulseLimit; VerticalPositionFlyingOnly = builder.VerticalPositionFlyingOnly; UseOnlyWalking = builder.UseOnlyWalking; MaxSlope = builder.MaxSlope; MaxSprintSpeed = builder.MaxSprintSpeed; MaxRunSpeed = builder.MaxRunSpeed; MaxBackrunSpeed = builder.MaxBackrunSpeed; MaxRunStrafingSpeed = builder.MaxRunStrafingSpeed; MaxWalkSpeed = builder.MaxWalkSpeed; MaxBackwalkSpeed = builder.MaxBackwalkSpeed; MaxWalkStrafingSpeed = builder.MaxWalkStrafingSpeed; MaxCrouchWalkSpeed = builder.MaxCrouchWalkSpeed; MaxCrouchBackwalkSpeed = builder.MaxCrouchBackwalkSpeed; MaxCrouchStrafingSpeed = builder.MaxCrouchStrafingSpeed; CharacterHeadSize = builder.CharacterHeadSize; CharacterHeadHeight = builder.CharacterHeadHeight; CharacterCollisionScale = builder.CharacterCollisionScale; CharacterCollisionWidth = builder.CharacterCollisionWidth; CharacterCollisionHeight = builder.CharacterCollisionHeight; CharacterCollisionCrouchHeight = builder.CharacterCollisionCrouchHeight; if (builder.Inventory == null) { InventoryDefinition = new MyObjectBuilder_InventoryDefinition(); } else { InventoryDefinition = builder.Inventory; } if (builder.EnabledComponents != null) EnabledComponents = builder.EnabledComponents.Split(' ').ToList(); EnableSpawnInventoryAsContainer = builder.EnableSpawnInventoryAsContainer; if (EnableSpawnInventoryAsContainer) { Debug.Assert(builder.InventorySpawnContainerId.HasValue, "Enabled spawning inventory as container, but type id is null"); if (builder.InventorySpawnContainerId.HasValue) { InventorySpawnContainerId = builder.InventorySpawnContainerId.Value; } SpawnInventoryOnBodyRemoval = builder.SpawnInventoryOnBodyRemoval; } LootingTime = builder.LootingTime; DeadBodyShape = builder.DeadBodyShape; AnimationController = builder.AnimationController; MaxForce = builder.MaxForce; }
void SwitchToWeaponInternal(MyDefinitionId? gunId) { GridSelectionSystem.SwitchTo(gunId, m_singleWeaponMode); m_selectedGunId = gunId; Debug.Assert(gunId != null, "gunType Should not be null when switching weapon. (Cestmir)"); if (ControllerInfo.IsLocallyHumanControlled()) { if (m_weaponSelectedNotification == null) m_weaponSelectedNotification = new MyHudNotification(MySpaceTexts.NotificationSwitchedToWeapon); m_weaponSelectedNotification.SetTextFormatArguments(MyDeviceBase.GetGunNotificationName(m_selectedGunId.Value)); MyHud.Notifications.Add(m_weaponSelectedNotification); } }
public virtual void Init(MyObjectBuilder_EntityBase objectBuilder) { ProfilerShort.Begin("MyEntity.Init(objectBuilder)"); MarkedForClose = false; Closed = false; this.Render.PersistentFlags = MyPersistentEntityFlags2.CastShadows; if (objectBuilder != null) { if (objectBuilder.EntityDefinitionId.HasValue) { DefinitionId = objectBuilder.EntityDefinitionId; InitFromDefinition(objectBuilder, DefinitionId.Value); } if (objectBuilder.PositionAndOrientation.HasValue) { var posAndOrient = objectBuilder.PositionAndOrientation.Value; MatrixD matrix = MatrixD.CreateWorld(posAndOrient.Position, posAndOrient.Forward, posAndOrient.Up); MyUtils.AssertIsValid(matrix); PositionComp.SetWorldMatrix((MatrixD)matrix); if (MyPerGameSettings.LimitedWorld) { ClampToWorld(); } } // Do not copy EntityID if it gets overwritten later. It might // belong to some existing entity that we're making copy of. if (objectBuilder.EntityId != 0) this.EntityId = objectBuilder.EntityId; this.Name = objectBuilder.Name; this.Render.PersistentFlags = objectBuilder.PersistentFlags; this.Components.Deserialize(objectBuilder.ComponentContainer); } AllocateEntityID(); this.InScene = false; MyEntities.SetEntityName(this, false); if (SyncFlag) { CreateSync(); } GameLogic.Init(objectBuilder); ProfilerShort.End(); }
protected override void Init(MyObjectBuilder_DefinitionBase objectBuilder) { base.Init(objectBuilder); var builder = (MyObjectBuilder_CharacterDefinition)objectBuilder; Name = builder.Name; Model = builder.Model; ReflectorTexture = builder.ReflectorTexture; LeftGlare = builder.LeftGlare; RightGlare = builder.RightGlare; LeftLightBone = builder.LeftLightBone; RightLightBone = builder.RightLightBone; LightOffset = builder.LightOffset; LightGlareSize = builder.LightGlareSize; HeadBone = builder.HeadBone; Camera3rdBone = builder.Camera3rdBone; LeftHandIKStartBone = builder.LeftHandIKStartBone; LeftHandIKEndBone = builder.LeftHandIKEndBone; RightHandIKStartBone = builder.RightHandIKStartBone; RightHandIKEndBone = builder.RightHandIKEndBone; WeaponBone = builder.WeaponBone; LeftHandItemBone = builder.LeftHandItemBone; RighHandItemBone = builder.RightHandItemBone; Skeleton = builder.Skeleton; LeftForearmBone = builder.LeftForearmBone; LeftUpperarmBone = builder.LeftUpperarmBone; RightForearmBone = builder.RightForearmBone; RightUpperarmBone = builder.RightUpperarmBone; SpineBone = builder.SpineBone; BendMultiplier1st = builder.BendMultiplier1st; BendMultiplier3rd = builder.BendMultiplier3rd; MaterialsDisabledIn1st = builder.MaterialsDisabledIn1st; FeetIKEnabled = builder.FeetIKEnabled; ModelRootBoneName = builder.ModelRootBoneName; LeftHipBoneName = builder.LeftHipBoneName; LeftKneeBoneName = builder.LeftKneeBoneName; LeftAnkleBoneName = builder.LeftAnkleBoneName; RightHipBoneName = builder.RightHipBoneName; RightKneeBoneName = builder.RightKneeBoneName; RightAnkleBoneName = builder.RightAnkleBoneName; UsesAtmosphereDetector = builder.UsesAtmosphereDetector; UsesReverbDetector = builder.UsesReverbDetector; NeedsOxygen = builder.NeedsOxygen; OxygenConsumptionMultiplier = builder.OxygenConsumptionMultiplier; OxygenConsumption = builder.OxygenConsumption; PressureLevelForLowDamage = builder.PressureLevelForLowDamage; DamageAmountAtZeroPressure = builder.DamageAmountAtZeroPressure; RagdollDataFile = builder.RagdollDataFile; //HelmetVariation = builder.HelmetVariation; JumpSoundName = builder.JumpSoundName; JetpackIdleSoundName = builder.JetpackIdleSoundName; JetpackRunSoundName = builder.JetpackRunSoundName; CrouchDownSoundName = builder.CrouchDownSoundName; CrouchUpSoundName = builder.CrouchUpSoundName; PainSoundName = builder.PainSoundName; SuffocateSoundName = builder.SuffocateSoundName; DeathSoundName = builder.DeathSoundName; DeathBySuffocationSoundName = builder.DeathBySuffocationSoundName; IronsightActSoundName = builder.IronsightActSoundName; IronsightDeactSoundName = builder.IronsightDeactSoundName; FastFlySoundName = builder.FastFlySoundName; HelmetOxygenNormalSoundName = builder.HelmetOxygenNormalSoundName; HelmetOxygenLowSoundName = builder.HelmetOxygenLowSoundName; HelmetOxygenCriticalSoundName = builder.HelmetOxygenCriticalSoundName; HelmetOxygenNoneSoundName = builder.HelmetOxygenNoneSoundName; MovementSoundName = builder.MovementSoundName; LoopingFootsteps = builder.LoopingFootsteps; VisibleOnHud = builder.VisibleOnHud; UsableByPlayer = builder.UsableByPlayer; RagdollRootBody = builder.RagdollRootBody; InitialAnimation = builder.InitialAnimation; PhysicalMaterial = builder.PhysicalMaterial; JumpForce = builder.JumpForce; RotationToSupport = builder.RotationToSupport; FeetIKSettings = new Dictionary <MyCharacterMovementEnum, MyFeetIKSettings>(); if (builder.IKSettings != null) { foreach (var feetSettings in builder.IKSettings) { string[] states = feetSettings.MovementState.Split(','); foreach (string stateSet in states) { string stateDef = stateSet.Trim(); if (stateDef != "") { Debug.Assert(Enum.GetNames(typeof(MyCharacterMovementEnum)).Contains(stateDef), "State " + stateDef + " is not defined in Character Movement States"); MyCharacterMovementEnum state; if (Enum.TryParse(stateDef, true, out state)) { MyFeetIKSettings fSettings = new MyFeetIKSettings(); fSettings.Enabled = feetSettings.Enabled; fSettings.AboveReachableDistance = feetSettings.AboveReachableDistance; fSettings.BelowReachableDistance = feetSettings.BelowReachableDistance; fSettings.VerticalShiftDownGain = feetSettings.VerticalShiftDownGain; fSettings.VerticalShiftUpGain = feetSettings.VerticalShiftUpGain; fSettings.FootSize = new Vector3(feetSettings.FootWidth, feetSettings.AnkleHeight, feetSettings.FootLenght); FeetIKSettings.Add(state, fSettings); } } } } } SuitResourceStorage = builder.SuitResourceStorage; Jetpack = builder.Jetpack; if (builder.BoneSets != null) { BoneSets = builder.BoneSets.ToDictionary(x => x.Name, x => x.Bones.Split(' ')); } if (builder.BoneLODs != null) { BoneLODs = builder.BoneLODs.ToDictionary(x => Convert.ToSingle(x.Name), x => x.Bones.Split(' ')); } if (builder.AnimationMappings != null) { AnimationNameToSubtypeName = builder.AnimationMappings.ToDictionary(mapping => mapping.Name, mapping => mapping.AnimationSubtypeName); } if (builder.RagdollBonesMappings != null) { RagdollBonesMappings = builder.RagdollBonesMappings.ToDictionary(x => x.Name, x => new RagdollBoneSet(x.Bones, x.CollisionRadius)); } if (builder.RagdollPartialSimulations != null) { RagdollPartialSimulations = builder.RagdollPartialSimulations.ToDictionary(x => x.Name, x => x.Bones.Split(' ')); } Mass = builder.Mass; ImpulseLimit = builder.ImpulseLimit; VerticalPositionFlyingOnly = builder.VerticalPositionFlyingOnly; UseOnlyWalking = builder.UseOnlyWalking; MaxSlope = builder.MaxSlope; MaxSprintSpeed = builder.MaxSprintSpeed; MaxRunSpeed = builder.MaxRunSpeed; MaxBackrunSpeed = builder.MaxBackrunSpeed; MaxRunStrafingSpeed = builder.MaxRunStrafingSpeed; MaxWalkSpeed = builder.MaxWalkSpeed; MaxBackwalkSpeed = builder.MaxBackwalkSpeed; MaxWalkStrafingSpeed = builder.MaxWalkStrafingSpeed; MaxCrouchWalkSpeed = builder.MaxCrouchWalkSpeed; MaxCrouchBackwalkSpeed = builder.MaxCrouchBackwalkSpeed; MaxCrouchStrafingSpeed = builder.MaxCrouchStrafingSpeed; CharacterHeadSize = builder.CharacterHeadSize; CharacterHeadHeight = builder.CharacterHeadHeight; CharacterCollisionScale = builder.CharacterCollisionScale; CharacterCollisionWidth = builder.CharacterCollisionWidth; CharacterCollisionHeight = builder.CharacterCollisionHeight; CharacterCollisionCrouchHeight = builder.CharacterCollisionCrouchHeight; if (builder.Inventory == null) { InventoryDefinition = new MyObjectBuilder_InventoryDefinition(); } else { InventoryDefinition = builder.Inventory; } if (builder.EnabledComponents != null) { EnabledComponents = builder.EnabledComponents.Split(' ').ToList(); } EnableSpawnInventoryAsContainer = builder.EnableSpawnInventoryAsContainer; if (EnableSpawnInventoryAsContainer) { Debug.Assert(builder.InventorySpawnContainerId.HasValue, "Enabled spawning inventory as container, but type id is null"); if (builder.InventorySpawnContainerId.HasValue) { InventorySpawnContainerId = builder.InventorySpawnContainerId.Value; } SpawnInventoryOnBodyRemoval = builder.SpawnInventoryOnBodyRemoval; } LootingTime = builder.LootingTime; DeadBodyShape = builder.DeadBodyShape; AnimationController = builder.AnimationController; MaxForce = builder.MaxForce; }
public void AttachPilot(MyCharacter pilot, bool storeOriginalPilotWorld = true, bool calledFromInit = false, bool merged = false) { System.Diagnostics.Debug.Assert(pilot != null); System.Diagnostics.Debug.Assert(m_pilot == null); if (Sync.IsServer) { MyMultiplayer.ReplicateImmediatelly(MyExternalReplicable.FindByObject(pilot), MyExternalReplicable.FindByObject(this.CubeGrid)); } MyAnalyticsHelper.ReportActivityStart(pilot, "cockpit", "cockpit", string.Empty, string.Empty); m_pilot = pilot; m_pilot.OnMarkForClose += m_pilotClosedHandler; m_pilot.IsUsing = this; if (storeOriginalPilotWorld) { m_pilotRelativeWorld.Value = (Matrix)MatrixD.Multiply(pilot.WorldMatrix, this.PositionComp.WorldMatrixNormalizedInv); } if (pilot.InScene) MyEntities.Remove(pilot); m_pilot.Physics.Enabled = false; m_pilot.PositionComp.SetWorldMatrix(WorldMatrix, this); m_pilot.Physics.Clear(); //m_pilot.SetPosition(GetPosition() - WorldMatrix.Forward * 0.5f); if (!Hierarchy.Children.Any(x => x.Entity == m_pilot)) //may contain after load Hierarchy.AddChild(m_pilot, true, true); var gunEntity = m_pilot.CurrentWeapon as MyEntity; if (gunEntity != null && !m_forgetTheseWeapons.Contains(m_pilot.CurrentWeapon.DefinitionId)) { m_pilotGunDefinition = m_pilot.CurrentWeapon.DefinitionId; } else m_pilotGunDefinition = null; MyAnimationDefinition animationDefinition; MyDefinitionId id = new MyDefinitionId(typeof(MyObjectBuilder_AnimationDefinition), BlockDefinition.CharacterAnimation); if (!MyDefinitionManager.Static.TryGetDefinition(id, out animationDefinition) && !MyFileSystem.FileExists(BlockDefinition.CharacterAnimation)) { BlockDefinition.CharacterAnimation = null; } m_pilotFirstPerson = pilot.IsInFirstPersonView; PlacePilotInSeat(pilot); m_pilot.SuitBattery.ResourceSink.TemporaryConnectedEntity = this; m_rechargeSocket.PlugIn(m_pilot.SuitBattery.ResourceSink); if (pilot.ControllerInfo.Controller != null) { Sync.Players.SetPlayerToCockpit(pilot.ControllerInfo.Controller.Player, this); } // Control should be handled elsewhere if we initialize the grid in the Init(...) if (!calledFromInit) { GiveControlToPilot(); m_pilot.SwitchToWeapon(null); } if (Sync.IsServer) { m_attachedCharacterId.Value = m_pilot.EntityId; m_storeOriginalPlayerWorldMatrix.Value = storeOriginalPilotWorld; } var jetpack = m_pilot.JetpackComp; if (jetpack != null) { m_pilotJetpackEnabledBackup = jetpack.TurnedOn; m_pilot.JetpackComp.TurnOnJetpack(false); } else { m_pilotJetpackEnabledBackup = null; } m_lastPilot = pilot; if (GetInCockpitSound != MySoundPair.Empty && !calledFromInit && !merged) PlayUseSound(true); m_playIdleSound = true; if(MyVisualScriptLogicProvider.PlayerEnteredCockpit != null) MyVisualScriptLogicProvider.PlayerEnteredCockpit(Name, pilot.GetPlayerIdentityId(), CubeGrid.Name); }
public virtual void Init(MyObjectBuilder_EntityBase objectBuilder) { ProfilerShort.Begin("MyEntity.Init(objectBuilder)"); MarkedForClose = false; Closed = false; this.Render.PersistentFlags = MyPersistentEntityFlags2.CastShadows; if (objectBuilder != null) { if (objectBuilder.EntityId != 0) this.EntityId = objectBuilder.EntityId; else AllocateEntityID(); DefinitionId = objectBuilder.GetId(); if (objectBuilder.EntityDefinitionId != null) // backward compatibility { Debug.Assert(objectBuilder.SubtypeName == null || objectBuilder.SubtypeName == objectBuilder.EntityDefinitionId.Value.SubtypeName); DefinitionId = objectBuilder.EntityDefinitionId.Value; } if (objectBuilder.PositionAndOrientation.HasValue) { var posAndOrient = objectBuilder.PositionAndOrientation.Value; MatrixD matrix = MatrixD.CreateWorld(posAndOrient.Position, posAndOrient.Forward, posAndOrient.Up); MyUtils.AssertIsValid(matrix); PositionComp.SetWorldMatrix((MatrixD)matrix); ClampToWorld(); } this.Name = objectBuilder.Name; this.Render.PersistentFlags = objectBuilder.PersistentFlags; // This needs to be called after Entity has it's valid EntityID so components when are initiliazed or added to container, they get valid EntityID InitComponentsExtCallback(this.Components, DefinitionId.Value.TypeId, DefinitionId.Value.SubtypeId, objectBuilder.ComponentContainer); } else { AllocateEntityID(); } this.InScene = false; MyEntitiesInterface.SetEntityName(this, false); if (SyncFlag) { CreateSync(); } GameLogic.Init(objectBuilder); ProfilerShort.End(); }
void SwitchToWeaponInternal(MyDefinitionId? weapon, bool updateSync) { if (updateSync) { RequestSwitchToWeapon(weapon, null, 0); return; } StopCurrentWeaponShooting(); MyAnalyticsHelper.ReportActivityEnd(this, "item_equip"); if (weapon.HasValue) { // var gun = GetWeaponType(weapon.Value.TypeId); SwitchToWeaponInternal(weapon); string[] weaponNameParts = ((System.Type)weapon.Value.TypeId).Name.Split('_'); MyAnalyticsHelper.ReportActivityStart(this, "item_equip", "character", "ship_item_usage", weaponNameParts.Length > 1 ? weaponNameParts[1] : weaponNameParts[0]); } else { m_selectedGunId = null; GridSelectionSystem.SwitchTo(null); } }
/// <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; } if (sync) { MySyncDestructions.CreateFracturePiece((Sandbox.Common.ObjectBuilders.MyObjectBuilder_FracturedPiece)fracturedPiece.GetObjectBuilder()); } return(fracturedPiece); }
public abstract void Activate(MyDefinitionId?blockDefinitionId = null);
/// <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 void AttachPilot(MyCharacter pilot, bool storeOriginalPilotWorld = true, bool calledFromInit = false) { System.Diagnostics.Debug.Assert(pilot != null); System.Diagnostics.Debug.Assert(m_pilot == null); MyAnalyticsHelper.ReportActivityStart(pilot, "cockpit", "cockpit", string.Empty, string.Empty); m_pilot = pilot; m_pilot.OnMarkForClose += m_pilotClosedHandler; m_pilot.IsUsing = this; StartLoopSound(); if (storeOriginalPilotWorld) { m_pilotRelativeWorld.Value = (Matrix)MatrixD.Multiply(pilot.WorldMatrix, this.PositionComp.WorldMatrixNormalizedInv); } if (pilot.InScene) MyEntities.Remove(pilot); m_pilot.Physics.Enabled = false; m_pilot.PositionComp.SetWorldMatrix(WorldMatrix); m_pilot.Physics.Clear(); //m_pilot.SetPosition(GetPosition() - WorldMatrix.Forward * 0.5f); Hierarchy.AddChild(m_pilot, true, true); var gunEntity = m_pilot.CurrentWeapon as MyEntity; if (gunEntity != null) { m_pilotGunDefinition = m_pilot.CurrentWeapon.DefinitionId; } else m_pilotGunDefinition = null; MyAnimationDefinition animationDefinition; MyDefinitionId id = new MyDefinitionId(typeof(MyObjectBuilder_AnimationDefinition), BlockDefinition.CharacterAnimation); if (!MyDefinitionManager.Static.TryGetDefinition(id, out animationDefinition) && !MyFileSystem.FileExists(BlockDefinition.CharacterAnimation)) { BlockDefinition.CharacterAnimation = null; } PlacePilotInSeat(pilot); m_pilot.SuitBattery.ResourceSink.TemporaryConnectedEntity = this; m_rechargeSocket.PlugIn(m_pilot.SuitBattery.ResourceSink); if (pilot.ControllerInfo.Controller != null) { Sync.Players.SetPlayerToCockpit(pilot.ControllerInfo.Controller.Player, this); } // Control should be handled elsewhere if we initialize the grid in the Init(...) if (!calledFromInit) GiveControlToPilot(); m_pilot.SwitchToWeapon(null); if (Sync.IsServer) { m_attachedCharacterId.Value = m_pilot.EntityId; m_storeOriginalPlayerWorldMatrix.Value = storeOriginalPilotWorld; } }
protected override unsafe void Init(MyObjectBuilder_DefinitionBase builder) { base.Init(builder); MyObjectBuilder_PlanetGeneratorDefinition definition = builder as MyObjectBuilder_PlanetGeneratorDefinition; if ((definition.InheritFrom != null) && (definition.InheritFrom.Length > 0)) { this.InheritFrom(definition.InheritFrom); } if (definition.Environment != null) { this.EnvironmentId = new MyDefinitionId?(definition.Environment.Value); } else { this.m_pgob = definition; } if (definition.PlanetMaps != null) { this.PlanetMaps = definition.PlanetMaps.Value; } if (definition.HasAtmosphere != null) { this.HasAtmosphere = definition.HasAtmosphere.Value; } if (definition.CloudLayers != null) { this.CloudLayers = definition.CloudLayers; } if (definition.SoundRules != null) { this.SoundRules = new MyPlanetEnvironmentalSoundRule[definition.SoundRules.Length]; for (int i = 0; i < definition.SoundRules.Length; i++) { MyPlanetEnvironmentalSoundRule rule = new MyPlanetEnvironmentalSoundRule { Latitude = definition.SoundRules[i].Latitude, Height = definition.SoundRules[i].Height, SunAngleFromZenith = definition.SoundRules[i].SunAngleFromZenith, EnvironmentSound = MyStringHash.GetOrCompute(definition.SoundRules[i].EnvironmentSound) }; rule.Latitude.ConvertToSine(); rule.SunAngleFromZenith.ConvertToCosine(); this.SoundRules[i] = rule; } } if (definition.MusicCategories != null) { this.MusicCategories = definition.MusicCategories; } if (definition.HillParams != null) { this.HillParams = definition.HillParams.Value; } if (definition.Atmosphere != null) { this.Atmosphere = definition.Atmosphere; } if (definition.GravityFalloffPower != null) { this.GravityFalloffPower = definition.GravityFalloffPower.Value; } if (definition.HostileAtmosphereColorShift != null) { this.HostileAtmosphereColorShift = definition.HostileAtmosphereColorShift; } if (definition.MaterialsMaxDepth != null) { this.MaterialsMaxDepth = definition.MaterialsMaxDepth.Value; } if (definition.MaterialsMinDepth != null) { this.MaterialsMinDepth = definition.MaterialsMinDepth.Value; } if ((definition.CustomMaterialTable != null) && (definition.CustomMaterialTable.Length != 0)) { this.SurfaceMaterialTable = new MyPlanetMaterialDefinition[definition.CustomMaterialTable.Length]; for (int i = 0; i < this.SurfaceMaterialTable.Length; i++) { this.SurfaceMaterialTable[i] = definition.CustomMaterialTable[i].Clone() as MyPlanetMaterialDefinition; if ((this.SurfaceMaterialTable[i].Material == null) && !this.SurfaceMaterialTable[i].HasLayers) { MyLog.Default.WriteLine("Custom material does not contain any material ids."); } else if (this.SurfaceMaterialTable[i].HasLayers) { float depth = this.SurfaceMaterialTable[i].Layers[0].Depth; for (int j = 1; j < this.SurfaceMaterialTable[i].Layers.Length; j++) { float *singlePtr1 = (float *)ref this.SurfaceMaterialTable[i].Layers[j].Depth; singlePtr1[0] += depth; depth = this.SurfaceMaterialTable[i].Layers[j].Depth; } } } } if ((definition.DistortionTable != null) && (definition.DistortionTable.Length != 0)) { this.DistortionTable = definition.DistortionTable; } if (definition.DefaultSurfaceMaterial != null) { this.DefaultSurfaceMaterial = definition.DefaultSurfaceMaterial; } if (definition.DefaultSubSurfaceMaterial != null) { this.DefaultSubSurfaceMaterial = definition.DefaultSubSurfaceMaterial; } if (definition.SurfaceGravity != null) { this.SurfaceGravity = definition.SurfaceGravity.Value; } if (definition.AtmosphereSettings != null) { this.AtmosphereSettings = definition.AtmosphereSettings; } this.FolderName = (definition.FolderName != null) ? definition.FolderName : definition.Id.SubtypeName; if ((definition.ComplexMaterials != null) && (definition.ComplexMaterials.Length != 0)) { this.MaterialGroups = new MyPlanetMaterialGroup[definition.ComplexMaterials.Length]; int index = 0; while (index < definition.ComplexMaterials.Length) { this.MaterialGroups[index] = definition.ComplexMaterials[index].Clone() as MyPlanetMaterialGroup; MyPlanetMaterialGroup group = this.MaterialGroups[index]; MyPlanetMaterialPlacementRule[] materialRules = group.MaterialRules; List <int> indices = new List <int>(); int num6 = 0; while (true) { if (num6 >= materialRules.Length) { if (indices.Count > 0) { materialRules = materialRules.RemoveIndices <MyPlanetMaterialPlacementRule>(indices); } group.MaterialRules = materialRules; index++; break; } if ((materialRules[num6].Material == null) && ((materialRules[num6].Layers == null) || (materialRules[num6].Layers.Length == 0))) { MyLog.Default.WriteLine("Material rule does not contain any material ids."); indices.Add(num6); } else { if ((materialRules[num6].Layers != null) && (materialRules[num6].Layers.Length != 0)) { float depth = materialRules[num6].Layers[0].Depth; for (int i = 1; i < materialRules[num6].Layers.Length; i++) { float *singlePtr2 = (float *)ref materialRules[num6].Layers[i].Depth; singlePtr2[0] += depth; depth = materialRules[num6].Layers[i].Depth; } } materialRules[num6].Slope.ConvertToCosine(); materialRules[num6].Latitude.ConvertToSine(); materialRules[num6].Longitude.ConvertToCosineLongitude(); } num6++; } } } if (definition.OreMappings != null) { this.OreMappings = definition.OreMappings; } if (definition.MaterialBlending != null) { this.MaterialBlending = definition.MaterialBlending.Value; } if (definition.SurfaceDetail != null) { this.Detail = definition.SurfaceDetail; } if (definition.AnimalSpawnInfo != null) { this.AnimalSpawnInfo = definition.AnimalSpawnInfo; } if (definition.NightAnimalSpawnInfo != null) { this.NightAnimalSpawnInfo = definition.NightAnimalSpawnInfo; } if (definition.SectorDensity != null) { this.SectorDensity = definition.SectorDensity.Value; } MyObjectBuilder_PlanetMapProvider mapProvider = definition.MapProvider; if (definition.MapProvider == null) { MyObjectBuilder_PlanetMapProvider local1 = definition.MapProvider; MyObjectBuilder_PlanetTextureMapProvider provider1 = new MyObjectBuilder_PlanetTextureMapProvider(); provider1.Path = this.FolderName; mapProvider = provider1; } this.MapProvider = mapProvider; this.MesherPostprocessing = definition.MesherPostprocessing; if (this.MesherPostprocessing == null) { MyLog.Default.Warning("PERFORMANCE WARNING: Postprocessing voxel triangle decimation steps not defined for " + this, Array.Empty <object>()); } this.MinimumSurfaceLayerDepth = definition.MinimumSurfaceLayerDepth; }
public bool RemovePilot() { if (m_pilot == null) return true; MyAnalyticsHelper.ReportActivityEnd(m_pilot, "Cockpit"); System.Diagnostics.Debug.Assert(m_pilot.Physics != null); if (m_pilot.Physics == null) { //probably already closed pilot left in cockpit m_pilot = null; return true; } StopLoopSound(); m_pilot.OnMarkForClose -= m_pilotClosedHandler; if (m_pilot.IsDead) { if (this.ControllerInfo.Controller != null) this.SwitchControl(m_pilot); Hierarchy.RemoveChild(m_pilot); MyEntities.Add(m_pilot); m_pilot.WorldMatrix = WorldMatrix; m_pilotGunDefinition = null; m_rechargeSocket.Unplug(); m_pilot.SuitBattery.ResourceSink.TemporaryConnectedEntity = null; m_pilot = null; return true; } bool usePilotOriginalWorld = false; MatrixD placementMatrix = MatrixD.Identity; if (m_pilotRelativeWorld.Value.HasValue) { placementMatrix = MatrixD.Multiply((MatrixD)m_pilotRelativeWorld.Value.Value, this.WorldMatrix); if (m_pilot.CanPlaceCharacter(ref placementMatrix)) usePilotOriginalWorld = true; } Vector3D? allowedPosition = null; if (!usePilotOriginalWorld) { allowedPosition = FindFreeNeighbourPosition(); if (!allowedPosition.HasValue) allowedPosition = PositionComp.GetPosition(); } RemovePilotFromSeat(m_pilot); EndShootAll(); if (usePilotOriginalWorld || allowedPosition.HasValue) { Hierarchy.RemoveChild(m_pilot); MyEntities.Add(m_pilot); m_pilot.Physics.Enabled = true; m_rechargeSocket.Unplug(); m_pilot.SuitBattery.ResourceSink.TemporaryConnectedEntity = null; m_pilot.Stand(); // allowedPosition is in center of character MatrixD placeMatrix = (usePilotOriginalWorld) ? placementMatrix : MatrixD.CreateWorld(allowedPosition.Value - WorldMatrix.Up, WorldMatrix.Forward, WorldMatrix.Up); if (m_pilot.Physics.CharacterProxy != null) m_pilot.Physics.CharacterProxy.ImmediateSetWorldTransform = true; if (!MyEntities.CloseAllowed) { m_pilot.PositionComp.SetWorldMatrix(placeMatrix, this); } if (m_pilot.Physics.CharacterProxy != null) m_pilot.Physics.CharacterProxy.ImmediateSetWorldTransform = false; if (Parent != null && Parent.Physics != null) // Cockpit could be removing the pilot after it no longer belongs to any grid (e.g. during a split) { m_pilot.Physics.LinearVelocity = Parent.Physics.LinearVelocity; if (Parent.Physics.LinearVelocity.LengthSquared() > 100) { var jetpack = m_pilot.JetpackComp; if (jetpack != null) { jetpack.EnableDampeners(false); jetpack.TurnOnJetpack(true); } } } if (this.ControllerInfo.Controller != null) { this.SwitchControl(m_pilot); } if (m_pilotGunDefinition != null) m_pilot.SwitchToWeapon(m_pilotGunDefinition); else m_pilot.SwitchToWeapon(null); var pilot = m_pilot; m_pilot = null; if (MySession.Static.CameraController == this) { MySession.Static.SetCameraController(MyCameraControllerEnum.Entity, pilot); } return true; } else { //System.Diagnostics.Debug.Assert(false, "There is no place where to put astronaut. Kill him!"); } return false; }