/// <summary> /// Creates a missile with homing and target finding capabilities. /// </summary> public GuidedMissile(IMyEntity missile, IMyCubeBlock firedBy, TargetingOptions opt, Ammo ammo, LastSeen initialTarget = null, bool isSlave = false) : base(missile, firedBy) { myLogger = new Logger("GuidedMissile", () => missile.getBestName(), () => m_stage.ToString()); myAmmo = ammo; myDescr = ammo.Description; if (ammo.Description.HasAntenna) myAntenna = new MissileAntenna(missile); TryHard = true; AllGuidedMissiles.Add(this); missile.OnClose += missile_OnClose; if (myAmmo.IsCluster && !isSlave) myCluster = new Cluster(myAmmo.MagazineDefinition.Capacity - 1); accelerationPerUpdate = (myDescr.Acceleration + myAmmo.MissileDefinition.MissileAcceleration) / 60f; addSpeedPerUpdate = myDescr.Acceleration / 60f; Options = opt; Options.TargetingRange = ammo.Description.TargetRange; myTargetSeen = initialTarget; myLogger.debugLog("Options: " + Options, "GuidedMissile()"); //myLogger.debugLog("AmmoDescription: \n" + MyAPIGateway.Utilities.SerializeToXML<Ammo.AmmoDescription>(myDescr), "GuidedMissile()"); }
public LastSeenTarget(LastSeen seen, IMyCubeBlock block = null) { m_lastSeen = seen; m_block = block; m_lastPostion = m_lastSeen.LastKnownPosition; m_lastPositionUpdate = m_lastSeen.LastSeenAt; }
/// <summary> /// does not check seen for isValid /// </summary> /// <param name="seen"></param> /// <param name="forced">for receiving LastSeen for self</param> public void receive(LastSeen seen, bool forced = false) { if (seen.Entity == CubeBlock.CubeGrid && !forced) { //{ // alwaysLog("do not tell me about myself: ", "receive()", Logger.severity.TRACE); return; } //} LastSeen toUpdate; if (myLastSeen.TryGetValue(seen.Entity.EntityId, out toUpdate)) { if (seen.update(ref toUpdate)) { //if (toUpdate.Entity.getBestName().looseContains("Leo"))// toUpdate.LastSeenAt.secondsSince() > 3) // log("updating: " + seen.Entity.getBestName(), "receive()", Logger.severity.TRACE); myLastSeen.Remove(toUpdate.Entity.EntityId); myLastSeen.Add(toUpdate.Entity.EntityId, toUpdate); } //else // if (toUpdate.Entity.getBestName().looseContains("Leo")) // log("not updating: " + seen.Entity.getBestName(), "receive()", Logger.severity.TRACE); } else { //{ myLastSeen.Add(seen.Entity.EntityId, seen); } // log("got a new last seen: " + seen.Entity.DisplayName, "receive()", Logger.severity.TRACE); //} }
/// <summary> /// <para>Add a LastSeen to this storage or updates an existing one. LastSeen will be pushed to connected storages.</para> /// <para>Not optimized for use within a loop.</para> /// </summary> /// <param name="seen">LastSeen data to receive.</param> public void Receive(LastSeen seen) { HashSet <RelayStorage> sendToSet = ResourcePool <HashSet <RelayStorage> > .Get(); try { AddStorage(sendToSet, this); foreach (RelayStorage sto in sendToSet) { using (sto.lock_lastSeen.AcquireExclusiveUsing()) sto.in_Receive(seen); if (sto.m_nextClean_lastSeen <= Globals.UpdateCount) { Log.DebugLog("Running cleanup on last seen", Logger.severity.INFO); sto.ForEachLastSeen(s => { }); } } } finally { sendToSet.Clear(); ResourcePool <HashSet <RelayStorage> > .Return(sendToSet); } }
public void Update(LastSeen seen, IMyCubeBlock block = null) { m_lastSeen = seen; if (block != null) m_block = block; m_lastPostion = m_lastSeen.LastKnownPosition; m_lastPositionUpdate = m_lastSeen.LastSeenAt; }
private void CreateHolo(LastSeen seen) { if (!(seen.Entity is IMyCubeGrid)) { return; } SeenHolo sh; if (m_holoEntities.TryGetValue(seen.Entity.EntityId, out sh)) { sh.Seen = seen; return; } if (!CanDisplay(seen)) { return; } Profiler.StartProfileBlock("CreateHolo.GetObjectBuilder"); MyObjectBuilder_CubeGrid builder = (MyObjectBuilder_CubeGrid)seen.Entity.GetObjectBuilder(); Profiler.EndProfileBlock(); MyEntities.RemapObjectBuilder(builder); builder.IsStatic = false; builder.CreatePhysics = false; builder.EnableSmallToLargeConnections = false; Profiler.StartProfileBlock("CreateHolo.CreateFromObjectBuilder"); MyCubeGrid holo = (MyCubeGrid)MyEntities.CreateFromObjectBuilder(builder); Profiler.EndProfileBlock(); Profiler.StartProfileBlock("CreateHolo.SetupProjection"); SetupProjection(holo); Profiler.EndProfileBlock(); Profiler.StartProfileBlock("CreateHolo.AddEntity"); MyAPIGateway.Entities.AddEntity(holo); Profiler.EndProfileBlock(); Log.DebugLog("created holo for " + seen.Entity.nameWithId() + ", holo: " + holo.nameWithId()); m_holoEntities.Add(seen.Entity.EntityId, new SeenHolo() { Seen = seen, Holo = holo }); MyCubeGrid actual = (MyCubeGrid)seen.Entity; actual.OnBlockAdded += Actual_OnBlockAdded; actual.OnBlockRemoved += Actual_OnBlockRemoved; actual.OnBlockIntegrityChanged += OnBlockIntegrityChanged; }
public sortableLastSeen(Vector3D myPos, LastSeen seen, IMyCubeBlockExtensions.Relations relations) { this.seen = seen; this.relations = relations; TimeSpan sinceLastSeen; predictedPos = seen.predictPosition(out sinceLastSeen); distance = (int)(predictedPos - myPos).Length(); seconds = (int)sinceLastSeen.TotalSeconds; }
/// <summary> /// If necissary, update toUpdate with this. /// </summary> /// <param name="toUpdate">LastSeen that may need an update</param> /// <returns>true iff an update was performed</returns> public bool update(ref LastSeen toUpdate) { if ((!this.EntityHasRadar && toUpdate.EntityHasRadar) || (toUpdate.Info != null && (this.Info == null || this.Info.IsNewerThan(toUpdate.Info))) || (this.isNewerThan(toUpdate))) { LastSeen param = toUpdate; toUpdate = new LastSeen(this, toUpdate); return(true); } return(false); }
/// <summary> /// If necissary, update toUpdate with this. /// </summary> /// <param name="toUpdate">LastSeen that may need an update</param> /// <returns>true iff an update was performed</returns> public bool update(ref LastSeen toUpdate) { if (this.LastSeenAt > toUpdate.LastSeenAt || this.LastBroadcast > toUpdate.LastBroadcast || this.LastJam > toUpdate.LastJam || this.LastRadar > toUpdate.LastRadar || this.RadarInfoTicks() > toUpdate.RadarInfoTicks()) { toUpdate = new LastSeen(this, toUpdate); return(true); } return(false); }
/// <summary> /// <para>Internal receive method. Adds the LastSeen to this storage or updates an existing one.</para> /// <para>lock_m_lastSeen should be exclusively locked before invoking this method.</para> /// </summary> private void in_Receive(LastSeen seen) { LastSeen toUpdate; if (m_lastSeen.TryGetValue(seen.Entity.EntityId, out toUpdate)) { if (seen.update(ref toUpdate)) { m_lastSeen[toUpdate.Entity.EntityId] = toUpdate; } } else { m_lastSeen.Add(seen.Entity.EntityId, seen); } }
public void UpdateAfterSimulation100() { try { if (!myRadioAntenna.IsWorking) return; float radiusSquared; MyObjectBuilder_RadioAntenna antBuilder = CubeBlock.GetObjectBuilderCubeBlock() as MyObjectBuilder_RadioAntenna; if (!antBuilder.EnableBroadcasting) radiusSquared = 0; else radiusSquared = myRadioAntenna.Radius * myRadioAntenna.Radius; LastSeen self = new LastSeen(CubeBlock.CubeGrid, LastSeen.UpdateTime.Broadcasting); Registrar.ForEach((RadioAntenna ant) => { // send antenna self to radio antennae if (CubeBlock.canSendTo(ant.CubeBlock, false, radiusSquared, true)) ant.Receive(self, true); // relay information to friendlies if (CubeBlock.canSendTo(ant.CubeBlock, true, radiusSquared, true)) Relay(ant); }); ForEachLastSeen(seen => { // relay information to friendly players foreach (Player player in Player.AllPlayers) if (CubeBlock.canSendTo(player.myPlayer, true, radiusSquared, true)) player.receive(seen); // relay information to missile antennae Registrar.ForEach((MissileAntenna ant) => { if (CubeBlock.canSendTo(ant.Entity, true, radiusSquared, true)) ant.Receive(seen); }); return false; }); RelayAttached(); } catch (Exception e) { myLogger.alwaysLog("Exception: " + e, "UpdateAfterSimulation100()", Logger.severity.ERROR); } }
private LastSeen(LastSeen first, LastSeen second) { this.Info = RadarInfo.getNewer(first.Info, second.Info); LastSeen newer = first.isNewerThan(second) ? first : second; this.Entity = newer.Entity; this.LastSeenAt = newer.LastSeenAt; this.LastKnownPosition = newer.LastKnownPosition; this.LastKnownVelocity = newer.LastKnownVelocity; this.LastBroadcast = first.LastBroadcast.CompareTo(second.LastBroadcast) > 0 ? first.LastBroadcast : second.LastBroadcast; this.LastRadar = first.LastRadar.CompareTo(second.LastBroadcast) > 0 ? first.LastRadar : second.LastRadar; this.LastJam = first.LastJam.CompareTo(second.LastBroadcast) > 0 ? first.LastJam : second.LastJam; value_isValid = true; }
/// <summary> /// Send a LastSeen to one or more NetworkStorage. Faster than looping through the collection and invoking Receive() for each one. /// </summary> public static void Receive(ICollection<RelayStorage> storage, LastSeen seen) { HashSet<RelayStorage> sendToSet = ResourcePool<HashSet<RelayStorage>>.Pool.Get(); try { foreach (RelayStorage sto in storage) AddStorage(sendToSet, sto); foreach (RelayStorage sto in sendToSet) using (sto.lock_lastSeen.AcquireExclusiveUsing()) sto.in_Receive(seen); } finally { sendToSet.Clear(); ResourcePool<HashSet<RelayStorage>>.Pool.Return(sendToSet); } }
public void UpdateAfterSimulation100() { if (CubeBlock == null || CubeBlock.Closed || CubeBlock.CubeGrid == null) return; try { // send beacon self to radio antenna LastSeen self = new LastSeen(CubeBlock.CubeGrid, LastSeen.UpdateTime.Broadcasting); float radiusSquared = myBeacon.Radius * myBeacon.Radius; Registrar.ForEach((RadioAntenna ant) => { if (CubeBlock.canSendTo(ant.CubeBlock, false, radiusSquared, true)) ant.Receive(self, true); return false; }); } catch (Exception e) { myLogger.alwaysLog("Exception: " + e, "UpdateAfterSimulation100()", Logger.severity.ERROR); } }
/// <summary> /// Gets the radar equipment with the highest power level from a LastSeen. /// </summary> /// <param name="gridLastSeen">LastSeen for the detected grid.</param> /// <param name="strongestEquipment">The equipment with the highest power level.</param> /// <param name="powerLevel">The power level of the equipment.</param> /// <returns>True iff a radar equipment was found.</returns> public static bool GetRadarEquipment(LastSeen gridLastSeen, out IMyCubeBlock strongestEquipment, out float powerLevel) { strongestEquipment = null; powerLevel = 0f; IMyCubeBlock strongest_in = null; float powerLevel_in = 0f; bool recentRadar = gridLastSeen.isRecent_Radar(); bool recentJammer = gridLastSeen.isRecent_Jam(); Registrar.ForEach((RadarEquipment re) => { if (re.CubeBlock.CubeGrid == gridLastSeen.Entity) { if (!re.IsWorking) { return; } float reStr = 0f; if (recentRadar && re.myDefinition.Radar) // PowerLevel_Radar can be > 0 even if it is not a radar { reStr = re.PowerLevel_Radar; } if (recentJammer && re.PowerLevel_Jammer > reStr) { reStr = re.PowerLevel_Jammer; } if (reStr > powerLevel_in) { powerLevel_in = reStr; strongest_in = re.CubeBlock; } } }); strongestEquipment = strongest_in; powerLevel = powerLevel_in; return(strongestEquipment != null); }
private bool CanDisplay(LastSeen seen, out UserSettings.ByteSettingName settingName) { switch (seen.Type) { case LastSeen.EntityType.Character: case LastSeen.EntityType.Grid: switch (myPlayer.IdentityId.getRelationsTo(seen.Entity)) { case ExtensionsRelations.Relations.Enemy: case ExtensionsRelations.Relations.NoOwner: settingName = UserSettings.ByteSettingName.EnemiesOnHUD; return(true); case ExtensionsRelations.Relations.Neutral: settingName = UserSettings.ByteSettingName.NeutralOnHUD; return(true); case ExtensionsRelations.Relations.Faction: settingName = UserSettings.ByteSettingName.FactionOnHUD; return(true); case ExtensionsRelations.Relations.Owner: settingName = UserSettings.ByteSettingName.OwnerOnHUD; return(true); default: settingName = UserSettings.ByteSettingName.EnemiesOnHUD; return(false); } case LastSeen.EntityType.Missile: settingName = UserSettings.ByteSettingName.MissileOnHUD; return(true); default: settingName = UserSettings.ByteSettingName.EnemiesOnHUD; return(false); } }
private bool CanDisplay(LastSeen seen) { if (!CheckRelations(seen.Entity)) { return(false); } TimeSpan time = Globals.ElapsedTime - seen.RadarInfoTime(); if (time > Static.displayAllowed) { if (time > Static.keepInCache) { m_holoEntitiesRemove.Add(seen.Entity.EntityId); } return(false); } float rangeDetection = m_rangeDetection; rangeDetection *= rangeDetection; return(Vector3D.DistanceSquared(m_centreEntity.GetPosition(), seen.Entity.GetCentre()) <= rangeDetection); }
private LastSeen(LastSeen first, LastSeen second) { this.EntityHasRadar = first.EntityHasRadar || second.EntityHasRadar; this.Info = RadarInfo.getNewer(first.Info, second.Info); LastSeen newer; if (first.isNewerThan(second)) { newer = first; } else { newer = second; } this.Entity = newer.Entity; this.LastSeenAt = newer.LastSeenAt; this.LastKnownPosition = newer.LastKnownPosition; this.LastKnownVelocity = newer.LastKnownVelocity; value_isValid = true; }
/// <summary> /// Send a LastSeen to one or more NetworkStorage. Faster than looping through the collection and invoking Receive() for each one. /// </summary> public static void Receive(ICollection <RelayStorage> storage, LastSeen seen) { HashSet <RelayStorage> sendToSet = ResourcePool <HashSet <RelayStorage> > .Get(); try { foreach (RelayStorage sto in storage) { AddStorage(sendToSet, sto); } foreach (RelayStorage sto in sendToSet) { using (sto.lock_lastSeen.AcquireExclusiveUsing()) sto.in_Receive(seen); } } finally { sendToSet.Clear(); ResourcePool <HashSet <RelayStorage> > .Return(sendToSet); } }
private LastSeen(LastSeen first, LastSeen second) { this.Info = first.RadarInfoTicks() > second.RadarInfoTicks() ? first.Info : second.Info; LastSeen newer, older; if (first.LastSeenAt > second.LastSeenAt) { newer = first; older = second; } else { newer = second; older = first; } this.Entity = newer.Entity; this.LastSeenAt = newer.LastSeenAt; this.LastKnownPosition = newer.LastKnownPosition; this.LastKnownVelocity = newer.LastKnownVelocity; this.m_lastBroadcast = new OlderBy(this.LastSeenAt.Ticks, Math.Max(first.LastBroadcast, second.LastBroadcast)); this.m_lastJam = new OlderBy(this.LastSeenAt.Ticks, Math.Max(first.LastJam, second.LastJam)); this.m_lastRadar = new OlderBy(this.LastSeenAt.Ticks, Math.Max(first.LastRadar, second.LastRadar)); if (first.m_type == EntityType.None) { this.m_type = second.m_type; } else { this.m_type = first.m_type; } value_isValid = true; }
/// <summary> /// If necissary, update toUpdate with this. /// </summary> /// <param name="toUpdate">LastSeen that may need an update</param> /// <returns>true iff an update was performed</returns> public bool update(ref LastSeen toUpdate) { if (this.anyNewer(toUpdate) || (this.Info != null && (toUpdate.Info == null || this.Info.IsNewerThan(toUpdate.Info)))) { toUpdate = new LastSeen(this, toUpdate); return true; } return false; }
public DistanceSeen(float distance, LastSeen seen) { this.Distance = distance; this.Seen = seen; }
/// <summary> /// Try to get a LastSeen by EntitiyId. /// </summary> public bool TryGetLastSeen(long entityId, out LastSeen seen) { using (lock_lastSeen.AcquireSharedUsing()) return m_lastSeen.TryGetValue(entityId, out seen); }
/// <summary> /// <para>Internal receive method. Adds the LastSeen to this storage or updates an existing one.</para> /// <para>lock_m_lastSeen should be exclusively locked before invoking this method.</para> /// </summary> private void in_Receive(LastSeen seen) { LastSeen toUpdate; if (m_lastSeen.TryGetValue(seen.Entity.EntityId, out toUpdate)) { if (seen.update(ref toUpdate)) m_lastSeen[toUpdate.Entity.EntityId] = toUpdate; } else m_lastSeen.Add(seen.Entity.EntityId, seen); }
private bool CanDisplay(LastSeen seen) { if (!CheckRelations(seen.Entity)) return false; if (seen.Info == null) return false; TimeSpan time = Globals.ElapsedTime - seen.Info.DetectedAt; if (time > Static.displayAllowed) { if (time > Static.keepInCache) m_holoEntitiesRemove.Add(seen.Entity.EntityId); return false; } float rangeDetection = m_rangeDetection.Value; rangeDetection *= rangeDetection; return Vector3D.DistanceSquared(m_centreEntity.GetPosition(), seen.Entity.GetCentre()) <= rangeDetection; }
public bool tryGetLastSeen(long entityId, out LastSeen result) { return(myLastSeen.TryGetValue(entityId, out result)); }
private bool isNewerThan(LastSeen other) { return this.LastSeenAt.CompareTo(other.LastSeenAt) > 0; }
/// <remarks> /// Runs on separate thread. /// </remarks> private void TargetLastSeen() { if (myAntenna == null || myAntenna.lastSeenCount == 0) { if (myTargetSeen != null && myTarget.TType == TargetType.None) { myLogger.debugLog("Retargeting last", "TargetLastSeen()"); myTarget = new LastSeenTarget(myTargetSeen); SetFiringDirection(); } return; } if (DateTime.UtcNow - failed_lastSeenTarget < checkLastSeen) return; LastSeen fetched; if (myTargetSeen != null && myAntenna.tryGetLastSeen(myTargetSeen.Entity.EntityId, out fetched) && fetched.isRecent()) { myLogger.debugLog("using previous last seen: " + fetched.Entity.getBestName(), "TargetLastSeen()"); myTarget = new LastSeenTarget(fetched); SetFiringDirection(); return; } if (Options.TargetEntityId.HasValue) { if (myAntenna.tryGetLastSeen(Options.TargetEntityId.Value, out fetched)) { myLogger.debugLog("using last seen from entity id: " + fetched.Entity.getBestName(), "TargetLastSeen()"); myTarget = new LastSeenTarget(fetched); SetFiringDirection(); } else myLogger.debugLog("failed to get last seen from entity id", "TargetLastSeen()"); return; } Vector3D myPos = MyEntity.GetPosition(); LastSeen closest = null; double closestDist = double.MaxValue; myLogger.debugLog("last seen count: " + myAntenna.lastSeenCount, "TargetLastSeen()"); myAntenna.ForEachLastSeen(seen => { myLogger.debugLog("checking: " + seen.Entity.getBestName(), "TargetLastSeen()"); if (seen.isRecent() && CubeBlock.canConsiderHostile(seen.Entity) && Options.CanTargetType(seen.Entity)) { double dist = Vector3D.DistanceSquared(myPos, seen.LastKnownPosition); if (dist < closestDist) { closestDist = dist; closest = seen; } } return false; }); if (closest == null) { myLogger.debugLog("failed to get a target from last seen", "TargetLastSeen()"); failed_lastSeenTarget = DateTime.UtcNow; myTargetSeen = null; } else { myLogger.debugLog("got a target from last seen: " + closest.Entity.getBestName(), "TargetLastSeen()"); myTarget = new LastSeenTarget(closest); SetFiringDirection(); myTargetSeen = closest; } }
/// <summary> /// <para>Add a LastSeen to this storage or updates an existing one. LastSeen will be pushed to connected storages.</para> /// <para>Not optimized for use within a loop.</para> /// </summary> /// <param name="seen">LastSeen data to receive.</param> public void Receive(LastSeen seen) { HashSet<RelayStorage> sendToSet = ResourcePool<HashSet<RelayStorage>>.Pool.Get(); try { AddStorage(sendToSet, this); foreach (RelayStorage sto in sendToSet) { using (sto.lock_lastSeen.AcquireExclusiveUsing()) sto.in_Receive(seen); if (sto.m_nextClean_lastSeen <= Globals.UpdateCount) { m_logger.debugLog("Running cleanup on last seen", Logger.severity.INFO); sto.ForEachLastSeen(s => { }); } } } finally { sendToSet.Clear(); ResourcePool<HashSet<RelayStorage>>.Pool.Return(sendToSet); } }
public bool tryGetLastSeen(long entityId, out LastSeen result) { bool retreived; using (lock_m_lastSeen.AcquireSharedUsing()) retreived = m_lastSeen.TryGetValue(entityId, out result); if (!retreived) return false; if (result.IsValid) return true; using (lock_m_lastSeen.AcquireExclusiveUsing()) m_lastSeen.Remove(entityId); return false; }
/// <summary> /// does not check seen for isValid /// </summary> /// <param name="forced">for receiving LastSeen for self</param> public void Receive(LastSeen seen, bool forced = false) { if (seen.Entity == Entity.Invoke() && !forced) return; LastSeen toUpdate; using (lock_m_lastSeen.AcquireExclusiveUsing()) if (m_lastSeen.TryGetValue(seen.Entity.EntityId, out toUpdate)) { if (seen.update(ref toUpdate)) m_lastSeen[toUpdate.Entity.EntityId] = toUpdate; } else m_lastSeen.Add(seen.Entity.EntityId, seen); }
private bool CanTarget(LastSeen seen) { try { if (m_mustBeRecent && !seen.isRecent()) { m_logger.debugLog("no longer recent: " + seen.Entity.getBestName() + ", age: " + (DateTime.UtcNow - seen.LastSeenAt), "CanTarget()"); return false; } // if it is too far from start, cannot target if (MaximumRange > 1f && Vector3.DistanceSquared(m_startPosition, seen.GetPosition()) > MaximumRange * MaximumRange) { m_logger.debugLog("out of range of start position: " + seen.Entity.getBestName(), "CanTarget()"); return false; } // if it is too fast, cannot target float speedTarget = m_navSet.Settings_Current.SpeedTarget - 1f; if (seen.GetLinearVelocity().LengthSquared() >= speedTarget * speedTarget) { m_logger.debugLog("too fast to target: " + seen.Entity.getBestName(), "CanTarget()"); return false; } return GridCondition == null || GridCondition(seen.Entity as IMyCubeGrid); } catch (NullReferenceException nre) { m_logger.alwaysLog("Exception: " + nre, "CanTarget()", Logger.severity.ERROR); if (!seen.Entity.Closed) throw nre; m_logger.debugLog("Caught exception caused by grid closing, ignoring.", "CanTarget()"); return false; } }
private void LoadData() { if (m_data == null) { m_logger.debugLog("No data to load"); return; } m_logger.alwaysLog("Save version: " + m_data.ModVersion, Logger.severity.INFO); // network Dictionary<Message.Builder_Message, Message> messages = new Dictionary<Message.Builder_Message, Message>(); SerializableGameTime.Adjust = new TimeSpan(m_data.SaveTime); foreach (RelayStorage.Builder_NetworkStorage bns in m_data.AntennaStorage) { RelayNode node; if (!Registrar.TryGetValue(bns.PrimaryNode, out node)) { m_logger.alwaysLog("Failed to get node for: " + bns.PrimaryNode, Logger.severity.WARNING); continue; } RelayStorage store = node.Storage; if (store == null) // probably always true { node.ForceCreateStorage(); store = node.Storage; if (store == null) { m_logger.debugLog("failed to create storage for " + node.LoggingName, Logger.severity.ERROR); continue; } } foreach (LastSeen.Builder_LastSeen bls in bns.LastSeenList) { LastSeen ls = new LastSeen(bls); if (ls.IsValid) store.Receive(ls); else m_logger.debugLog("failed to create a valid last seen from builder for " + bls.EntityId, Logger.severity.WARNING); } m_logger.debugLog("added " + bns.LastSeenList.Length + " last seen to " + store.PrimaryNode.LoggingName, Logger.severity.DEBUG); foreach (Message.Builder_Message bm in bns.MessageList) { Message msg; if (!messages.TryGetValue(bm, out msg)) { msg = new Message(bm); messages.Add(bm, msg); } else { m_logger.debugLog("found linked message", Logger.severity.TRACE); } if (msg.IsValid) store.Receive(msg); else m_logger.debugLog("failed to create a valid message from builder for " + bm.DestCubeBlock, Logger.severity.WARNING); } m_logger.debugLog("added " + bns.MessageList.Length + " message to " + store.PrimaryNode.LoggingName, Logger.severity.DEBUG); } // system disruption foreach (Disruption.Builder_Disruption bd in m_data.SystemDisruption) { Disruption disrupt; switch (bd.Type) { case "AirVentDepressurize": disrupt = new AirVentDepressurize(); break; case "CryoChamberMurder": disrupt = new CryoChamberMurder(); break; case "DisableTurret": disrupt = new DisableTurret(); break; case "DoorLock": disrupt = new DoorLock(); break; case "EMP": disrupt = new EMP(); break; case "GravityReverse": disrupt = new GravityReverse(); break; case "JumpDriveDrain": disrupt = new JumpDriveDrain(); break; case "MedicalRoom": disrupt = new MedicalRoom(); break; case "TraitorTurret": disrupt = new TraitorTurret(); break; default: m_logger.alwaysLog("Unknown disruption: " + bd.Type, Logger.severity.WARNING); continue; } disrupt.Start(bd); } // autopilot if (m_data.Autopilot != null) foreach (ShipAutopilot.Builder_Autopilot ba in m_data.Autopilot) { ShipAutopilot autopilot; if (Registrar.TryGetValue(ba.AutopilotBlock, out autopilot)) autopilot.Resume = ba; else m_logger.alwaysLog("failed to find autopilot block " + ba.AutopilotBlock, Logger.severity.WARNING); } // programmable block if (m_data.ProgrammableBlock != null) foreach (ProgrammableBlock.Builder_ProgrammableBlock bpa in m_data.ProgrammableBlock) { ProgrammableBlock pb; if (Registrar.TryGetValue(bpa.BlockId, out pb)) pb.ResumeFromSave(bpa); else m_logger.alwaysLog("failed to find programmable block " + bpa.BlockId, Logger.severity.WARNING); } // text panel if (m_data.TextPanel != null) foreach (TextPanel.Builder_TextPanel btp in m_data.TextPanel) { TextPanel panel; if (Registrar.TryGetValue(btp.BlockId, out panel)) panel.ResumeFromSave(btp); else m_logger.alwaysLog("failed to find text panel " + btp.BlockId, Logger.severity.WARNING); } // weapon if (m_data.Weapon != null) foreach (WeaponTargeting.Builder_WeaponTargeting bwt in m_data.Weapon) { WeaponTargeting targeting; if (WeaponTargeting.TryGetWeaponTargeting(bwt.WeaponId, out targeting)) targeting.ResumeFromSave(bwt); else m_logger.alwaysLog("failed to find weapon " + bwt.WeaponId, Logger.severity.WARNING); } // entity values if (m_data.EntityValues != null) EntityValue.ResumeFromSave(m_data.EntityValues); m_data = null; }
/// <summary> /// Attempts to choose a targetable block from a LastSeen. /// </summary> /// <returns>True iff the LastSeen can be targeted, either because it has no blocks or because a block was found.</returns> private bool ChooseBlock(LastSeen seen, out IMyCubeBlock block) { block = null; if (SEAD) { float powerLevel; return RadarEquipment.GetRadarEquipment(seen, out block, out powerLevel); } if (seen.Info == null || !seen.Info.IsRecent()) return true; IMyCubeGrid grid = seen.Entity as IMyCubeGrid; if (grid == null) return true; if (Options.blocksToTarget.IsNullOrEmpty() && (Options.CanTarget & TargetType.Destroy) == 0) return true; double distValue; if (!GetTargetBlock(grid, Options.CanTarget, out block, out distValue, false)) return false; return true; }
public void UpdateTarget(LastSeen enemy) { m_enemy = enemy; m_navSet.Settings_Task_NavEngage.CollisionAvoidance = false; }
private bool anyNewer(LastSeen other) { return this.LastSeenAt.CompareTo(other.LastSeenAt) > 0 || this.LastBroadcast.CompareTo(other.LastBroadcast) > 0 || this.LastJam.CompareTo(other.LastJam) > 0 || this.LastRadar.CompareTo(other.LastRadar) > 0; }
public void UpdateAfterSimulation100() { try { if (!myRadioAntenna.IsWorking) { return; } //Showoff.doShowoff(CubeBlock, myLastSeen.Values.GetEnumerator(), myLastSeen.Count); float radiusSquared; MyObjectBuilder_RadioAntenna antBuilder = CubeBlock.GetObjectBuilderCubeBlock() as MyObjectBuilder_RadioAntenna; if (!antBuilder.EnableBroadcasting) { radiusSquared = 0; } else { radiusSquared = myRadioAntenna.Radius * myRadioAntenna.Radius; } // send antenna self to radio antennae LinkedList <RadioAntenna> canSeeMe = new LinkedList <RadioAntenna>(); // friend and foe alike foreach (RadioAntenna ant in RadioAntenna.registry) { if (CubeBlock.canSendTo(ant.CubeBlock, false, radiusSquared, true)) { canSeeMe.AddLast(ant); } } LastSeen self = new LastSeen(CubeBlock.CubeGrid); foreach (RadioAntenna ant in canSeeMe) { ant.receive(self); } // relay information to friendlies foreach (RadioAntenna ant in value_registry) { if (CubeBlock.canSendTo(ant.CubeBlock, true, radiusSquared, true)) { foreach (LastSeen seen in myLastSeen.Values) { ant.receive(seen); } foreach (Message mes in myMessages) { ant.receive(mes); } } } Receiver.sendToAttached(CubeBlock, myLastSeen); Receiver.sendToAttached(CubeBlock, myMessages); UpdateEnemyNear(); } catch (Exception e) { myLogger.log("Exception: " + e, "UpdateAfterSimulation100()", Logger.severity.ERROR); } }
private bool isNewerThan(LastSeen other) { return(this.LastSeenAt.CompareTo(other.LastSeenAt) > 0); }
/// <summary> /// Try to get a LastSeen by EntitiyId. /// </summary> public bool TryGetLastSeen(long entityId, out LastSeen seen) { using (lock_lastSeen.AcquireSharedUsing()) return(m_lastSeen.TryGetValue(entityId, out seen)); }
private bool CanTarget(LastSeen seen) { try { // if it is too far from start, cannot target if (MaximumRange > 1f && Vector3.DistanceSquared(m_startPosition, seen.GetPosition()) > MaximumRange * MaximumRange) { m_logger.debugLog("out of range of start position: " + seen.Entity.getBestName(), "CanTarget()"); if (m_reason < ReasonCannotTarget.Too_Far) { m_reason = ReasonCannotTarget.Too_Far; m_reasonGrid = seen.Entity.EntityId; } return false; } // if it is too fast, cannot target float speedTarget = m_navSet.Settings_Current.SpeedTarget - 1f; if (seen.GetLinearVelocity().LengthSquared() >= speedTarget * speedTarget) { m_logger.debugLog("too fast to target: " + seen.Entity.getBestName(), "CanTarget()"); if (m_reason < ReasonCannotTarget.Too_Fast) { m_reason = ReasonCannotTarget.Too_Fast; m_reasonGrid = seen.Entity.EntityId; } return false; } if (GridCondition != null && !GridCondition(seen.Entity as IMyCubeGrid)) { m_logger.debugLog("Failed grid condition: " + seen.Entity.getBestName(), "CanTarget()"); if (m_reason < ReasonCannotTarget.Grid_Condition) { m_reason = ReasonCannotTarget.Grid_Condition; m_reasonGrid = seen.Entity.EntityId; } return false; } return true; } catch (NullReferenceException nre) { m_logger.alwaysLog("Exception: " + nre, "CanTarget()", Logger.severity.ERROR); if (!seen.Entity.Closed) throw nre; m_logger.debugLog("Caught exception caused by grid closing, ignoring.", "CanTarget()"); return false; } }
public void UpdateTarget(LastSeen enemy) { m_enemy = enemy; }
public GuidedMissile(Cluster missiles, IMyCubeBlock firedBy, TargetingOptions opt, Ammo ammo, LastSeen initialTarget = null) : this (missiles.Master, firedBy, opt, ammo, initialTarget) { myCluster = missiles; }
private void CreateHolo(LastSeen seen) { if (!(seen.Entity is IMyCubeGrid)) return; SeenHolo sh; if (m_holoEntities.TryGetValue(seen.Entity.EntityId, out sh)) { sh.Seen = seen; return; } if (!CanDisplay(seen)) return; Profiler.StartProfileBlock(GetType().Name, "CreateHolo.GetObjectBuilder"); MyObjectBuilder_CubeGrid builder = (MyObjectBuilder_CubeGrid)seen.Entity.GetObjectBuilder(); Profiler.EndProfileBlock(); MyEntities.RemapObjectBuilder(builder); builder.IsStatic = false; builder.CreatePhysics = false; builder.EnableSmallToLargeConnections = false; Profiler.StartProfileBlock(GetType().Name, "CreateHolo.CreateFromObjectBuilder"); MyCubeGrid holo = (MyCubeGrid)MyEntities.CreateFromObjectBuilder(builder); Profiler.EndProfileBlock(); Profiler.StartProfileBlock(GetType().Name, "CreateHolo.SetupProjection"); SetupProjection(holo); Profiler.EndProfileBlock(); Profiler.StartProfileBlock(GetType().Name, "CreateHolo.AddEntity"); MyAPIGateway.Entities.AddEntity(holo); Profiler.EndProfileBlock(); m_logger.debugLog("created holo for " + seen.Entity.nameWithId() + ", holo: " + holo.nameWithId()); m_holoEntities.Add(seen.Entity.EntityId, new SeenHolo() { Seen = seen, Holo = holo }); MyCubeGrid actual = (MyCubeGrid)seen.Entity; actual.OnBlockAdded += Actual_OnBlockAdded; actual.OnBlockRemoved += Actual_OnBlockRemoved; actual.OnBlockIntegrityChanged += OnBlockIntegrityChanged; }
public LastSeenTarget(LastSeen seen) { m_lastSeen = seen; }
public void UpdateTarget(LastSeen enemy) { if (enemy == null) { m_logger.debugLog(m_currentTarget != null, "lost target", Logger.severity.DEBUG); m_currentTarget = null; m_orbiter = null; return; } if (m_currentTarget == null || m_currentTarget.Entity != enemy.Entity) { m_logger.debugLog("new target: " + enemy.Entity.getBestName(), Logger.severity.DEBUG); m_currentTarget = enemy; m_navSet.Settings_Task_NavEngage.DestinationEntity = m_currentTarget.Entity; } }
public void UpdateTarget(LastSeen enemy) { m_currentTarget = enemy; }
private void UpdateGPS(UserSettings.ByteSettingName setting, GpsData relateData) { relateData.distanceSeen.Sort(); int index; for (index = 0; index < relateData.distanceSeen.Count && index < relateData.entities.Count; index++) { Log.DebugLog("index(" + index + ") >= relateData.distanceSeen.Count(" + relateData.distanceSeen.Count + ")", Logger.severity.FATAL, condition: index >= relateData.distanceSeen.Count); LastSeen seen = relateData.distanceSeen[index].Seen; // we do not display if it is broadcasting so there is no reason to use LastSeen.HostileName() string name; MyRelationsBetweenPlayerAndBlock seRelate; switch (setting) { case UserSettings.ByteSettingName.FactionOnHUD: name = seen.Entity.DisplayName; seRelate = MyRelationsBetweenPlayerAndBlock.FactionShare; break; case UserSettings.ByteSettingName.OwnerOnHUD: name = seen.Entity.DisplayName; seRelate = MyRelationsBetweenPlayerAndBlock.Owner; break; case UserSettings.ByteSettingName.MissileOnHUD: name = "Missile " + index; seRelate = MyRelationsBetweenPlayerAndBlock.Enemies; break; case UserSettings.ByteSettingName.NeutralOnHUD: name = "Neutral " + index; seRelate = MyRelationsBetweenPlayerAndBlock.Neutral; break; case UserSettings.ByteSettingName.EnemiesOnHUD: name = "Enemy " + index; seRelate = MyRelationsBetweenPlayerAndBlock.Enemies; break; default: Log.AlwaysLog("case not implemented: " + setting, Logger.severity.ERROR); continue; } MyEntity entity = relateData.entities[index]; if (entity != null) { if (entity != seen.Entity) { Log.DebugLog("removing marker: " + entity.nameWithId()); MyHud.LocationMarkers.UnregisterMarker(entity); } else if (MyHud.LocationMarkers.MarkerEntities.ContainsKey(entity)) { continue; } } entity = (MyEntity)seen.Entity; relateData.entities[index] = entity; Log.DebugLog("adding marker: " + entity.nameWithId()); MyHud.LocationMarkers.RegisterMarker(entity, new MyHudEntityParams() { FlagsEnum = MyHudIndicatorFlagsEnum.SHOW_ALL, Text = new StringBuilder(name), OffsetText = true, TargetMode = seRelate }); } // remove remaining while (index < relateData.entities.Count) { MyEntity entity = relateData.entities[index]; if (entity != null) { Log.DebugLog("removing marker: " + entity.nameWithId()); MyHud.LocationMarkers.UnregisterMarker(entity); relateData.entities[index] = null; } index++; } }
/// <summary> /// Creates a missile with homing and target finding capabilities. /// </summary> public GuidedMissile(IMyEntity missile, IMyCubeBlock firedBy, TargetingOptions opt, Ammo ammo, LastSeen initialTarget = null) : base(missile, firedBy) { myLogger = new Logger("GuidedMissile", () => missile.getBestName(), () => m_stage.ToString()); myAmmo = ammo; myDescr = ammo.Description; if (ammo.Description.HasAntenna) myAntenna = new MissileAntenna(missile); TryHard = true; AllGuidedMissiles.Add(this); AddMissileOwner(MyEntity, CubeBlock.OwnerId); MyEntity.OnClose += MyEntity_OnClose; accelerationPerUpdate = (myDescr.Acceleration + myAmmo.MissileDefinition.MissileAcceleration) / 60f; addSpeedPerUpdate = myDescr.Acceleration / 60f; Options = opt; Options.TargetingRange = ammo.Description.TargetRange; myTargetSeen = initialTarget; myLogger.debugLog("Options: " + Options + ", initial target: " + (initialTarget == null ? "null" : initialTarget.Entity.getBestName()), "GuidedMissile()"); //myLogger.debugLog("AmmoDescription: \n" + MyAPIGateway.Utilities.SerializeToXML<Ammo.AmmoDescription>(myDescr), "GuidedMissile()"); }
public void UpdateAfterSimulation100() { //if (!IsInitialized) return; if (CubeBlock == null || CubeBlock.Closed || CubeBlock.CubeGrid == null) { return; } try { if (!myBeacon.IsWorking) { if (isRadar && powerLevel > 0) { powerLevel += powerDecrease; } return; } // send beacon self to radio antenna LinkedList <RadioAntenna> canSeeMe = new LinkedList <RadioAntenna>(); // friend and foe alike float radiusSquared = myBeacon.Radius * myBeacon.Radius; foreach (RadioAntenna ant in RadioAntenna.registry) { if (CubeBlock.canSendTo(ant.CubeBlock, false, radiusSquared, true)) { canSeeMe.AddLast(ant); } } LastSeen self = new LastSeen(CubeBlock.CubeGrid, isRadar); foreach (RadioAntenna ant in canSeeMe) { ant.receive(self); } //log("beacon made self known to "+canSeeMe.Count+" antennas", "UpdateAfterSimulation100()", Logger.severity.TRACE); if (!isRadar) { return; } // Radar float Radius = myBeacon.Radius; // cap small radar if (isSmallBlock) { if (Radius > maxRadiusSmallRadar) { myLogger.debugLog("Reduce radius from " + Radius + " to " + maxRadiusSmallRadar, "UpdateAfterSimulation100()"); myBeacon.SetValueFloat("Radius", maxRadiusSmallRadar); Radius = maxRadiusSmallRadar; } } // adjust power level if (powerLevel < 0) { powerLevel = 0; } powerLevel += powerIncrease; if (powerLevel > Radius) { powerLevel = Radius; } myLogger.debugLog("Radius = " + Radius + ", power level = " + powerLevel, "UpdateAfterSimulation100()"); // figure out what radar sees LinkedList <LastSeen> radarSees = new LinkedList <LastSeen>(); HashSet <IMyEntity> allGrids = new HashSet <IMyEntity>(); MyAPIGateway.Entities.GetEntities_Safe(allGrids, (entity) => { return(entity is IMyCubeGrid); }); foreach (IMyEntity ent in allGrids) //if (ent is IMyCubeGrid || ent is IMyCharacter) { // get detection distance float volume = ent.LocalAABB.Volume(); float power = (volume + radarPower_A) / (volume + radarPower_B) / radarPower_C * powerLevel; if (!CubeBlock.canSendTo(ent, false, power)) // not in range { continue; } //log("radar found a grid: " + (ent as IMyCubeGrid).DisplayName, "UpdateAfterSimulation100()", Logger.severity.TRACE); // report to attached antennas and remotes LastSeen seen = new LastSeen(ent, false, new RadarInfo(volume)); radarSees.AddLast(seen); //foreach (RadioAntenna ant in RadioAntenna.registry) // if (CubeBlock.canSendTo(ant.CubeBlock, true)) // ant.receive(seen); //foreach (RemoteControl rem in RemoteControl.registry.Values) // if (CubeBlock.canSendTo(rem.CubeBlock, true)) // rem.receive(seen); } Receiver.sendToAttached(CubeBlock, radarSees); } catch (Exception e) { alwaysLog("Exception: " + e, "UpdateAfterSimulation100()", Logger.severity.ERROR); } }
public void UpdateTarget(LastSeen enemy) { m_enemy = enemy; m_navSet.Settings_Task_NavEngage.DestinationEntity = enemy.Entity; }