public Equipment(Hashtable hash) : base(hash) { _equipType = (EquipmentType)GetValueFromHash(hash, "_equipType"); _price = (int)GetValueFromHash(hash, "_price"); _minTech = (TechLevel)GetValueFromHash(hash, "_minTech"); _chance = (int)GetValueFromHash(hash, "_chance"); }
public Equipment(EquipmentType type, int price, TechLevel minTechLevel, int chance) { _equipType = type; _price = price; _minTech = minTechLevel; _chance = chance; }
public Weapon(WeaponType type, int power, bool disabling, int price, TechLevel minTechLevel, int chance): base(EquipmentType.Weapon, price, minTechLevel, chance) { _type = type; _power = power; _disabling = disabling; }
public Shield(ShieldType type, int power, int price, TechLevel minTechLevel, int chance) : base(EquipmentType.Shield, price, minTechLevel, chance) { _type = type; _power = power; _charge = _power; }
public PoliticalSystem(PoliticalSystemType type, int reactionIllegal, Activity activityPolice, Activity activityPirates, Activity activityTraders, TechLevel minTechLevel, TechLevel maxTechLevel, int bribeLevel, bool drugsOk, bool firearmsOk, TradeItemType wanted) { Type = type; ReactionIllegal = reactionIllegal; ActivityPolice = activityPolice; ActivityPirates = activityPirates; ActivityTraders = activityTraders; MinimumTechLevel = minTechLevel; MaximumTechLevel = maxTechLevel; BribeLevel = bribeLevel; DrugsOk = drugsOk; FirearmsOk = firearmsOk; Wanted = wanted; }
public ShipSpec(ShipType type, Size size, int cargoBays, int weaponSlots, int shieldSlots, int gadgetSlots, int crewQuarters, int fuelTanks, int fuelCost, int hullStrength, int repairCost, int price, int occurrence, Activity police, Activity pirates, Activity traders, TechLevel minTechLevel) { _type = type; _size = size; _cargoBays = cargoBays; _weaponSlots = weaponSlots; _shieldSlots = shieldSlots; _gadgetSlots = gadgetSlots; _crewQuarters = crewQuarters; _fuelTanks = fuelTanks; _fuelCost = fuelCost; _hullStrength = hullStrength; _repairCost = repairCost; _price = price; _occurrence = occurrence; _police = police; _pirates = pirates; _traders = traders; _minTech = minTechLevel; }
public static ThingDef TryFindRandomShellDef(ThingDef turret, bool allowEMP = true, bool mustHarmHealth = true, TechLevel techLevel = TechLevel.Undefined, bool allowAntigrainWarhead = false, float maxMarketValue = -1f) { if (!TurretGunUtility.NeedsShells(turret)) { return(null); } ThingFilter fixedFilter = turret.building.turretGunDef.building.fixedStorageSettings.filter; ThingDef result; if ((from x in DefDatabase <ThingDef> .AllDefsListForReading where fixedFilter.Allows(x) && (allowEMP || x.projectileWhenLoaded.projectile.damageDef != DamageDefOf.EMP) && (!mustHarmHealth || x.projectileWhenLoaded.projectile.damageDef.harmsHealth) && (techLevel == TechLevel.Undefined || x.techLevel <= techLevel) && (allowAntigrainWarhead || x != ThingDefOf.Shell_AntigrainWarhead) && (maxMarketValue < 0f || x.BaseMarketValue <= maxMarketValue) select x).TryRandomElement(out result)) { return(result); } return(null); }
private static void CalculateAllowedThingStuffPairs(IEnumerable <ThingDef> allowed, TechLevel techLevel, QualityGenerator qualityGenerator) { allowedThingStuffPairs.Clear(); foreach (ThingDef item in allowed) { for (int i = 0; i < 5; i++) { if (GenStuff.TryRandomStuffFor(item, out ThingDef stuff, techLevel)) { QualityCategory quality = (!item.HasComp(typeof(CompQuality))) ? QualityCategory.Normal : QualityUtility.GenerateQuality(qualityGenerator); allowedThingStuffPairs.Add(new ThingStuffPairWithQuality(item, stuff, quality)); } } } }
private double MassTL(ConfigNode cfg = null) { if (techLevel != -1) { TechLevel oldTL = new TechLevel(), newTL = new TechLevel(); if (!oldTL.Load(cfg == null ? config : cfg, techNodes, engineType, origTechLevel)) return 1.0; if (!newTL.Load(cfg == null ? config : cfg, techNodes, engineType, techLevel)) return 1.0; return newTL.Mass(oldTL, engineType.Contains("S")); } return 1.0; }
public void setTechLevelsSpent(TechLevel techLevelsSpent) { this.techLevelsSpent = techLevelsSpent; }
public Faction RandomAlliedFaction(bool allowHidden = false, bool allowDefeated = false, bool allowNonHumanlike = true, TechLevel minTechLevel = TechLevel.Undefined) { Faction result; if ((from x in this.AllFactions where !x.IsPlayer && (allowHidden || !x.def.hidden) && (allowDefeated || !x.defeated) && (allowNonHumanlike || x.def.humanlikeFaction) && (minTechLevel == TechLevel.Undefined || x.def.techLevel >= minTechLevel) && x.PlayerRelationKind == FactionRelationKind.Ally select x).TryRandomElement(out result)) { return(result); } return(null); }
private Thing GenerateReward(float value, TechLevel techLevel, Predicate <ThingDef> validator = null) { if (Rand.Chance(0.5f) && (validator == null || validator(ThingDefOf.Silver))) { Thing thing = ThingMaker.MakeThing(ThingDefOf.Silver, null); thing.stackCount = ThingUtility.RoundedResourceStackCount(Mathf.Max(GenMath.RoundRandom(value), 1)); return(thing); } ThingDef thingDef = default(ThingDef); if (Rand.Chance(0.35f) && (from x in ItemCollectionGeneratorUtility.allGeneratableItems where x.itemGeneratorTags != null && x.itemGeneratorTags.Contains(ItemCollectionGeneratorUtility.SpecialRewardTag) && (validator == null || validator(x)) && Mathf.Abs((float)(1.0 - x.BaseMarketValue / value)) <= 0.34999999403953552 select x).TryRandomElement <ThingDef>(out thingDef)) { Thing thing2 = ThingMaker.MakeThing(thingDef, GenStuff.RandomStuffFor(thingDef)); CompQuality compQuality = thing2.TryGetComp <CompQuality>(); if (compQuality != null) { compQuality.SetQuality(QualityUtility.RandomBaseGenItemQuality(), ArtGenerationContext.Outsider); } return(thing2); } if (Rand.Chance(0.13f)) { float minExpensiveMineableResourceMarketValue = ThingDefOf.Uranium.BaseMarketValue; ThingDef thingDef2 = default(ThingDef); if ((from x in ItemCollectionGenerator_Meteorite.mineables where x.building.isResourceRock && x.building.mineableThing.BaseMarketValue >= minExpensiveMineableResourceMarketValue && (validator == null || validator(x.building.mineableThing)) select x).TryRandomElement <ThingDef>(out thingDef2)) { float num = (float)(value * 0.89999997615814209); ThingDef mineableThing = thingDef2.building.mineableThing; Thing thing3 = ThingMaker.MakeThing(mineableThing, null); thing3.stackCount = Mathf.Max(GenMath.RoundRandom(num / mineableThing.BaseMarketValue), 1); return(thing3); } } Option option2 = (from option in ItemCollectionGeneratorUtility.allGeneratableItems.Select(delegate(ThingDef td) { if ((int)td.techLevel > (int)techLevel) { return(null); } if (td.itemGeneratorTags != null && td.itemGeneratorTags.Contains(ItemCollectionGeneratorUtility.SpecialRewardTag)) { return(null); } if (!td.IsWithinCategory(ThingCategoryDefOf.Apparel) && !td.IsWithinCategory(ThingCategoryDefOf.Weapons) && !td.IsWithinCategory(ThingCategoryDefOf.Art) && (td.building == null || !td.Minifiable) && (td.tradeTags == null || !td.tradeTags.Contains("Exotic"))) { return(null); } if (validator != null && !validator(td)) { return(null); } ThingDef stuff = null; if (td.MadeFromStuff && !GenStuff.TryRandomStuffByCommonalityFor(td, out stuff, techLevel)) { return(null); } Option option3 = new Option(); option3.thingDef = td; option3.quality = ((!td.HasComp(typeof(CompQuality))) ? QualityCategory.Normal : QualityUtility.RandomQuality()); option3.stuff = stuff; return(option3); }) where option != null select option).MinBy(delegate(Option option) { float value2 = StatDefOf.MarketValue.Worker.GetValue(StatRequest.For(option.thingDef, option.stuff, option.quality), true); return(Mathf.Abs(value - value2)); }); Thing thing4 = ThingMaker.MakeThing(option2.thingDef, option2.stuff); CompQuality compQuality2 = thing4.TryGetComp <CompQuality>(); if (compQuality2 != null) { compQuality2.SetQuality(option2.quality, ArtGenerationContext.Outsider); } return(thing4); }
public static void DrawSettings(Rect rect) { Listing_Standard ls = new Listing_Standard(GameFont.Small); ls.ColumnWidth = rect.width - 30f; ls.Begin(rect); ls.Gap(); bool a; bool b; bool c; string s = "Your calculated tech level: "; if (!restrictOnTechLevel) { s += "N/A (fixed tech level)"; } else if (Current.Game != null) { s += Enum.GetName(typeof(TechLevel), Base.playerTechLevel); } else { s += "Not in game"; } Rect standard = ls.Label(s); float standardHeight = standard.height; ls.GapLine(); ls.CheckboxLabeled("Try to exempt clothing research options", ref exemptClothing, "Refers to a list of clothing research projects and exempts their products from restriction."); ls.GapLine(); ls.CheckboxLabeled("Restrict items above the colony's current tech level", ref restrictOnTechLevel, "Instead of manually setting the tech level above which to restrict tech, you can automatically use the colony's tech level."); ls.Gap(); ls.GapLine(); if (restrictOnTechLevel) { ls.Label("Method by which this mod will calculate your tech level:"); ls.Gap(); a = ls.RadioButton_NewTemp("Highest tech researched", useHighestResearched, tooltip: "If you have even one tech in a tech level researched, you will be considered that tech for the purpose of raids."); ls.Gap(); b = ls.RadioButton_NewTemp("Tech completion of a certain percent", usePercentResearched, tooltip: "Once you research a certain % of a tech level's available technologies, you will be considered that tech level for the purpose of raids."); if (usePercentResearched) { percentResearchNeeded = Mathf.Clamp(percentResearchNeeded, 0.05f, 1f); Rect percentResearchRect = ls.GetRect(standardHeight); Rect percentResearchLabelRect = percentResearchRect.LeftPartPixels(450); // Rect percentResearchSliderRect = percentResearchRect.RightPartPixels(percentResearchRect.width - 450); // Widgets.Label(percentResearchLabelRect, "Percent required:"); percentResearchNeeded = Widgets.HorizontalSlider(percentResearchLabelRect, percentResearchNeeded, 0.05f, 1f, middleAlignment: false, label: Mathf.RoundToInt(percentResearchNeeded * 100) + "%", leftAlignedLabel: null, rightAlignedLabel: null, roundTo: 0.05f); } else { ls.Gap(); } ls.Gap(); c = ls.RadioButton_NewTemp("Actual colonist tech level", useActualTechLevel, tooltip: "Not recommended unless you have a mod to increase your tech level somehow."); if (a && a != useHighestResearched) { useHighestResearched = true; usePercentResearched = false; useActualTechLevel = false; if (Current.Game != null) { Base.playerTechLevel = Base.GetPlayerTech(); } } else if (b && b != usePercentResearched) { useHighestResearched = false; usePercentResearched = true; useActualTechLevel = false; if (Current.Game != null) { Base.playerTechLevel = Base.GetPlayerTech(); } } else if (c && c != useActualTechLevel) { useHighestResearched = false; usePercentResearched = false; useActualTechLevel = true; if (Current.Game != null) { Base.playerTechLevel = Base.GetPlayerTech(); } } } else { Rect techLevelRect = ls.GetRect(Text.LineHeight); Rect techLabelRect = techLevelRect.LeftPartPixels(300); Rect techSliderRect = techLevelRect.RightPartPixels(techLevelRect.width - 300); Widgets.Label(techLabelRect, "Minimum tech level to restrict items"); minToRestrict = (TechLevel)Mathf.RoundToInt(Widgets.HorizontalSlider(techSliderRect, (float)minToRestrict, (float)TechLevel.Animal, (float)TechLevel.Archotech, middleAlignment: false, label: Enum.GetName(typeof(TechLevel), (int)minToRestrict), leftAlignedLabel: null, rightAlignedLabel: null, roundTo: 1f)); } ls.GapLine(); ls.CheckboxLabeled("Restrict even if the item is researched", ref evenResearched, "Warning: without a mod to let your colony advance in tech, you will NEVER be able to use certain items."); ls.Gap(); ls.Gap(); ls.End(); }
// Check if can switch to TL public static bool CanTL(ConfigNode cfg, ConfigNode mod, string type, int level) { TechLevel nTL = new TechLevel(); if (!nTL.Load(cfg, mod, type, level)) return false; return HighLogic.CurrentGame.Mode != Game.Modes.CAREER || nTL.techRequired.Equals("") || ResearchAndDevelopment.GetTechnologyState(nTL.techRequired) == RDTech.State.Available; }
public double Mass(TechLevel oldTL, bool constantThrust = false) { if (oldTL.massMultiplier > 0 && massMultiplier > 0) return massMultiplier / oldTL.massMultiplier; if (constantThrust) return oldTL.TWR / TWR; else return oldTL.atmosphereCurve.Evaluate(0) / atmosphereCurve.Evaluate(0); }
// MULTIPLIERS public double Thrust(TechLevel oldTL, bool constantMass = false) { if (oldTL.thrustMultiplier > 0 && thrustMultiplier > 0) return thrustMultiplier / oldTL.thrustMultiplier; if(constantMass) return TWR / oldTL.TWR; else return TWR / oldTL.TWR * oldTL.atmosphereCurve.Evaluate(0) / atmosphereCurve.Evaluate(0); }
public TechLevel(TechLevel t) { atmosphereCurve = t.atmosphereCurve; velocityCurve = t.velocityCurve; TWR = t.TWR; thrustMultiplier = t.thrustMultiplier; massMultiplier = t.massMultiplier; techRequired = t.techRequired; minThrottleMultiplier = t.minThrottleMultiplier; }
virtual public void DoConfig(ConfigNode cfg) { // fix propellant ratios to not be rounded if (cfg.HasNode("PROPELLANT")) { foreach (ConfigNode pNode in cfg.GetNodes("PROPELLANT")) { if (pNode.HasValue("ratio")) { double dtmp; if (double.TryParse(pNode.GetValue("ratio"), out dtmp)) pNode.SetValue("ratio", (dtmp * 100.0).ToString()); } } } float heat = -1; if (cfg.HasValue("heatProduction")) // ohai amsi: allow heat production to be changed by multiplier { heat = (float)Math.Round(float.Parse(cfg.GetValue("heatProduction")) * heatMult, 0); cfg.SetValue("heatProduction", heat.ToString()); } // load throttle (for later) curThrottle = throttle; if (cfg.HasValue("throttle")) float.TryParse(cfg.GetValue("throttle"), out curThrottle); else if(cfg.HasValue("minThrust") && cfg.HasValue("maxThrust")) curThrottle = float.Parse(cfg.GetValue("minThrust")) / float.Parse(cfg.GetValue("maxThrust")); float TLMassMult = 1.0f; if (techLevel != -1) { // load techlevels TechLevel cTL = new TechLevel(); //print("For engine " + part.name + ", config " + configuration + ", max TL: " + TechLevel.MaxTL(cfg, techNodes, engineType)); cTL.Load(cfg, techNodes, engineType, techLevel); TechLevel oTL = new TechLevel(); oTL.Load(cfg, techNodes, engineType, origTechLevel); // set atmosphereCurve if (cfg.HasValue("IspSL") && cfg.HasValue("IspV")) { cfg.RemoveNode("atmosphereCurve"); ConfigNode curve = new ConfigNode("atmosphereCurve"); float ispSL, ispV; float.TryParse(cfg.GetValue("IspSL"), out ispSL); float.TryParse(cfg.GetValue("IspV"), out ispV); FloatCurve aC = new FloatCurve(); aC = Mod(cTL.atmosphereCurve, ispSL, ispV); aC.Save(curve); cfg.AddNode(curve); } // set heatProduction and dissipation if (heat > 0) { cfg.SetValue("heatProduction", MassTL(heat).ToString("0")); part.heatDissipation = 0.12f / MassTL(1.0f); } // set thrust and throttle if (cfg.HasValue(thrustRating)) { float thr; float.TryParse(cfg.GetValue(thrustRating), out thr); configMaxThrust = ThrustTL(thr); cfg.SetValue(thrustRating, configMaxThrust.ToString("0.0000")); if (cfg.HasValue("minThrust")) { float.TryParse(cfg.GetValue("minThrust"), out thr); configMinThrust = ThrustTL(thr); cfg.SetValue("minThrust", configMinThrust.ToString("0.0000")); } else { if (thrustRating.Equals("thrusterPower")) { configMinThrust = configMaxThrust * 0.5f; } else { configMinThrust = configMaxThrust; if (curThrottle > 1.0f) { if (techLevel >= curThrottle) curThrottle = 1.0f; else curThrottle = -1.0f; } if (curThrottle >= 0.0f) { curThrottle = (float)((double)curThrottle * cTL.Throttle()); configMinThrust *= curThrottle; } cfg.SetValue("minThrust", configMinThrust.ToString("0.0000")); } } curThrottle = configMinThrust / configMaxThrust; if(origMass > 0) TLMassMult = MassTL(1.0f); } } else { if(cfg.HasValue(thrustRating) && curThrottle > 0f && !cfg.HasValue("minThrust")) { configMinThrust = curThrottle * float.Parse(cfg.GetValue(thrustRating)); cfg.SetValue("minThrust", configMinThrust.ToString("0.0000")); } } // mass change if (origMass > 0) { float ftmp; configMassMult = 1.0f; if (cfg.HasValue("massMult")) if (float.TryParse(cfg.GetValue("massMult"), out ftmp)) configMassMult = ftmp; part.mass = origMass * configMassMult * massMult * TLMassMult; } // KIDS integration if(cfg.HasNode("atmosphereCurve")) { ConfigNode newCurveNode = new ConfigNode("atmosphereCurve"); FloatCurve oldCurve = new FloatCurve(); oldCurve.Load(cfg.GetNode("atmosphereCurve")); FloatCurve newCurve = Mod(oldCurve, ispSLMult, ispVMult); newCurve.Save(newCurveNode); cfg.RemoveNode("atmosphereCurve"); cfg.AddNode(newCurveNode); } }
public override string GetInfo () { if (configs.Count < 2) return TLTInfo(); string info = TLTInfo() + "\nAlternate configurations:\n"; TechLevel moduleTLInfo = new TechLevel(); if (techNodes != null) moduleTLInfo.Load(techNodes, techLevel); else moduleTLInfo = null; foreach (ConfigNode config in configs) { if(!config.GetValue ("name").Equals (configuration)) { info += " " + config.GetValue ("name") + "\n"; if(config.HasValue (thrustRating)) info += " (" + ThrustTL(config.GetValue (thrustRating), config).ToString("0.00") + " Thrust"; else info += " (Unknown Thrust"; FloatCurve isp = new FloatCurve(); if(config.HasNode ("atmosphereCurve")) { isp.Load (config.GetNode ("atmosphereCurve")); info += ", " + isp.Evaluate (isp.maxTime).ToString() + "-" + isp.Evaluate (isp.minTime).ToString() + "Isp"; } else if (config.HasValue("IspSL") && config.HasValue("IspV")) { float ispSL = 1.0f, ispV = 1.0f; float.TryParse(config.GetValue("IspSL"), out ispSL); float.TryParse(config.GetValue("IspV"), out ispV); TechLevel cTL = new TechLevel(); if (cTL.Load(config, techNodes, engineType, techLevel)) { ispSL *= ispSLMult * cTL.atmosphereCurve.Evaluate(1); ispV *= ispVMult * cTL.atmosphereCurve.Evaluate(0); info += ", " + ispSL.ToString("0") + "-" + ispV.ToString("0") + "Isp"; } } info += ")\n"; } } return info; }
public override void LordToilTick() { base.LordToilTick(); LordToilData_Siege data = this.Data; if (this.lord.ticksInToil == 450) { this.lord.CurLordToil.UpdateAllDuties(); } if (this.lord.ticksInToil > 450) { if (this.lord.ticksInToil % 500 == 0) { this.UpdateAllDuties(); } } if (Find.TickManager.TicksGame % 500 == 0) { if (!(from frame in this.Frames where !frame.Destroyed select frame).Any <Frame>()) { if (!(from blue in data.blueprints where !blue.Destroyed select blue).Any <Blueprint>()) { if (!base.Map.listerThings.ThingsInGroup(ThingRequestGroup.BuildingArtificial).Any((Thing b) => b.Faction == this.lord.faction && b.def.building.buildingTags.Contains("Artillery"))) { this.lord.ReceiveMemo("NoArtillery"); return; } } } int num = GenRadial.NumCellsInRadius(20f); int num2 = 0; int num3 = 0; for (int i = 0; i < num; i++) { IntVec3 c = data.siegeCenter + GenRadial.RadialPattern[i]; if (c.InBounds(base.Map)) { List <Thing> thingList = c.GetThingList(base.Map); for (int j = 0; j < thingList.Count; j++) { if (thingList[j].def.IsShell) { num2 += thingList[j].stackCount; } if (thingList[j].def == ThingDefOf.MealSurvivalPack) { num3 += thingList[j].stackCount; } } } } if (num2 < 4) { ThingDef turret_Mortar = ThingDefOf.Turret_Mortar; bool allowEMP = false; TechLevel techLevel = this.lord.faction.def.techLevel; ThingDef thingDef = TurretGunUtility.TryFindRandomShellDef(turret_Mortar, allowEMP, true, techLevel, false, 250f); if (thingDef != null) { this.DropSupplies(thingDef, 10); } } if (num3 < 5) { this.DropSupplies(ThingDefOf.MealSurvivalPack, 12); } } }
public IEnumerable <ResearchProjectDef> GetExpertiseDefsFor(Pawn pawn, FactionDef faction) { //1. Gather info on that pawn //a. tech level TechLevel factionTechLevel = faction?.techLevel ?? 0; TechLevel childhoodLevel = 0; SkillDef childhoodSkill = null; bool isPlayer = pawn.Faction?.IsPlayer ?? false; techLevel = TechPoolIncludesBackground || !isPlayer?FindBGTechLevel(pawn, out childhoodLevel, out childhoodSkill) : factionTechLevel; TechLevel workingTechLevel = startingTechLevel = techLevel; //b. higest skills SkillRecord highestSkillRecord = pawn.skills.skills.Aggregate(AccessHighestSkill); SkillDef highestSkill = highestSkillRecord.def; IEnumerable <SkillRecord> secondCandidates = pawn.skills.skills.Except(highestSkillRecord).Where(x => SkillIsRelevant(x.def, techLevel)); SkillDef secondSkill = secondCandidates.Aggregate(AccessHighestSkill).def; //c. age float middleAge = pawn.RaceProps.lifeExpectancy / 2; int matureAge = pawn.RaceProps.lifeStageAges.FindLastIndex(x => x.minAge < middleAge); //not always the last possible age because there are mods with an "eldery" stage int growthAdjust = 0; int oldBonus = 0; if (pawn.ageTracker.CurLifeStageIndex < matureAge) { growthAdjust = matureAge - pawn.ageTracker.CurLifeStageIndex; } else if (pawn.ageTracker.AgeBiologicalYears > middleAge) { oldBonus = 1; } //d. special cases isFighter = highestSkill == SkillDefOf.Melee; isShooter = highestSkill == SkillDefOf.Shooting; int fighterHandicap = (isFighter | isShooter) ? 1 : 0; bool guru = techLevel < TechLevel.Archotech && highestSkill == SkillDefOf.Intellectual && highestSkillRecord.Level >= Rand.Range(7, 10); //2. Calculate how many techs he should know int minSlots = techLevel > TechLevel.Medieval ? 1 : oldBonus; int slots = Mathf.Max(minSlots, FactionExpertiseRange(techLevel) - growthAdjust + oldBonus - fighterHandicap); if (slots == 0) { if (Prefs.LogVerbose) { Log.Warning($"... No slots for {pawn.gender.GetObjective()}, returning null. (StartingTechLevel is {techLevel}, CurLifeStageIndex is {pawn.ageTracker.CurLifeStageIndex}, fighterHandicap is {fighterHandicap})"); } return(null); } //3. Info for debugging. if (Prefs.LogVerbose) { StringBuilder stringBuilder = new StringBuilder(); string factionName = faction.label.ToLower() ?? pawn.Possessive().ToLower() + faction; if (TechPoolIncludesStarting) { stringBuilder.Append($"default for {factionName}"); } if (TechPoolIncludesTechLevel) { stringBuilder.AppendWithComma($"{factionTechLevel.ToString().ToLower()} age"); } if (TechPoolIncludesScenario) { stringBuilder.AppendWithComma($"{Find.Scenario.name.ToLower()} scenario"); } if (TechPoolIncludesBackground) { stringBuilder.AppendWithComma($"{childhoodLevel.ToString().ToLower()} childhood & {techLevel.ToString().ToLower()} background"); } Log.Message($"... Including technologies from: " + stringBuilder.ToString() + "."); stringBuilder.Clear(); string guruText = guru ? " (allowing advanced knowledge)" : ""; stringBuilder.Append($"... As {pawn.ageTracker.CurLifeStage.label}, {pawn.ProSubj()} gets {slots} slots. {pawn.Possessive().CapitalizeFirst()} highest relevant skills are {highestSkill.label}{guruText} & {secondSkill.label}."); Log.Message(stringBuilder.ToString()); } //4. Finally, Distribute knowledge bool strict = false; bool useChildhood = childhoodSkill != null && TechPoolIncludesBackground && SkillIsRelevant(childhoodSkill, childhoodLevel) && slots > 1; var filtered = TechTracker.FindTechs(x => TechPool(isPlayer, x, workingTechLevel, strict)); int pass = 0; List <ResearchProjectDef> result = new List <ResearchProjectDef>(); if (guru) { workingTechLevel++; } while (result.Count() < slots) { pass++; filtered.ExecuteEnumerable(); if (filtered.EnumerableNullOrEmpty()) { Log.Warning("[HumanResources] Empty technology pool!"); } var remaining = filtered.Where(x => !result.Contains(x)); if (remaining.EnumerableNullOrEmpty()) { break; } SkillDef skill = null; if (pass == 1 && remaining.Any(x => x.Skills.Contains(highestSkill))) { skill = highestSkill; } else if (pass == 2 && remaining.Any(x => x.Skills.Contains(secondSkill))) { skill = useChildhood ? childhoodSkill : secondSkill; } ResearchProjectDef selected = remaining.RandomElementByWeightWithDefault(x => TechLikelihoodForSkill(pawn, x.Skills, slots, pass, skill), 1f) ?? remaining.RandomElement(); result.Add(selected); //prepare next pass: strict = false; if ((guru && pass == 1) | result.NullOrEmpty()) { workingTechLevel--; } if (useChildhood) { if (pass == 1) { strict = true; workingTechLevel = childhoodLevel; } if (pass == 2) { workingTechLevel = techLevel; } } if (workingTechLevel == 0) { break; } } if (!result.NullOrEmpty()) { return(result); } Log.Error($"[HumanResources] Couldn't calculate any expertise for {pawn}"); return(null); }
public bool Includes(TechLevel level) { return(level >= min && level <= max); }
protected virtual void SetValues(ShipType type) { int typeInt = (int)type; _type = type; _size = Consts.ShipSpecs[typeInt]._size; _cargoBays = Consts.ShipSpecs[typeInt]._cargoBays; _weaponSlots = Consts.ShipSpecs[typeInt]._weaponSlots; _shieldSlots = Consts.ShipSpecs[typeInt]._shieldSlots; _gadgetSlots = Consts.ShipSpecs[typeInt]._gadgetSlots; _crewQuarters = Consts.ShipSpecs[typeInt]._crewQuarters; _fuelTanks = Consts.ShipSpecs[typeInt]._fuelTanks; _fuelCost = Consts.ShipSpecs[typeInt]._fuelCost; _hullStrength = Consts.ShipSpecs[typeInt]._hullStrength; _repairCost = Consts.ShipSpecs[typeInt]._repairCost; _price = Consts.ShipSpecs[typeInt]._price; _occurrence = Consts.ShipSpecs[typeInt]._occurrence; _police = Consts.ShipSpecs[typeInt]._police; _pirates = Consts.ShipSpecs[typeInt]._pirates; _traders = Consts.ShipSpecs[typeInt]._traders; _minTech = Consts.ShipSpecs[typeInt]._minTech; _hullUpgraded = Consts.ShipSpecs[typeInt]._hullUpgraded; _imageIndex = Consts.ShipSpecs[typeInt]._imageIndex; }
bool MatchThingTech(TechLevel tech) { return(tech >= techLevel.min && tech <= techLevel.max); }
public bool TryGetRandomNonColonyHumanlikeFaction(out Faction faction, bool tryMedievalOrBetter, bool allowDefeated = false, TechLevel minTechLevel = TechLevel.Undefined) { IEnumerable <Faction> source = from x in this.AllFactions where !x.IsPlayer && !x.def.hidden && x.def.humanlikeFaction && (allowDefeated || !x.defeated) && (minTechLevel == TechLevel.Undefined || x.def.techLevel >= minTechLevel) select x; return(source.TryRandomElementByWeight(delegate(Faction x) { if (tryMedievalOrBetter && x.def.techLevel < TechLevel.Medieval) { return 0.1f; } return 1f; }, out faction)); }
/// <summary> /// Load from XML: Initializing constructor from an XML node. /// </summary> /// <param name="node">An <see cref="XmlNode"/> within /// a Nova component definition file (xml document). /// </param> public Component(XmlNode node) : base(node) { Properties = new Dictionary <string, ComponentProperty>(); XmlNode mainNode = node.FirstChild; while (mainNode != null) { try { switch (mainNode.Name.ToLower()) { case "mass": Mass = int.Parse(mainNode.FirstChild.Value, System.Globalization.CultureInfo.InvariantCulture); break; case "cost": Cost = new Resources(mainNode); break; case "tech": RequiredTech = new TechLevel(mainNode); break; case "description": XmlText xmltxtDescription = (XmlText)mainNode.FirstChild; if (xmltxtDescription != null) { this.Description = xmltxtDescription.Value; } break; case "race_restrictions": Restrictions = new RaceRestriction(mainNode); break; case "image": { // Paths are always stored in external files using forward slashes. ImageFile = mainNode.FirstChild.Value; ImageFile = ImageFile.Replace('/', Path.DirectorySeparatorChar); // relative or absolute path? we normally store the relative path but will handle loading either incase the file has been manually modified. try { FileInfo info = new FileInfo(ImageFile); if (info.Exists) { // was absolute, so keep as is and load up the image ComponentImage = new Bitmap(ImageFile); } else { { string graphicsPath = FileSearcher.GetGraphicsPath(); if (graphicsPath != null) { ImageFile = Path.Combine(graphicsPath, ImageFile); info = new FileInfo(ImageFile); } } if (info.Exists) { // now we have an absolute path, load the image ComponentImage = new Bitmap(ImageFile); } else { // No further action. FileSearcher will report an error (once only) if the graphics are not available. } } } catch (System.NotSupportedException) { // The path doesn't make sense, maybe it wasn't relative. // Don't change anything and don't load the image ImageFile = mainNode.FirstChild.Value.Replace('/', Path.DirectorySeparatorChar); ComponentImage = null; Report.Error("Unable to locate the image file " + ImageFile); } break; } case "property": { // Load the property. It may be of any type (Bomb, IntegerProperty, Hull, etc), so // check the save file first to determine what to load, and use the appropriate constructor. string propertyType = mainNode.SelectSingleNode("Type").FirstChild.Value; ComponentProperty newProperty; switch (propertyType.ToLower()) { case "armor": { newProperty = new IntegerProperty(mainNode); break; } case "battle movement": { newProperty = new DoubleProperty(mainNode); break; } case "beam deflector": { newProperty = new ProbabilityProperty(mainNode); break; } case "bomb": { newProperty = new Bomb(mainNode); break; } case "capacitor": { newProperty = new CapacitorProperty(mainNode); break; } case "cloak": { newProperty = new ProbabilityProperty(mainNode); break; } case "defense": { newProperty = new Defense(mainNode); break; } case "energy dampener": { newProperty = new DoubleProperty(mainNode); break; } case "cargo": { newProperty = new IntegerProperty(mainNode); break; } case "colonizer": { newProperty = new Colonizer(mainNode); break; } case "computer": { newProperty = new Computer(mainNode); break; } case "engine": { newProperty = new Engine(mainNode); break; } case "fuel": { newProperty = new Fuel(mainNode); break; } case "gate": { newProperty = new Gate(mainNode); break; } case "hull": { newProperty = new Hull(mainNode); break; } case "hull affinity": { newProperty = new HullAffinity(mainNode); break; } case "jammer": { newProperty = new ProbabilityProperty(mainNode); break; } case "mass driver": { newProperty = new MassDriver(mainNode); break; } case "mine layer": { newProperty = new MineLayer(mainNode); break; } case "mine layer efficiency": { newProperty = new DoubleProperty(mainNode); break; } case "mining robot": { newProperty = new IntegerProperty(mainNode); break; } case "orbital adjuster": { newProperty = new IntegerProperty(mainNode); break; } case "radiation": { newProperty = new Radiation(mainNode); break; } case "shield": { newProperty = new IntegerProperty(mainNode); break; } case "scanner": { newProperty = new Scanner(mainNode); break; } case "tachyon detector": { newProperty = new ProbabilityProperty(mainNode); break; } case "terraform": { newProperty = new Terraform(mainNode); break; } case "transport ships only": { newProperty = new SimpleProperty(mainNode); break; } case "weapon": { newProperty = new Weapon(mainNode); break; } default: { // it is an error to arrive here, but try to recover using an integer property Report.Error("Component property type " + propertyType + " not recognised, using default constructor"); newProperty = new IntegerProperty(mainNode); break; } } if (newProperty != null) { this.Properties.Add(propertyType, newProperty); } break; } } } catch (Exception e) { Report.FatalError(e.Message + "\n Details: \n" + e.ToString()); } mainNode = mainNode.NextSibling; } }
public void setTechLevels(TechLevel techLevels) { this.techLevels = techLevels; }
private static float TechLevelDiff(TechLevel def, TechLevel target) { return((float)TechLevel.Ultra - Mathf.Abs((float)target - (float)def)); }
public static ThingDef RandomCheapWallStuff(Faction faction, bool notVeryFlammable = false) { TechLevel techLevel = (faction != null) ? faction.def.techLevel : TechLevel.Spacer; return(BaseGenUtility.RandomCheapWallStuff(techLevel, notVeryFlammable)); }
public ShipSpec(Hashtable hash) : base(hash) { _type = (ShipType)GetValueFromHash(hash, "_type", _type); _size = (Size)GetValueFromHash(hash, "_size", _size); _cargoBays = (int)GetValueFromHash(hash, "_cargoBays", _cargoBays); _weaponSlots = (int)GetValueFromHash(hash, "_weaponSlots", _weaponSlots); _shieldSlots = (int)GetValueFromHash(hash, "_shieldSlots", _shieldSlots); _gadgetSlots = (int)GetValueFromHash(hash, "_gadgetSlots", _gadgetSlots); _crewQuarters = (int)GetValueFromHash(hash, "_crewQuarters", _crewQuarters); _fuelTanks = (int)GetValueFromHash(hash, "_fuelTanks", _fuelTanks); _fuelCost = (int)GetValueFromHash(hash, "_fuelCost", _fuelCost); _hullStrength = (int)GetValueFromHash(hash, "_hullStrength", _hullStrength); _repairCost = (int)GetValueFromHash(hash, "_repairCost", _repairCost); _price = (int)GetValueFromHash(hash, "_price", _price); _occurrence = (int)GetValueFromHash(hash, "_occurrence", _occurrence); _police = (Activity)GetValueFromHash(hash, "_police", _police); _pirates = (Activity)GetValueFromHash(hash, "_pirates", _pirates); _traders = (Activity)GetValueFromHash(hash, "_traders", _traders); _minTech = (TechLevel)GetValueFromHash(hash, "_minTech", _minTech); _hullUpgraded = (bool)GetValueFromHash(hash, "_hullUpgraded", _hullUpgraded); _imageIndex = (int)GetValueFromHash(hash, "_imageIndex", Consts.ShipImgUseDefault); // Get the images if the ship uses the custom images. if (ImageIndex == (int)ShipType.Custom) Game.CurrentGame.ParentWindow.CustomShipImages = (Image[])GetValueFromHash(hash, "_images", Game.CurrentGame.ParentWindow.CustomShipImages); // Get the name if the ship is a custom design. if (Type == ShipType.Custom) { Strings.ShipNames[(int)ShipType.Custom] = (string)GetValueFromHash(hash, "_name", Strings.ShipNames[(int)ShipType.Custom]); Consts.ShipSpecs[(int)ShipType.Custom] = new ShipSpec(_type, _size, _cargoBays, _weaponSlots, _shieldSlots, _gadgetSlots, _crewQuarters, _fuelTanks, _fuelCost, _hullStrength, _repairCost, _price, _occurrence, _police, _pirates, _traders, _minTech); UpdateCustomImageOffsetConstants(); } }
static void Postfix() { if (Faction.OfPlayerSilentFail?.def?.techLevel == null || Faction.OfPlayer.def.techLevel == TechLevel.Undefined) // abort if our techlevel is undefined for some reason { LogOutput.WriteLogMessage(Errorlevel.Debug, "Aborted reasearch manager postfix!"); return; } LogOutput.WriteLogMessage(Errorlevel.Debug, "Research Manager called"); if (Find.CurrentMap == null) { //LogOutput.WriteLogMessage(Errorlevel.Information, "Research Manager called while loading a new map. Flushing old values."); FlushCfg(); } if (firstpass || facName != Faction.OfPlayer.def.defName) { startedAt = DateTime.Now; LogOutput.WriteLogMessage(Errorlevel.Debug, "Research Manager restarted"); facName = Faction.OfPlayer.def.defName; try { GetAndReloadTL(); //store the default value for the techlevel because we will modify it later and we need the one from right now isTribe = factionDefault == TechLevel.Neolithic; //LoadCfgValues(); firstpass = false; } catch (Exception ex) { LogOutput.WriteLogMessage(Errorlevel.Error, "Caught error in Reapply All Mods: " + ex.ToString()); } } UpdateFinishedProjectCounts(); TechLevel newLevel = TechAdvancing.Rules.GetNewTechLevel(); if (newLevel != TechLevel.Undefined) { if (firstNotificationHidden && DateTime.Now.Subtract(TimeSpan.FromSeconds(5)) > startedAt) //hiding the notification on world start { if (Faction.OfPlayer.def.techLevel < newLevel) { Find.LetterStack.ReceiveLetter("newTechLevelLetterTitle".Translate(), "newTechLevelLetterContents".Translate(isTribe ? "configTribe".Translate() : "configColony".Translate()) + " " + newLevel.ToString() + ".", LetterDefOf.PositiveEvent); } } else { firstNotificationHidden = true; } LogOutput.WriteLogMessage(Errorlevel.Debug, $"Factiondeflevel was changed from {Faction.OfPlayer.def.techLevel} to {newLevel} via call #1."); Faction.OfPlayer.def.techLevel = newLevel; } /*** * how techlevel increases: * player researched all techs of techlevel X and below. the techlevel rises to X+1 * * player researched more than 50% of the techlevel Y then the techlevel rises to Y **/ RecalculateTechlevel(false); }
public Faction RandomNonHostileFaction(bool allowHidden = false, bool allowDefeated = false, bool allowNonHumanlike = true, TechLevel minTechLevel = TechLevel.Undefined) { Faction faction; Faction result; if ((from x in this.AllFactions where !x.IsPlayer && (allowHidden || !x.def.hidden) && (allowDefeated || !x.defeated) && (allowNonHumanlike || x.def.humanlikeFaction) && (minTechLevel == TechLevel.Undefined || x.def.techLevel >= minTechLevel) && !x.HostileTo(Faction.OfPlayer) select x).TryRandomElement(out faction)) { result = faction; } else { result = null; } return(result); }
private static TechLevel Increase(TechLevel techLevel) { return(techLevel + 1); }
public override void DoWindowContents(Rect canvas) { // zooming in seems to cause Text.Font to start at Tiny, make sure it's set to Small for our panels. Text.Font = GameFont.Small; float drawpos = 0; DrawText(canvas, description, ref drawpos); AddSpace(ref drawpos, 10f); if (Widgets.RadioButtonLabeled(new Rect(canvas.x + 20, drawpos, 100f, 60f), "configRadioBtnNeolithic".Translate(), baseTechlvlCfg == 0)) //translation default: Neolithic / Tribal { baseTechlvlCfg = 0; } if (Widgets.RadioButtonLabeled(new Rect(canvas.x + 200f, drawpos, 100f, 60f), "configRadioBtnAutoDetect".Translate(), baseTechlvlCfg == 1)) //translation default: Auto-Detect (default) { baseTechlvlCfg = 1; } if (Widgets.RadioButtonLabeled(new Rect(canvas.x + 400f, drawpos, 100f, 60f), "configRadioBtnIndustrial".Translate(), baseTechlvlCfg == 2)) //translation default: Industrial / Colony { baseTechlvlCfg = 2; } AddSpace(ref drawpos, 70f); DrawText(canvas, "configBaseTechLvl".Translate() + " (" + ((baseTechlvlCfg == 1) ? ((_ResearchManager.isTribe) ? "configTribe".Translate() : "configColony".Translate()) : ((baseTechlvlCfg == 0) ? "configSetToTribe".Translate() : "configSetToColony".Translate())) + "): " + ((baseTechlvlCfg == 1) ? _ResearchManager.factionDefault.ToString().TranslateOrDefault(null, "TA_TL_") : ((baseTechlvlCfg == 0) ? "configNeolithic".Translate() : "configIndustrial".Translate())), ref drawpos); AddSpace(ref drawpos, 20f); baseFactionTechLevel = _ResearchManager.factionDefault; if (baseTechlvlCfg != 1) { baseFactionTechLevel = (baseTechlvlCfg == 0) ? TechLevel.Neolithic : TechLevel.Industrial; } DrawText(canvas, descriptionA2 + " (" + "configWordDefault".Translate() + Conditionvalue_A_Default + ")", ref drawpos); string bufferA = null; string bufferB = null; Widgets.TextFieldNumeric(new Rect(canvas.x + Verse.Text.CalcSize(descriptionA2_calc + " (" + "configWordDefault".Translate() + Conditionvalue_A_Default + ")").x - 25f, canvas.y + drawpos - 22f, 50f, Verse.Text.CalcSize("Text").y), ref Conditionvalue_A, ref bufferA, -100, 100); AddSpace(ref drawpos, 10f); DrawText(canvas, "configExpectedTechLvl".Translate() + " " + ((TechLevel)Math.Min((int)TechLevel.Archotech, (int)previewTechLevels[0])).ToString().TranslateOrDefault(null, "TA_TL_"), ref drawpos); AddSpace(ref drawpos, 20f); DrawText(canvas, descriptionB2.Replace("50", Conditionvalue_B_s.ToString()) + " (" + "configWordDefault".Translate() + Conditionvalue_B_Default + ")", ref drawpos); Widgets.TextFieldNumeric(new Rect(canvas.x + Verse.Text.CalcSize(descriptionB2_calc + " (" + "configWordDefault".Translate() + Conditionvalue_B_Default + ")").x - 25f, canvas.y + drawpos - 22f, 50f, Verse.Text.CalcSize("Text").y), ref Conditionvalue_B, ref bufferB, -100, 100); AddSpace(ref drawpos, 10f); DrawText(canvas, "configExpectedTechLvl".Translate() + " " + ((TechLevel)Math.Min((int)TechLevel.Archotech, (int)previewTechLevels[1])).ToString().TranslateOrDefault(null, "TA_TL_"), ref drawpos); AddSpace(ref drawpos, 20f); DrawText(canvas, descriptionB2_s + " (" + "configWordDefault".Translate() + Conditionvalue_B_s_Default + ")", ref drawpos); AddSpace(ref drawpos, 10f); Conditionvalue_B_s = (int)Widgets.HorizontalSlider(new Rect(canvas.x, canvas.y + drawpos, 500, 15), Conditionvalue_B_s, 1, 100, true, "50%", "1%", "100%", 1); DrawText(new Rect(canvas.x + 530, canvas.y - 5, canvas.width, canvas.height), $"{Conditionvalue_B_s}%", ref drawpos); AddSpace(ref drawpos, 20f); //if (b_configCheckboxNeedTechColonists != (configCheckboxNeedTechColonists == 1)) //{ // previewTechLevels[2] = (Util.ColonyHasHiTechPeople()) ? TechLevel.Archotech : TechAdvancing_Config_Tab.maxTechLevelForTribals; //} b_configCheckboxNeedTechColonists = configCheckboxNeedTechColonists == 1; Widgets.CheckboxLabeled(new Rect(canvas.x, drawpos, Verse.Text.CalcSize("configCheckboxNeedTechColonists".Translate(maxTechLevelForTribals.ToString().TranslateOrDefault(null, "TA_TL_"))).x + 40f, 40f), "configCheckboxNeedTechColonists".Translate(maxTechLevelForTribals.ToString().TranslateOrDefault(null, "TA_TL_")), ref b_configCheckboxNeedTechColonists, false); configCheckboxNeedTechColonists = (b_configCheckboxNeedTechColonists) ? 1 : 0; AddSpace(ref drawpos, 32f); if (previewTechLevels[2] == maxTechLevelForTribals && b_configCheckboxNeedTechColonists) { DrawText(canvas, "configCheckboxNeedTechColonists_CappedAt".Translate(maxTechLevelForTribals.ToString().TranslateOrDefault(null, "TA_TL_")), ref drawpos, false, Color.red); } AddSpace(ref drawpos, 50f); DrawText(canvas, "configResultingTechLvl".Translate() + " " + Rules.GetNewTechLevel().ToString().TranslateOrDefault(null, "TA_TL_"), ref drawpos); AddSpace(ref drawpos, 30f); DrawText(canvas, "availableTechLvls".Translate(), ref drawpos); AddSpace(ref drawpos, 10f); string[] techLevels = Enum.GetNames(typeof(TechLevel)); for (int i = 0; i < techLevels.Length; i++) { DrawText(canvas, techLevels[i].ToString().TranslateOrDefault(null, "TA_TL_") + " = " + i, ref drawpos); } }
public static List <ThingStuffPairWithQuality> GenerateDefsWithPossibleTotalValue(IntRange countRange, float totalValue, IEnumerable <ThingDef> allowed, TechLevel techLevel, QualityGenerator qualityGenerator, Func <ThingStuffPairWithQuality, float> getMinValue, Func <ThingStuffPairWithQuality, float> getMaxValue, Func <ThingDef, float> weightSelector = null, int tries = 100, float maxMass = float.MaxValue) { List <ThingStuffPairWithQuality> chosen = new List <ThingStuffPairWithQuality>(); if (countRange.max <= 0) { return(chosen); } if (countRange.min < 1) { countRange.min = 1; } CalculateAllowedThingStuffPairs(allowed, techLevel, qualityGenerator); float trashThreshold = GetTrashThreshold(countRange, totalValue, getMaxValue); allowedThingStuffPairs.RemoveAll((ThingStuffPairWithQuality x) => getMaxValue(x) < trashThreshold); if (!allowedThingStuffPairs.Any()) { return(chosen); } float minCandidateValueEver = 3.40282347E+38f; float maxCandidateValueEver = -3.40282347E+38f; float minMassEver = 3.40282347E+38f; foreach (ThingStuffPairWithQuality allowedThingStuffPair in allowedThingStuffPairs) { ThingStuffPairWithQuality current = allowedThingStuffPair; minCandidateValueEver = Mathf.Min(minCandidateValueEver, getMinValue(current)); maxCandidateValueEver = Mathf.Max(maxCandidateValueEver, getMaxValue(current)); if (current.thing.category != ThingCategory.Pawn) { minMassEver = Mathf.Min(minMassEver, GetNonTrashMass(current, trashThreshold, getMinValue)); } } minCandidateValueEver = Mathf.Max(minCandidateValueEver, trashThreshold); float totalMinValueSoFar = 0f; float totalMaxValueSoFar = 0f; float minMassSoFar = 0f; int num = 0; do { num++; if (num > 10000) { Log.Error("Too many iterations."); break; } IEnumerable <ThingStuffPairWithQuality> enumerable = allowedThingStuffPairs.Where(delegate(ThingStuffPairWithQuality x) { if (maxMass != 3.40282347E+38f && x.thing.category != ThingCategory.Pawn) { float nonTrashMass = GetNonTrashMass(x, trashThreshold, getMinValue); if (minMassSoFar + nonTrashMass > maxMass) { return(false); } if (chosen.Count < countRange.min && minMassSoFar + minMassEver * (float)(countRange.min - chosen.Count - 1) + nonTrashMass > maxMass) { return(false); } } if (totalMinValueSoFar + Mathf.Max(getMinValue(x), trashThreshold) > totalValue) { return(false); } if (chosen.Count < countRange.min && totalMinValueSoFar + minCandidateValueEver * (float)(countRange.min - chosen.Count - 1) + Mathf.Max(getMinValue(x), trashThreshold) > totalValue) { return(false); } return(true); }); if (countRange.max != 2147483647 && totalMaxValueSoFar < totalValue * 0.5f) { IEnumerable <ThingStuffPairWithQuality> enumerable2 = enumerable; enumerable = from x in enumerable where totalMaxValueSoFar + maxCandidateValueEver * (float)(countRange.max - chosen.Count - 1) + getMaxValue(x) >= totalValue * 0.5f select x; if (!enumerable.Any()) { enumerable = enumerable2; } } float maxCandidateMinValue = -3.40282347E+38f; foreach (ThingStuffPairWithQuality item in enumerable) { maxCandidateMinValue = Mathf.Max(maxCandidateMinValue, Mathf.Max(getMinValue(item), trashThreshold)); } if (!enumerable.TryRandomElementByWeight(delegate(ThingStuffPairWithQuality x) { float a = 1f; if (countRange.max != 2147483647 && chosen.Count < countRange.max && totalValue >= totalMaxValueSoFar) { int num2 = countRange.max - chosen.Count; float b = (totalValue - totalMaxValueSoFar) / (float)num2; a = Mathf.InverseLerp(0f, b, getMaxValue(x)); } float b2 = 1f; if (chosen.Count < countRange.min && totalValue >= totalMinValueSoFar) { int num3 = countRange.min - chosen.Count; float num4 = (totalValue - totalMinValueSoFar) / (float)num3; float num5 = Mathf.Max(getMinValue(x), trashThreshold); if (num5 > num4) { b2 = num4 / num5; } } float num6 = Mathf.Max(Mathf.Min(a, b2), 1E-05f); if (weightSelector != null) { num6 *= weightSelector(x.thing); } if (totalValue > totalMaxValueSoFar) { int num7 = Mathf.Max(countRange.min - chosen.Count, 1); float num8 = Mathf.InverseLerp(0f, maxCandidateMinValue * 0.85f, GetMaxValueWithMaxMass(x, minMassSoFar, maxMass, getMinValue, getMaxValue) * (float)num7); num6 *= num8 * num8; } if (PawnWeaponGenerator.IsDerpWeapon(x.thing, x.stuff)) { num6 *= 0.1f; } if (techLevel != 0) { TechLevel techLevel2 = x.thing.techLevel; if ((int)techLevel2 < (int)techLevel && (int)techLevel2 <= 2 && (x.thing.IsApparel || x.thing.IsWeapon)) { num6 *= 0.1f; } } return(num6); }, out ThingStuffPairWithQuality result)) { break; } chosen.Add(result); totalMinValueSoFar += Mathf.Max(getMinValue(result), trashThreshold); totalMaxValueSoFar += getMaxValue(result); if (result.thing.category != ThingCategory.Pawn) { minMassSoFar += GetNonTrashMass(result, trashThreshold, getMinValue); } }while (chosen.Count < countRange.max && (chosen.Count < countRange.min || !(totalMaxValueSoFar >= totalValue * 0.9f))); return(chosen); }
public static List <ThingStuffPair> GenerateDefsWithPossibleTotalValue(int count, float totalValue, IEnumerable <ThingDef> allowed, TechLevel techLevel, Func <Thing, float> getValue, Func <ThingStuffPair, float> getMinValue, Func <ThingStuffPair, float> getMaxValue, Func <ThingDef, float> weightSelector = null, int tries = 100) { List <ThingStuffPair> list = new List <ThingStuffPair>(); ItemCollectionGeneratorByTotalValueUtility.allowedFiltered.Clear(); ItemCollectionGeneratorByTotalValueUtility.allowedFiltered.AddRange(allowed); ItemCollectionGeneratorByTotalValueUtility.allowedFiltered.RemoveAll(delegate(ThingDef x) { if ((int)x.techLevel > (int)techLevel) { return(true); } if (!x.MadeFromStuff && getMinValue(new ThingStuffPair(x, null, 1f)) > totalValue) { return(true); } return(false); }); ItemCollectionGeneratorByTotalValueUtility.allowedStuff.Clear(); for (int i = 0; i < ItemCollectionGeneratorByTotalValueUtility.allowedFiltered.Count; i++) { ThingDef thingDef = ItemCollectionGeneratorByTotalValueUtility.allowedFiltered[i]; if (thingDef.MadeFromStuff) { List <ThingDef> list2 = default(List <ThingDef>); if (!ItemCollectionGeneratorByTotalValueUtility.allowedStuff.TryGetValue(thingDef, out list2)) { list2 = new List <ThingDef>(); ItemCollectionGeneratorByTotalValueUtility.allowedStuff.Add(thingDef, list2); } foreach (ThingDef item in GenStuff.AllowedStuffsFor(thingDef)) { if (!(item.stuffProps.commonality <= 0.0) && (int)item.techLevel <= (int)techLevel && !(getMinValue(new ThingStuffPair(thingDef, item, 1f)) > totalValue)) { list2.Add(item); } } } } ItemCollectionGeneratorByTotalValueUtility.allowedFiltered.RemoveAll((ThingDef x) => x.MadeFromStuff && !ItemCollectionGeneratorByTotalValueUtility.allowedStuff[x].Any()); if (!ItemCollectionGeneratorByTotalValueUtility.allowedFiltered.Any()) { return(list); } float num = 0f; int num2 = 0; while (num2 < tries) { float num3 = 0f; float num4 = 0f; ItemCollectionGeneratorByTotalValueUtility.newCandidates.Clear(); for (int j = 0; j < count; j++) { ThingDef thingDef2 = (weightSelector == null) ? ItemCollectionGeneratorByTotalValueUtility.allowedFiltered.RandomElement() : ItemCollectionGeneratorByTotalValueUtility.allowedFiltered.RandomElementByWeight(weightSelector); ThingDef stuff = (!thingDef2.MadeFromStuff) ? null : ItemCollectionGeneratorByTotalValueUtility.allowedStuff[thingDef2].RandomElementByWeight((ThingDef x) => x.stuffProps.commonality); ThingStuffPair thingStuffPair = new ThingStuffPair(thingDef2, stuff, 1f); ItemCollectionGeneratorByTotalValueUtility.newCandidates.Add(thingStuffPair); num3 += getMinValue(thingStuffPair); num4 += getMaxValue(thingStuffPair); } float num5 = (float)((!(num3 <= totalValue)) ? (num3 - totalValue) : 0.0); float num6 = (float)((!(num4 >= totalValue)) ? (totalValue - num4) : 0.0); if (!list.Any() || num > num5 + num6) { list.Clear(); list.AddRange(ItemCollectionGeneratorByTotalValueUtility.newCandidates); num = num5 + num6; } if (!(num <= 0.0)) { num2++; continue; } break; } return(list); }
private TechLevel GetRandomTechLevel() { return(TechLevel.GetRandomPopulation(rnd)); }
private static float TechLevelDiff(TechLevel def, TechLevel target) { return((float)TechLevel.Transcendent - Mathf.Abs((float)target - (float)def)); }
public override void Init() { base.Init(); LordToilData_Siege data = this.Data; data.baseRadius = Mathf.InverseLerp(14f, 25f, (float)this.lord.ownedPawns.Count / 50f); data.baseRadius = Mathf.Clamp(data.baseRadius, 14f, 25f); List <Thing> list = new List <Thing>(); foreach (Blueprint_Build blueprint_Build in SiegeBlueprintPlacer.PlaceBlueprints(data.siegeCenter, base.Map, this.lord.faction, data.blueprintPoints)) { data.blueprints.Add(blueprint_Build); using (List <ThingDefCountClass> .Enumerator enumerator2 = blueprint_Build.MaterialsNeeded().GetEnumerator()) { while (enumerator2.MoveNext()) { ThingDefCountClass cost = enumerator2.Current; Thing thing = list.FirstOrDefault((Thing t) => t.def == cost.thingDef); if (thing != null) { thing.stackCount += cost.count; } else { Thing thing2 = ThingMaker.MakeThing(cost.thingDef, null); thing2.stackCount = cost.count; list.Add(thing2); } } } ThingDef thingDef = blueprint_Build.def.entityDefToBuild as ThingDef; if (thingDef != null) { ThingDef turret = thingDef; bool allowEMP = false; TechLevel techLevel = this.lord.faction.def.techLevel; ThingDef thingDef2 = TurretGunUtility.TryFindRandomShellDef(turret, allowEMP, true, techLevel, false, 250f); if (thingDef2 != null) { Thing thing3 = ThingMaker.MakeThing(thingDef2, null); thing3.stackCount = 5; list.Add(thing3); } } } for (int i = 0; i < list.Count; i++) { list[i].stackCount = Mathf.CeilToInt((float)list[i].stackCount * Rand.Range(1f, 1.2f)); } List <List <Thing> > list2 = new List <List <Thing> >(); for (int j = 0; j < list.Count; j++) { while (list[j].stackCount > list[j].def.stackLimit) { int num = Mathf.CeilToInt((float)list[j].def.stackLimit * Rand.Range(0.9f, 0.999f)); Thing thing4 = ThingMaker.MakeThing(list[j].def, null); thing4.stackCount = num; list[j].stackCount -= num; list.Add(thing4); } } List <Thing> list3 = new List <Thing>(); for (int k = 0; k < list.Count; k++) { list3.Add(list[k]); if (k % 2 == 1 || k == list.Count - 1) { list2.Add(list3); list3 = new List <Thing>(); } } List <Thing> list4 = new List <Thing>(); int num2 = Mathf.RoundToInt(LordToil_Siege.MealCountRangePerRaider.RandomInRange * (float)this.lord.ownedPawns.Count); for (int l = 0; l < num2; l++) { Thing item = ThingMaker.MakeThing(ThingDefOf.MealSurvivalPack, null); list4.Add(item); } list2.Add(list4); DropPodUtility.DropThingGroupsNear(data.siegeCenter, base.Map, list2, 110, false, false, true, false); data.desiredBuilderFraction = LordToil_Siege.BuilderCountFraction.RandomInRange; }
public static bool TryGetRandomThingWhichCanWeighNoMoreThan(IEnumerable <ThingDef> candidates, TechLevel stuffTechLevel, float maxMass, out ThingStuffPair thingStuffPair) { if (!(from x in candidates where PossibleToWeighNoMoreThan(x, maxMass, GenStuff.AllowedStuffsFor(x, stuffTechLevel)) select x).TryRandomElement(out ThingDef thingDef)) { thingStuffPair = default(ThingStuffPair); return(false); } ThingDef result; if (thingDef.MadeFromStuff) { if (!(from x in GenStuff.AllowedStuffsFor(thingDef, stuffTechLevel) where thingDef.GetStatValueAbstract(StatDefOf.Mass, x) <= maxMass select x).TryRandomElementByWeight((ThingDef x) => x.stuffProps.commonality, out result)) { thingStuffPair = default(ThingStuffPair); return(false); } } else { result = null; } thingStuffPair = new ThingStuffPair(thingDef, result); return(true); }
public override void DefsLoaded() { //1. Preparing settings UpdateSettings(); //2. Adding Tech Tab to Pawns //ThingDef injection stolen from the work of notfood for Psychology var zombieThinkTree = DefDatabase <ThinkTreeDef> .GetNamedSilentFail("Zombie"); IEnumerable <ThingDef> things = (from def in DefDatabase <ThingDef> .AllDefs where def.race?.intelligence == Intelligence.Humanlike && (zombieThinkTree == null || def.race.thinkTreeMain != zombieThinkTree) select def); List <string> registered = new List <string>(); foreach (ThingDef t in things) { if (t.inspectorTabsResolved == null) { t.inspectorTabsResolved = new List <InspectTabBase>(1); } t.inspectorTabsResolved.Add(InspectTabManager.GetSharedInstance(typeof(ITab_PawnKnowledge))); if (t.comps == null) { t.comps = new List <CompProperties>(1); } t.comps.Add(new CompProperties_Knowledge()); registered.Add(t.defName); } InspectPaneUtility.Reset(); //3. Preparing knowledge support infrastructure //a. Things everyone knows UniversalWeapons.AddRange(DefDatabase <ThingDef> .AllDefs.Where(x => x.IsWeapon)); UniversalCrops.AddRange(DefDatabase <ThingDef> .AllDefs.Where(x => x.plant != null && x.plant.Sowable)); //b. Minus things unlocked on research ThingFilter lateFilter = new ThingFilter(); foreach (ResearchProjectDef tech in DefDatabase <ResearchProjectDef> .AllDefs) { tech.InferSkillBias(); tech.CreateStuff(lateFilter, unlocked); foreach (ThingDef weapon in tech.UnlockedWeapons()) { UniversalWeapons.Remove(weapon); } foreach (ThingDef plant in tech.UnlockedPlants()) { UniversalCrops.Remove(plant); } } ; //b. Also removing atipical weapons List <string> ForbiddenWeaponTags = TechDefOf.WeaponsNotBasic.weaponTags; UniversalWeapons.RemoveAll(x => SplitSimpleWeapons(x, ForbiddenWeaponTags)); List <ThingDef> garbage = new List <ThingDef>(); garbage.Add(TechDefOf.WeaponsNotBasic); //c. Classifying pawn backstories PawnBackgroundUtility.BuildCache(); //d. Telling humans what's going on ThingCategoryDef knowledgeCat = TechDefOf.Knowledge; IEnumerable <ThingDef> codifiedTech = DefDatabase <ThingDef> .AllDefs.Where(x => x.IsWithinCategory(knowledgeCat)); if (Prefs.LogVerbose || FullStartupReport) { Log.Message($"[HumanResources] Codified technologies: {codifiedTech.Select(x => x.label).ToStringSafeEnumerable()}"); Log.Message($"[HumanResources] Basic crops: {UniversalCrops.ToStringSafeEnumerable()}"); Log.Message($"[HumanResources] Basic weapons: {UniversalWeapons.ToStringSafeEnumerable()}"); Log.Message($"[HumanResources] Basic weapons that require training: {SimpleWeapons.ToStringSafeEnumerable()}"); Log.Warning($"[HumanResources] Basic weapons tags: {SimpleWeapons.Where(x => !x.weaponTags.NullOrEmpty()).SelectMany(x => x.weaponTags).Distinct().ToStringSafeEnumerable()}"); if (FullStartupReport) { Log.Warning("[HumanResources] Backstories classified by TechLevel:"); for (int i = 0; i < 8; i++) { TechLevel level = (TechLevel)i; IEnumerable <string> found = PawnBackgroundUtility.TechLevelByBackstory.Where(e => e.Value == level).Select(e => e.Key); if (!found.EnumerableNullOrEmpty()) { Log.Message($"- {level.ToString().CapitalizeFirst()} ({found.EnumerableCount()}): {found.ToStringSafeEnumerable()}"); } } Log.Warning("[HumanResources] Techs classified by associated skill:"); var skills = DefDatabase <SkillDef> .AllDefsListForReading.GetEnumerator(); while (skills.MoveNext()) { SkillDef skill = skills.Current; IEnumerable <string> found = Extension_Research.SkillsByTech.Where(e => e.Value.Contains(skill)).Select(e => e.Key.label); Log.Message($"- {skill.LabelCap} ({found.EnumerableCount()}): {found.ToStringSafeEnumerable()}"); } } } else { Log.Message($"[HumanResources] This is what we know: {codifiedTech.EnumerableCount()} technologies processed, {UniversalCrops.Count()} basic crops, {UniversalWeapons.Count()} basic weapons + {SimpleWeapons.Count()} that require training."); } //4. Filling gaps on the database //a. TechBook dirty trick, but only now this is possible! TechDefOf.TechBook.stuffCategories = TechDefOf.UnfinishedTechBook.stuffCategories = TechDefOf.LowTechCategories.stuffCategories; TechDefOf.TechDrive.stuffCategories = TechDefOf.HiTechCategories.stuffCategories; garbage.Add(TechDefOf.LowTechCategories); garbage.Add(TechDefOf.HiTechCategories); //b. Filling main tech category with subcategories foreach (ThingDef t in lateFilter.AllowedThingDefs.Where(t => !t.thingCategories.NullOrEmpty())) { foreach (ThingCategoryDef c in t.thingCategories) { c.childThingDefs.Add(t); if (!knowledgeCat.childCategories.NullOrEmpty() && !knowledgeCat.childCategories.Contains(c)) { knowledgeCat.childCategories.Add(c); } } } //c. Populating knowledge recipes and book shelves foreach (RecipeDef r in DefDatabase <RecipeDef> .AllDefs.Where(x => x.ingredients.Count == 1 && x.fixedIngredientFilter.AnyAllowedDef == null)) { r.fixedIngredientFilter.ResolveReferences(); r.defaultIngredientFilter.ResolveReferences(); } foreach (ThingDef t in DefDatabase <ThingDef> .AllDefs.Where(x => x.thingClass == typeof(Building_BookStore))) { t.building.fixedStorageSettings.filter.ResolveReferences(); t.building.defaultStorageSettings.filter.ResolveReferences(); } //d. Removing temporary defs from database. foreach (ThingDef def in garbage) { AccessTools.Method(typeof(DefDatabase <ThingDef>), "Remove").Invoke(this, new object[] { def }); } }
public static bool PossibleToWeighNoMoreThan(IEnumerable <ThingDef> candidates, TechLevel stuffTechLevel, float maxMass, int count) { if (maxMass == 3.40282347E+38f || count <= 0) { return(true); } if (maxMass < 0f) { return(false); } float num = 3.40282347E+38f; foreach (ThingDef candidate in candidates) { num = Mathf.Min(num, GetMinMass(candidate, stuffTechLevel)); } return(num <= maxMass * (float)count); }
private static bool SkillIsRelevant(SkillDef skill, TechLevel level) { return(TechTracker.FindSkills(x => x.Skill == skill && x.Techs.Any(y => y.techLevel == level)).Any()); }
public Gadget(GadgetType type, SkillType skillBonus, int price, TechLevel minTechLevel, int chance) : base(EquipmentType.Gadget, price, minTechLevel, chance) { _type = type; _skillBonus = skillBonus; }
public Gadget(GadgetType type, SkillType skillBonus, int price, TechLevel minTechLevel, int chance) : base(EquipmentType.Gadget, price, minTechLevel, chance) { _type = type; _skillBonus = skillBonus; }
public override void Resolve(ResolveParams rp) { Map map = BaseGen.globalSettings.map; Faction arg_3C_0; if ((arg_3C_0 = rp.faction) == null) { arg_3C_0 = (Find.FactionManager.RandomEnemyFaction(false, false, true, TechLevel.Industrial) ?? Find.FactionManager.RandomEnemyFaction(false, false, true, TechLevel.Undefined)); } Faction faction = arg_3C_0; Rot4? thingRot = rp.thingRot; Rot4 rot = (!thingRot.HasValue) ? Rot4.Random : thingRot.Value; ThingDef arg_9D_0; if ((arg_9D_0 = rp.mortarDef) == null) { arg_9D_0 = (from x in DefDatabase <ThingDef> .AllDefsListForReading where x.category == ThingCategory.Building && x.building.IsMortar select x).RandomElement <ThingDef>(); } ThingDef thingDef = arg_9D_0; IntVec3 intVec; if (!this.TryFindMortarSpawnCell(rp.rect, rot, thingDef, out intVec)) { return; } if (thingDef.HasComp(typeof(CompMannable))) { IntVec3 c = ThingUtility.InteractionCellWhenAt(thingDef, intVec, rot, map); Lord singlePawnLord = LordMaker.MakeNewLord(faction, new LordJob_ManTurrets(), map, null); PawnKindDef kind = faction.RandomPawnKind(); Faction faction2 = faction; int tile = map.Tile; PawnGenerationRequest value = new PawnGenerationRequest(kind, faction2, PawnGenerationContext.NonPlayer, tile, false, false, false, false, true, true, 1f, false, true, true, true, false, false, false, null, null, null, null, null, null, null, null); ResolveParams resolveParams = rp; resolveParams.faction = faction; resolveParams.singlePawnGenerationRequest = new PawnGenerationRequest?(value); resolveParams.rect = CellRect.SingleCell(c); resolveParams.singlePawnLord = singlePawnLord; BaseGen.symbolStack.Push("pawn", resolveParams); } ThingDef turret = thingDef; bool allowEMP = false; TechLevel techLevel = faction.def.techLevel; ThingDef thingDef2 = TurretGunUtility.TryFindRandomShellDef(turret, allowEMP, true, techLevel, false, 250f); if (thingDef2 != null) { ResolveParams resolveParams2 = rp; resolveParams2.faction = faction; resolveParams2.singleThingDef = thingDef2; resolveParams2.singleThingStackCount = new int?(Rand.RangeInclusive(5, Mathf.Min(8, thingDef2.stackLimit))); BaseGen.symbolStack.Push("thing", resolveParams2); } ResolveParams resolveParams3 = rp; resolveParams3.faction = faction; resolveParams3.singleThingDef = thingDef; resolveParams3.rect = CellRect.SingleCell(intVec); resolveParams3.thingRot = new Rot4?(rot); BaseGen.symbolStack.Push("thing", resolveParams3); }