/// <summary>Creates a new part from save.</summary> public KIS_Item(AvailablePart availablePart, ConfigNode itemNode, ModuleKISInventory inventory, float quantity = 1) { // Get part node this.availablePart = availablePart; partNode = new ConfigNode(); itemNode.GetNode("PART").CopyTo(partNode); // init config this.InitConfig(availablePart, inventory, quantity); // Get mass if (itemNode.HasValue("resourceMass")) { resourceMass = float.Parse(itemNode.GetValue("resourceMass")); } else { resourceMass = availablePart.partPrefab.GetResourceMass(); } if (itemNode.HasValue("contentMass")) { contentMass = float.Parse(itemNode.GetValue("contentMass")); } if (itemNode.HasValue("contentCost")) { contentCost = float.Parse(itemNode.GetValue("contentCost")); } if (itemNode.HasValue("inventoryName")) { inventoryName = itemNode.GetValue("inventoryName"); } }
public static double GetParachuteDragFromPart(AvailablePart parachute) { /* foreach (AvailablePart.ModuleInfo mi in parachute.moduleInfos) { if (mi.info.Contains("Fully-Deployed Drag")) { string[] split = mi.info.Split(new Char[] { ':', '\n' }); for (int i = 0; i < split.Length; i++) { if (split[i].Contains("Fully-Deployed Drag")) { float drag = 500; if (!float.TryParse(split[i + 1], out drag)) { string[] split2 = split[i + 1].Split('>'); if (!float.TryParse(split2[1], out drag)) { Debug.Log("[SR] Failure trying to read parachute data. Assuming 500 drag."); drag = 500; } } return drag; } } } }*/ double area = 0; if (parachute.partPrefab.Modules.Contains("ModuleParachute")) { area = ((ModuleParachute)parachute.partPrefab.Modules["ModuleParachute"]).areaDeployed; } return area; }
public static Blueprint ProcessFactoryPart(AvailablePart part) { var resources = new Dictionary<string, WorkshopResource>(); if (PartRecipes.ContainsKey(part.name)) { var recipe = FactoryRecipes[part.name]; foreach (var workshopResource in recipe.Prepare(part.partPrefab.mass)) { if (resources.ContainsKey(workshopResource.Name)) { resources[workshopResource.Name].Merge(workshopResource); } else { resources[workshopResource.Name] = workshopResource; } } } else { Debug.LogWarning("[OSE] - No FactoryRecipeFound for " + part.title); return null; } var blueprint = new Blueprint(); blueprint.AddRange(resources.Values); blueprint.Funds = Mathf.Max(part.cost - (float)blueprint.ResourceCosts(), 0); return blueprint; }
public static string GetDescription(AvailablePart part) { var sb = new StringBuilder(); sb.AppendLine(part.title); sb.AppendLine(part.description); return sb.ToString(); }
void AddAlternator(ConfigNode node, AvailablePart aPart) { // Get or add module ModuleReliabilityAlternator rModule = aPart.partPrefab.GetComponent<ModuleReliabilityAlternator>(); if (rModule) { Logger.DebugWarning("ModuleReliabilityAlternator already added to \"" + aPart.name + "\"!"); } else { rModule = aPart.partPrefab.AddModule("ModuleReliabilityAlternator") as ModuleReliabilityAlternator; if (!rModule) { Logger.DebugError("Problem adding module to engine!"); return; } } //Configure the base values ConfigureBaseValues(node, rModule); if (node.HasValue("idleChanceToFailPerfect")) { rModule.idleChanceToFailPerfect = double.Parse(node.GetValue("idleChanceToFailPerfect")); } if (node.HasValue("idleChanceToFailTerrible")) { rModule.idleChanceToFailTerrible = double.Parse(node.GetValue("idleChanceToFailTerrible")); } if (node.HasValue("stressedChanceToFailPerfect")) { rModule.stressedChanceToFailPerfect = double.Parse(node.GetValue("stressedChanceToFailPerfect")); } if (node.HasValue("stressedChanceToFailTerrible")) { rModule.stressedChanceToFailTerrible = double.Parse(node.GetValue("stressedChanceToFailTerrible")); } if (node.HasValue("maxGeesPerfect")) { rModule.maxGeesPerfect = double.Parse(node.GetValue("maxGeesPerfect")); } if (node.HasValue("maxGeesTerrible")) { rModule.maxGeesTerrible = double.Parse(node.GetValue("maxGeesTerrible")); } }
public VesselData(VesselData vd) { name = vd.name; id = vd.id; craftURL = vd.craftURL; craftPart = vd.craftPart; flagURL = vd.flagURL; vesselType = vd.vesselType; body = vd.body; orbit = vd.orbit; latitude = vd.latitude; longitude = vd.longitude; altitude = vd.altitude; height = vd.height; orbiting = vd.orbiting; owned = vd.owned; pqsCity = vd.pqsCity; pqsOffset = vd.pqsOffset; heading = vd.heading; pitch = vd.pitch; roll = vd.roll; foreach (CrewData cd in vd.crew) { crew.Add(new CrewData(cd)); } }
protected void DoUnlock(AvailablePart part) { ProtoTechNode ptn = ResearchAndDevelopment.Instance.GetTechState(part.TechRequired); // The tech may be null - we need to create it if (ptn == null) { ptn = new ProtoTechNode(); ptn.state = RDTech.State.Unavailable; ptn.techID = part.TechRequired; ptn.scienceCost = 9999; // ignored } if (unlockTech) { ptn.state = RDTech.State.Available; } if (!HighLogic.CurrentGame.Parameters.Difficulty.BypassEntryPurchaseAfterResearch && !ptn.partsPurchased.Contains(part)) { ptn.partsPurchased.Add(part); } else { ptn.partsPurchased = new List<AvailablePart>(); } ResearchAndDevelopment.Instance.SetTechState(part.TechRequired, ptn); }
public void Load(ConfigNode node) { if (node.HasValue("Name")) { var partName = node.GetValue("Name"); Part = PartLoader.getPartInfoByName(partName); } }
public PartEntryCostHolder(ConfigNode node, AvailablePart part, string Name = "") { Load(node); if(Name != "") name = Name; entryCost = part.entryCost; ap = part; }
public static Part CreatePart(AvailablePart avPart, Vector3 position, Quaternion rotation, Part flagFromPart) { UnityEngine.Object obj = UnityEngine.Object.Instantiate(avPart.partPrefab); if (!obj) { KAS_Shared.DebugError("CreatePart(Crate) Failed to instantiate " + avPart.partPrefab.name); return null; } Part newPart = (Part)obj; newPart.gameObject.SetActive(true); newPart.gameObject.name = avPart.name; newPart.partInfo = avPart; newPart.highlightRecurse = true; newPart.SetMirror(Vector3.one); ShipConstruct newShip = new ShipConstruct(); newShip.Add(newPart); newShip.SaveShip(); newShip.shipName = avPart.title; newShip.shipType = 1; VesselCrewManifest vessCrewManifest = new VesselCrewManifest(); Vessel currentVessel = FlightGlobals.ActiveVessel; Vessel v = newShip.parts[0].localRoot.gameObject.AddComponent<Vessel>(); v.id = Guid.NewGuid(); v.vesselName = newShip.shipName; v.Initialize(false); v.Landed = true; v.rootPart.flightID = ShipConstruction.GetUniqueFlightID(HighLogic.CurrentGame.flightState); v.rootPart.missionID = flagFromPart.missionID; v.rootPart.flagURL = flagFromPart.flagURL; //v.rootPart.collider.isTrigger = true; //v.landedAt = "somewhere"; Staging.beginFlight(); newShip.parts[0].vessel.ResumeStaging(); Staging.GenerateStagingSequence(newShip.parts[0].localRoot); Staging.RecalculateVesselStaging(newShip.parts[0].vessel); FlightGlobals.SetActiveVessel(currentVessel); v.SetPosition(position); v.SetRotation(rotation); // Solar panels from containers don't work otherwise for (int i = 0; i < newPart.Modules.Count; i++) { ConfigNode node = new ConfigNode(); node.AddValue("name", newPart.Modules[i].moduleName); newPart.LoadModule(node, i); } return newPart; }
public static Blueprint ProcessPart(AvailablePart part) { var resources = new Dictionary<string, WorkshopResource>(); if (PartRecipes.ContainsKey(part.name)) { var recipe = PartRecipes[part.name]; foreach (var workshopResource in recipe.Prepare(part.partPrefab.mass)) { if (resources.ContainsKey(workshopResource.Name)) { resources[workshopResource.Name].Merge(workshopResource); } else { resources[workshopResource.Name] = workshopResource; } } } else { foreach (var workshopResource in DefaultPartRecipe.Prepare(part.partPrefab.mass)) { if (resources.ContainsKey(workshopResource.Name)) { resources[workshopResource.Name].Merge(workshopResource); } else { resources[workshopResource.Name] = workshopResource; } } } foreach (PartResource partResource in part.partPrefab.Resources) { if (ResourceRecipes.ContainsKey(partResource.resourceName)) { var definition = PartResourceLibrary.Instance.GetDefinition(partResource.resourceName); var recipe = ResourceRecipes[partResource.resourceName]; foreach (var workshopResource in recipe.Prepare(partResource.maxAmount * definition.density)) { if (resources.ContainsKey(workshopResource.Name)) { resources[workshopResource.Name].Merge(workshopResource); } else { resources[workshopResource.Name] = workshopResource; } } } } var blueprint = new Blueprint(); blueprint.AddRange(resources.Values); blueprint.Funds = Mathf.Max(0, part.cost - (float)blueprint.ResourceCosts()); return blueprint; }
public override bool Load(ConfigNode configNode) { // Load base class bool valid = base.Load(configNode); valid &= ConfigNodeUtil.ParseValue<AvailablePart>(configNode, "part", x => part = x, this); return valid; }
private PartContent(AvailablePart avPart, KASModuleGrab grab) { part = avPart; grabModule = grab; pristine_mass = part.partPrefab.mass; foreach (var res in part.partPrefab.GetComponents<PartResource>()) { pristine_mass += (float)(res.amount * res.info.density); } }
public static void ItemDescription(AvailablePart part, string resourceName, double productivity) { GUILayout.BeginVertical(); var text = new StringBuilder(); text.AppendLine(part.title); var density = PartResourceLibrary.Instance.GetDefinition(resourceName).density; var requiredResources = (part.partPrefab.mass / density) * productivity; text.AppendLine(" " + requiredResources.ToString("0.00") + " " + resourceName); GUILayout.Box(text.ToString(), WorkshopStyles.Databox(), GUILayout.Width(250), GUILayout.Height(50)); GUILayout.EndVertical(); }
private bool EditorItemsFilter(AvailablePart avPart) { if (avPartItems.Contains(avPart)) { return true; } else { return false; } }
public KISItemWrapper AddItem(AvailablePart aPart, ConfigNode configNode, float quantity = 1, int slot = -1) { return KISItemWrapper.FromObject(_partModule.InvokeMethod("AddItem", new object[] { aPart, configNode, quantity, slot }, new[] { typeof (AvailablePart), typeof (ConfigNode), typeof (float), typeof (int) })); }
private void fixSader(AvailablePart availablePart, string brokenShaderName, Shader fixShader) { // Debug.Log ("IconFixAddon : part: " + availablePart.name); foreach (Renderer r in availablePart.iconPrefab.GetComponentsInChildren<Renderer>(true)) { foreach (Material m in r.materials) { if (m.shader.name == brokenShaderName) { Debug.Log ("IconFixAddon: fixing icon of: " + availablePart.name); m.shader = fixShader; } } } }
public VesselData(VesselData vd) { name = vd.name; id = vd.id; craftURL = vd.craftURL; craftPart = vd.craftPart; flagURL = vd.flagURL; vesselType = vd.vesselType; body = vd.body; orbit = vd.orbit; orbiting = vd.orbiting; owned = vd.owned; }
private bool MaxSizeReached(AvailablePart avPart, int qty) { KASModuleGrab moduleGrab = avPart.partPrefab.GetComponent <KASModuleGrab>(); if (moduleGrab) { if (totalSize + (moduleGrab.storedSize * qty) > maxSize) { return(true); } } return(false); }
public static void UpdateEntryCost(AvailablePart ap) { string name = GetPartName(ap); EntryCostDatabase.ClearTracker(); PartEntryCostHolder h; if (holders.TryGetValue(name, out h)) { ap.SetEntryCost(h.GetCost()); } }
public void onPartPurchased(AvailablePart ap) { Part part = ap.partPrefab; if (part != null) { for (int i = part.Modules.Count - 1; i >= 0; --i) { PartModule m = part.Modules[i]; if (m is ModuleEngineConfigs) { ModuleEngineConfigs mec = m as ModuleEngineConfigs; mec.CheckConfigs(); for (int j = mec.configs.Count - 1; j >= 0; --j) { ConfigNode cfg = mec.configs[j]; if (cfg.HasValue("name")) { string cfgName = cfg.GetValue("name"); // TL upgrades if (mec.techLevel >= 0) { string tUName = Utilities.GetPartName(ap) + cfgName; SetTLUnlocked(tUName, mec.techLevel); } // unlock the config if it defaults to unlocked, or if autoUnlock is on. bool auto = mec.autoUnlock; if (cfg.HasValue("techRequired")) { string tech = cfg.GetValue("techRequired"); if (tech != "" && tech != ap.TechRequired) { auto = false; } } bool unlocked = false; if (cfg.HasValue("unlocked")) { bool.TryParse(cfg.GetValue("unlocked"), out unlocked); } if (auto || unlocked) { SetConfigUnlock(cfgName, true); } } } } } } }
public static Blueprint ProcessPart(AvailablePart part) { var resources = new Dictionary <string, WorkshopResource>(); List <WorkshopResource> prepResources = null; if (PartRecipes.ContainsKey(part.name)) { prepResources = PartRecipes[part.name].Prepare(part.partPrefab.mass); } else { prepResources = DefaultPartRecipe.Prepare(part.partPrefab.mass); } foreach (var workshopResource in prepResources) { if (resources.ContainsKey(workshopResource.Name)) { resources[workshopResource.Name].Merge(workshopResource); } else { resources[workshopResource.Name] = workshopResource; } } foreach (PartResource partResource in part.partPrefab.Resources) { if (ResourceRecipes.ContainsKey(partResource.resourceName)) { var definition = PartResourceLibrary.Instance.GetDefinition(partResource.resourceName); var recipe = ResourceRecipes[partResource.resourceName]; foreach (var workshopResource in recipe.Prepare(partResource.maxAmount * definition.density)) { if (resources.ContainsKey(workshopResource.Name)) { resources[workshopResource.Name].Merge(workshopResource); } else { resources[workshopResource.Name] = workshopResource; } } } } var blueprint = new Blueprint(); blueprint.AddRange(resources.Values); blueprint.Funds = Mathf.Max(0, part.cost - (float)blueprint.ResourceCosts()); return(blueprint); }
public static Part CreatePart(AvailablePart avPart, Vector3 position, Quaternion rotation, Part flagFromPart) { UnityEngine.Object obj = UnityEngine.Object.Instantiate(avPart.partPrefab); if (!obj) { KAS_Shared.DebugError("CreatePart(Crate) Failed to instantiate " + avPart.partPrefab.name); return null; } Part newPart = (Part)obj; newPart.gameObject.SetActive(true); newPart.gameObject.name = "KASCreatedPart"; newPart.partInfo = avPart; newPart.highlightRecurse = true; ShipConstruct newShip = new ShipConstruct(); newShip.Add(newPart); newShip.SaveShip(); newShip.shipName = avPart.title; newShip.shipType = 1; VesselCrewManifest vessCrewManifest = new VesselCrewManifest(); Vessel currentVessel = FlightGlobals.ActiveVessel; Vessel v = newShip.parts[0].localRoot.gameObject.AddComponent<Vessel>(); v.id = Guid.NewGuid(); v.vesselName = newShip.shipName; v.Initialize(false); v.Landed = true; v.rootPart.flightID = ShipConstruction.GetUniqueFlightID(HighLogic.CurrentGame.flightState); v.rootPart.missionID = (uint)Guid.NewGuid().GetHashCode(); v.rootPart.flagURL = flagFromPart.flagURL; //v.rootPart.collider.isTrigger = true; v.rootPart.FindModelTransform("model").localScale *= v.rootPart.rescaleFactor; //v.landedAt = "somewhere"; Staging.beginFlight(); newShip.parts[0].vessel.ResumeStaging(); Staging.GenerateStagingSequence(newShip.parts[0].localRoot); Staging.RecalculateVesselStaging(newShip.parts[0].vessel); FlightGlobals.SetActiveVessel(currentVessel); v.SetPosition(position); v.SetRotation(rotation); return newPart; }
private void Remove(AvailablePart avPart, int qty) { var item = PartContent.Get(contents, avPart.name, false); if (item != null) { item.pristine_count = Math.Max(0, item.pristine_count - qty); RefreshTotalSize(); } else { KAS_Shared.DebugLog("Remove(Container) - Nothing to remove"); } }
/// <summary> /// Throws on not-found... /// </summary> public static Resources.IResource GetOrThrow(AvailablePart part, bool withInterior = true) { var res = Get(part, withInterior); if (res == null) { var errTxt = "Part [" + part.name + "] is not resource-managed. Currently managed parts: [" + (iManagedParts.Any() ? String.Join(", ", (iManagedParts.Select(p => p.Value.Part.name).ToArray())) : "NONE!!") + "], PartLoader: [" + (PartLoader.LoadedPartsList.Any() ? String.Join(", ", PartLoader.LoadedPartsList.Select(el => el.name).ToArray()) : "NONE") + "]"; errTxt.Log(); throw new Exception(errTxt); } return(res); }
/// <summary>Localizes the values in the part's prefab config.</summary> /// <param name="partInfo">The p[art info to localize.</param> public static void LocalizePrefab(AvailablePart partInfo) { var newPartConfig = GetPartPrefabConfig(partInfo); if (newPartConfig == null) { return; } UpdateStockMembersInPart(partInfo.partPrefab); var newModuleConfigs = newPartConfig.GetNodes("MODULE"); var prefabModuleConfigs = partInfo.partConfig.GetNodes("MODULE"); if (newModuleConfigs.Length <= prefabModuleConfigs.Length) { // Due to the ModuleManager patches, the prefab config may have more modules than the // disk version. for (var i = 0; i < newModuleConfigs.Length; i++) { var newConf = newModuleConfigs[i]; var prefabConf = prefabModuleConfigs[i]; if (newConf.GetValue("name") == prefabConf.GetValue("name")) { MergeLocalizableValues(prefabConf, newConf); } else { DebugEx.Warning("Skipping module on part {0}: newName={1}, prefabName={2}", partInfo.name, newConf.GetValue("name"), prefabConf.GetValue("name")); } // Reload all KSPField strings in the module to get the changed version. if (i < partInfo.partPrefab.Modules.Count) { LoadKspFieldsFromNode(partInfo.partPrefab.Modules[i], prefabConf); } else { DebugEx.Error( "Cannot reload strings in {0}: module #{1} not found", partInfo.partPrefab, i); } } } else { // MM patches can delete modules, but this is not supported. DebugEx.Error( "Cannot refresh part config fields in part {0}. Config file has more modules than the" + " prefab: in file={1}, in prefab={2}", partInfo.name, newModuleConfigs.Length, prefabModuleConfigs.Length); } }
/// <summary> /// check the ISP of the engine /// </summary> public static bool CheckISP(AvailablePart part, string[] value, ConfigNodes.CheckNodes.CompareType equality = ConfigNodes.CheckNodes.CompareType.Equals, bool vacuum = false) { if (!IsEngine(part)) { return(false); } if (part.partPrefab == null) { return(false); } foreach (var engine in part.partPrefab.Modules.OfType <ModuleEngines>()) { float atm = engine.atmosphereCurve.Evaluate(1); float vac = engine.atmosphereCurve.Evaluate(0); float isp; if (vacuum) { isp = vac; } else { isp = atm; } if (equality == ConfigNodes.CheckNodes.CompareType.Equals) { return(value.Contains(isp.ToString(), StringComparer.OrdinalIgnoreCase)); } else { if (value.Length > 1) { Logger.Log($"ISP comparisons against multiple values when not using Equals only use the first value. Value list is: {string.Join(", ", value)}", Logger.LogLevel.Warn); } if (double.TryParse(value[0], out double d)) { if (equality == ConfigNodes.CheckNodes.CompareType.GreaterThan && isp > d) { return(true); } else if (equality == ConfigNodes.CheckNodes.CompareType.LessThan && isp < d) { return(true); } } } } return(false); }
/// <summary> /// Retrieves the part configuration node trought available part in partloader /// </summary> /// <param name="part"></param> /// <returns></returns> public static ConfigNode GetPartConfig(string part) { AvailablePart thispart = GetSourcePart(part); if (thispart == null) { Debug.LogError("GetPartConfig: PART NOT FOUND"); return(null); } else { return(thispart.partConfig); } }
private float GetPartSize(AvailablePart avPart) { KASModuleGrab grabModule = avPart.partPrefab.GetComponent <KASModuleGrab>(); if (grabModule) { return(grabModule.storedSize); } else { KAS_Shared.DebugError("Cannot retrieve part size, grab module not found !"); return(0); } }
private void PartPurchasedHandler(AvailablePart apart) { ModuleSAS module; if (apart.partPrefab.tryGetFirstModuleOfType <ModuleSAS>(out module)) { this.LogDebug("Purchased new SAS part {0}: SASServiceLevel = {1} (old max = {2}).", apart.title, module.SASServiceLevel, maxSASServiceLevel ); researchedSASParts.Add(apart); maxSASServiceLevel = Math.Max(maxSASServiceLevel, module.SASServiceLevel); } }
public static void UpdatePartEntryCosts() { for (int a = PartLoader.LoadedPartsList.Count - 1; a >= 0; --a) { AvailablePart ap = PartLoader.LoadedPartsList[a]; if (ap == null || ap.partPrefab == null) { continue; } UpdateEntryCost(ap); } }
bool AllUnlocked(HashSet <string> set) { foreach (string entry in set) { AvailablePart part = PartLoader.getPartInfoByName(entry); if (!(ResearchAndDevelopment.PartTechAvailable(part) /*&& ResearchAndDevelopment.PartModelPurchased(part)*/)) { //In career mode I certainly don't purchase parts until I need them to fulfil a contract //And if you can't get the contracts until you have purchased them... return(false); } } return(true); }
/// <summary> /// check the propellants this engine uses /// </summary> public static bool CheckPropellant(AvailablePart part, string[] values, bool contains = true, bool exact = false) { ModuleEngines e; for (int i = 0; i < part.partPrefab.Modules.Count; ++i) { e = part.partPrefab.Modules[i] as ModuleEngines; if (e != null && Contains(values, e.propellants, p => p.name, contains, exact)) { return(true); } } return(false); }
/// <summary>Returns part's volume basing on its geometrics.</summary> /// <remarks> /// The volume is calculated basing on the smallest boundary box that encapsulates all the meshes /// in the part. The deployable parts can take much more space in the deployed state. /// </remarks> /// <param name="avPart">The part proto to get the models from.</param> /// <param name="variant"> /// The part's variant. If it's <c>null</c>, then the variant will be attempted to read from /// <paramref name="partNode"/>. /// </param> /// <param name="partNode"> /// The part's persistent config. It will be looked up for the variant if it's not specified. /// </param> /// <returns>The volume in liters.</returns> public double GetPartVolume( AvailablePart avPart, PartVariant variant = null, ConfigNode partNode = null) { var itemModule = avPart.partPrefab.Modules.OfType <KIS.ModuleKISItem>().FirstOrDefault(); if (itemModule != null && itemModule.volumeOverride > 0) { return(itemModule.volumeOverride // Ignore geometry. * KISAPI.PartNodeUtils.GetTweakScaleSizeModifier(partNode)); // But respect TweakScale. } var boundsSize = GetPartBounds(avPart, variant: variant, partNode: partNode); return(boundsSize.x * boundsSize.y * boundsSize.z * 1000f); }
private kerbalExpressionSystem getOrCreateExpressionSystem(KerbalEVA p) { kerbalExpressionSystem e = p.part.GetComponent <kerbalExpressionSystem>(); Log.dbg("expr. system: {0}", dumper(e)); Log.dbg("kerbalEVA: {0}", dumper(p)); Log.dbg("part: {0}", dumper(p.part)); if (e == null) { AvailablePart evaPrefab = PartLoader.getPartInfoByName("kerbalEVA"); Log.dbg("eva prefab: {0}", dumper(evaPrefab)); Part prefabEvaPart = evaPrefab.partPrefab; Log.dbg("eva prefab part: {0}", prefabEvaPart); ProtoCrewMember protoCrew = FlightGlobals.ActiveVessel.GetVesselCrew() [0]; Log.dbg("proto crew: {0}", protoCrew); //kerbalExpressionSystem prefabExpr = prefabEva.GetComponent<kerbalExpressionSystem> (); Animator a = p.part.GetComponent <Animator> (); if (a == null) { Log.dbg("Creating Animator..."); Animator prefabAnim = prefabEvaPart.GetComponent <Animator> (); Log.dbg("animator prefab: {0}", dumper(prefabAnim)); a = p.part.gameObject.AddComponent <Animator> (); Log.dbg("animator component: {0}", dumper(a)); a.avatar = prefabAnim.avatar; a.runtimeAnimatorController = prefabAnim.runtimeAnimatorController; a.cullingMode = AnimatorCullingMode.CullUpdateTransforms; a.rootRotation = Quaternion.identity; a.applyRootMotion = false; //Animator.rootPosition = new Vector3(0.4f, 1.5f, 0.4f); //Animator.rootRotation = new Quaternion(-0.7f, 0.5f, -0.1f, -0.5f); } Log.dbg("Creating kerbalExpressionSystem..."); e = p.part.gameObject.AddComponent <kerbalExpressionSystem> (); e.evaPart = p.part; e.animator = a; e.protoCrewMember = protoCrew; Log.dbg("expression component: {0}", dumper(e)); } return(e); }
public static List <LabEquipment> getAvailableRacks() { List <LabEquipment> list = new List <LabEquipment>(); for (int idx = 0, count = racks.Length; idx < count; idx++) { var p = racks[idx]; AvailablePart part = PartLoader.getPartInfoByName(p.Value); if (part != null && ResearchAndDevelopment.PartModelPurchased(part)) { list.Add(getLabEquipment(part.partPrefab, p.Key)); } } return(list); }
public static void printPartInfo(AvailablePart part) { TextWriter file = TextWriter.CreateForType <PartCatalog>("catalogConfig.txt"); //UnityEngine.Debug.Log(part.partPrefab.); //printConfigNode(GameDatabase.Instance.GetConfigNode(part.partUrl),"",file); UrlDir.UrlConfig[] configs = GameDatabase.Instance.GetConfigs("PART"); UrlDir.UrlConfig config = Array.Find <UrlDir.UrlConfig>(configs, (c => part.name == c.name.Replace('_', '.'))); file.WriteLine("New Config: " + config.name); file.WriteLine("URL : " + config.url); printConfigNode(config.config, " ", file); file.Flush(); file.Close(); }
/// <summary> /// Retrieves the ConfigNode of the specified node in a part. /// </summary> /// <param name="part"></param> /// <param name="nodeName"></param> /// <param name="valueName"></param> /// <param name="value"></param> /// <returns></returns> public static ConfigNode GetPartModuleConfig(this Part part, string nodeName, string valueName, string value) { AvailablePart thispart = GetSourcePart(part); if (thispart == null) { Debug.LogError("GetPartConfig: PART NOT FOUND"); return(null); } else { ConfigNode resultingNode = thispart.partConfig.GetNode(nodeName, valueName, value); return(resultingNode); } }
internal static bool checkFolder(AvailablePart part, string[] values) { if (Core.partFolderDict.ContainsKey(part.name)) { foreach (string s in values) { if (Core.partFolderDict[part.name] == s.Trim()) { return(true); } } } return(false); }
public void PartPurchased(AvailablePart part) { if (System.IgnoreEvents) { return; } var techState = ResearchAndDevelopment.Instance.GetTechState(part.TechRequired); if (techState != null) { LunaLog.Log($"Relaying part purchased on tech: {techState.techID}; part: {part.name}"); System.MessageSender.SendPartPurchasedMessage(techState.techID, part.name); } }
private static AvailablePart ParsePartValue(string partName) { // Underscores in part names get replaced with spaces. Nobody knows why. partName = partName.Replace('_', '.'); // Get the part AvailablePart part = PartLoader.getPartInfoByName(partName); if (part == null) { throw new ArgumentException("'" + partName + "' is not a valid Part."); } return(part); }
public static double calculate(AvailablePart part) { double sum = calculateBasic(part); sum += calculateCommandModule(part); sum += calculateKerbNetAccessModule(part); sum += calculateDataTransmitterModule(part); sum += calculateProbeControlPointModule(part); sum += calculateReactionWheelModule(part); sum += calculateSASModule(part); sum += calculateScienceContainerModule(part); sum += calculateScienceExperimentModule(part); sum += calculateSeatModule(part); return(sum); }
public static bool checkCrewCapacity(AvailablePart part, string value) { foreach (string s in value.Split(',')) { int i; if (int.TryParse(s.Trim(), out i)) { if (Math.Max(i, 0) == part.partPrefab.CrewCapacity) { return(true); } } } return(false); }
public TweakEquippableItem(string partName) { avPart = PartLoader.getPartInfoByName(partName); if (avPart == null) { DebugEx.Error("Cannot find part {0} for main menu tweaker", partName); } itemModule = avPart.partPrefab.FindModuleImplementing <ModuleKISItem>(); if (itemModule == null || !itemModule.equipable && !itemModule.carriable) { DebugEx.Warning("Part is not a KIS carriable/equippable item: {0}", avPart.name); avPart = null; return; } }
bool PartInFilteredButtons(AvailablePart part, Dictionary <string, ToggleState> buttons, Dictionary <string, HashSet <AvailablePart> > filterHash) { foreach (string name in buttons.Keys) { if (!buttons[name].enabled) { continue; } if (filterHash[name].Contains(part)) { return(true); } } return(false); }
public static List <AvailablePart> getAvailableExperimentParts(string type, bool includeExperimental = false) { string[] partsRegistry = null; List <AvailablePart> list = null; switch (type) { case OMS_EXPERIMENTS: partsRegistry = omsRegistry; break; case KEMINI_EXPERIMENTS: //partsRegistry = keminiRegistry; partsRegistry = getKeminiRegister(); break; default: return(list); } // Avoid multiple allocations; the collection is small enough that the memory overhead is better than the reallocation overhead list = new List <AvailablePart>(partsRegistry.Length); for (int idx = 0, count = partsRegistry.Length; idx < count; idx++) { AvailablePart part = PartLoader.getPartInfoByName(partsRegistry[idx]); if (part == null) { continue; } /* * bool isPurchased = ResearchAndDevelopment.PartModelPurchased (part); * bool isTechAvailable = ResearchAndDevelopment.PartTechAvailable (part); * bool isExperimental = ResearchAndDevelopment.IsExperimentalPart (part); * NE_Helper.log ("Part " + part.name + * " techlevel: [" + isTechAvailable + "]" + * " experimental: [" + isExperimental + "]" + * " purchased: [" + isPurchased + "]"); */ if (ResearchAndDevelopment.PartModelPurchased(part) || (includeExperimental && ResearchAndDevelopment.PartTechAvailable(part))) { list.Add(part); } } return(list); }
protected override void OnUpdate() { base.OnUpdate(); if (lastUpdate > UnityEngine.Time.realtimeSinceStartup + .1) { return; } CelestialBody targetBody = StnSciParameter.getTargetBody(this); AvailablePart experimentType = StnSciParameter.getExperimentType(this); if (targetBody == null || experimentType == null) { if (targetBody == null || experimentType == null) { Debug.Log("targetBody or experimentType is null"); return; } } lastUpdate = UnityEngine.Time.realtimeSinceStartup; Vessel vessel = FlightGlobals.ActiveVessel; if (vessel != null) { foreach (Part part in vessel.Parts) { if (part.name == experimentType.name) { StationExperiment e = part.FindModuleImplementing <StationExperiment>(); if (e != null) { if (e.completed >= this.Root.DateAccepted && e.completed > e.launched) { ScienceData[] data = e.GetData(); foreach (ScienceData datum in data) { if (datum.subjectID.ToLower().Contains("@" + targetBody.name.ToLower() + "inspace")) { SetComplete(); return; } } } } } } } SetIncomplete(); }
private void EvaAddLifeSupport(AvailablePart part) { Part prefabPart = part.partPrefab; this.Log("Adding resources to " + part.name + "/" + prefabPart.partInfo.title); EvaAddPartModule(prefabPart); EvaAddResource(prefabPart, globalSettings.EvaElectricityConsumptionRate, globalSettings.Electricity, false); EvaAddResource(prefabPart, globalSettings.FoodConsumptionRate, globalSettings.Food, false); EvaAddResource(prefabPart, globalSettings.WaterConsumptionRate, globalSettings.Water, false); EvaAddResource(prefabPart, globalSettings.OxygenConsumptionRate, globalSettings.Oxygen, false); EvaAddResource(prefabPart, globalSettings.CO2ProductionRate, globalSettings.CO2, false); EvaAddResource(prefabPart, globalSettings.WasteProductionRate, globalSettings.Waste, false); EvaAddResource(prefabPart, globalSettings.WasteWaterProductionRate, globalSettings.WasteWater, false); }
/// <summary> /// check the part against another subcategory. Hard limited to a depth of 10 /// </summary> public static bool CheckSubcategory(AvailablePart part, string[] value, int depth) { if (depth > 10) { Logger.Log("subcategory check depth limit (10) exceeded. Check terminated on suspicion of circular subcategory checking!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", Logger.LogLevel.Error); return(false); } foreach (string s in value) { if (LoadAndProcess.subCategoriesDict.TryGetValue(s, out ConfigNodes.SubcategoryNode subcategory) && subcategory.CheckPartFilters(part, ++depth)) { return(true); } } return(false); }
private ConfigNode findExperimentModulInPC(ProtoPartModuleSnapshot kasModule, AvailablePart experiment) { ConfigNode partConf = kasModule.moduleValues; foreach (ConfigNode contentPart in partConf.GetNodes(CONTENT_PART)) { NE_Helper.log("ContentPart: " + contentPart.GetValue("name")); if (contentPart.GetValue("name") == experiment.name) { foreach (ConfigNode module in contentPart.GetNodes("MODULE")) { if (module.GetValue("name") == experimentModulname[experiment.name]) return module; } } } return null; }
// New part from scene public KIS_Item(Part part, ModuleKISInventory inventory, float quantity = 1) { // Get part node this.availablePart = PartLoader.getPartInfoByName(part.partInfo.name); this.partNode = new ConfigNode(); KIS_Shared.PartSnapshot(part).CopyTo(this.partNode); // init config this.InitConfig(availablePart, inventory, quantity); // Get mass this.resourceMass = part.GetResourceMass(); ModuleKISInventory itemInventory = part.GetComponent<ModuleKISInventory>(); if (itemInventory) { this.contentMass = itemInventory.GetContentMass(); this.contentCost = itemInventory.GetContentCost(); if (itemInventory.invName != "") this.inventoryName = itemInventory.invName; } }
public static string GetKisStats(AvailablePart part) { var sb = new StringBuilder(); sb.AppendLine("Mass: " + part.partPrefab.mass + " tons"); sb.AppendLine("Volume: " + KIS_Shared.GetPartVolume(part).ToString("0.0") + " litres"); sb.AppendLine("Costs: " + part.cost + "$"); foreach (var resourceInfo in part.partPrefab.Resources) { if (WorkshopRecipeDatabase.HasResourceRecipe(resourceInfo.resourceName)) { sb.AppendLine(resourceInfo.resourceName + ": " + resourceInfo.maxAmount + " / " + resourceInfo.maxAmount); } else { sb.AppendLine(resourceInfo.resourceName + ": 0 / " + resourceInfo.maxAmount); } } return sb.ToString(); }
void AddAltimeter(ConfigNode node, AvailablePart aPart) { // Get or add module ModuleReliabilityAltimeter rModule = aPart.partPrefab.GetComponent<ModuleReliabilityAltimeter>(); if (rModule) { Logger.DebugWarning("ModuleReliabilityAltimeter already added to \"" + aPart.name + "\"!"); } else { rModule = aPart.partPrefab.AddModule("ModuleReliabilityAltimeter") as ModuleReliabilityAltimeter; if (!rModule) { Logger.DebugError("Problem adding module to command pod!"); return; } } ConfigureBaseValues(node, rModule); ConfigureInstrumentValues(node, rModule); }
private void EvaAddPartModule(AvailablePart part, string module) { try { ConfigNode mn = new ConfigNode("MODULE"); mn.AddValue("name", module); part.partPrefab.AddModule(mn); Logging.Log("The expected exception did not happen when adding " + module + " to " + part.name + "!"); } catch (Exception ex) { if (ex.Message.Contains("Object reference not set")) { Logging.Log("kappa-ray: added " + module + " to " + part.name, false); } else { Logging.Log("Unexpected error while adding " + module + " to " + part.name + ": " + ex.Message + "\n" + ex.StackTrace, false); } } }
internal static bool FindPart(AvailablePart part) { if (part == null) { return false; } if (Text == string.Empty) { return true; } string _partinfo = PartInfo (part, Text); if (_partinfo == string.Empty) { return false; } string _Text = Text; if (QSettings.Instance.enableSearchExtension && _Text.StartsWith(QSettings.Instance.searchRegex) && _Text.EndsWith((string)QSettings.Instance.searchRegex)) { try { _Text = _Text.Substring(1, _Text.Length -2); return Regex.IsMatch (_partinfo, _Text); } catch { return FindStandard (_partinfo, _Text); } } else { return FindStandard (_partinfo, Text); } }
public override bool protovesselHasDoneExperiement(ProtoVessel pv, AvailablePart experiment, CelestialBody targetBody, double contractAccepted) { NE_Helper.log("KEES-Experiement stategy"); foreach (ProtoPartSnapshot part in pv.protoPartSnapshots) { NE_Helper.log("KEES-Experiement stategy, Part: " + part.partName); if (part.partName == experiment.name) { if (experimentFound(part, experiment, targetBody, contractAccepted)) return true; } else if (part.partName == KEES_PC) { if (payloadCarrierFound(part, experiment, targetBody, contractAccepted)) return true; } else if (isKasContainerPart(part)) { if (payloadCarrierFound(part, experiment, targetBody, contractAccepted)) return true; } } return false; }
public KIS_Item AddItem(AvailablePart availablePart, ConfigNode partNode, float qty = 1, int slot = -1) { KIS_Item item = null; if (items.ContainsKey(slot)) { slot = -1; } int maxSlot = (slotsX * slotsY) - 1; if (slot < 0 || slot > maxSlot) { slot = GetFreeSlot(); if (slot == -1) { KIS_Shared.DebugError("AddItem error : No free slot available for " + availablePart.title); return null; } } item = new KIS_Item(availablePart, partNode, this, qty); items.Add(slot, item); if (showGui) items[slot].EnableIcon(itemIconResolution); RefreshMassAndVolume(); return item; }
/// <summary> /// Calculates the cost of a part /// </summary> /// <returns>The cost.</returns> /// <param name="pt">AvailablePart.</param> public static int cost(AvailablePart pt) { return cost(pt.partPrefab); }
public static bool PartResearched(AvailablePart p) { return ResearchAndDevelopment.PartTechAvailable(p) && ResearchAndDevelopment.PartModelPurchased(p); }
public static float GetPackedPartVolume(AvailablePart part) { var moduleKisItem = KISWrapper.GetKisItem(part.partPrefab); return moduleKisItem != null ? moduleKisItem.volumeOverride : KIS_Shared.GetPartVolume(part); }