From cdfcf1ab8f02a66f0a56495825955314faa96b2c Mon Sep 17 00:00:00 2001 From: siimav Date: Thu, 8 Aug 2024 00:37:45 +0300 Subject: [PATCH] Eliminate many double or triple dictionary lookups --- .../RemoteTechProgressTracker.cs | 12 ++++---- .../Behaviour/Expression.cs | 11 ++++---- .../ContractConfigurator/BehaviourFactory.cs | 8 +++--- source/ContractConfigurator/ContractGroup.cs | 2 +- .../ContractRequirement.cs | 10 +++---- source/ContractConfigurator/ContractType.cs | 7 ++--- .../ExpressionParser/BaseParser.cs | 10 +++---- .../ExpressionParser/DataNode.cs | 10 +++---- .../ExpressionParser/ExpressionParser.cs | 28 +++++++++---------- .../SimpleTypes/ListExpressionParser.cs | 2 +- .../ExpressionParser/Wrappers/Tech.cs | 8 +++--- .../ContractConfigurator/MissionControlUI.cs | 9 +++--- .../Parameter/Duration.cs | 8 +++--- .../Parameter/RecoverKerbalCustom.cs | 2 +- .../Parameter/SCANsatCoverage.cs | 2 +- .../Parameter/VesselParameter.cs | 12 ++++---- .../VesselParameter/CollectScienceCustom.cs | 12 ++++---- .../VesselParameter/RecoverVessel.cs | 2 +- .../ContractConfigurator/ParameterFactory.cs | 4 +-- .../ScenarioModules/ContractVesselTracker.cs | 13 ++++----- .../ScenarioModules/PersistentDataStore.cs | 13 ++++----- .../Util/ConfigNodeUtil.cs | 23 ++++++++------- .../Util/ContractDisabler.cs | 4 +-- .../ContractConfigurator/Util/DebugWindow.cs | 6 ++-- .../Util/DraftTwitchViewers.cs | 3 +- .../ContractConfigurator/Util/Extensions.cs | 2 +- source/ContractConfigurator/Util/Science.cs | 6 ++-- .../ContractConfigurator/Util/TitleTracker.cs | 2 +- 28 files changed, 112 insertions(+), 119 deletions(-) diff --git a/source/CC_RemoteTech/RemoteTechProgressTracker.cs b/source/CC_RemoteTech/RemoteTechProgressTracker.cs index 20e83da42..22d64cf97 100644 --- a/source/CC_RemoteTech/RemoteTechProgressTracker.cs +++ b/source/CC_RemoteTech/RemoteTechProgressTracker.cs @@ -172,15 +172,15 @@ private void Initialize() // Add celestial bodies to listing foreach (CelestialBody cb in FlightGlobals.Bodies) { - if (!celestialBodies.ContainsKey(cb)) + if (!celestialBodies.TryGetValue(cb, out CelestialBodyInfo cbi)) { - CelestialBodyInfo cbi = new CelestialBodyInfo(); + cbi = new CelestialBodyInfo(); cbi.body = cb; cbi.coverage = 0; celestialBodies[cb] = cbi; } - celestialBodies[cb].sat = RTCore.Instance.Satellites[cb.Guid()]; + cbi.sat = RTCore.Instance.Satellites[cb.Guid()]; } initialized = true; @@ -343,9 +343,9 @@ public override void OnSave(ConfigNode node) public static double GetCoverage(CelestialBody body) { // Calculate the coverage - if (Instance != null && Instance.celestialBodies.ContainsKey(body)) + if (Instance != null && Instance.celestialBodies.TryGetValue(body, out CelestialBodyInfo cbi)) { - UInt32 cov = Instance.celestialBodies[body].coverage; + UInt32 cov = cbi.coverage; UInt32 count = 0; while (cov > 0) { @@ -365,7 +365,7 @@ public static double GetCoverage(CelestialBody body) /// The range public double ActiveRange(CelestialBody body) { - return celestialBodies.ContainsKey(body) ? celestialBodies[body].activeRange : 0.0; + return celestialBodies.TryGetValue(body, out CelestialBodyInfo cbi) ? cbi.activeRange : 0.0; } /// diff --git a/source/ContractConfigurator/Behaviour/Expression.cs b/source/ContractConfigurator/Behaviour/Expression.cs index 8ceb5467e..a59b7a3ba 100644 --- a/source/ContractConfigurator/Behaviour/Expression.cs +++ b/source/ContractConfigurator/Behaviour/Expression.cs @@ -123,9 +123,10 @@ protected override void OnCompleted() protected override void OnParameterStateChange(ContractParameter param) { - if (param.ID != null && param.State == ParameterState.Complete && onParameterComplete.ContainsKey(param.ID)) + if (param.ID != null && param.State == ParameterState.Complete && + onParameterComplete.TryGetValue(param.ID, out List exprs)) { - ExecuteExpressions(onParameterComplete[param.ID]); + ExecuteExpressions(exprs); onParameterComplete[param.ID].Clear(); } } @@ -172,11 +173,11 @@ protected override void OnLoad(ConfigNode configNode) // Store it for later if (child.name == "PARAMETER_COMPLETED") { - if (!onParameterComplete.ContainsKey(parameter)) + if (!onParameterComplete.TryGetValue(parameter, out List list)) { - onParameterComplete[parameter] = new List(); + onParameterComplete[parameter] = list = new List(); } - onParameterComplete[parameter].Add(expVal); + list.Add(expVal); } else { diff --git a/source/ContractConfigurator/BehaviourFactory.cs b/source/ContractConfigurator/BehaviourFactory.cs index febbae4ff..74ac525dd 100644 --- a/source/ContractConfigurator/BehaviourFactory.cs +++ b/source/ContractConfigurator/BehaviourFactory.cs @@ -109,10 +109,10 @@ public static void Register(Type factoryType, string typeName) { LoggingUtil.LogDebug(typeof(BehaviourFactory), "Registering behaviour factory class {0} for handling BEHAVIOUR nodes with type = {1}.", factoryType.FullName, typeName); - if (factories.ContainsKey(typeName)) + if (factories.TryGetValue(typeName, out Type fType)) { LoggingUtil.LogError(typeof(BehaviourFactory), "Cannot register {0}[{1}] to handle type {2}: already handled by {3}[{4}]", - factoryType.FullName, factoryType.Module, typeName, factories[typeName].FullName, factories[typeName].Module); + factoryType.FullName, factoryType.Module, typeName, fType.FullName, fType.Module); } else { @@ -147,7 +147,7 @@ public static bool GenerateBehaviourFactory(ConfigNode behaviourConfig, Contract behaviourFactory = new InvalidBehaviourFactory(); valid = false; } - else if (!factories.ContainsKey(type)) + else if (!factories.TryGetValue(type, out Type fType)) { LoggingUtil.LogError(typeof(ParameterFactory), "CONTRACT_TYPE '{0}', BEHAVIOUR '{1}' of type '{2}': Unknown behaviour '{3}'.", contractType.name, behaviourConfig.GetValue("name"), behaviourConfig.GetValue("type"), type); @@ -157,7 +157,7 @@ public static bool GenerateBehaviourFactory(ConfigNode behaviourConfig, Contract else { // Create an instance of the factory - behaviourFactory = (BehaviourFactory)Activator.CreateInstance(factories[type]); + behaviourFactory = (BehaviourFactory)Activator.CreateInstance(fType); } // Set attributes diff --git a/source/ContractConfigurator/ContractGroup.cs b/source/ContractConfigurator/ContractGroup.cs index 1f2360974..1a5306a4c 100644 --- a/source/ContractConfigurator/ContractGroup.cs +++ b/source/ContractConfigurator/ContractGroup.cs @@ -41,7 +41,7 @@ public static string GroupDisplayName(string groupName) return ""; } - ContractGroup group = contractGroups.ContainsKey(groupName) ? contractGroups[groupName] : null; + contractGroups.TryGetValue(groupName, out ContractGroup group); return group == null ? "" : group.displayName; } diff --git a/source/ContractConfigurator/ContractRequirement.cs b/source/ContractConfigurator/ContractRequirement.cs index 24584b9c4..cea6307f1 100644 --- a/source/ContractConfigurator/ContractRequirement.cs +++ b/source/ContractConfigurator/ContractRequirement.cs @@ -156,7 +156,7 @@ public static ContractRequirement LoadRequirement(ConfigNode configNode) { return null; } - Type type = requirementTypes.ContainsKey(typeName) ? requirementTypes[typeName] : null; + requirementTypes.TryGetValue(typeName, out Type type); if (type == null) { throw new Exception("No ContractRequirement with type = '" + typeName + "'."); @@ -280,10 +280,10 @@ public static void Register(Type crType, string typeName) { LoggingUtil.LogDebug(typeof(ContractRequirement), "Registering ContractRequirement class {0} for handling REQUIREMENT nodes with type = {1}.", crType.FullName, typeName); - if (requirementTypes.ContainsKey(typeName)) + if (requirementTypes.TryGetValue(typeName, out Type rType)) { LoggingUtil.LogError(typeof(ContractRequirement), "Cannot register {0}[{1}] to handle type {2}: already handled by {3}[{4}]", - crType.FullName, crType.Module, typeName, requirementTypes[typeName].FullName, requirementTypes[typeName].Module); + crType.FullName, crType.Module, typeName, rType.FullName, rType.Module); } else { @@ -319,7 +319,7 @@ public static bool GenerateRequirement(ConfigNode configNode, ContractType contr requirement = new InvalidContractRequirement(); valid = false; } - else if (!requirementTypes.ContainsKey(type)) + else if (!requirementTypes.TryGetValue(type, out Type rType)) { LoggingUtil.LogError(typeof(ParameterFactory), "CONTRACT_TYPE '{0}', REQUIREMENT '{1}' of type '{2}': Unknown requirement '{3}'.", contractType.name, configNode.GetValue("name"), configNode.GetValue("type"), type); @@ -329,7 +329,7 @@ public static bool GenerateRequirement(ConfigNode configNode, ContractType contr else { // Create an instance of the ContractRequirement - requirement = (ContractRequirement)Activator.CreateInstance(requirementTypes[type]); + requirement = (ContractRequirement)Activator.CreateInstance(rType); } // Set attributes diff --git a/source/ContractConfigurator/ContractType.cs b/source/ContractConfigurator/ContractType.cs index 352114113..e6dc3a4a8 100644 --- a/source/ContractConfigurator/ContractType.cs +++ b/source/ContractConfigurator/ContractType.cs @@ -81,9 +81,9 @@ public static IEnumerable AllValidContractTypeNames public static ContractType GetContractType(string name) { - if (name != null && contractTypes.ContainsKey(name)) + if (name != null && contractTypes.TryGetValue(name, out ContractType ct)) { - return contractTypes[name]; + return ct; } return null; } @@ -881,9 +881,8 @@ public void ResearchBodiesCheck(ConfiguredContract contract) Dictionary bodyInfoDict = RBWrapper.RBactualAPI.CelestialBodies; foreach (CelestialBody body in contract.ContractBodies) { - if (bodyInfoDict.ContainsKey(body) && !body.isHomeWorld) + if (!body.isHomeWorld && bodyInfoDict.TryGetValue(body, out RBWrapper.CelestialBodyInfo bodyInfo)) { - RBWrapper.CelestialBodyInfo bodyInfo = bodyInfoDict[body]; if (!bodyInfo.isResearched) { throw new ContractRequirementException(StringBuilderCache.Format("Research Bodies: {0} has not yet been researched.", body.name)); diff --git a/source/ContractConfigurator/ExpressionParser/BaseParser.cs b/source/ContractConfigurator/ExpressionParser/BaseParser.cs index 6d860e0cc..57727ded1 100644 --- a/source/ContractConfigurator/ExpressionParser/BaseParser.cs +++ b/source/ContractConfigurator/ExpressionParser/BaseParser.cs @@ -190,9 +190,9 @@ public static void RegisterParserType(Type objectType, Type parserType) /// An instance of the expression parser, or null if none can be created public static ExpressionParser GetParser() { - if (parserTypes.ContainsKey(typeof(T))) + if (parserTypes.TryGetValue(typeof(T), out Type t)) { - return (ExpressionParser)Activator.CreateInstance(parserTypes[typeof(T)]); + return (ExpressionParser)Activator.CreateInstance(t); } else if (typeof(T).IsEnum) { @@ -257,11 +257,11 @@ protected void Init(string expression) /// The callable function. protected static void RegisterGlobalFunction(Function function) { - if (!globalFunctions.ContainsKey(function.Name)) + if (!globalFunctions.TryGetValue(function.Name, out List list)) { - globalFunctions[function.Name] = new List(); + globalFunctions[function.Name] = list = new List(); } - globalFunctions[function.Name].Add(function); + list.Add(function); } protected static Type GetRequiredType(Exception e) diff --git a/source/ContractConfigurator/ExpressionParser/DataNode.cs b/source/ContractConfigurator/ExpressionParser/DataNode.cs index aab87424d..e30acb76a 100644 --- a/source/ContractConfigurator/ExpressionParser/DataNode.cs +++ b/source/ContractConfigurator/ExpressionParser/DataNode.cs @@ -95,14 +95,14 @@ public object this[string s] { DataNode node = NodeForKey(ref s); lastModified = Time.fixedTime; - if (!node.data.ContainsKey(s)) + if (!node.data.TryGetValue(s, out Value val)) { node.data[s] = new Value(value); } else { - node.data[s].value = value; - node.data[s].initialized = true; + val.value = value; + val.initialized = true; } LoggingUtil.LogVerbose(this, "DataNode[{0}], storing {1} = {2}", node.name, s, OutputValue(value)); @@ -152,7 +152,7 @@ public void SetDeterministic(string s, bool value) public bool IsInitialized(string key) { DataNode node = NodeForKey(ref key); - return node.data.ContainsKey(key) && node.data[key] != null && node.data[key].initialized; + return node.data.TryGetValue(key, out Value val) && val != null && val.initialized; } public void BlankInit(string key, Type type) @@ -167,7 +167,7 @@ public void BlankInit(string key, Type type) public Type GetType(string key) { DataNode node = NodeForKey(ref key); - return node.data.ContainsKey(key) && node.data[key] != null ? node.data[key].type : null; + return node.data.TryGetValue(key, out Value val) && val != null ? val.type : null; } public DataNode Parent diff --git a/source/ContractConfigurator/ExpressionParser/ExpressionParser.cs b/source/ContractConfigurator/ExpressionParser/ExpressionParser.cs index a1a568817..7bf252f62 100644 --- a/source/ContractConfigurator/ExpressionParser/ExpressionParser.cs +++ b/source/ContractConfigurator/ExpressionParser/ExpressionParser.cs @@ -29,11 +29,11 @@ public ExpressionParser() /// The callable method. public static void RegisterMethod(Function method) { - if (!classMethods.ContainsKey(method.Name)) + if (!classMethods.TryGetValue(method.Name, out List list)) { - classMethods[method.Name] = new List(); + classMethods[method.Name] = list = new List(); } - classMethods[method.Name].Add(method); + list.Add(method); } /// @@ -42,11 +42,11 @@ public static void RegisterMethod(Function method) /// The callable function. public static void RegisterLocalFunction(Function function) { - if (!classFunctions.ContainsKey(function.Name)) + if (!classFunctions.TryGetValue(function.Name, out List list)) { - classFunctions[function.Name] = new List(); + classFunctions[function.Name] = list = new List(); } - classFunctions[function.Name].Add(function); + list.Add(function); } /// @@ -56,16 +56,16 @@ public static void RegisterLocalFunction(Function function) /// Enumeration of functions public IEnumerable GetFunctions(string name) { - if (classFunctions.ContainsKey(name)) + if (classFunctions.TryGetValue(name, out List list)) { - foreach (Function f in classFunctions[name]) + foreach (Function f in list) { yield return f; } } - if (globalFunctions.ContainsKey(name)) + if (globalFunctions.TryGetValue(name, out List list2)) { - foreach (Function f in globalFunctions[name]) + foreach (Function f in list2) { yield return f; } @@ -826,10 +826,8 @@ public void ParseToken(string expected) public virtual T ParseVarOrIdentifier(Token token) { // Look it up in temporary variables - if (tempVariables.ContainsKey(token.sval)) + if (tempVariables.TryGetValue(token.sval, out KeyValuePair pair)) { - KeyValuePair pair = tempVariables[token.sval]; - // Check for a method call before we start messing with types Token methodToken = ParseMethodToken(); if (methodToken != null) @@ -1001,9 +999,9 @@ public IEnumerable GetCalledFunction(string functionName, ref Function s } else { - if (classMethods.ContainsKey(functionName)) + if (classMethods.TryGetValue(functionName, out List list)) { - methods = classMethods[functionName].ToList(); + methods = list.ToList(); } else { diff --git a/source/ContractConfigurator/ExpressionParser/Parsers/SimpleTypes/ListExpressionParser.cs b/source/ContractConfigurator/ExpressionParser/Parsers/SimpleTypes/ListExpressionParser.cs index 0c50eea22..8a5d5d374 100644 --- a/source/ContractConfigurator/ExpressionParser/Parsers/SimpleTypes/ListExpressionParser.cs +++ b/source/ContractConfigurator/ExpressionParser/Parsers/SimpleTypes/ListExpressionParser.cs @@ -119,7 +119,7 @@ protected static T SelectUnique(List input) // Get details from the base parser ContractType contractType = BaseParser.currentParser.currentDataNode.Root.Factory as ContractType; string key = BaseParser.currentParser.currentKey; - DataNode.UniquenessCheck uniquenessCheck = contractType.uniquenessChecks.ContainsKey(key) ? contractType.uniquenessChecks[key] : DataNode.UniquenessCheck.NONE; + DataNode.UniquenessCheck uniquenessCheck = contractType.uniquenessChecks.TryGetValue(key, out DataNode.UniquenessCheck uc) ? uc : DataNode.UniquenessCheck.NONE; DataNode dataNode = BaseParser.currentParser.currentDataNode; // Provide warning of a better method diff --git a/source/ContractConfigurator/ExpressionParser/Wrappers/Tech.cs b/source/ContractConfigurator/ExpressionParser/Wrappers/Tech.cs index b986fce2d..17e1a4be3 100644 --- a/source/ContractConfigurator/ExpressionParser/Wrappers/Tech.cs +++ b/source/ContractConfigurator/ExpressionParser/Wrappers/Tech.cs @@ -32,7 +32,7 @@ public static Tech GetTech(string techID) return null; } - return allTech.ContainsKey(techID) ? allTech[techID] : null; + return allTech.TryGetValue(techID, out Tech tech) ? tech : null; } public bool IsUnlocked() @@ -113,12 +113,12 @@ private static bool SetupTech() foreach (ConfigNode parentNode in techNode.GetNodes("Parent")) { string parentID = parentNode.GetValue("parentID"); - if (allTech.ContainsKey(parentID)) + if (allTech.TryGetValue(parentID, out Tech tech)) { hasParent = true; - allTech[parentID].children.Add(current); + tech.children.Add(current); - current.level = allTech[parentID].level + 1; + current.level = tech.level + 1; } } diff --git a/source/ContractConfigurator/MissionControlUI.cs b/source/ContractConfigurator/MissionControlUI.cs index d502c76c0..6bbec456f 100644 --- a/source/ContractConfigurator/MissionControlUI.cs +++ b/source/ContractConfigurator/MissionControlUI.cs @@ -109,9 +109,9 @@ public GroupContainer(Type stockContractType) this.stockContractType = stockContractType; // Determine the agent - if (contractAgents.ContainsKey(stockContractType.Name)) + if (contractAgents.TryGetValue(stockContractType.Name, out Agent tmp)) { - agent = contractAgents[stockContractType.Name]; + agent = tmp; } } @@ -177,7 +177,7 @@ public static string DisplayName(Type type) LoadConfig(); } - return contractNames.ContainsKey(type.Name) ? contractNames[type.Name] : type.Name; + return contractNames.TryGetValue(type.Name, out string n) ? n : type.Name; } public string OrderKey() @@ -1621,9 +1621,8 @@ protected string ResearchBodyText(ContractType contractType) Dictionary bodyInfoDict = RBWrapper.RBactualAPI.CelestialBodies; foreach (CelestialBody body in contractType.contractBodies) { - if (bodyInfoDict.ContainsKey(body) && !body.isHomeWorld) + if (!body.isHomeWorld && bodyInfoDict.TryGetValue(body, out RBWrapper.CelestialBodyInfo bodyInfo)) { - RBWrapper.CelestialBodyInfo bodyInfo = bodyInfoDict[body]; // Must have researched <<1>> output += RequirementLine(Localizer.Format("#cc.mcui.req.researchBody", body.displayName), bodyInfo.isResearched); } diff --git a/source/ContractConfigurator/Parameter/Duration.cs b/source/ContractConfigurator/Parameter/Duration.cs index 2ea8e92c1..e867fc6c3 100644 --- a/source/ContractConfigurator/Parameter/Duration.cs +++ b/source/ContractConfigurator/Parameter/Duration.cs @@ -62,7 +62,7 @@ protected override string GetParameterTitle() Vessel currentVessel = CurrentVessel(); string title = null; - if (currentVessel != null && endTimes.ContainsKey(currentVessel.id) && endTimes[currentVessel.id] > 0.01 || + if (currentVessel != null && endTimes.TryGetValue(currentVessel.id, out double t) && t > 0.01 || currentVessel == null && endTime > 0.01) { double time = currentVessel != null ? endTimes[currentVessel.id] : endTime; @@ -268,7 +268,7 @@ protected override void OnUpdate() if (Planetarium.GetUniversalTime() - lastUpdate > 1.0f) { Vessel currentVessel = CurrentVessel(); - double time = currentVessel != null && endTimes.ContainsKey(currentVessel.id) ? endTimes[currentVessel.id] : endTime; + double time = currentVessel != null && endTimes.TryGetValue(currentVessel.id, out double t) ? t : endTime; if (time != 0.0 || resetClock) { lastUpdate = Planetarium.GetUniversalTime(); @@ -293,12 +293,12 @@ protected override void OnUpdate() protected override bool VesselMeetsCondition(Vessel vessel) { - if (vessel == null || !endTimes.ContainsKey(vessel.id)) + if (vessel == null || !endTimes.TryGetValue(vessel.id, out double t)) { return false; } - return Planetarium.GetUniversalTime() > endTimes[vessel.id]; + return Planetarium.GetUniversalTime() > t; } } } diff --git a/source/ContractConfigurator/Parameter/RecoverKerbalCustom.cs b/source/ContractConfigurator/Parameter/RecoverKerbalCustom.cs index a82b39482..bca2cd17c 100644 --- a/source/ContractConfigurator/Parameter/RecoverKerbalCustom.cs +++ b/source/ContractConfigurator/Parameter/RecoverKerbalCustom.cs @@ -105,7 +105,7 @@ protected override void OnParameterSave(ConfigNode node) node.AddNode(kerbalNode); kerbal.Save(kerbalNode); - kerbalNode.AddValue("recovered", recovered.ContainsKey(kerbal.name) && recovered[kerbal.name]); + kerbalNode.AddValue("recovered", recovered.TryGetValue(kerbal.name, out bool b) && b); } } diff --git a/source/ContractConfigurator/Parameter/SCANsatCoverage.cs b/source/ContractConfigurator/Parameter/SCANsatCoverage.cs index 45b997e58..3f2b6ba3e 100644 --- a/source/ContractConfigurator/Parameter/SCANsatCoverage.cs +++ b/source/ContractConfigurator/Parameter/SCANsatCoverage.cs @@ -58,7 +58,7 @@ public static string ScanDisplayName(string scanName) nameRemap["VisualHiRes"] = Localizer.GetStringByTag("#cc.scansat.scan.VisualHiRes"); } - return nameRemap.ContainsKey(scanName) ? nameRemap[scanName] : scanName; + return nameRemap.TryGetValue(scanName, out string name) ? name : scanName; } protected override string GetParameterTitle() diff --git a/source/ContractConfigurator/Parameter/VesselParameter.cs b/source/ContractConfigurator/Parameter/VesselParameter.cs index b7c8a8dc8..b6cda757b 100644 --- a/source/ContractConfigurator/Parameter/VesselParameter.cs +++ b/source/ContractConfigurator/Parameter/VesselParameter.cs @@ -178,16 +178,16 @@ protected virtual bool SetState(Vessel vessel, Contracts.ParameterState state) } // Initialize - if (!vesselInfo.ContainsKey(vessel.id)) + if (!vesselInfo.TryGetValue(vessel.id, out VesselInfo vi)) { - vesselInfo[vessel.id] = new VesselInfo(vessel.id, vessel); + vesselInfo[vessel.id] = vi = new VesselInfo(vessel.id, vessel); } // Set the completion time if (state == Contracts.ParameterState.Complete && - vesselInfo[vessel.id].state != Contracts.ParameterState.Complete) + vi.state != Contracts.ParameterState.Complete) { - vesselInfo[vessel.id].completionTime = Planetarium.GetUniversalTime(); + vi.completionTime = Planetarium.GetUniversalTime(); } // Force to failure if failWhenUnmet is set @@ -204,9 +204,9 @@ protected virtual bool SetState(Vessel vessel, Contracts.ParameterState state) // Set the state if (allowStateReset || state != ParameterState.Incomplete) { - if (vesselInfo[vessel.id].state != state) + if (vi.state != state) { - vesselInfo[vessel.id].state = state; + vi.state = state; return true; } else diff --git a/source/ContractConfigurator/Parameter/VesselParameter/CollectScienceCustom.cs b/source/ContractConfigurator/Parameter/VesselParameter/CollectScienceCustom.cs index fd9213ca0..4ac1f1bf6 100644 --- a/source/ContractConfigurator/Parameter/VesselParameter/CollectScienceCustom.cs +++ b/source/ContractConfigurator/Parameter/VesselParameter/CollectScienceCustom.cs @@ -221,9 +221,9 @@ protected void UpdateDelegates() if (param.ID.Contains("Subject")) { string exp = param.ID.Remove(param.ID.IndexOf("Subject")); - if (matchingSubjects.ContainsKey(exp)) + if (matchingSubjects.TryGetValue(exp, out ScienceSubject subj)) { - param.SetTitle(matchingSubjects[exp].title); + param.SetTitle(subj.title); param.SetState(ParameterState.Complete); } else @@ -613,7 +613,7 @@ private ScienceRecoveryMethod RecoveryMethod(string exp) } else { - if (!idealRecoverMethodCache.ContainsKey(exp)) + if (!idealRecoverMethodCache.TryGetValue(exp, out ScienceRecoveryMethod method)) { IEnumerable expNodes = PartLoader.Instance.loadedParts. Where(p => p.moduleInfos.Any(mod => mod.moduleName == "Science Experiment")). @@ -625,15 +625,15 @@ private ScienceRecoveryMethod RecoveryMethod(string exp) // Either has no parts or a full science transmitter if (!expNodes.Any() || expNodes.Any(n => ConfigNodeUtil.ParseValue(n, "xmitDataScalar", 0.0f) >= 0.999)) { - idealRecoverMethodCache[exp] = ScienceRecoveryMethod.RecoverOrTransmit; + idealRecoverMethodCache[exp] = method = ScienceRecoveryMethod.RecoverOrTransmit; } else { - idealRecoverMethodCache[exp] = ScienceRecoveryMethod.Recover; + idealRecoverMethodCache[exp] = method = ScienceRecoveryMethod.Recover; } } - return idealRecoverMethodCache[exp]; + return method; } } diff --git a/source/ContractConfigurator/Parameter/VesselParameter/RecoverVessel.cs b/source/ContractConfigurator/Parameter/VesselParameter/RecoverVessel.cs index 3cc43c281..919d2d598 100644 --- a/source/ContractConfigurator/Parameter/VesselParameter/RecoverVessel.cs +++ b/source/ContractConfigurator/Parameter/VesselParameter/RecoverVessel.cs @@ -78,7 +78,7 @@ protected override bool VesselMeetsCondition(Vessel vessel) { LoggingUtil.LogVerbose(this, "Checking VesselMeetsCondition: {0}", vessel.id); - return recovered.ContainsKey(vessel) && recovered[vessel]; + return recovered.TryGetValue(vessel, out bool b) && b; } } } diff --git a/source/ContractConfigurator/ParameterFactory.cs b/source/ContractConfigurator/ParameterFactory.cs index 9d34001ff..ce587b057 100644 --- a/source/ContractConfigurator/ParameterFactory.cs +++ b/source/ContractConfigurator/ParameterFactory.cs @@ -331,7 +331,7 @@ public static bool GenerateParameterFactory(ConfigNode parameterConfig, Contract paramFactory = new InvalidParameterFactory(); valid = false; } - else if (!factories.ContainsKey(type)) + else if (!factories.TryGetValue(type, out Type fType)) { LoggingUtil.LogError(typeof(ParameterFactory), "CONTRACT_TYPE '{0}', PARAMETER '{1}' of type '{2}': Unknown parameter '{3}'.", contractType.name, parameterConfig.GetValue("name"), parameterConfig.GetValue("type"), type); @@ -341,7 +341,7 @@ public static bool GenerateParameterFactory(ConfigNode parameterConfig, Contract else { // Create an instance of the factory - paramFactory = (ParameterFactory)Activator.CreateInstance(factories[type]); + paramFactory = (ParameterFactory)Activator.CreateInstance(fType); } // Set attributes diff --git a/source/ContractConfigurator/ScenarioModules/ContractVesselTracker.cs b/source/ContractConfigurator/ScenarioModules/ContractVesselTracker.cs index 6719962fa..4ecde1a37 100644 --- a/source/ContractConfigurator/ScenarioModules/ContractVesselTracker.cs +++ b/source/ContractConfigurator/ScenarioModules/ContractVesselTracker.cs @@ -96,12 +96,11 @@ IEnumerator CompleteVesselLoad(string key, Guid id) yield return new WaitForEndOfFrame(); } - if (!vessels.ContainsKey(key)) + if (!vessels.TryGetValue(key, out VesselInfo vi)) { yield break; } - VesselInfo vi = vessels[key]; Vessel vessel = FlightGlobals.FindVessel(id); if (vessel == null || vessel.state == Vessel.State.DEAD) { @@ -306,7 +305,7 @@ protected virtual void OnVesselDestroy(Vessel vessel) public void AssociateVessel(string key, Vessel vessel) { // Already associated! - if (vessel != null && vessels.ContainsKey(key) && vessels[key].id == vessel.id) + if (vessel != null && vessels.TryGetValue(key, out VesselInfo vi) && vi.id == vessel.id) { return; } @@ -325,9 +324,9 @@ public void AssociateVessel(string key, Vessel vessel) } // First remove whatever was there - if (vessels.ContainsKey(key)) + if (vessels.TryGetValue(key, out VesselInfo oldVi)) { - Guid oldVesselId = vessels[key].id; + Guid oldVesselId = oldVi.id; Vessel oldVessel = FlightGlobals.Vessels.Find(v => v != null && v.id == oldVesselId); vessels.Remove(key); @@ -354,9 +353,9 @@ public void AssociateVessel(string key, Vessel vessel) /// The vessel that is associated to the given key or null if none. public Vessel GetAssociatedVessel(string key) { - if (vessels.ContainsKey(key)) + if (vessels.TryGetValue(key, out VesselInfo vi)) { - return FlightGlobals.FindVessel(vessels[key].id); + return FlightGlobals.FindVessel(vi.id); } return null; } diff --git a/source/ContractConfigurator/ScenarioModules/PersistentDataStore.cs b/source/ContractConfigurator/ScenarioModules/PersistentDataStore.cs index 4fe4f7a7b..d976ccaf7 100644 --- a/source/ContractConfigurator/ScenarioModules/PersistentDataStore.cs +++ b/source/ContractConfigurator/ScenarioModules/PersistentDataStore.cs @@ -70,17 +70,17 @@ public void Store(ConfigNode node) /// public T Retrieve(string key) { - if (!data.ContainsKey(key)) + if (!data.TryGetValue(key, out object obj)) { return default(T); } try { - return (T)data[key]; + return (T)obj; } catch (InvalidCastException) { - throw new DataStoreCastException(typeof(T), data[key].GetType()); + throw new DataStoreCastException(typeof(T), obj.GetType()); } } @@ -102,11 +102,10 @@ public bool HasKey(string key) /// The value public object Retrieve(string key, out Type type) { - if (!data.ContainsKey(key)) + if (!data.TryGetValue(key, out object result)) { throw new Exception("Key '" + key + "' is not in persistent data store!"); } - object result = data[key]; type = result.GetType(); return result; } @@ -118,11 +117,11 @@ public object Retrieve(string key, out Type type) /// public ConfigNode Retrieve(string key) { - if (!configNodes.ContainsKey(key)) + if (!configNodes.TryGetValue(key, out ConfigNode cn)) { return new ConfigNode(); } - return configNodes[key]; + return cn; } public override void OnLoad(ConfigNode node) diff --git a/source/ContractConfigurator/Util/ConfigNodeUtil.cs b/source/ContractConfigurator/Util/ConfigNodeUtil.cs index db7259d13..be132f4b6 100644 --- a/source/ContractConfigurator/Util/ConfigNodeUtil.cs +++ b/source/ContractConfigurator/Util/ConfigNodeUtil.cs @@ -291,11 +291,11 @@ public static T ParseSingleValue(string key, string stringValue, bool allowEx } else if (typeof(T) == typeof(ContractGroup)) { - if (!ContractGroup.contractGroups.ContainsKey(stringValue)) + if (!ContractGroup.contractGroups.TryGetValue(stringValue, out ContractGroup cg)) { throw new ArgumentException("No contract group with name '" + stringValue + "'"); } - value = (T)(object)ContractGroup.contractGroups[stringValue]; + value = (T)(object)cg; } else if (typeof(T) == typeof(CelestialBody)) { @@ -639,11 +639,11 @@ public static bool ParseValue(ConfigNode configNode, string key, Action se // Defer loading this value DeferredLoadObject loadObj = null; - if (!deferredLoads.ContainsKey(path) || deferredLoads[path].GetType().GetGenericArguments().First() != typeof(T)) + if (!deferredLoads.TryGetValue(path, out DeferredLoadBase dlb) || dlb.GetType().GetGenericArguments().First() != typeof(T)) { - deferredLoads[path] = new DeferredLoadObject(configNode, key, setter, obj, validation, currentDataNode); + deferredLoads[path] = dlb = new DeferredLoadObject(configNode, key, setter, obj, validation, currentDataNode); } - loadObj = (DeferredLoadObject)deferredLoads[path]; + loadObj = (DeferredLoadObject)dlb; // New dependency - try again if (!loadObj.dependencies.Contains(dependency)) @@ -1034,9 +1034,9 @@ public static Type ParseTypeValue(string name) } else { - if (typeMap.ContainsKey(name)) + if (typeMap.TryGetValue(name, out Type tmp)) { - return typeMap[name]; + return tmp; } // Get all assemblies, but look at the ContractConfigurator ones first @@ -1094,13 +1094,13 @@ public static Experience.ExperienceTrait ParseExperienceTrait(string traitName) private static void AddFoundKey(ConfigNode configNode, string key) { // Initialize the list - if (!keysFound.ContainsKey(configNode)) + if (!keysFound.TryGetValue(configNode, out Dictionary dict)) { - keysFound[configNode] = new Dictionary(); + keysFound[configNode] = dict = new Dictionary(); } // Add the key - keysFound[configNode][key] = 1; + dict[key] = 1; } /// @@ -1208,14 +1208,13 @@ public static bool ValidateUnexpectedValues(ConfigNode configNode, IContractConf { bool valid = true; - if (!keysFound.ContainsKey(configNode)) + if (!keysFound.TryGetValue(configNode, out Dictionary found)) { obj.hasWarnings = true; LoggingUtil.LogWarning(obj.GetType(), "{0}: did not attempt to load values for ConfigNode!", obj.ErrorPrefix()); return false; } - Dictionary found = keysFound[configNode]; foreach (ConfigNode.Value pair in configNode.values) { if (!found.ContainsKey(pair.name)) diff --git a/source/ContractConfigurator/Util/ContractDisabler.cs b/source/ContractConfigurator/Util/ContractDisabler.cs index d9434f560..53a2cae86 100644 --- a/source/ContractConfigurator/Util/ContractDisabler.cs +++ b/source/ContractConfigurator/Util/ContractDisabler.cs @@ -110,12 +110,12 @@ public static bool IsEnabled(Type contract) public static IEnumerable DisablingGroups(Type contract) { - if (!contractDetails.ContainsKey(contract)) + if (!contractDetails.TryGetValue(contract, out ContractDetails cd)) { return Enumerable.Empty(); } - return contractDetails[contract].disablingGroups; + return cd.disablingGroups; } } } diff --git a/source/ContractConfigurator/Util/DebugWindow.cs b/source/ContractConfigurator/Util/DebugWindow.cs index abf36be66..db90d4876 100644 --- a/source/ContractConfigurator/Util/DebugWindow.cs +++ b/source/ContractConfigurator/Util/DebugWindow.cs @@ -613,7 +613,7 @@ static string DebugInfo(IContractConfiguratorFactory obj) return ""; } - if (!toolTipCache.ContainsKey(obj) || toolTipCache[obj].Key != obj.dataNode.lastModified) + if (!toolTipCache.TryGetValue(obj, out var kvp) || kvp.Key != obj.dataNode.lastModified) { string result = ""; result += "Config Node Details\n"; @@ -624,10 +624,10 @@ static string DebugInfo(IContractConfiguratorFactory obj) result += "Log Details\n"; result += obj.log; - toolTipCache[obj] = new KeyValuePair(obj.dataNode.lastModified, result); + toolTipCache[obj] = kvp = new KeyValuePair(obj.dataNode.lastModified, result); } - return toolTipCache[obj].Value; + return kvp.Value; } static string DataNodeDebug(DataNode node, int indent = 0) diff --git a/source/ContractConfigurator/Util/DraftTwitchViewers.cs b/source/ContractConfigurator/Util/DraftTwitchViewers.cs index 4fc97d79c..7f93709eb 100644 --- a/source/ContractConfigurator/Util/DraftTwitchViewers.cs +++ b/source/ContractConfigurator/Util/DraftTwitchViewers.cs @@ -123,12 +123,11 @@ public static string KerbalName(string defaultName) public static void OnSuccess(Dictionary dict) { Instance.routinesRunning--; - if (!dict.ContainsKey("name")) + if (!dict.TryGetValue("name", out string name)) { return; } - string name = dict["name"]; LoggingUtil.LogDebug(typeof(DraftTwitchViewers), "DraftTwitchViewers Success: {0}", name); // Queue the name if it is new diff --git a/source/ContractConfigurator/Util/Extensions.cs b/source/ContractConfigurator/Util/Extensions.cs index cbfccc547..004bb1d16 100644 --- a/source/ContractConfigurator/Util/Extensions.cs +++ b/source/ContractConfigurator/Util/Extensions.cs @@ -171,7 +171,7 @@ public static IEnumerable GetHashes(this Vessel vessel) while (otherVessel.Any()) { ProtoPartSnapshot px = otherVessel.Dequeue(); - if (!visited.ContainsKey(px) || visited[px] != 2) + if (!visited.TryGetValue(px, out int v) || v != 2) { queue.Enqueue(px); break; diff --git a/source/ContractConfigurator/Util/Science.cs b/source/ContractConfigurator/Util/Science.cs index 233d535f0..83a81fbb8 100644 --- a/source/ContractConfigurator/Util/Science.cs +++ b/source/ContractConfigurator/Util/Science.cs @@ -495,15 +495,15 @@ public static IEnumerable AvailableExperiments(CelestialBody private static ExperimentRules GetExperimentRules(string id) { // Get the experiment rules - if (!experimentRules.ContainsKey(id)) + if (!experimentRules.TryGetValue(id, out ExperimentRules rules)) { if (!id.StartsWith("ROCScience_")) { LoggingUtil.LogWarning(typeof(Science), "Experiment '{0}' is unknown, assuming a standard experiment.", id); } - experimentRules[id] = new ExperimentRules(id); + experimentRules[id] = rules = new ExperimentRules(id); } - return experimentRules[id]; + return rules; } } diff --git a/source/ContractConfigurator/Util/TitleTracker.cs b/source/ContractConfigurator/Util/TitleTracker.cs index 610850bea..641c2d915 100644 --- a/source/ContractConfigurator/Util/TitleTracker.cs +++ b/source/ContractConfigurator/Util/TitleTracker.cs @@ -138,7 +138,7 @@ public void UpdateContractWindow(string newTitle) // Get the cascading list for our contract if (text == null && ContractsApp.Instance != null) { - UICascadingList.CascadingListItem list = TitleTrackerHelper.UIListMap.ContainsKey(parameter.Root.ContractGuid) ? TitleTrackerHelper.UIListMap[parameter.Root.ContractGuid] : null; + UICascadingList.CascadingListItem list = TitleTrackerHelper.UIListMap.TryGetValue(parameter.Root.ContractGuid, out var i) ? i : null; if (list != null) {