private void SetupSwitcherWidget(PartModule pm, AvailablePart.ModuleInfo pmInfo, Transform parent, PartListTooltipWidget extInfoVariantsWidgePrefab) { string title = ""; string info = ""; if (pm is ModuleB9PartSwitch) { GetB9Info((ModuleB9PartSwitch)pm, out title, out info); } else if (pm is ModulePartVariants) { GetVariantsInfo((ModulePartVariants)pm, out title, out info); } PartListTooltipWidget widget = Instantiate(extInfoVariantsWidgePrefab); widget.Setup(title, info); widget.transform.SetParent(parent, false); // Create a button Button button = widget.gameObject.AddComponent <Button>(); button.enabled = true; ColorBlock colors = button.colors; colors.highlightedColor = new Color32(242, 213, 50, 100); button.colors = colors; button.onClick.AddListener(OnSwitcherWidgetClick); ButtonWidget handler = widget.gameObject.AddComponent <ButtonWidget>(); handler.switcherModule = pm; handler.widget = widget; }
private void PrepareInfoDescription(AvailablePart part, ModuleScienceExperiment moduleScienceExperiment, List <string> itemInfo) { try { List <AvailablePart.ModuleInfo> infos = part.moduleInfos; AvailablePart.ModuleInfo d = null; foreach (AvailablePart.ModuleInfo x in infos) { if (!x.info.Contains(moduleScienceExperiment.experimentActionName)) { continue; } d = x; break; } if (d == null) { return; } d.info = string.Concat(d.info, "\n", GetInfo(itemInfo, _usageMaskInt)); } catch (Exception ex) { Debug.LogException(ex); } }
private bool PrepareInfoDescriptionSE(AvailablePart part, string ExperimentDisplayName, List <string> itemInfo) { try { List <AvailablePart.ModuleInfo> infos = part.moduleInfos; AvailablePart.ModuleInfo d = null; foreach (AvailablePart.ModuleInfo i in infos) { if (!i.moduleDisplayName.Contains(ExperimentDisplayName)) { continue; } d = i; break; } if (d == null) { return(true); } d.info = string.Concat(d.info, "\n", GetInfo(itemInfo, _usageMaskInt)); } catch (Exception ex) { Debug.Log("DennyTX: " + ex); } return(false); }
private void Impact() { if (Impact_Present && !Impact_Present_X) { _partsWithScienceIMP = PartLoader.LoadedPartsList.Where(p => p.name.Contains("Impact")).ToList(); foreach (AvailablePart part in _partsWithScienceIMP) { ScienceExperiment experimentIMP = new ScienceExperiment(); switch (part.name) { case "Impact Seismometer": experimentIMP = ResearchAndDevelopment.GetExperiment("ImpactSeismometer"); _usageMaskInt = "<b><color=red>SURFACE ONLY, automated</color></b>"; break; case "Impact Spectrometer": experimentIMP = ResearchAndDevelopment.GetExperiment("ImpactSpectrometer"); _usageMaskInt = "<b><color=red>ORBIT ONLY, automated</color></b>"; break; } List <string> itemInfo = PrepareSituationAndBiomes(experimentIMP); AvailablePart.ModuleInfo d = new AvailablePart.ModuleInfo { moduleDisplayName = experimentIMP.experimentTitle, info = GetInfo(itemInfo, _usageMaskInt) }; part.moduleInfos.Add(d); } Impact_Present_X = true; } }
// See CompilePartInfo public static AvailablePart.ModuleInfo GetModuleInfo(PartModule pm) { AvailablePart.ModuleInfo moduleInfo = new AvailablePart.ModuleInfo(); if (pm is IModuleInfo) { IModuleInfo iModuleInfo = pm as IModuleInfo; moduleInfo.moduleName = iModuleInfo.GetModuleTitle(); moduleInfo.info = iModuleInfo.GetInfo().Trim(); moduleInfo.primaryInfo = iModuleInfo.GetPrimaryField(); } else { moduleInfo.moduleName = (pm.GUIName ?? KSPUtil.PrintModuleName(pm.moduleName)); moduleInfo.info = pm.GetInfo().Trim(); } if (pm.showUpgradesInModuleInfo && pm.HasUpgrades()) { moduleInfo.info += "\n" + pm.PrintUpgrades(); } moduleInfo.moduleDisplayName = pm.GetModuleDisplayName(); if (moduleInfo.moduleDisplayName == string.Empty) { moduleInfo.moduleDisplayName = moduleInfo.moduleName; } return(moduleInfo); }
//to call only on partprefab, as it create the partinfo public static PartModule createModule(Part part, ConfigNode nodeToCreate, bool withModuleInfo = true) { string moduleName = nodeToCreate.GetValue("name"); if (moduleName == null) { return(null); } PartModule newMod = part.AddModule(moduleName); if (Awaken(newMod)) { // uses reflection to find and call the PartModule.Awake() private method newMod.Load(nodeToCreate); //add info if (withModuleInfo && newMod.GetInfo().Length > 0) { //create AvailablePart.ModuleInfo info = new AvailablePart.ModuleInfo(); info.moduleName = newMod.moduleName.Replace("Module", ""); info.info = newMod.GetInfo(); //add part.partInfo.moduleInfos.Add(info); //sort info part.partInfo.moduleInfos.Sort((o1, o2) => o1.moduleName.CompareTo(o2.moduleName)); } return(newMod); } else { //Debug.log("create a module done & awake KO "); return(null); } }
public void Start() { IEnumerable <AvailablePart> pl = PartLoader.LoadedPartsList.Where(part => part.partPrefab.Modules != null && part.partPrefab.Modules.Contains <ModuleBdbBoiloff>()); foreach (AvailablePart p in pl) { for (int i = 0; i < p.moduleInfos.Count; i++) { AvailablePart.ModuleInfo mi = p.moduleInfos[i]; if (mi.moduleName == "Bdb Boiloff") { string s = ""; ModuleBdbBoiloff pm = p.partPrefab.GetComponent <ModuleBdbBoiloff>(); if (pm != null) { s = pm.GetInfoEditor(); } if (s != "") { mi.info = s; } else { p.moduleInfos.Remove(mi); } break; } } } }
static string PartInfo(AvailablePart part, string search) { string _partinfo = " "; if (!string.IsNullOrEmpty(part.tags) && searchExtension(partInfos.TAG, search)) { _partinfo += part.tags + " "; } if (part.title != null && searchExtension(partInfos.TITLE, search)) { _partinfo += part.title + " "; } if (part.author != null && searchExtension(partInfos.AUTHOR, search)) { _partinfo += part.author + " "; } if (part.manufacturer != null && searchExtension(partInfos.MANUFACTURER, search)) { _partinfo += part.manufacturer + " "; } if (part.name != null && searchExtension(partInfos.NAME, search)) { _partinfo += part.name + " "; } if (!float.IsNaN(part.partSize) && searchExtension(partInfos.PARTSIZE, search)) { _partinfo += part.partSize + " "; } if (part.resourceInfos.Count > 0 && searchExtension(partInfos.RESOURCEINFOS, search)) { _partinfo += part.resourceInfo + " "; List <AvailablePart.ResourceInfo> _resourceInfos = part.resourceInfos; for (int _i = _resourceInfos.Count - 1; _i >= 0; --_i) { AvailablePart.ResourceInfo _resourceInfo = _resourceInfos[_i]; _partinfo += _resourceInfo.resourceName + " "; } } if (part.TechRequired != null && searchExtension(partInfos.TECHREQUIRED, search)) { _partinfo += part.TechRequired + " "; } if (part.moduleInfos.Count > 0 && searchExtension(partInfos.MODULE, search)) { List <AvailablePart.ModuleInfo> _moduleInfos = part.moduleInfos; for (int _i = _moduleInfos.Count - 1; _i >= 0; --_i) { AvailablePart.ModuleInfo _moduleInfo = _moduleInfos[_i]; _partinfo += _moduleInfo.moduleName + " "; } } if (part.description != null && searchExtension(partInfos.DESCRIPTION, search)) { _partinfo += part.description; } return(_partinfo); }
/// <summary> /// This method creates a new AvailablePart.ModuleInfo object with /// the Technology Perk info block. /// </summary> /// <param name="part">Part to get the infos</param> /// <returns></returns> private AvailablePart.ModuleInfo CreateTechPerkInfoforPart(Part part) { // Get the infos for the TechPerk info block string perk_infos = this.RefreshPartInfo(part, "ModuleRTAntennaPassive"); // creates a new info block AvailablePart.ModuleInfo NewPerkInfo = new AvailablePart.ModuleInfo(); NewPerkInfo.info = perk_infos; NewPerkInfo.moduleName = "Technology Perk"; return(NewPerkInfo); }
/// <summary> /// This method creates a new AvailablePart.ModuleInfo object with /// the Technology Perk info block. /// </summary> /// <param name="part">Part to get the infos</param> /// <returns></returns> private AvailablePart.ModuleInfo CreateTechPerkInfoforPart(Part part) { // Get the infos for the TechPerk info block var perkInfos = RefreshPartInfo(part, "ModuleRTAntennaPassive"); // creates a new info block var newPerkInfo = new AvailablePart.ModuleInfo { info = perkInfos, moduleName = Localizer.Format("#RT_Editor_TechnologyPerk")//"Technology Perk" }; return(newPerkInfo); }
/// <summary> /// This method creates a new AvailablePart.ModuleInfo object with /// the Technology Perk info block. /// </summary> /// <param name="part">Part to get the infos</param> /// <returns></returns> private AvailablePart.ModuleInfo CreateTechPerkInfoforPart(Part part) { // Get the infos for the TechPerk info block var perkInfos = RefreshPartInfo(part, "ModuleRTAntennaPassive"); // creates a new info block var newPerkInfo = new AvailablePart.ModuleInfo { info = perkInfos, moduleName = "Technology Perk" }; return newPerkInfo; }
public static void majInfo(Part p, ModuleEngines me) { //update info for (int i = 0; i < p.partInfo.moduleInfos.Count; i++) { AvailablePart.ModuleInfo info = p.partInfo.moduleInfos[i]; if (info.moduleName == "Engine" || info.moduleName == "EngineFX") { info.primaryInfo = me.GetPrimaryField(); info.info = me.GetInfo(); info.onDrawWidget = me.GetDrawModulePanelCallback(); break; } } }
// This happens every time Space Center is entered, may be a place of optimization // if it take noticable time void Start() { for (int i = 0; i < PartLoader.LoadedPartsList.Count; i++) { AvailablePart ap = PartLoader.LoadedPartsList[i]; var part = ap.partPrefab; for (int i1 = 0; i1 < ap.moduleInfos.Count; i1++) { var m = ap.moduleInfos[i1]; if (m.moduleName == "R&D") { AvailablePart.ModuleInfo info = m; m.info = KRnDModule.GetInfo(part); break; } } } }
private void RoverScience() { if (!ROV_Present || ROV_Present_X) { return; } _partsWithScienceROV = PartLoader.LoadedPartsList.Where(p => p.name.Contains("roverBrain")).ToList(); foreach (AvailablePart part in _partsWithScienceROV) { ScienceExperiment experimentROV = ResearchAndDevelopment.GetExperiment("RoverScienceExperiment"); List <string> itemInfo = PrepareSituationAndBiomes(experimentROV); _usageMaskInt = "<b><color=red>SURFACE ONLY, find a place</color></b>"; AvailablePart.ModuleInfo d = new AvailablePart.ModuleInfo { moduleDisplayName = experimentROV.experimentTitle, info = GetInfo(itemInfo, _usageMaskInt) }; part.moduleInfos.Add(d); } ROV_Present_X = true; }
private IEnumerator RefreshPartInfo() { yield return(null); try{ foreach (var ap in PartLoader.LoadedPartsList.Where(ap => ap.partPrefab.Modules != null)) { AvailablePart.ModuleInfo target = null; foreach (var mi in ap.moduleInfos) { if (mi.moduleName == "Reliability Info") { target = mi; } } if (target != null & !this.currentSettings.EnabledForSave) { ap.moduleInfos.Remove(target); } if (target == null & this.currentSettings.EnabledForSave) { IEnumerable <ModuleReliabilityInfo> reliabilityModules = ap.partPrefab.Modules.OfType <ModuleReliabilityInfo>(); if (reliabilityModules.Count() != 0) { AvailablePart.ModuleInfo newModuleInfo = new AvailablePart.ModuleInfo(); newModuleInfo.moduleName = "Reliability Info"; newModuleInfo.info = reliabilityModules.First().GetInfo(); ap.moduleInfos.Add(newModuleInfo); } } } Log("Refresh Finished"); }catch (Exception e) { this.Log("ERROR [" + e.GetType().ToString() + "]: " + e.Message + "\n" + e.StackTrace); } }
private void UpdateInfoToolTip(bool getHoveredpart = true) { // Get the part if requested if (getHoveredpart) { selectedPart = hoveredPart; } if (selectedPart == null) { ShowInfoToolTip(false); return; } // Create the UI if (!objectsCreated) { //UIPartActionWindow customPAW = Instantiate(UIPartActionController.Instance.windowPrefab); //customPAW.transform.SetParent(UIMasterController.Instance.actionCanvas.transform, false); //customPAW.gameObject.SetActive(true); //customPAW.gameObject.name = "FloatingPartTooltip"; //customPAW.Setup(selectedPart, UIPartActionWindow.DisplayType.Selected, UI_Scene.Editor); //customPAW.gameObject.GetChild("VerticalLayout").DestroyGameObject(); //infoToolTipInstance = Instantiate(FindObjectOfType<PartListTooltipController>().tooltipPrefab, customPAW.gameObject.transform); //infoToolTip = infoToolTipInstance.gameObject; //infoToolTip.transform.SetSiblingIndex(2); // Create tooltip object infoToolTipInstance = Instantiate(FindObjectOfType <PartListTooltipController>().tooltipPrefab, DialogCanvasUtil.DialogCanvasRect); infoToolTip = infoToolTipInstance.gameObject; // Get various UI GameObjects descriptionText = infoToolTip.GetChild("DescriptionText"); descriptionTopObject = infoToolTip.GetChild("Scroll View"); descriptionContent = descriptionText.transform.parent.gameObject; manufacturerPanel = infoToolTip.GetChild("ManufacturerPanel"); primaryInfoTopObject = infoToolTip.GetChild("ThumbAndPrimaryInfo").GetChild("Scroll View"); footerTopObject = infoToolTip.GetChild("Footer"); extWidgetsContent = infoToolTipInstance.panelExtended.GetChild("Content"); // Make it draggable DragPanelOffsettable dragpanel = infoToolTip.AddComponent <DragPanelOffsettable>(); dragpanel.edgeOffset = 20; // Remove part thumbnail infoToolTip.GetChild("ThumbContainer").DestroyGameObject(); // Remove RMBHint infoToolTip.GetChild("RMBHint").DestroyGameObject(); // Remove module widget list variant spacer infoToolTipInstance.extInfoListSpacerVariants.gameObject.DestroyGameObject(); // Adjust size LayoutElement leftPanel = infoToolTip.GetChild("StandardInfo").GetComponent <LayoutElement>(); leftPanel.preferredWidth = 240; leftPanel.minWidth = 240; LayoutElement costPanel = infoToolTip.GetChild("CostPanel").GetComponent <LayoutElement>(); costPanel.preferredWidth = 150; // Add switcher toggle infoButton = CreateButton(footerTopObject.transform, OnSwitcherToggle); infoButton.GetComponent <LayoutElement>().minWidth = 106; infoButton.GetComponent <LayoutElement>().preferredHeight = 24; infoButton.GetComponentInChildren <TextMeshProUGUI>().SetText("Show part info"); objectsCreated = true; } // Destroy module/ressource widgets PartListTooltipWidget[] extWidgets = extWidgetsContent.GetComponentsInChildren <PartListTooltipWidget>(true); for (int i = 0; i < extWidgets.Count(); i++) { extWidgets[i].gameObject.DestroyGameObject(); } // Destroy switcher widgets PartListTooltipWidget[] switchWidgets = descriptionContent.GetComponentsInChildren <PartListTooltipWidget>(true); for (int i = 0; i < switchWidgets.Count(); i++) { switchWidgets[i].gameObject.DestroyGameObject(); } // TODO: revert scrollbars to top bool hasSwitcher = false; // Create partmodule and switcher widgets foreach (PartModule pm in selectedPart.Modules) { if (!pm.enabled || !pm.isEnabled) { continue; } AvailablePart.ModuleInfo pmInfo = GetModuleInfo(pm); if (pm is ModuleB9PartSwitch || pm is ModulePartVariants) { SetupSwitcherWidget(pm, pmInfo, descriptionContent.transform, infoToolTipInstance.extInfoVariantsWidgePrefab); hasSwitcher = true; continue; } if (string.IsNullOrEmpty(pmInfo.info)) { continue; } PartListTooltipWidget widget = Instantiate(infoToolTipInstance.extInfoModuleWidgetPrefab); widget.Setup(pmInfo.moduleDisplayName, pmInfo.info); widget.transform.SetParent(infoToolTipInstance.extInfoListContainer, false); } // Move or hide module spacer if (infoToolTipInstance.extInfoListContainer.childCount > 2 && selectedPart.Resources.Count > 0) { infoToolTipInstance.extInfoListSpacer.gameObject.SetActive(true); infoToolTipInstance.extInfoListSpacer.SetSiblingIndex(infoToolTipInstance.extInfoListContainer.childCount - 1); } else { infoToolTipInstance.extInfoListSpacer.gameObject.SetActive(false); } // Add ressource widgets foreach (PartResource pr in selectedPart.Resources) { AvailablePart.ResourceInfo prInfo = GetResourceInfo(pr); if (string.IsNullOrEmpty(prInfo.info)) { continue; } //if (RemoveControlCharacters(pm.GetInfo()).Equals("")) continue; PartListTooltipWidget widget = Instantiate(infoToolTipInstance.extInfoRscWidgePrefab); widget.Setup(prInfo.displayName, prInfo.info); widget.transform.SetParent(infoToolTipInstance.extInfoListContainer, false); } // Setup info infoToolTipInstance.textName.text = selectedPart.partInfo.title; infoToolTipInstance.textManufacturer.text = selectedPart.partInfo.manufacturer; infoToolTipInstance.textDescription.text = selectedPart.partInfo.description; infoToolTipInstance.textInfoBasic.text = GetPartInfo(selectedPart); infoToolTipInstance.textCost.text = Localizer.Format("#autoLOC_456128", new string[] { "<sprite=\"CurrencySpriteAsset\" name=\"Funds\" tint=1>", ( selectedPart.partInfo.cost + selectedPart.GetModuleCosts(0.0f, ModifierStagingSituation.CURRENT) //TODO: this is wrong if ressource amount != maxamount ).ToString("N2") }); infoToolTipInstance.panelExtended.SetActive(infoToolTipInstance.extInfoListContainer.GetComponentsInChildren <PartListTooltipWidget>(true).Count() > 0); // Reposition tooltip if new part selected if (getHoveredpart) { UIMasterController.RepositionTooltip((RectTransform)infoToolTip.transform, Vector2.one, 8f); } // Update switcher button visibility infoButton.SetActive(hasSwitcher); ShowSwitcherWidgets(hasSwitcher); }
public void Update() { this.enabled = true; AvailablePart intakePart = PartLoader.getPartInfoByName("CircularIntake"); if (intakePart != null) { if (intakePart.partPrefab.FindModulesImplementing<AtmosphericIntake>().Count <= 0 && PartLoader.Instance.IsReady()) { plugin_init = false; } } if (!resources_configured) { ConfigNode plugin_settings = GameDatabase.Instance.GetConfigNode("Interstellar/InterstellarSettings/InterstellarSettings"); if (plugin_settings != null) { if (plugin_settings.HasValue("HydrogenResourceName")) { PluginHelper.hydrogen_resource_name = plugin_settings.GetValue("HydrogenResourceName"); Debug.Log("[KSP Interstellar] Hydrogen resource name set to " + PluginHelper.hydrogen_resource_name); } if (plugin_settings.HasValue("OxygenResourceName")) { PluginHelper.oxygen_resource_name = plugin_settings.GetValue("OxygenResourceName"); Debug.Log("[KSP Interstellar] Oxygen resource name set to " + PluginHelper.oxygen_resource_name); } if (plugin_settings.HasValue("AluminiumResourceName")) { PluginHelper.aluminium_resource_name = plugin_settings.GetValue("AluminiumResourceName"); Debug.Log("[KSP Interstellar] Aluminium resource name set to " + PluginHelper.aluminium_resource_name); } if (plugin_settings.HasValue("MethaneResourceName")) { PluginHelper.methane_resource_name = plugin_settings.GetValue("MethaneResourceName"); Debug.Log("[KSP Interstellar] Methane resource name set to " + PluginHelper.methane_resource_name); } if (plugin_settings.HasValue("ArgonResourceName")) { PluginHelper.argon_resource_name = plugin_settings.GetValue("ArgonResourceName"); Debug.Log("[KSP Interstellar] Argon resource name set to " + PluginHelper.argon_resource_name); } if (plugin_settings.HasValue("WaterResourceName")) { PluginHelper.water_resource_name = plugin_settings.GetValue("WaterResourceName"); Debug.Log("[KSP Interstellar] Water resource name set to " + PluginHelper.water_resource_name); } if (plugin_settings.HasValue("HydrogenPeroxideResourceName")) { PluginHelper.hydrogen_peroxide_resource_name = plugin_settings.GetValue("HydrogenPeroxideResourceName"); Debug.Log("[KSP Interstellar] Hydrogen Peroxide resource name set to " + PluginHelper.hydrogen_peroxide_resource_name); } if (plugin_settings.HasValue("AmmoniaResourceName")) { PluginHelper.ammonia_resource_name = plugin_settings.GetValue("AmmoniaResourceName"); Debug.Log("[KSP Interstellar] Ammonia resource name set to " + PluginHelper.ammonia_resource_name); } if (plugin_settings.HasValue("ThermalMechanicsDisabled")) { PluginHelper.is_thermal_dissip_disabled = bool.Parse(plugin_settings.GetValue("ThermalMechanicsDisabled")); Debug.Log("[KSP Interstellar] ThermalMechanics set to enabled: " + !PluginHelper.is_thermal_dissip_disabled); } if (plugin_settings.HasValue("RadiatorEmissiveGlowDisabled")) { PluginHelper.is_radiator_emissive_glow_disabled = bool.Parse(plugin_settings.GetValue("RadiatorEmissiveGlowDisabled")); Debug.Log("[KSP Interstellar] Radiator Glow set to enabled: " + !PluginHelper.is_radiator_emissive_glow_disabled); } resources_configured = true; } else { showInstallationErrorMessage(); } } if (!plugin_init) { gdb = GameDatabase.Instance; plugin_init = true; AvailablePart kerbalRadiationPart = PartLoader.getPartInfoByName("kerbalEVA"); if (kerbalRadiationPart.partPrefab.Modules != null) { if (kerbalRadiationPart.partPrefab.FindModulesImplementing<FNModuleRadiation>().Count == 0) { kerbalRadiationPart.partPrefab.gameObject.AddComponent<FNModuleRadiation>(); } } else { kerbalRadiationPart.partPrefab.gameObject.AddComponent<FNModuleRadiation>(); } List<AvailablePart> available_parts = PartLoader.LoadedPartsList; foreach (AvailablePart available_part in available_parts) { Part prefab_available_part = available_part.partPrefab; try { if(prefab_available_part.Modules != null) { if(prefab_available_part.FindModulesImplementing<ModuleResourceIntake>().Count > 0) { ModuleResourceIntake intake = prefab_available_part.Modules["ModuleResourceIntake"] as ModuleResourceIntake; if(intake.resourceName == "IntakeAir") { Type type = AssemblyLoader.GetClassByName(typeof(PartModule), "AtmosphericIntake"); AtmosphericIntake pm = null; if(type != null) { pm = prefab_available_part.gameObject.AddComponent(type) as AtmosphericIntake; prefab_available_part.Modules.Add(pm); pm.area = intake.area*intake.unitScalar*intake.maxIntakeSpeed/20; } PartResource intake_air_resource = prefab_available_part.Resources["IntakeAir"]; if (intake_air_resource != null && !prefab_available_part.Resources.Contains("IntakeAtm")) { ConfigNode node = new ConfigNode("RESOURCE"); node.AddValue("name", "IntakeAtm"); node.AddValue("maxAmount", intake_air_resource.maxAmount); node.AddValue("amount", intake_air_resource.amount); prefab_available_part.AddResource(node); } } } if (prefab_available_part.FindModulesImplementing<ModuleDeployableSolarPanel>().Count > 0) { ModuleDeployableSolarPanel panel = prefab_available_part.Modules["ModuleDeployableSolarPanel"] as ModuleDeployableSolarPanel; if (panel.chargeRate > 0) { Type type = AssemblyLoader.GetClassByName(typeof(PartModule), "FNSolarPanelWasteHeatModule"); FNSolarPanelWasteHeatModule pm = null; if (type != null) { pm = prefab_available_part.gameObject.AddComponent(type) as FNSolarPanelWasteHeatModule; prefab_available_part.Modules.Add(pm); } } if (!prefab_available_part.Resources.Contains("WasteHeat") && panel.chargeRate > 0) { ConfigNode node = new ConfigNode("RESOURCE"); node.AddValue("name", "WasteHeat"); node.AddValue("maxAmount", panel.chargeRate * 100); node.AddValue("amount", 0); PartResource pr = prefab_available_part.AddResource(node); if (available_part.resourceInfo != null && pr != null) { if (available_part.resourceInfo.Length == 0) { available_part.resourceInfo = pr.resourceName + ":" + pr.amount + " / " + pr.maxAmount; } else { available_part.resourceInfo = available_part.resourceInfo + "\n" + pr.resourceName + ":" + pr.amount + " / " + pr.maxAmount; } } } if (!prefab_available_part.Resources.Contains("Megajoules") && panel.chargeRate > 0) { ConfigNode node = new ConfigNode("RESOURCE"); node.AddValue("name", "Megajoules"); node.AddValue("maxAmount", panel.chargeRate); node.AddValue("amount", 0); PartResource pr = prefab_available_part.AddResource(node); if (available_part.resourceInfo != null && pr != null) { if (available_part.resourceInfo.Length == 0) { available_part.resourceInfo = pr.resourceName + ":" + pr.amount + " / " + pr.maxAmount; } else { available_part.resourceInfo = available_part.resourceInfo + "\n" + pr.resourceName + ":" + pr.amount + " / " + pr.maxAmount; } } } } if(prefab_available_part.FindModulesImplementing<ElectricEngineController>().Count() > 0) { available_part.moduleInfo = prefab_available_part.FindModulesImplementing<ElectricEngineController>().First().GetInfo(); available_part.moduleInfos.RemoveAll(modi => modi.moduleName == "Engine"); AvailablePart.ModuleInfo mod_info = available_part.moduleInfos.Where(modi => modi.moduleName == "Electric Engine Controller").First(); mod_info.moduleName = "Electric Engine"; } if(prefab_available_part.FindModulesImplementing<FNNozzleController>().Count() > 0) { available_part.moduleInfo = prefab_available_part.FindModulesImplementing<FNNozzleController>().First().GetInfo(); available_part.moduleInfos.RemoveAll(modi => modi.moduleName == "Engine"); AvailablePart.ModuleInfo mod_info = available_part.moduleInfos.Where(modi => modi.moduleName == "FNNozzle Controller").First(); mod_info.moduleName = "Thermal Nozzle"; } if(prefab_available_part.CrewCapacity > 0 || prefab_available_part.FindModulesImplementing<ModuleCommand>().Count > 0) { Type type = AssemblyLoader.GetClassByName(typeof(PartModule), "FNModuleRadiation"); FNModuleRadiation pm = null; if(type != null) { pm = prefab_available_part.gameObject.AddComponent(type) as FNModuleRadiation; prefab_available_part.Modules.Add(pm); double rad_hardness = prefab_available_part.mass /(Math.Max(prefab_available_part.CrewCapacity,0.1))*7.5; pm.rad_hardness = rad_hardness; AvailablePart.ModuleInfo minfo = new AvailablePart.ModuleInfo(); minfo.moduleName = "Radiation Status"; minfo.info = pm.GetInfo(); available_part.moduleInfos.Add(minfo); } print("Adding ModuleRadiation to " + prefab_available_part.name); } } }catch(Exception ex) { if (prefab_available_part != null) { print("[KSP Interstellar] Exception caught adding to: " + prefab_available_part.name + " part: " + ex.ToString()); } else { print("[KSP Interstellar] Exception caught adding to unknown module"); } } } } //Destroy (this); }
public void Update() { this.enabled = true; AvailablePart intakePart = PartLoader.getPartInfoByName("CircularIntake"); if (intakePart != null) { if (intakePart.partPrefab.FindModulesImplementing <AtmosphericIntake>().Count <= 0 && PartLoader.Instance.IsReady()) { plugin_init = false; } } if (!resources_configured) { ConfigNode plugin_settings = GameDatabase.Instance.GetConfigNode("WarpPlugin/WarpPluginSettings/WarpPluginSettings"); if (plugin_settings != null) { if (plugin_settings.HasValue("HydrogenResourceName")) { PluginHelper.hydrogen_resource_name = plugin_settings.GetValue("HydrogenResourceName"); Debug.Log("[KSP Interstellar] Hydrogen resource name set to " + PluginHelper.hydrogen_resource_name); } if (plugin_settings.HasValue("OxygenResourceName")) { PluginHelper.oxygen_resource_name = plugin_settings.GetValue("OxygenResourceName"); Debug.Log("[KSP Interstellar] Oxygen resource name set to " + PluginHelper.oxygen_resource_name); } if (plugin_settings.HasValue("AluminiumResourceName")) { PluginHelper.aluminium_resource_name = plugin_settings.GetValue("AluminiumResourceName"); Debug.Log("[KSP Interstellar] Aluminium resource name set to " + PluginHelper.aluminium_resource_name); } if (plugin_settings.HasValue("MethaneResourceName")) { PluginHelper.methane_resource_name = plugin_settings.GetValue("MethaneResourceName"); Debug.Log("[KSP Interstellar] Methane resource name set to " + PluginHelper.methane_resource_name); } if (plugin_settings.HasValue("ArgonResourceName")) { PluginHelper.argon_resource_name = plugin_settings.GetValue("ArgonResourceName"); Debug.Log("[KSP Interstellar] Argon resource name set to " + PluginHelper.argon_resource_name); } if (plugin_settings.HasValue("WaterResourceName")) { PluginHelper.water_resource_name = plugin_settings.GetValue("WaterResourceName"); Debug.Log("[KSP Interstellar] Water resource name set to " + PluginHelper.water_resource_name); } if (plugin_settings.HasValue("HydrogenPeroxideResourceName")) { PluginHelper.hydrogen_peroxide_resource_name = plugin_settings.GetValue("HydrogenPeroxideResourceName"); Debug.Log("[KSP Interstellar] Hydrogen Peroxide resource name set to " + PluginHelper.hydrogen_peroxide_resource_name); } if (plugin_settings.HasValue("AmmoniaResourceName")) { PluginHelper.ammonia_resource_name = plugin_settings.GetValue("AmmoniaResourceName"); Debug.Log("[KSP Interstellar] Ammonia resource name set to " + PluginHelper.ammonia_resource_name); } if (plugin_settings.HasValue("ThermalMechanicsDisabled")) { PluginHelper.is_thermal_dissip_disabled = bool.Parse(plugin_settings.GetValue("ThermalMechanicsDisabled")); Debug.Log("[KSP Interstellar] ThermalMechanics set to enabled: " + !PluginHelper.is_thermal_dissip_disabled); } resources_configured = true; } else { showInstallationErrorMessage(); } } if (!plugin_init) { gdb = GameDatabase.Instance; plugin_init = true; AvailablePart kerbalRadiationPart = PartLoader.getPartInfoByName("kerbalEVA"); if (kerbalRadiationPart.partPrefab.Modules != null) { if (kerbalRadiationPart.partPrefab.FindModulesImplementing <FNModuleRadiation>().Count == 0) { kerbalRadiationPart.partPrefab.gameObject.AddComponent <FNModuleRadiation>(); } } else { kerbalRadiationPart.partPrefab.gameObject.AddComponent <FNModuleRadiation>(); } List <AvailablePart> available_parts = PartLoader.LoadedPartsList; foreach (AvailablePart available_part in available_parts) { Part prefab_available_part = available_part.partPrefab; try { if (prefab_available_part.Modules != null) { if (prefab_available_part.FindModulesImplementing <ModuleResourceIntake>().Count > 0) { ModuleResourceIntake intake = prefab_available_part.Modules["ModuleResourceIntake"] as ModuleResourceIntake; if (intake.resourceName == "IntakeAir") { Type type = AssemblyLoader.GetClassByName(typeof(PartModule), "AtmosphericIntake"); AtmosphericIntake pm = null; if (type != null) { pm = prefab_available_part.gameObject.AddComponent(type) as AtmosphericIntake; prefab_available_part.Modules.Add(pm); pm.area = intake.area * intake.unitScalar * intake.maxIntakeSpeed / 20; } PartResource intake_air_resource = prefab_available_part.Resources["IntakeAir"]; if (intake_air_resource != null && !prefab_available_part.Resources.Contains("IntakeAtm")) { ConfigNode node = new ConfigNode("RESOURCE"); node.AddValue("name", "IntakeAtm"); node.AddValue("maxAmount", intake_air_resource.maxAmount); node.AddValue("amount", intake_air_resource.amount); prefab_available_part.AddResource(node); } } } if (prefab_available_part.FindModulesImplementing <ModuleDeployableSolarPanel>().Count > 0) { ModuleDeployableSolarPanel panel = prefab_available_part.Modules["ModuleDeployableSolarPanel"] as ModuleDeployableSolarPanel; if (panel.chargeRate > 0) { Type type = AssemblyLoader.GetClassByName(typeof(PartModule), "FNSolarPanelWasteHeatModule"); FNSolarPanelWasteHeatModule pm = null; if (type != null) { pm = prefab_available_part.gameObject.AddComponent(type) as FNSolarPanelWasteHeatModule; prefab_available_part.Modules.Add(pm); } } if (!prefab_available_part.Resources.Contains("WasteHeat") && panel.chargeRate > 0) { ConfigNode node = new ConfigNode("RESOURCE"); node.AddValue("name", "WasteHeat"); node.AddValue("maxAmount", panel.chargeRate * 100); node.AddValue("amount", 0); PartResource pr = prefab_available_part.AddResource(node); if (available_part.resourceInfo != null && pr != null) { if (available_part.resourceInfo.Length == 0) { available_part.resourceInfo = pr.resourceName + ":" + pr.amount + " / " + pr.maxAmount; } else { available_part.resourceInfo = available_part.resourceInfo + "\n" + pr.resourceName + ":" + pr.amount + " / " + pr.maxAmount; } } } } if (prefab_available_part.FindModulesImplementing <ElectricEngineController>().Count() > 0) { available_part.moduleInfo = prefab_available_part.FindModulesImplementing <ElectricEngineController>().First().GetInfo(); available_part.moduleInfos.RemoveAll(modi => modi.moduleName == "Engine"); AvailablePart.ModuleInfo mod_info = available_part.moduleInfos.Where(modi => modi.moduleName == "Electric Engine Controller").First(); mod_info.moduleName = "Electric Engine"; } if (prefab_available_part.FindModulesImplementing <FNNozzleController>().Count() > 0) { available_part.moduleInfo = prefab_available_part.FindModulesImplementing <FNNozzleController>().First().GetInfo(); available_part.moduleInfos.RemoveAll(modi => modi.moduleName == "Engine"); AvailablePart.ModuleInfo mod_info = available_part.moduleInfos.Where(modi => modi.moduleName == "FNNozzle Controller").First(); mod_info.moduleName = "Thermal Nozzle"; } if (prefab_available_part.CrewCapacity > 0) { Type type = AssemblyLoader.GetClassByName(typeof(PartModule), "FNModuleRadiation"); FNModuleRadiation pm = null; if (type != null) { pm = prefab_available_part.gameObject.AddComponent(type) as FNModuleRadiation; prefab_available_part.Modules.Add(pm); double rad_hardness = prefab_available_part.mass / ((double)prefab_available_part.CrewCapacity) * 7.5; pm.rad_hardness = rad_hardness; } print("Adding ModuleRadiation to " + prefab_available_part.name); } } }catch (Exception ex) { if (prefab_available_part != null) { print("[KSP Interstellar] Exception caught adding to: " + prefab_available_part.name + " part: " + ex.ToString()); } else { print("[KSP Interstellar] Exception caught adding to unknown module"); } } } } //Destroy (this); }
public void Update() { this.enabled = true; AvailablePart intakePart = PartLoader.getPartInfoByName("CircularIntake"); if (intakePart != null) { if (intakePart.partPrefab.FindModulesImplementing <AtmosphericIntake>().Count <= 0 && PartLoader.Instance.IsReady()) { plugin_init = false; } } if (!resources_configured) { // read WarpPluginSettings.cfg ConfigNode plugin_settings = GameDatabase.Instance.GetConfigNode("WarpPlugin/WarpPluginSettings/WarpPluginSettings"); if (plugin_settings != null) { if (plugin_settings.HasValue("PartTechUpgrades")) { PartTechUpgrades = new Dictionary <string, string>(); string rawstring = plugin_settings.GetValue("PartTechUpgrades"); string[] splitValues = rawstring.Split(',').Select(sValue => sValue.Trim()).ToArray(); int pairs = splitValues.Length / 2; int totalValues = splitValues.Length / 2 * 2; for (int i = 0; i < totalValues; i += 2) { PartTechUpgrades.Add(splitValues[i], splitValues[i + 1]); } Debug.Log("[KSP Interstellar] Part Tech Upgrades set to: " + rawstring); } if (plugin_settings.HasValue("OrsResourceMappings")) { OrsResourceMappings = new Dictionary <string, string>(); string rawstring = plugin_settings.GetValue("OrsResourceMappings"); string[] splitValues = rawstring.Split(',').Select(sValue => sValue.Trim()).ToArray(); int pairs = splitValues.Length / 2; int totalValues = pairs * 2; for (int i = 0; i < totalValues; i += 2) { OrsResourceMappings.Add(splitValues[i], splitValues[i + 1]); } } if (plugin_settings.HasValue("RadiationMechanicsDisabled")) { PluginHelper._radiationMechanicsDisabled = bool.Parse(plugin_settings.GetValue("RadiationMechanicsDisabled")); Debug.Log("[KSP Interstellar] Radiation Mechanics Disabled set to: " + PluginHelper.RadiationMechanicsDisabled.ToString()); } if (plugin_settings.HasValue("ThermalMechanicsDisabled")) { PluginHelper._isThermalDissipationDisabled = bool.Parse(plugin_settings.GetValue("ThermalMechanicsDisabled")); Debug.Log("[KSP Interstellar] ThermalMechanics set to : " + (!PluginHelper.IsThermalDissipationDisabled).ToString()); } if (plugin_settings.HasValue("SolarPanelClampedHeating")) { PluginHelper._isPanelHeatingClamped = bool.Parse(plugin_settings.GetValue("SolarPanelClampedHeating")); Debug.Log("[KSP Interstellar] Solar panels clamped heating set to enabled: " + PluginHelper.IsSolarPanelHeatingClamped.ToString()); } if (plugin_settings.HasValue("RecieverTempTweak")) { PluginHelper._isRecieverTempTweaked = bool.Parse(plugin_settings.GetValue("RecieverTempTweak")); Debug.Log("[KSP Interstellar] Microwave reciever CoreTemp tweak is set to enabled: " + PluginHelper.IsRecieverCoreTempTweaked.ToString()); } if (plugin_settings.HasValue("LimitedWarpTravel")) { PluginHelper._limitedWarpTravel = bool.Parse(plugin_settings.GetValue("LimitedWarpTravel")); Debug.Log("[KSP Interstellar] Apply Limited Warp Travel: " + PluginHelper.LimitedWarpTravel.ToString()); } if (plugin_settings.HasValue("MatchDemandWithSupply")) { PluginHelper._matchDemandWithSupply = bool.Parse(plugin_settings.GetValue("MatchDemandWithSupply")); Debug.Log("[KSP Interstellar] Match Demand With Supply: " + PluginHelper.MatchDemandWithSupply.ToString()); } if (plugin_settings.HasValue("MaxPowerDrawForExoticMatterMult")) { PluginHelper._maxPowerDrawForExoticMatterMult = float.Parse(plugin_settings.GetValue("MaxPowerDrawForExoticMatterMult")); Debug.Log("[KSP Interstellar] Max Power Draw For Exotic Matter Multiplier set to: " + PluginHelper.MaxPowerDrawForExoticMatterMult.ToString("0.000000")); } if (plugin_settings.HasValue("GravityConstant")) { PluginHelper._gravityConstant = Single.Parse(plugin_settings.GetValue("GravityConstant")); Debug.Log("[KSP Interstellar] Gravity constant set to: " + PluginHelper.GravityConstant.ToString("0.000000")); } if (plugin_settings.HasValue("IspCoreTempMult")) { PluginHelper._ispCoreTempMult = double.Parse(plugin_settings.GetValue("IspCoreTempMult")); Debug.Log("[KSP Interstellar] Isp core temperature multiplier set to: " + PluginHelper.IspCoreTempMult.ToString("0.000000")); } if (plugin_settings.HasValue("ElectricEngineIspMult")) { PluginHelper._electricEngineIspMult = double.Parse(plugin_settings.GetValue("ElectricEngineIspMult")); Debug.Log("[KSP Interstellar] Electric EngineIsp Multiplier set to: " + PluginHelper.ElectricEngineIspMult.ToString("0.000000")); } if (plugin_settings.HasValue("GlobalThermalNozzlePowerMaxTrustMult")) { PluginHelper._globalThermalNozzlePowerMaxThrustMult = double.Parse(plugin_settings.GetValue("GlobalThermalNozzlePowerMaxTrustMult")); Debug.Log("[KSP Interstellar] Maximum Global Thermal Power Maximum Thrust Multiplier set to: " + PluginHelper.GlobalThermalNozzlePowerMaxThrustMult.ToString("0.0")); } if (plugin_settings.HasValue("GlobalMagneticNozzlePowerMaxTrustMult")) { PluginHelper._globalMagneticNozzlePowerMaxThrustMult = double.Parse(plugin_settings.GetValue("GlobalMagneticNozzlePowerMaxTrustMult")); Debug.Log("[KSP Interstellar] Maximum Global Magnetic Nozzle Power Maximum Thrust Multiplier set to: " + PluginHelper.GlobalMagneticNozzlePowerMaxThrustMult.ToString("0.0")); } if (plugin_settings.HasValue("GlobalElectricEnginePowerMaxTrustMult")) { PluginHelper._globalElectricEnginePowerMaxThrustMult = double.Parse(plugin_settings.GetValue("GlobalElectricEnginePowerMaxTrustMult")); Debug.Log("[KSP Interstellar] Maximum Global Electric Engine Power Maximum Thrust Multiplier set to: " + PluginHelper.GlobalElectricEnginePowerMaxThrustMult.ToString("0.0")); } if (plugin_settings.HasValue("LfoFuelTrustModifier")) { PluginHelper._lfoFuelThrustModifier = double.Parse(plugin_settings.GetValue("LfoFuelTrustModifier")); Debug.Log("[KSP Interstellar] Maximum Lfo Fuel Thrust Multiplier set to: " + PluginHelper.LfoFuelThrustModifier.ToString("0.0")); } if (plugin_settings.HasValue("MaxThermalNozzleIsp")) { PluginHelper._maxThermalNozzleIsp = float.Parse(plugin_settings.GetValue("MaxThermalNozzleIsp")); Debug.Log("[KSP Interstellar] Maximum Thermal Nozzle Isp set to: " + PluginHelper.MaxThermalNozzleIsp.ToString("0.0")); } if (plugin_settings.HasValue("TrustCoreTempThreshold")) { PluginHelper._thrustCoreTempThreshold = double.Parse(plugin_settings.GetValue("TrustCoreTempThreshold")); Debug.Log("[KSP Interstellar] Thrust core temperature threshold set to: " + PluginHelper.ThrustCoreTempThreshold.ToString("0.0")); } if (plugin_settings.HasValue("LowCoreTempBaseTrust")) { PluginHelper._lowCoreTempBaseThrust = double.Parse(plugin_settings.GetValue("LowCoreTempBaseTrust")); Debug.Log("[KSP Interstellar] Low core temperature base thrust modifier set to: " + PluginHelper.LowCoreTempBaseThrust.ToString("0.0")); } if (plugin_settings.HasValue("HighCoreTempTrustMult")) { PluginHelper._highCoreTempThrustMult = double.Parse(plugin_settings.GetValue("HighCoreTempTrustMult")); Debug.Log("[KSP Interstellar] High core temperature thrust divider set to: " + PluginHelper.HighCoreTempThrustMult.ToString("0.0")); } if (plugin_settings.HasValue("BasePowerConsumption")) { PluginHelper._basePowerConsumption = double.Parse(plugin_settings.GetValue("BasePowerConsumption")); Debug.Log("[KSP Interstellar] Base Power Consumption set to: " + PluginHelper.BasePowerConsumption.ToString("0.0")); } if (plugin_settings.HasValue("PowerConsumptionMultiplier")) { PluginHelper._powerConsumptionMultiplier = double.Parse(plugin_settings.GetValue("PowerConsumptionMultiplier")); Debug.Log("[KSP Interstellar] Base Power Consumption set to: " + PluginHelper.PowerConsumptionMultiplier.ToString("0.0")); } if (plugin_settings.HasValue("IspNtrPropellantModifierBase")) { PluginHelper._ispNtrPropellantModifierBase = float.Parse(plugin_settings.GetValue("IspNtrPropellantModifierBase")); Debug.Log("[KSP Interstellar] Isp Ntr Propellant Modifier Base set to: " + PluginHelper.IspNtrPropellantModifierBase.ToString("0.0")); } if (plugin_settings.HasValue("IspElectroPropellantModifierBase")) { PluginHelper._ispElectroPropellantModifierBase = float.Parse(plugin_settings.GetValue("IspNtrPropellantModifierBase")); Debug.Log("[KSP Interstellar] Isp Ntr Propellant Modifier Base set to: " + PluginHelper.IspElectroPropellantModifierBase.ToString("0.0")); } if (plugin_settings.HasValue("ElectricEnginePowerPropellantIspMultLimiter")) { PluginHelper._electricEnginePowerPropellantIspMultLimiter = float.Parse(plugin_settings.GetValue("ElectricEnginePowerPropellantIspMultLimiter")); Debug.Log("[KSP Interstellar] Electric Engine Power Propellant IspMultiplier Limiter set to: " + PluginHelper.ElectricEnginePowerPropellantIspMultLimiter.ToString("0.0")); } if (plugin_settings.HasValue("ElectricEngineAtmosphericDensityTrustLimiter")) { PluginHelper._electricEngineAtmosphericDensityThrustLimiter = float.Parse(plugin_settings.GetValue("ElectricEngineAtmosphericDensityTrustLimiter")); Debug.Log("[KSP Interstellar] Electric Engine Power Propellant IspMultiplier Limiter set to: " + PluginHelper.ElectricEngineAtmosphericDensityThrustLimiter.ToString("0.0")); } if (plugin_settings.HasValue("MaxAtmosphericAltitudeMult")) { PluginHelper._maxAtmosphericAltitudeMult = double.Parse(plugin_settings.GetValue("MaxAtmosphericAltitudeMult")); Debug.Log("[KSP Interstellar] Maximum Atmospheric Altitude Multiplier set to: " + PluginHelper.MaxAtmosphericAltitudeMult.ToString("0.0")); } if (plugin_settings.HasValue("MinAtmosphericAirDensity")) { PluginHelper._minAtmosphericAirDensity = double.Parse(plugin_settings.GetValue("MinAtmosphericAirDensity")); Debug.Log("[KSP Interstellar] Minimum Atmospheric Air Density set to: " + PluginHelper.MinAtmosphericAirDensity.ToString("0.0")); } if (plugin_settings.HasValue("JetUpgradeTech0")) { PluginHelper.JetUpgradeTech0 = plugin_settings.GetValue("JetUpgradeTech0"); Debug.Log("[KSP Interstellar] JetUpgradeTech0" + PluginHelper.JetUpgradeTech0); } if (plugin_settings.HasValue("JetUpgradeTech1")) { PluginHelper.JetUpgradeTech1 = plugin_settings.GetValue("JetUpgradeTech1"); Debug.Log("[KSP Interstellar] JetUpgradeTech1" + PluginHelper.JetUpgradeTech1); } if (plugin_settings.HasValue("JetUpgradeTech2")) { PluginHelper.JetUpgradeTech2 = plugin_settings.GetValue("JetUpgradeTech2"); Debug.Log("[KSP Interstellar] JetUpgradeTech2" + PluginHelper.JetUpgradeTech2); } if (plugin_settings.HasValue("JetUpgradeTech3")) { PluginHelper.JetUpgradeTech3 = plugin_settings.GetValue("JetUpgradeTech3"); Debug.Log("[KSP Interstellar] JetUpgradeTech3" + PluginHelper.JetUpgradeTech3); } resources_configured = true; } else { showInstallationErrorMessage(); } } if (plugin_init) { return; } gdb = GameDatabase.Instance; plugin_init = true; List <AvailablePart> available_parts = PartLoader.LoadedPartsList; foreach (AvailablePart available_part in available_parts) { Part prefab_available_part = available_part.partPrefab; try { if (prefab_available_part.Modules == null) { continue; } ModuleResourceIntake intake = prefab_available_part.FindModuleImplementing <ModuleResourceIntake>(); if (intake != null && intake.resourceName == "IntakeAir") { var pm = prefab_available_part.gameObject.AddComponent <AtmosphericIntake>(); prefab_available_part.Modules.Add(pm); pm.area = intake.area; //pm.aoaThreshold = intake.aoaThreshold; pm.intakeTransformName = intake.intakeTransformName; //pm.maxIntakeSpeed = intake.maxIntakeSpeed; pm.unitScalar = intake.unitScalar; //pm.useIntakeCompensation = intake.useIntakeCompensation; //pm.storesResource = intake.storesResource; PartResource intake_air_resource = prefab_available_part.Resources["IntakeAir"]; if (intake_air_resource != null && !prefab_available_part.Resources.Contains(InterstellarResourcesConfiguration.Instance.IntakeAtmosphere)) { ConfigNode node = new ConfigNode("RESOURCE"); node.AddValue("name", InterstellarResourcesConfiguration.Instance.IntakeAtmosphere); node.AddValue("maxAmount", intake_air_resource.maxAmount); node.AddValue("possibleAmount", intake_air_resource.amount); prefab_available_part.AddResource(node); } } if (prefab_available_part.FindModulesImplementing <ModuleDeployableSolarPanel>().Any()) { var existingSolarControlModule = prefab_available_part.FindModuleImplementing <FNSolarPanelWasteHeatModule>(); if (existingSolarControlModule == null) { ModuleDeployableSolarPanel panel = prefab_available_part.FindModuleImplementing <ModuleDeployableSolarPanel>(); if (panel.chargeRate > 0) { //Type type = AssemblyLoader.GetClassByName(typeof(PartModule), "FNSolarPanelWasteHeatModule"); Type type = typeof(FNSolarPanelWasteHeatModule); //if (type != null) //{ FNSolarPanelWasteHeatModule pm = prefab_available_part.gameObject.AddComponent(type) as FNSolarPanelWasteHeatModule; prefab_available_part.Modules.Add(pm); //} } //if (!prefab_available_part.Resources.Contains("WasteHeat") && panel.chargeRate > 0) //{ // ConfigNode node = new ConfigNode("RESOURCE"); // node.AddValue("name", "WasteHeat"); // node.AddValue("maxAmount", panel.chargeRate * 100); // node.AddValue("possibleAmount", 0); // PartResource pr = prefab_available_part.AddResource(node); // if (available_part.resourceInfo != null && pr != null) // { // if (available_part.resourceInfo.Length == 0) // available_part.resourceInfo = pr.resourceName + ":" + pr.amount + " / " + pr.maxAmount; // else // available_part.resourceInfo = available_part.resourceInfo + "\n" + pr.resourceName + ":" + pr.amount + " / " + pr.maxAmount; // } //} } } if (prefab_available_part.FindModulesImplementing <ElectricEngineControllerFX>().Count() > 0) { available_part.moduleInfo = prefab_available_part.FindModulesImplementing <ElectricEngineControllerFX>().First().GetInfo(); available_part.moduleInfos.RemoveAll(modi => modi.moduleName == "Engine"); AvailablePart.ModuleInfo mod_info = available_part.moduleInfos.FirstOrDefault(modi => modi.moduleName == "Electric Engine Controller"); if (mod_info != null) { mod_info.moduleName = "Electric Engine"; } } } catch (Exception ex) { if (prefab_available_part != null) { print("[KSP Interstellar] Exception caught adding to: " + prefab_available_part.name + " part: " + ex.ToString()); } else { print("[KSP Interstellar] Exception caught adding to unknown module"); } } } }
public void Start() { Settings.LoadConfig(); if (CheckForKIFA()) { return; } Start2(); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); List <AvailablePart> loadedParts = PartLoader.LoadedPartsList; // PartLoader.Instance.loadedParts; StringBuilder stringBuilder; bool fileExists = File.Exists(VOL_CFG_FILE); Log.Info("Finding Parts Volume...."); using (List <AvailablePart> .Enumerator partEnumerator = loadedParts.GetEnumerator()) { while (partEnumerator.MoveNext()) { AvailablePart current = partEnumerator.Current; string[] urlParts = current.partUrl.Split('/'); string urlName = urlParts[urlParts.Length - 1]; // // urlName more precisely correspond to part name in the config than current.name, // but KerbalEVA and flag have empty urlname and need to be filtered, so: // string partName = urlParts[urlParts.Length - 1]; if (partName == "") { partName = current.name; } if (partBlacklist.Contains(partName) || Regex.IsMatch(partName, blacklistRegexPattern)) { Log.Info(String.Format("partName: {0, -40} found in the blacklist and ignored.", partName + ",")); continue; } bool contains_ModuleCargoPart = false; bool contains_ModuleInventoryPart = false; bool contains_KSPPartVolumeModule = false; bool containsCrew = false; bool isTank = false; bool isTankNotIgnoreable = false; bool sizeTooBig = false; bool isStock = false; bool isRcsPart = false; bool isEnginePart = false; ConfigNode currentCargoPart = null; if (!Settings.doStock) { if (urlParts[0] == "Squad" || urlParts[0] == "SquadExpansion") { if (!partWhitelist.Contains(partName)) { isStock = true; } } } var moduleNodes = current.partConfig.GetNodes("MODULE"); for (int i = 0; i < moduleNodes.Length; i++) { var name = moduleNodes[i].GetValue("name"); if (name == "ModuleCargoPart") { contains_ModuleCargoPart = true; currentCargoPart = moduleNodes[i]; } if (name == "ModuleInventoryPart") { contains_ModuleInventoryPart = true; } if (name == "KSPPartVolumeModule") { contains_KSPPartVolumeModule = true; } if (name == "ModuleRCS" || name == "ModuleRCSFX") { isRcsPart = true; } if (name == "ModuleEngines" || name == "ModuleEnginesFX") { isEnginePart = true; } // Check for manned if (!Settings.manned) { int CrewCapacity = 0; if (current.partConfig.TryGetValue("CrewCapacity", ref CrewCapacity)) { if (CrewCapacity > 0) { containsCrew = true; } } } } if (contains_KSPPartVolumeModule) { contains_ModuleCargoPart = false; } var resNodes = current.partConfig.GetNodes("RESOURCE"); float mass = 0; current.partConfig.TryGetValue("mass", ref mass); float totalResMass = 0; //if (!Settings.doTanks) { foreach (var resNode in resNodes) { var name = resNode.GetValue("name"); if (resourceBlackList.Contains(name)) { continue; } float maxAmount = 0; resNode.TryGetValue("maxAmount", ref maxAmount); var definition = PartResourceLibrary.Instance.GetDefinition(name); if (definition != null) { var density = definition.density; float resMass = maxAmount * density; totalResMass += resMass; } } if (totalResMass > mass) { isTankNotIgnoreable = true; isTank = !Settings.doTanks; } } stringBuilder = new StringBuilder(); Bounds bounds = default(Bounds); foreach (Bounds rendererBound in PartGeometryUtil.GetRendererBounds((Part)current.partPrefab)) { bounds.Encapsulate(rendererBound); } #if false Bounds colliderBounds = default(Bounds); foreach (Bounds rendererBound in PartGeometryUtil.GetPartColliderBounds((Part)current.partPrefab)) { colliderBounds.Encapsulate(rendererBound); } Bounds allBounds = default(Bounds); var a = PartGeometryUtil.GetPartColliderBounds(current.partPrefab); allBounds = PartGeometryUtil.MergeBounds(a, current.iconPrefab.transform.root); #endif float vol = (float)(bounds.size.x * bounds.size.y * bounds.size.z) * 1000f; if (vol > Settings.largestAllowablePart && Settings.limitSize) { sizeTooBig = true; } var maxLen = Math.Max(bounds.size.x, Math.Max(bounds.size.y, bounds.size.z)); var minLen = Math.Min(bounds.size.x, Math.Min(bounds.size.y, bounds.size.z)); var tankVol = Math.Pow(minLen * 0.5, 2) * maxLen * Math.PI * 1000; var adjVol = AdjustedVolume(current, vol, isEnginePart, isRcsPart, out float adj); int stackableQuantity = Math.Min((int)Settings.maxCommonStackVolume / (int)adjVol, Settings.maxPartsInStack); bool isManipulableOnly = false; bool isKSP_PartVolumeModule = false; string currentCargoPartPackedVolume = ""; if (currentCargoPart != null) { Log.Info("currentCargoPart: " + current.name); if (currentCargoPart.HasValue("packedVolume")) { currentCargoPartPackedVolume = currentCargoPart.GetValue("packedVolume"); currentCargoPart.SetValue("packedVolume", adjVol.ToString("F0")); Log.Info(String.Format("partName: {0, -40} packedVolume: {1,7}, calcPackedVolume: {2,7:F0}", partName + ",", currentCargoPartPackedVolume, adjVol)); var v = float.Parse(currentCargoPartPackedVolume); if (v <= 0) { isManipulableOnly = true; } isKSP_PartVolumeModule = currentCargoPart.HasValue("KSP_PartVolume"); } else { Log.Error(String.Format("partName: {0, -40} packedVolume not found", partName + ",")); } } if (contains_ModuleInventoryPart) { adjVol = -1; } StringBuilder tmp = new StringBuilder(); tmp.AppendLine("// " + current.partUrl); tmp.AppendLine("// Dimensions: x: " + bounds.size.x.ToString("F2") + ", y: " + bounds.size.y.ToString("F2") + ", z: " + bounds.size.z.ToString("F2")); tmp.AppendLine(string.Format("// Bounding Box Size: {0} liters", vol)); tmp.AppendLine("// Volume adjustment: " + (adj * 100).ToString("F0") + "%"); if (isRcsPart) { tmp.AppendLine("// RCS module detected"); } if (isEnginePart) { tmp.AppendLine("// Engine module detected"); } Part part = UnityEngine.Object.Instantiate(current.partPrefab); part.gameObject.SetActive(value: false); if (isTankNotIgnoreable) { var volume = DetermineVolume(part) * 1000; stringBuilder.AppendLine("// Calculated tank volume: " + volume.ToString("F1")); stringBuilder.AppendLine("// Calculated tankVol (max x min) volume: " + tankVol.ToString("F1")); } tmp.AppendLine("//"); if (!containsCrew && !isTank && !sizeTooBig && !isStock && !contains_ModuleInventoryPart && (!contains_ModuleCargoPart || (contains_ModuleCargoPart && Settings.processManipulableOnly && isManipulableOnly) || (!isKSP_PartVolumeModule && partWhitelist.Contains(partName)) )) { stringBuilder.Append(tmp); string adjName = partName.Replace(' ', '?').Replace('(', '?').Replace(')', '?'); if (contains_ModuleCargoPart) { stringBuilder.AppendLine("@PART[" + adjName + "]:HAS[@MODULE[ModuleCargoPart]]:Final"); stringBuilder.AppendLine("{"); stringBuilder.AppendLine(" @MODULE[ModuleCargoPart]"); stringBuilder.AppendLine(" {"); stringBuilder.AppendLine(" %packedVolume = " + adjVol.ToString("F0")); } else { stringBuilder.AppendLine("@PART[" + adjName + "]:HAS[!MODULE[ModuleCargoPart]]:Final"); stringBuilder.AppendLine("{"); stringBuilder.AppendLine(" MODULE"); stringBuilder.AppendLine(" {"); stringBuilder.AppendLine(" name = ModuleCargoPart"); stringBuilder.AppendLine(" packedVolume = " + adjVol.ToString("F0")); } if (Settings.stackParts && stackableQuantity > 1) { stringBuilder.AppendLine(" %stackableQuantity = " + stackableQuantity); } { stringBuilder.AppendLine(" %KSP_PartVolume = true"); stringBuilder.AppendLine(" }"); stringBuilder.AppendLine("}"); } RestartWindowVisible = true; newPartsDetected = true; part = UnityEngine.Object.Instantiate(current.partPrefab); part.gameObject.SetActive(value: false); foreach (PartModule m in part.Modules) { if (m.moduleName == "ModuleCargoPart") { var mcp = m as ModuleCargoPart; mcp.part = part; mcp.packedVolume = adjVol; if (stackableQuantity > 1) { mcp.stackableQuantity = stackableQuantity; } for (int i = current.moduleInfos.Count - 1; i >= 0; --i) { AvailablePart.ModuleInfo info = current.moduleInfos[i]; if (info.moduleName == Localizer.Format("#autoLOC_8002221")) // Cargo Part { try { info.info = mcp.GetInfo(); } catch (Exception ex) { Log.Error("PartInfo.Start, Part: " + current.partUrl + ", Exception caught in ModuleCargoPart.GetInfo, exception: " + ex.Message + "\n" + ex.StackTrace); info.info = "KSP_PartVolume error"; } break; } } } } } else { if (!fileExists) { stringBuilder.Append(tmp); stringBuilder.AppendLine("// Bypass reasons:"); if (containsCrew) { stringBuilder.AppendLine("// contains crew "); } if (isTank) { stringBuilder.AppendLine("// is tank"); } if (sizeTooBig) { stringBuilder.AppendLine("// size exceeds largestAllowablePart: " + Settings.largestAllowablePart); } if (isStock) { stringBuilder.AppendLine("// is stock"); } if (contains_ModuleCargoPart && !Settings.processManipulableOnly || contains_ModuleCargoPart && !isManipulableOnly) { stringBuilder.AppendLine("// contains ModuleCargoPart (packedVolume = " + currentCargoPartPackedVolume + ")"); } if (contains_ModuleInventoryPart) { stringBuilder.AppendLine("// contains ModuleInventoryPart"); } stringBuilder.AppendLine("//"); adjVol = -999; #if true current.partConfig.RemoveNode(currentCargoPart); //Part part = UnityEngine.Object.Instantiate(current.partPrefab); //part.gameObject.SetActive(value: false); Statics.Check4DelModCargoPart(part); //Destroy(part); #endif } } Destroy(part); if (!Statics.modifiedParts.ContainsKey(current.partUrl)) { Statics.modifiedParts.Add(current.partUrl, new PartModification(stringBuilder, adjVol, adjVol == -999)); } else { Log.Error("modifiedParts already contains: " + current.partUrl); } if (!fileExists) { stringBuilder.AppendLine("// ----------------------------------------------------------------------"); } } } stringBuilder = new StringBuilder(); if (Statics.modifiedParts.Count > 0) { foreach (var d in Statics.modifiedParts) { stringBuilder.Append(d.Value.cfg.ToString()); } File.AppendAllText(VOL_CFG_FILE, stringBuilder.ToString()); } stopwatch.Stop(); Log.Info("File written to " + VOL_CFG_FILE); Log.Info(string.Format("Run in {0}ms", (object)stopwatch.ElapsedMilliseconds)); //if (numCargoPartsAdded > 0) // ShowWarning(numCargoPartsAdded); }
private IEnumerator RefreshPartInfo() { if (CurrentSettings == null || PartLoader.LoadedPartsList == null) { yield break; } ScreenMessages.PostScreenMessage("Database Part Info reloading started", 1, ScreenMessageStyle.UPPER_CENTER); this.IsReady = false; yield return(null); float lastTime = Time.realtimeSinceStartup; var apList = PartLoader.LoadedPartsList.Where(ap => ap.partPrefab.Modules != null); int totcnt = 1; if (apList == null) { Log.Info("apList is null"); } else { totcnt = apList.Count(); } int cnt = 0; try { foreach (var ap in PartLoader.LoadedPartsList.Where(ap => ap.partPrefab.Modules != null)) { cnt++; if (Time.realtimeSinceStartup - lastTime > 2) { lastTime = Time.realtimeSinceStartup; int intPercent = Mathf.CeilToInt(((float)cnt / (float)totcnt * 100f)); ScreenMessages.PostScreenMessage("Database reloading " + intPercent + "%", 1, ScreenMessageStyle.UPPER_CENTER); } AvailablePart.ModuleInfo target = null; foreach (var mi in ap.moduleInfos) { if (mi.moduleName == "Reliability Info") { target = mi; } } if (target != null & !this.CurrentSettings.EnabledForSave) { ap.moduleInfos.Remove(target); } if (this.CurrentSettings.EnabledForSave) { if (target != null) { ap.moduleInfos.Remove(target); } IEnumerable <ModuleReliabilityInfo> reliabilityModules = ap.partPrefab.Modules.OfType <ModuleReliabilityInfo>(); if (reliabilityModules.Count() != 0) { AvailablePart.ModuleInfo newModuleInfo = new AvailablePart.ModuleInfo(); newModuleInfo.moduleName = "Reliability Info"; newModuleInfo.info = reliabilityModules.First().GetInfo(); ap.moduleInfos.Add(newModuleInfo); } } } Log.Info("Refresh Finished"); this.IsReady = true; } catch (Exception e) { Log.Info("ERROR [" + e.GetType().ToString() + "]: " + e.Message + "\n" + e.StackTrace); } ScreenMessages.PostScreenMessage("Database Part Info reloading finished", 2, ScreenMessageStyle.UPPER_CENTER); }
private void Start() { commNetParams = HighLogic.CurrentGame.Parameters.CustomParams <CommNet.CommNetParams>(); int TrackingLevels = 3; CBK cbk = new CBK(); if (cbk.founded) { TrackingLevels = cbk.levelsTracking; } float[] TrackingStationFloats = new float[TrackingLevels]; //{ 0.0f, 0.5f, 1.0f }; for (int i = 0; i < TrackingLevels; i++) { TrackingStationFloats[i] = (float)i / (TrackingLevels - 1); } float CurrentTrackingStationFloat = ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.TrackingStation); CurrentTrackingStationIndex = TrackingStationFloats.IndexOf(CurrentTrackingStationFloat); double[] DSNPowerModified = new double[TrackingLevels]; string[] DSNPowerModified_str = new string[TrackingLevels]; for (int i = 0; i < TrackingLevels; i++) { double dsnPower = GameVariables.Instance.GetDSNRange(TrackingStationFloats[i]); DSNPowerModified[i] = dsnPower /* * commNetParams.DSNModifier*/; DSNPowerModified_str[i] = Formatter.ValueExtraShortSpaced(DSNPowerModified[i]); } List <AvailablePart> partsDT = PartLoader.LoadedPartsList.Where (p => p.partPrefab.Modules.OfType <ModuleDataTransmitter>().Any()).ToList(); double BuiltInPowerModified = GetPowerMostCommonInternalAntenna(partsDT) * commNetParams.rangeModifier; string BuiltInPowerModified_str = Formatter.ValueExtraShortSpaced(BuiltInPowerModified); foreach (AvailablePart part in partsDT) { List <ModuleDataTransmitter> modules = part.partPrefab.Modules.OfType <ModuleDataTransmitter>().ToList(); if (modules.Count == 0) { continue; } var modinfos = part.moduleInfos.Where(i => modules[0].GUIName.Contains(i.moduleName)).ToList(); if (modules.Count != modinfos.Count) { continue; } for (int index = 0; index < modules.Count; index++) { ModuleDataTransmitter moduleDT = modules[index]; AvailablePart.ModuleInfo modinfo = modinfos[index]; double antennaPowerModified = moduleDT.antennaPower * commNetParams.rangeModifier; string[] DSNranges_str = new string[TrackingLevels]; double[] DSNranges = new double[TrackingLevels]; for (int i = 0; i < TrackingLevels; i++) { DSNranges[i] = Math.Sqrt(DSNPowerModified[i] * antennaPowerModified); } if (moduleDT.CommType != AntennaType.INTERNAL) { string BuiltInranges_str = Formatter.DistanceShort(Math.Sqrt(BuiltInPowerModified * antennaPowerModified)); for (int i = 0; i < TrackingLevels; i++) { DSNranges_str[i] = Formatter.DistanceShort(DSNranges[i]); } modinfo.info = Localizer.Format("#autoLOC_7001005", Formatter.ToTitleCase(moduleDT.antennaType.displayDescription())) + Localizer.Format("#autoLOC_7001006", Formatter.ValueShort(antennaPowerModified)) + (moduleDT.CommCombinable ? Localizer.Format("#CAE_Combinability_Exponent", moduleDT.CommCombinableExponent) : Localizer.Format("#CAE_Not_Combinable")) + Localizer.Format("#CAE_Title_vs"); if (moduleDT.CommType == AntennaType.RELAY) { modinfo.info += BuiltInPowerModified_str + Localizer.Format("#CAE_Built_In") + Localizer.Format("#CAE_Spaces") + BuiltInranges_str + "\n"; } for (int i = 0; i < TrackingLevels; i++) { modinfo.info += SmartAlphaChannel(i) + DSNPowerModified_str[i] + Localizer.Format("#CAE_DSN_LN", i + 1) + Localizer.Format("#CAE_Spaces") + DSNranges_str[i] + SmartAlphaChannel(i, false) + "\n"; } modinfo.info += Localizer.Format("#autoLOC_236840" /*\n<b>Packet size: </b><<1>> Mits\n*/, moduleDT.packetSize.ToString("F1")).TrimEnd() + " & " + Localizer.Format("#CAE_EC", moduleDT.packetResourceCost.ToString("#.##")) + "\n" + Localizer.Format("#autoLOC_236841" /*<b>Bandwidth: </b><<1>> Mits/sec\n*/, (moduleDT.packetSize / moduleDT.packetInterval).ToString("F2")) + "\n" + Localizer.Format("#autoLOC_236842" /*\n\nWhen Transmitting:*/).Trim() + Localizer.Format("#CAE_Consumption", Localizer.Format("#CAE_EC_Mit", moduleDT.DataResourceCost.ToString("#.#"))) ; } else // INTERNAL { for (int i = 0; i < TrackingLevels; i++) { DSNranges_str[i] = Formatter.DistanceExtraShort(DSNranges[i]); } string type = Formatter.ToTitleCase(moduleDT.CommType.displayDescription()); //Internal - ok if (type.Length > 8) { type = type.Substring(0, 7) + "."; } modinfo.info = Localizer.Format("#CAE_Type", type) + ", " + Localizer.Format("#CAE_Rating", Formatter.ValueShort(antennaPowerModified)) + (moduleDT.CommCombinable ? ", e:" + moduleDT.CommCombinableExponent : "") + Localizer.Format("#CAE_DSN_Short") + " "; if (TrackingLevels % 4 == 0) { modinfo.info += "<nobr>"; } for (int i = 0; i < TrackingLevels; i++) { modinfo.info += SmartAlphaChannel(i) + DSNranges_str[i] + (i != (TrackingLevels - 1)?", ":"") + SmartAlphaChannel(i, false); } if (TrackingLevels % 4 == 0) { modinfo.info += "</nobr>"; } modinfo.info += Localizer.Format("#CAE_Orange", Localizer.Format("#autoLOC_236846")); // #autoLOC_236846 = \n<i>Cannot transmit science</i>\n } } } }
//called only in the prefab public override void Upgrade(List <string> allTechName) { //Debug.log("[MUM0] upgrade a module ? " + moduleName+ ", " + tech + ", " + allTechName.Contains(tech) + ", " + (HighLogic.CurrentGame.Mode != Game.Modes.SANDBOX)); if (moduleName == null || moduleName.Length == 0 || tech == null || (!allTechName.Contains(tech) && HighLogic.CurrentGame.Mode != Game.Modes.SANDBOX)) { return; } Part p = partToUpdate(); //Debug.log("[MUM] upgrade the partPrefab ? " + (p == part) + " ? " + (p == part.partInfo.partPrefab)+ " " + configModule); foreach (ConfigNode config in configModule) { //Debug.log("[MUM] upgrade a module " + p.name + " , " + p.partInfo.moduleInfos.Count + "/ " + p.Modules.Count + " , " + type); //get the module if (type.Equals("replace")) { try { //get the module //ConfigNode node = new ConfigNode(); PartModule mod = p.Modules[config.GetValue("name")]; //mod.Save(node); ////Debug.log("[MUM] before : " + node); mod.Load(config); //node = new ConfigNode(); mod.Save(node); ////Debug.log("[MUM] after : " + node); //Debug.log("[MUM] after (info) : " + mod.GetInfo()); for (int i = 0; i < part.partInfo.moduleInfos.Count; i++) { AvailablePart.ModuleInfo info = part.partInfo.moduleInfos[i]; if (info.moduleName.Equals(mod.moduleName.Replace("Module", ""))) { info.info = mod.GetInfo(); } } } catch (Exception e) { //Debug.log("[MUM] can't MODIFY " + e); } } else if (type.Equals("create")) { try { PartModule mod = createModule(p, config); //Debug.log("[MUM] added : " + mod); } catch (Exception e) { //Debug.log("[MUM] can't ADD " + e); } } else if (type.Equals("delete")) { try { //Debug.log("[MUM] delete : " + p.Modules[config.GetValue("name")]); removeModuleAndInfo(p, p.Modules[config.GetValue("name")]); } catch (Exception e) { //Debug.log("[MUM] can't REMOVE " + e); } } //Debug.log("[MUM] relance "); } }
//called only in the prefab public override void Restore(ConfigNode initialNode) { Part p = partToUpdate(); ////Debug.log("[MUM] Restore '" + configModule + "' for initialNode node :" + initialNode); foreach (ConfigNode config in configModule) { string moduleUpgradeName = config.GetValue("name"); ////Debug.log("[MUM] Restore a module " + config.GetValue("name") + " " + p.partInfo.moduleInfos.Count + "/ " // + p.Modules.Count + " , " + type + " persisted=" + persisted); if (type.Equals("replace")) { try { //get the module PartModule mod = p.Modules[moduleUpgradeName]; //module exist? (it can be created from an upgrade not already done) if (mod != null) { //get the node in the initialNode foreach (ConfigNode intialModuleNode in initialNode.GetNodes("MODULE")) { ////Debug.log("[MUM] search module " + intialModuleNode.GetValue("name")); if (intialModuleNode.GetValue("name") == moduleUpgradeName) { //Debug.log("[MUM] Restore: replace values in " + moduleUpgradeName); mod.Load(intialModuleNode); } } //Restore info for (int i = 0; i < part.partInfo.moduleInfos.Count; i++) { AvailablePart.ModuleInfo info = part.partInfo.moduleInfos[i]; if (info.moduleName.Equals(mod.moduleName.Replace("Module", ""))) { info.info = mod.GetInfo(); } } } } catch (Exception e) { //Debug.log("[MUM] can't MODIFY " + p.Modules.Count + " : " + e); } } else if (type.Equals("delete")) { try { //do not add if already here if (!p.Modules.Contains(moduleUpgradeName)) { //Debug.log("[MUM] Restore : delete " + moduleUpgradeName); PartModule module = createModule(p, config); //TODO: test if null. if (module == null) { //Debug.logError("[MUM] Error : can't recreate the partmodule " + moduleUpgradeName); } //DONT DO THAT \/, it mess the name/index map of Parmodulelist //swap all module to be at the right place // Totally useless. But i do it. In case of a mod use the index. //PartModule previousModule = module; //PartModule nextModule = null; //for (int i = 0; i < p.Modules.Count; i++) //{ // nextModule = p.Modules[i]; // p.Modules[i] = previousModule; // previousModule = nextModule; //} // when upgrading with delete, the partmodule order is mess up anyway. // it doesn't mess up my test save, but it may be dangerous... } else { //Debug.log("[MUM] not create from Restore delete because module already here"); } } catch (Exception e) { //Debug.log("[MUM] can't ADD (from Restore of delete) " + e); } } else if (type.Equals("create")) { try { //do not del if not here if (p.Modules.Contains(moduleUpgradeName)) { //Debug.log("[MUM] delete : " + type); removeModuleAndInfo(p, p.Modules[moduleUpgradeName]); } else { //Debug.log("[MUM] do not del (Restore create) because it's not inside"); } } catch (Exception e) { //Debug.log("[MUM] can't REMOVE (from Restore of create) " + p.Modules.Count); } } } }