Committing all this noise even though it's sorta broken.
[AntennaRange.git] / RelayExtensions.cs
blob:a/RelayExtensions.cs -> blob:b/RelayExtensions.cs
--- a/RelayExtensions.cs
+++ b/RelayExtensions.cs
@@ -166,7 +166,25 @@
 		/// <param name="vessel">This <see cref="Vessel"/></param>
 		public static IAntennaRelay GetBestRelay(this Vessel vessel)
 		{
-			IAntennaRelay bestRelay = null;
+			BestVesselRelayCache relayCache;
+
+			if (RelayDatabase.Instance.TryGetBestVesselRelay(vessel, out relayCache))
+			{
+				if (
+					AntennaRelay.searchTimer.ElapsedMilliseconds - relayCache.timeStamp <
+					AntennaRelay.millisecondsBetweenSearches
+				)
+				{
+					return relayCache.relay;
+				}
+			}
+			else
+			{
+				relayCache = new BestVesselRelayCache();
+				relayCache.vessel = vessel;
+				RelayDatabase.Instance.SetBestVesselRelay(vessel, relayCache);
+			}
+
 			double bestScore = double.PositiveInfinity;
 			double relayScore = double.NaN;
 
@@ -180,11 +198,13 @@
 				if (relayScore < bestScore)
 				{
 					bestScore = relayScore;
-					bestRelay = relay;
-				}
-			}
-
-			return bestRelay;
+					relayCache.relay = relay;
+				}
+			}
+
+			relayCache.timeStamp = AntennaRelay.searchTimer.ElapsedMilliseconds;
+
+			return relayCache.relay;
 		}
 	}