示例#1
0
        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 = TechTracker.FindTechs(skill).Select(x => x.Tech.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 });
            }
        }
示例#2
0
        static void AddMissingSeed(StringBuilder report, ThingDef thingDef)
        {
            string name = thingDef.defName;

            foreach (string prefix in SeedsPleaseMod.knownPrefixes)
            {
                name = name.Replace(prefix, "");
            }
            name = name.CapitalizeFirst();

            report.AppendLine();
            report.Append("<!-- SeedsPlease :: ");
            report.Append(thingDef.defName);
            report.Append(" (");
            report.Append(thingDef.modContentPack.IsCoreMod ? "Patched" : thingDef.modContentPack.PackageId);
            report.Append(") ");

            SeedDef seed = DefDatabase <SeedDef> .GetNamedSilentFail("Seed_" + name);

            if (seed == null)
            {
                var template = ResourceBank.ThingDefOf.Seed_Psychoid;

                seed = new SeedDef()
                {
                    defName    = "Seed_" + name,
                    label      = name.ToLower() + " seeds",
                    plant      = thingDef,
                    harvest    = thingDef.plant.harvestedThingDef,
                    stackLimit = template.stackLimit,
                    seed       = new SeedProperties()
                    {
                        harvestFactor = 1f, seedFactor = 1f, baseChance = 0.95f, extraChance = 0.15f
                    },
                    tradeTags               = template.tradeTags,
                    thingCategories         = template.thingCategories,
                    soundDrop               = template.soundDrop,
                    soundInteract           = template.soundInteract,
                    statBases               = template.statBases,
                    graphicData             = template.graphicData,
                    description             = template.description,
                    thingClass              = template.thingClass,
                    pathCost                = template.pathCost,
                    rotatable               = template.rotatable,
                    drawGUIOverlay          = template.drawGUIOverlay,
                    alwaysHaulable          = template.alwaysHaulable,
                    comps                   = template.comps,
                    altitudeLayer           = template.altitudeLayer,
                    selectable              = template.selectable,
                    useHitPoints            = template.useHitPoints,
                    resourceReadoutPriority = template.resourceReadoutPriority,
                    category                = template.category,
                    uiIcon                  = template.uiIcon,
                    uiIconColor             = template.uiIconColor,
                };

                seed.BaseMarketValue = AssignMarketValueFromHarvest(thingDef);

                foreach (var category in seed.thingCategories)
                {
                    category.childThingDefs.Add(seed);
                }

                DefDatabase <ThingDef> .Add(seed);

                DefDatabase <SeedDef> .Add(seed);

                seed.ResolveReferences();

                report.Append("Autogenerated as ");
            }
            else
            {
                seed.sources.Add(thingDef);

                report.Append("Inserted to ");
            }

            report.Append(seed.defName);
            report.AppendLine("-->");
            report.AppendLine();

            var seedXml =
                new XElement("SeedsPlease.SeedDef", new XAttribute("ParentName", "SeedBase"),
                             new XElement("defName", seed.defName),
                             new XElement("label", seed.label),
                             new XElement("sources",
                                          new XElement("li", thingDef.defName)));

            report.AppendLine(seedXml.ToString());

            if (thingDef.plant.harvestedThingDef.IsStuff)
            {
                return;
            }

            float yieldCount = Mathf.Max(Mathf.Round(thingDef.plant.harvestYield / 3f), 4f);

            RecipeDef recipe = DefDatabase <RecipeDef> .GetNamedSilentFail("ExtractSeed_" + name);

            if (recipe == null)
            {
                var ingredient = new IngredientCount();
                ingredient.filter.SetAllow(thingDef.plant.harvestedThingDef, true);
                ingredient.SetBaseCount(yieldCount);

                recipe = new RecipeDef()
                {
                    defName     = "ExtractSeed_" + name,
                    label       = "extract " + name.ToLower() + " seeds",
                    description = "Extract seeds from " + thingDef.plant.harvestedThingDef.defName.Replace("Raw", ""),
                    ingredients = new List <IngredientCount>()
                    {
                        ingredient
                    },
                    defaultIngredientFilter = ingredient.filter,
                    fixedIngredientFilter   = ingredient.filter,
                    products = new List <ThingDefCountClass>()
                    {
                        new ThingDefCountClass()
                        {
                            thingDef = seed, count = 3
                        }
                    },
                    researchPrerequisite = thingDef.researchPrerequisites?.FirstOrFallback(),
                    workAmount           = 600f,
                    workSkill            = SkillDefOf.Cooking,
                    effectWorking        = EffecterDefOf.Vomit,
                    workSpeedStat        = StatDefOf.EatingSpeed,
                    jobString            = "Extracting seeds.",
                };

                DefDatabase <RecipeDef> .Add(recipe);

                ResourceBank.ThingDefOf.PlantProcessingTable.recipes.Add(recipe);
            }
            else
            {
                recipe.ingredients?.First()?.filter.SetAllow(thingDef.plant.harvestedThingDef, true);
            }

            var recipeXml =
                new XElement("RecipeDef", new XAttribute("ParentName", "ExtractSeed"),
                             new XElement("defName", recipe.defName),
                             new XElement("label", recipe.label),
                             new XElement("description", recipe.description),
                             new XElement("ingredients",
                                          new XElement("li",
                                                       new XElement("filter",
                                                                    new XElement("thingDefs",
                                                                                 new XElement("li", thingDef.plant.harvestedThingDef.defName))),
                                                       new XElement("count", yieldCount))),
                             new XElement("fixedIngredientFilter",
                                          new XElement("thingDefs",
                                                       new XElement("li", thingDef.plant.harvestedThingDef.defName))),
                             new XElement("products",
                                          new XElement(seed.defName, 3)));

            report.AppendLine();
            report.AppendLine(recipeXml.ToString());
        }
示例#3
0
        public override IEnumerable<FloatMenuOption> CompFloatMenuOptions(Pawn selPawn)
        {
            if (DebugSettings.godMode)
            {
                yield return FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("Debug-Info: WeaponRepair active.", null), selPawn, parent);
            }

            foreach (FloatMenuOption fmo in base.CompFloatMenuOptions(selPawn))
                yield return fmo;

            //Log.Error("1 " + Props.allowedDefSubName.NullOrEmpty().ToString() + " 2 " + parent.def.defName);


            //// Only show float menu for ThingDef-names 'Gun_xxxx'
            //if (!(Props.allowedDefSubName.NullOrEmpty() || Props.allowedDefSubName == "*") && !parent.def.defName.Contains(Props.allowedDefSubName))
            //    yield break;
            ThingCategoryDef grenadesCategory = DefDatabase<ThingCategoryDef>.GetNamedSilentFail("Grenades");
            if (!parent.def.IsRangedWeapon || grenadesCategory != null && parent.def.thingCategories.Any(t => t == grenadesCategory))
                yield break;

            if (!InNeedOfRepairs)
            {
                //string debugstring = " => " + parent.HitPoints.ToString() + " / " + parent.MaxHitPoints.ToString();
                //yield return FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("WeaponRepair_NoRepairNeeded".Translate(), null), selPawn, parent);
                yield break;
            }

            if (GetAvailableTwinThing(selPawn) == null)
            {
                yield return FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("WeaponRepair_NoWeaponTwinFound".Translate(), null), selPawn, parent);
                yield break;
            }

            if (GetValidWorkTableCount(selPawn) == 0)
            {
                yield return FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("WeaponRepair_NoRepairTableFound".Translate(), null), selPawn, parent);
                yield break;
            }


            // Check if this is reservable by the pawn
            if (!selPawn.CanReserve(parent, 1))
            {
                yield return FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("CannotUseReserved".Translate(), null), selPawn, parent);
                yield break;
            }
            // Check if this is reachable by the pawn
            if (!selPawn.CanReach(parent, PathEndMode.Touch, Danger.Deadly))
            {
                yield return FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("CannotUseNoPath".Translate(), null), selPawn, parent);
                yield break;
            }

            if (selPawn.workSettings.GetPriority(Props.workTypeDef) == 0)
            {
                string label = "WeaponRepair_NotAssignedToWorkType".Translate(Props.workTypeDef.gerundLabel);

                yield return FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(label, null), selPawn, parent);
                yield break;
            }

            Action hoverAction = delegate
            {
                Thing twin = GetAvailableTwinThing(selPawn);
                MoteMaker.MakeStaticMote(twin.Position, parent.Map, ThingDefOf.Mote_FeedbackGoto);
            };
            Action giveRepairJob = delegate { TryGiveWeaponRepairJobToPawn(selPawn); };
            yield return FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("WeaponRepair_RepairWeapon".Translate(), giveRepairJob, MenuOptionPriority.Default, hoverAction), selPawn, parent);
         
        }
示例#4
0
 public HairDef FindHairDef(string name)
 {
     return(DefDatabase <HairDef> .GetNamedSilentFail(name));
 }
        protected void DoSubRow(Rect rect, string key, HybridExtensionExposable extension, List <string> removeelements)
        {
            bool   isPawnKind = false;
            int    value      = (int)extension.hybridInfo.TryGetValue(key);
            string valuestr   = value.ToString();
            string label      = null;

            label = DefDatabase <ThingDef> .GetNamedSilentFail(key)?.label;

            if (label == null)
            {
                label = DefDatabase <PawnKindDef> .GetNamedSilentFail(key)?.label ?? "Undefined";

                isPawnKind = true;
            }
            Rect buttonRect = new Rect(rect.xMax - 90f, rect.y, 80f, rect.height);

            if (Widgets.ButtonText(buttonRect, "Delete"))
            {
                removeelements.Add(key);
            }
            buttonRect.x -= 80f;
            if (!isPawnKind)
            {
                if (Widgets.ButtonText(buttonRect, "PawnKind"))
                {
                    List <FloatMenuOption> list = new List <FloatMenuOption>();
                    if (!VariousDefOf.AllKinds.NullOrEmpty())
                    {
                        foreach (PawnKindDef def in VariousDefOf.AllKinds)
                        {
                            if (def.race.defName == key)
                            {
                                if (extension.hybridInfo.ContainsKey(def.defName))
                                {
                                    continue;
                                }
                                else
                                {
                                    list.Add(new FloatMenuOption(def.label, delegate { extension.hybridInfo.Add(def.defName, 1.0f); }, Widgets.GetIconFor(def.race), Color.white));
                                }
                            }
                        }
                    }
                    if (!list.NullOrEmpty())
                    {
                        Find.WindowStack.Add(new FloatMenu(list));
                    }
                    else
                    {
                        SoundDefOf.ClickReject.PlayOneShotOnCamera();
                    }
                }
                buttonRect.x -= 80f;
            }
            else
            {
                Widgets.Label(buttonRect, "  PawnKind");
                buttonRect.x -= 80f;
            }
            label += ": " + key;
            Widgets.Label(rect, " - " + label);
            Widgets.TextFieldNumeric(buttonRect, ref value, ref valuestr, 0, 9999999);
            extension.hybridInfo.SetOrAdd(key, value);
            buttonRect.x -= 80f;
            Widgets.Label(buttonRect, String.Format("{0,0:P2}", value / totalWeight));
            Widgets.DrawHighlightIfMouseover(rect);
            TooltipHandler.TipRegion(rect, Translations.CustomHybrid_Tooltip(info.GetDef?.label ?? "Undefined", extension.GetDef?.label ?? "Undefined", label, String.Format("{0,0:0.########%}", value / totalWeight)));
        }
示例#6
0
		public static List<Thing> generateTithe(double valueBase, double valueDiff, int multiplier, int resourceID, double traitValueMod )
		{
			FactionFC faction = Find.World.GetComponent<FactionFC>();
			List <Thing> things = new List<Thing>();
			ThingSetMaker thingSetMaker = new ThingSetMaker_MarketValue();
			ThingSetMakerParams param = new ThingSetMakerParams();
			param.totalMarketValueRange = new FloatRange((float)((valueBase* LoadedModManager.GetMod<FactionColoniesMod>().GetSettings<FactionColonies>().silverPerResource )- ((valueDiff + traitValueMod) *multiplier)), (float)((valueBase * LoadedModManager.GetMod<FactionColoniesMod>().GetSettings<FactionColonies>().silverPerResource) + ((valueDiff + traitValueMod) * multiplier)));
			param.filter = new ThingFilter();
			param.techLevel = FactionColonies.getPlayerColonyFaction().def.techLevel;

			switch (resourceID)
			{
				case 0: //food
					param.filter.SetAllow(ThingCategoryDefOf.FoodMeals, true);
					param.countRange = new IntRange(1, 5+multiplier);
					break;
				case 1: //weapons
					param.filter.SetAllow(ThingCategoryDefOf.Weapons, true);
					param.countRange = new IntRange(1, 4+(2*multiplier));
					break;
				case 2: //apparel
					param.filter.SetAllow(ThingCategoryDefOf.Apparel, true);
					param.countRange = new IntRange(1, 4+ (3*multiplier));
					break;
				case 3: //animals
					thingSetMaker = new ThingSetMaker_Animals();
					param.techLevel = TechLevel.Undefined;
					//param.countRange = new IntRange(1,4);
					break;
				case 4: //Logging
					param.filter.SetAllow(ThingDefOf.WoodLog, true);
					param.countRange = new IntRange(1, 5*multiplier);
					break;
				case 5: //Mining
					param.filter.SetAllow(StuffCategoryDefOf.Metallic, true);
					param.filter.SetAllow(ThingDefOf.Silver, false);
					//Android shit?
					param.filter.SetAllow(DefDatabase<ThingDef>.GetNamedSilentFail("Teachmat"), false);
					//Remove RimBees Beeswax
					param.filter.SetAllow(DefDatabase<StuffCategoryDef>.GetNamedSilentFail("RB_Waxy"), false);
					//Remove Alpha Animals skysteel
					param.filter.SetAllow(DefDatabase<ThingDef>.GetNamedSilentFail("AA_SkySteel"), false);
					param.countRange = new IntRange(1, 4*multiplier);
					break;
				case 6: //research
					Log.Message("generateTithe - Research Tithe - How did you get here?");

					break;
				case 7: //Power
					Log.Message("generateTithe - Power Tithe - How did you get here?");
					break;
				case 8: //Medicine/Bionics
					param.filter.SetAllow(ThingCategoryDefOf.Medicine, true);
					param.filter.SetAllow(DefDatabase<ThingCategoryDef>.GetNamedSilentFail("BodyPartsNatural"), true);
					switch (faction.techLevel)
					{
						case TechLevel.Archotech:
						case TechLevel.Ultra:
							param.filter.SetAllow(DefDatabase<ThingCategoryDef>.GetNamedSilentFail("BodyPartsUltra"), true);
							param.filter.SetAllow(DefDatabase<ThingCategoryDef>.GetNamedSilentFail("BodyPartsBionic"), true);
							param.filter.SetAllow(DefDatabase<ThingCategoryDef>.GetNamedSilentFail("BodyPartsProsthetic"), true);
							param.filter.SetAllow(DefDatabase<ThingCategoryDef>.GetNamedSilentFail("BodyPartsNatural"), true);

							if (DefDatabase<ThingCategoryDef>.GetNamedSilentFail("BionicProstheses") != null)
							param.filter.SetAllow(DefDatabase<ThingCategoryDef>.GetNamedSilentFail("BionicProstheses"), true);
							if (DefDatabase<ThingCategoryDef>.GetNamedSilentFail("AdvancedProstheses") != null)
								param.filter.SetAllow(DefDatabase<ThingCategoryDef>.GetNamedSilentFail("AdvancedProstheses"), true);
							if (DefDatabase<ThingCategoryDef>.GetNamedSilentFail("SyntheticOrgans") != null)
								param.filter.SetAllow(DefDatabase<ThingCategoryDef>.GetNamedSilentFail("SyntheticOrgans"), true);
							if (DefDatabase<ThingCategoryDef>.GetNamedSilentFail("Neurotrainers") != null)
								param.filter.SetAllow(DefDatabase<ThingCategoryDef>.GetNamedSilentFail("Neurotrainers"), true);
							break;
						case TechLevel.Spacer:
							param.filter.SetAllow(DefDatabase<ThingCategoryDef>.GetNamedSilentFail("BodyPartsBionic"), true);
							param.filter.SetAllow(DefDatabase<ThingCategoryDef>.GetNamedSilentFail("BodyPartsProsthetic"), true);
							param.filter.SetAllow(DefDatabase<ThingCategoryDef>.GetNamedSilentFail("BodyPartsNatural"), true);
							if (DefDatabase<ThingCategoryDef>.GetNamedSilentFail("BionicProstheses") != null)
								param.filter.SetAllow(DefDatabase<ThingCategoryDef>.GetNamedSilentFail("BionicProstheses"), true);
							if (DefDatabase<ThingCategoryDef>.GetNamedSilentFail("SyntheticOrgans") != null)
								param.filter.SetAllow(DefDatabase<ThingCategoryDef>.GetNamedSilentFail("SyntheticOrgans"), true);
							break;
						case TechLevel.Industrial:
							param.filter.SetAllow(DefDatabase<ThingCategoryDef>.GetNamedSilentFail("BodyPartsProsthetic"), true);
							param.filter.SetAllow(DefDatabase<ThingCategoryDef>.GetNamedSilentFail("BodyPartsNatural"), true);
							break;
						default:
							break;
					}

					

					param.countRange = new IntRange(1, 2 * multiplier);
					break;
			}

			//Log.Message(resourceID.ToString());


			//thingSetMaker.root
			things = thingSetMaker.Generate(param);
			return things;
		}
示例#7
0
        public CustomPawn LoadPawn(SaveRecordPawnV3 record)
        {
            PawnKindDef pawnKindDef = null;

            if (record.pawnKindDef != null)
            {
                pawnKindDef = DefDatabase <PawnKindDef> .GetNamedSilentFail(record.pawnKindDef);

                if (pawnKindDef == null)
                {
                    Logger.Warning("Could not find the pawn kind definition for the saved character: \"" + record.pawnKindDef + "\"");
                    return(null);
                }
            }

            ThingDef pawnThingDef = ThingDefOf.Human;

            if (record.thingDef != null)
            {
                ThingDef thingDef = DefDatabase <ThingDef> .GetNamedSilentFail(record.thingDef);

                if (thingDef != null)
                {
                    pawnThingDef = thingDef;
                }
            }

            Pawn source;

            if (pawnKindDef != null)
            {
                source = new Randomizer().GenerateKindOfColonist(pawnKindDef);
            }
            else
            {
                source = new Randomizer().GenerateColonist();
            }
            source.health.Reset();

            CustomPawn pawn = new CustomPawn(source);

            if (pawn.Id == null)
            {
                pawn.GenerateId();
            }
            else
            {
                pawn.Id = record.id;
            }

            pawn.Type = CustomPawnType.Colonist;

            pawn.Gender = record.gender;
            if (record.age > 0)
            {
                pawn.ChronologicalAge = record.age;
                pawn.BiologicalAge    = record.age;
            }
            if (record.chronologicalAge > 0)
            {
                pawn.ChronologicalAge = record.chronologicalAge;
            }
            if (record.biologicalAge > 0)
            {
                pawn.BiologicalAge = record.biologicalAge;
            }

            pawn.FirstName = record.firstName;
            pawn.NickName  = record.nickName;
            pawn.LastName  = record.lastName;

            HairDef h = FindHairDef(record.hairDef);

            if (h != null)
            {
                pawn.HairDef = h;
            }
            else
            {
                Logger.Warning("Could not load hair definition \"" + record.hairDef + "\"");
                Failed = true;
            }

            pawn.HeadGraphicPath      = record.headGraphicPath;
            pawn.Pawn.story.hairColor = record.hairColor;

            if (record.melanin >= 0.0f)
            {
                pawn.MelaninLevel = record.melanin;
            }
            else
            {
                pawn.MelaninLevel = PawnColorUtils.FindMelaninValueFromColor(record.skinColor);
            }
            // Set the skin color (only for Alien Races).
            if (pawn.AlienRace != null)
            {
                pawn.SkinColor = record.skinColor;
            }

            Backstory backstory = FindBackstory(record.childhood);

            if (backstory != null)
            {
                pawn.Childhood = backstory;
            }
            else
            {
                Logger.Warning("Could not load childhood backstory definition \"" + record.childhood + "\"");
                Failed = true;
            }
            if (record.adulthood != null)
            {
                backstory = FindBackstory(record.adulthood);
                if (backstory != null)
                {
                    pawn.Adulthood = backstory;
                }
                else
                {
                    Logger.Warning("Could not load adulthood backstory definition \"" + record.adulthood + "\"");
                    Failed = true;
                }
            }

            // Get the body type from the save record.  If there's no value in the save, then assign the
            // default body type from the pawn's backstories.
            // TODO: 1.0

            /*
             * BodyType? bodyType = null;
             * try {
             *  bodyType = (BodyType)Enum.Parse(typeof(BodyType), record.bodyType);
             * }
             * catch (Exception) {
             * }
             * if (!bodyType.HasValue) {
             *  if (pawn.Adulthood != null) {
             *      bodyType = pawn.Adulthood.BodyTypeFor(pawn.Gender);
             *  }
             *  else {
             *      bodyType = pawn.Childhood.BodyTypeFor(pawn.Gender);
             *  }
             * }
             * if (bodyType.HasValue) {
             *  pawn.BodyType = bodyType.Value;
             * }
             */
            BodyTypeDef bodyType = null;

            try {
                bodyType = DefDatabase <BodyTypeDef> .GetNamedSilentFail(record.bodyType);
            }
            catch (Exception) {
            }
            if (bodyType == null)
            {
                if (pawn.Adulthood != null)
                {
                    bodyType = pawn.Adulthood.BodyTypeFor(pawn.Gender);
                }
                else
                {
                    bodyType = pawn.Childhood.BodyTypeFor(pawn.Gender);
                }
            }
            if (bodyType != null)
            {
                pawn.BodyType = bodyType;
            }

            pawn.ClearTraits();
            for (int i = 0; i < record.traitNames.Count; i++)
            {
                string traitName = record.traitNames[i];
                Trait  trait     = FindTrait(traitName, record.traitDegrees[i]);
                if (trait != null)
                {
                    pawn.AddTrait(trait);
                }
                else
                {
                    Logger.Warning("Could not load trait definition \"" + traitName + "\"");
                    Failed = true;
                }
            }

            for (int i = 0; i < record.skillNames.Count; i++)
            {
                string   name = record.skillNames[i];
                SkillDef def  = FindSkillDef(pawn.Pawn, name);
                if (def == null)
                {
                    Logger.Warning("Could not load skill definition \"" + name + "\"");
                    Failed = true;
                    continue;
                }
                pawn.currentPassions[def]  = record.passions[i];
                pawn.originalPassions[def] = record.passions[i];
                pawn.SetOriginalSkillLevel(def, record.skillValues[i]);
                pawn.SetUnmodifiedSkillLevel(def, record.skillValues[i]);
            }
            if (record.originalPassions != null && record.originalPassions.Count == record.skillNames.Count)
            {
                for (int i = 0; i < record.skillNames.Count; i++)
                {
                    string   name = record.skillNames[i];
                    SkillDef def  = FindSkillDef(pawn.Pawn, name);
                    if (def == null)
                    {
                        Logger.Warning("Could not load skill definition \"" + name + "\"");
                        Failed = true;
                        continue;
                    }
                    //pawn.originalPassions[def] = record.originalPassions[i];
                }
            }

            foreach (var layer in PrepareCarefully.Instance.Providers.PawnLayers.GetLayersForPawn(pawn))
            {
                if (layer.Apparel)
                {
                    pawn.SetSelectedApparel(layer, null);
                    pawn.SetSelectedStuff(layer, null);
                }
            }
            for (int i = 0; i < record.apparelLayers.Count; i++)
            {
                int       layerIndex = record.apparelLayers[i];
                PawnLayer layer      = PrepareCarefully.Instance.Providers.PawnLayers.FindLayerFromDeprecatedIndex(layerIndex);
                if (layer == null)
                {
                    Logger.Warning("Could not find pawn layer from saved pawn layer index: \"" + layerIndex + "\"");
                    Failed = true;
                    continue;
                }
                ThingDef def = DefDatabase <ThingDef> .GetNamedSilentFail(record.apparel[i]);

                if (def == null)
                {
                    Logger.Warning("Could not load thing definition for apparel \"" + record.apparel[i] + "\"");
                    Failed = true;
                    continue;
                }
                ThingDef stuffDef = null;
                if (!string.IsNullOrEmpty(record.apparelStuff[i]))
                {
                    stuffDef = DefDatabase <ThingDef> .GetNamedSilentFail(record.apparelStuff[i]);

                    if (stuffDef == null)
                    {
                        Logger.Warning("Could not load stuff definition \"" + record.apparelStuff[i] + "\" for apparel \"" + record.apparel[i] + "\"");
                        Failed = true;
                        continue;
                    }
                }
                pawn.SetSelectedApparel(layer, def);
                pawn.SetSelectedStuff(layer, stuffDef);
                pawn.SetColor(layer, record.apparelColors[i]);
            }

            OptionsHealth healthOptions = PrepareCarefully.Instance.Providers.Health.GetOptions(pawn);

            for (int i = 0; i < record.implants.Count; i++)
            {
                SaveRecordImplantV3 implantRecord  = record.implants[i];
                UniqueBodyPart      uniqueBodyPart = healthOptions.FindBodyPartByName(implantRecord.bodyPart, implantRecord.bodyPartIndex != null ? implantRecord.bodyPartIndex.Value : 0);
                if (uniqueBodyPart == null)
                {
                    uniqueBodyPart = FindReplacementBodyPart(healthOptions, implantRecord.bodyPart);
                }
                if (uniqueBodyPart == null)
                {
                    Logger.Warning("Could not add the implant because it could not find the needed body part \"" + implantRecord.bodyPart + "\""
                                   + (implantRecord.bodyPartIndex != null ? " with index " + implantRecord.bodyPartIndex : ""));
                    Failed = true;
                    continue;
                }
                BodyPartRecord bodyPart = uniqueBodyPart.Record;
                if (implantRecord.recipe != null)
                {
                    RecipeDef recipeDef = FindRecipeDef(implantRecord.recipe);
                    if (recipeDef == null)
                    {
                        Logger.Warning("Could not add the implant because it could not find the recipe definition \"" + implantRecord.recipe + "\"");
                        Failed = true;
                        continue;
                    }
                    bool found = false;
                    foreach (var p in recipeDef.appliedOnFixedBodyParts)
                    {
                        if (p.defName.Equals(bodyPart.def.defName))
                        {
                            found = true;
                            break;
                        }
                    }
                    if (!found)
                    {
                        Logger.Warning("Could not apply the saved implant recipe \"" + implantRecord.recipe + "\" to the body part \"" + bodyPart.def.defName + "\".  Recipe does not support that part.");
                        Failed = true;
                        continue;
                    }
                    Implant implant = new Implant();
                    implant.BodyPartRecord = bodyPart;
                    implant.recipe         = recipeDef;
                    implant.label          = implant.Label;
                    pawn.AddImplant(implant);
                }
            }

            foreach (var injuryRecord in record.injuries)
            {
                HediffDef def = DefDatabase <HediffDef> .GetNamedSilentFail(injuryRecord.hediffDef);

                if (def == null)
                {
                    Logger.Warning("Could not add the injury because it could not find the hediff definition \"" + injuryRecord.hediffDef + "\"");
                    Failed = true;
                    continue;
                }
                InjuryOption option = healthOptions.FindInjuryOptionByHediffDef(def);
                if (option == null)
                {
                    Logger.Warning("Could not add the injury because it could not find a matching injury option for the saved hediff \"" + injuryRecord.hediffDef + "\"");
                    Failed = true;
                    continue;
                }
                BodyPartRecord bodyPart = null;
                if (injuryRecord.bodyPart != null)
                {
                    UniqueBodyPart uniquePart = healthOptions.FindBodyPartByName(injuryRecord.bodyPart,
                                                                                 injuryRecord.bodyPartIndex != null ? injuryRecord.bodyPartIndex.Value : 0);
                    if (uniquePart == null)
                    {
                        uniquePart = FindReplacementBodyPart(healthOptions, injuryRecord.bodyPart);
                    }
                    if (uniquePart == null)
                    {
                        Logger.Warning("Could not add the injury because it could not find the needed body part \"" + injuryRecord.bodyPart + "\""
                                       + (injuryRecord.bodyPartIndex != null ? " with index " + injuryRecord.bodyPartIndex : ""));
                        Failed = true;
                        continue;
                    }
                    bodyPart = uniquePart.Record;
                }
                Injury injury = new Injury();
                injury.Option         = option;
                injury.BodyPartRecord = bodyPart;
                if (injuryRecord.severity != null)
                {
                    injury.Severity = injuryRecord.Severity;
                }
                if (injuryRecord.painFactor != null)
                {
                    injury.PainFactor = injuryRecord.PainFactor;
                }
                pawn.AddInjury(injury);
            }

            pawn.CopySkillsAndPassionsToPawn();
            pawn.ClearPawnCaches();

            return(pawn);
        }
        public bool Load(PrepareCarefully loadout, string presetName)
        {
            SaveRecordPresetV4 preset = new SaveRecordPresetV4();

            Failed = false;
            try {
                Scribe.loader.InitLoading(PresetFiles.FilePathForSavedPreset(presetName));
                preset.ExposeData();

                if (preset.equipment != null)
                {
                    List <EquipmentSelection> equipment = new List <EquipmentSelection>(preset.equipment.Count);
                    foreach (var e in preset.equipment)
                    {
                        ThingDef thingDef = DefDatabase <ThingDef> .GetNamedSilentFail(e.def);

                        if (thingDef == null)
                        {
                            string replacementDefName;
                            if (thingDefReplacements.TryGetValue(e.def, out replacementDefName))
                            {
                                thingDef = DefDatabase <ThingDef> .GetNamedSilentFail(replacementDefName);
                            }
                        }
                        ThingDef stuffDef = null;
                        Gender   gender   = Gender.None;
                        if (!string.IsNullOrEmpty(e.stuffDef))
                        {
                            stuffDef = DefDatabase <ThingDef> .GetNamedSilentFail(e.stuffDef);
                        }
                        if (!string.IsNullOrEmpty(e.gender))
                        {
                            try {
                                gender = (Gender)Enum.Parse(typeof(Gender), e.gender);
                            }
                            catch (Exception) {
                                Log.Warning("Failed to load gender value for animal.");
                                Failed = true;
                                continue;
                            }
                        }
                        if (thingDef != null)
                        {
                            if (string.IsNullOrEmpty(e.stuffDef))
                            {
                                EquipmentKey    key    = new EquipmentKey(thingDef, null, gender);
                                EquipmentRecord record = PrepareCarefully.Instance.EquipmentDatabase[key];
                                if (record != null)
                                {
                                    equipment.Add(new EquipmentSelection(record, e.count));
                                }
                                else
                                {
                                    Log.Warning("Could not find equipment in equipment database: " + key);
                                    Failed = true;
                                    continue;
                                }
                            }
                            else
                            {
                                if (stuffDef != null)
                                {
                                    EquipmentKey    key    = new EquipmentKey(thingDef, stuffDef, gender);
                                    EquipmentRecord record = PrepareCarefully.Instance.EquipmentDatabase[key];
                                    if (record == null)
                                    {
                                        string thing = thingDef != null ? thingDef.defName : "null";
                                        string stuff = stuffDef != null ? stuffDef.defName : "null";
                                        Log.Warning(string.Format("Could not load equipment/resource from the preset.  This may be caused by an invalid thing/stuff combination: " + key));
                                        Failed = true;
                                        continue;
                                    }
                                    else
                                    {
                                        equipment.Add(new EquipmentSelection(record, e.count));
                                    }
                                }
                                else
                                {
                                    Log.Warning("Could not load stuff definition \"" + e.stuffDef + "\" for item \"" + e.def + "\"");
                                    Failed = true;
                                }
                            }
                        }
                        else
                        {
                            Log.Warning("Could not load thing definition \"" + e.def + "\"");
                            Failed = true;
                        }
                    }
                    loadout.Equipment.Clear();
                    foreach (var e in equipment)
                    {
                        loadout.Equipment.Add(e);
                    }
                }
                else
                {
                    Messages.Message("EdB.PC.Dialog.Preset.Error.EquipmentFailed".Translate(), MessageTypeDefOf.ThreatBig);
                    Log.Warning("Failed to load equipment from preset");
                    Failed = true;
                }
            }
            catch (Exception e) {
                Log.Error("Failed to load preset file");
                throw e;
            }
            finally {
                // I don't fully understand how these cross-references and saveables are resolved, but
                // if we don't clear them out, we get null pointer exceptions.
                HashSet <IExposable> saveables = (HashSet <IExposable>)(typeof(PostLoadIniter).GetField("saveablesToPostLoad", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(Scribe.loader.initer));
                if (saveables != null)
                {
                    saveables.Clear();
                }
                List <IExposable> crossReferencingExposables = (List <IExposable>)(typeof(CrossRefHandler).GetField("crossReferencingExposables", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(Scribe.loader.crossRefs));
                if (crossReferencingExposables != null)
                {
                    crossReferencingExposables.Clear();
                }
                Scribe.loader.FinalizeLoading();
            }

            List <CustomPawn> allPawns            = new List <CustomPawn>();
            List <CustomPawn> colonistCustomPawns = new List <CustomPawn>();
            List <CustomPawn> hiddenCustomPawns   = new List <CustomPawn>();

            try {
                foreach (SaveRecordPawnV4 p in preset.pawns)
                {
                    CustomPawn pawn = LoadPawn(p);
                    if (pawn != null)
                    {
                        allPawns.Add(pawn);
                        if (!pawn.Hidden)
                        {
                            colonistCustomPawns.Add(pawn);
                        }
                        else
                        {
                            hiddenCustomPawns.Add(pawn);
                        }
                    }
                    else
                    {
                        Messages.Message("EdB.PC.Dialog.Preset.Error.NoCharacter".Translate(), MessageTypeDefOf.ThreatBig);
                        Log.Warning("Preset was created with the following mods: " + preset.mods);
                    }
                }
            }
            catch (Exception e) {
                Messages.Message("EdB.PC.Dialog.Preset.Error.Failed".Translate(), MessageTypeDefOf.ThreatBig);
                Log.Warning(e.ToString());
                Log.Warning("Preset was created with the following mods: " + preset.mods);
                return(false);
            }

            loadout.ClearPawns();
            foreach (CustomPawn p in colonistCustomPawns)
            {
                loadout.AddPawn(p);
            }
            loadout.RelationshipManager.Clear();
            loadout.RelationshipManager.InitializeWithCustomPawns(colonistCustomPawns.AsEnumerable().Concat(hiddenCustomPawns));

            bool atLeastOneRelationshipFailed          = false;
            List <CustomRelationship> allRelationships = new List <CustomRelationship>();

            if (preset.relationships != null)
            {
                try {
                    foreach (SaveRecordRelationshipV3 r in preset.relationships)
                    {
                        if (string.IsNullOrEmpty(r.source) || string.IsNullOrEmpty(r.target) || string.IsNullOrEmpty(r.relation))
                        {
                            atLeastOneRelationshipFailed = true;
                            Log.Warning("Prepare Carefully failed to load a custom relationship from the preset: " + r);
                            continue;
                        }
                        CustomRelationship relationship = LoadRelationship(r, allPawns);
                        if (relationship == null)
                        {
                            atLeastOneRelationshipFailed = true;
                            Log.Warning("Prepare Carefully failed to load a custom relationship from the preset: " + r);
                        }
                        else
                        {
                            allRelationships.Add(relationship);
                        }
                    }
                }
                catch (Exception e) {
                    Messages.Message("EdB.PC.Dialog.Preset.Error.RelationshipFailed".Translate(), MessageTypeDefOf.ThreatBig);
                    Log.Warning(e.ToString());
                    Log.Warning("Preset was created with the following mods: " + preset.mods);
                    return(false);
                }
                if (atLeastOneRelationshipFailed)
                {
                    Messages.Message("EdB.PC.Dialog.Preset.Error.RelationshipFailed".Translate(), MessageTypeDefOf.ThreatBig);
                }
            }
            loadout.RelationshipManager.AddRelationships(allRelationships);

            if (preset.parentChildGroups != null)
            {
                foreach (var groupRecord in preset.parentChildGroups)
                {
                    ParentChildGroup group = new ParentChildGroup();
                    if (groupRecord.parents != null)
                    {
                        foreach (var id in groupRecord.parents)
                        {
                            CustomPawn parent = FindPawnById(id, colonistCustomPawns, hiddenCustomPawns);
                            if (parent != null)
                            {
                                var pawn = parent;
                                if (pawn != null)
                                {
                                    group.Parents.Add(pawn);
                                }
                                else
                                {
                                    Log.Warning("Prepare Carefully could not load a custom parent relationship because it could not find a matching pawn in the relationship manager.");
                                }
                            }
                            else
                            {
                                Log.Warning("Prepare Carefully could not load a custom parent relationship because it could not find a pawn with the saved identifer.");
                            }
                        }
                    }
                    if (groupRecord.children != null)
                    {
                        foreach (var id in groupRecord.children)
                        {
                            CustomPawn child = FindPawnById(id, colonistCustomPawns, hiddenCustomPawns);
                            if (child != null)
                            {
                                var pawn = child;
                                if (pawn != null)
                                {
                                    group.Children.Add(pawn);
                                }
                                else
                                {
                                    Log.Warning("Prepare Carefully could not load a custom child relationship because it could not find a matching pawn in the relationship manager.");
                                }
                            }
                            else
                            {
                                Log.Warning("Prepare Carefully could not load a custom child relationship because it could not find a pawn with the saved identifer.");
                            }
                        }
                    }
                    loadout.RelationshipManager.ParentChildGroups.Add(group);
                }
            }
            loadout.RelationshipManager.ReassignHiddenPawnIndices();

            if (Failed)
            {
                Messages.Message(preset.mods, MessageTypeDefOf.SilentInput);
                Messages.Message("EdB.PC.Dialog.Preset.Error.ThingDefFailed".Translate(), MessageTypeDefOf.ThreatBig);
                Log.Warning("Preset was created with the following mods: " + preset.mods);
                return(false);
            }

            return(true);
        }
示例#9
0
        private static TerrainDef GenerateBridgeDef(ThingDef material, bool deep, HashSet <TerrainDef> currentBridges,
                                                    string alternateTexture = "")
        {
            string defName;
            string label;

            if (deep)
            {
                defName = $"DeepWaterBridge{material.defName.Replace("Blocks", string.Empty)}{alternateTexture}";
                label   = $"{material.label.Replace(" blocks", string.Empty)} deep water bridge";
                if (currentBridges.Any(def => def.defName == defName))
                {
                    defName = $"DeepWaterBridge{material.defName}{alternateTexture}";
                    label   = $"{material.label} deep water bridge";
                }
            }
            else
            {
                defName = $"HeavyBridge{material.defName.Replace("Blocks", string.Empty)}{alternateTexture}";
                label   = $"{material.label.Replace(" blocks", string.Empty)} bridge";
                if (currentBridges.Any(def => def.defName == defName))
                {
                    defName = $"HeavyBridge{material.defName}{alternateTexture}";
                    label   = $"{material.label} bridge";
                }
            }

            var currentBridgeType = new TerrainDef
            {
                defName          = defName,
                label            = label,
                edgeType         = TerrainDef.TerrainEdgeType.Hard,
                renderPrecedence = 400,
                layerable        = true,
                affordances      =
                    new List <TerrainAffordanceDef>
                {
                    RimWorld.TerrainAffordanceDefOf.Light,
                    RimWorld.TerrainAffordanceDefOf.Medium,
                    RimWorld.TerrainAffordanceDefOf.Heavy
                },
                designationCategory         = DesignationCategoryDefOf.Structure,
                fertility                   = 0,
                constructEffect             = EffecterDefOf.ConstructMetal,
                destroyBuildingsOnDestroyed = true,
                destroyEffect               =
                    DefDatabase <EffecterDef> .GetNamedSilentFail("Bridge_Collapse"),
                destroyEffectWater =
                    DefDatabase <EffecterDef> .GetNamedSilentFail("Bridge_CollapseWater"),
                description =
                    "A flat surface of the chosen material on supportive beams which can be built over water. You can even build heavy structures on these bridges, but be careful, they are still fragile. If a bridge falls, buildings on top of it fall as well.",
                resourcesFractionWhenDeconstructed = 0,
                destroyOnBombDamageThreshold       = 40,
                statBases = new List <StatModifier>
                {
                    new StatModifier {
                        stat = StatDefOf.Flammability, value = 0
                    }
                }
            };

            if (deep)
            {
                currentBridgeType.uiIconPath = "Terrain/Surfaces/DeepWaterBridge_MenuIcon";
                currentBridgeType.terrainAffordanceNeeded = TerrainAffordanceDefOf.BridgeableDeep;
                currentBridgeType.statBases.Add(new StatModifier {
                    stat = StatDefOf.WorkToBuild, value = 3200
                });
                currentBridgeType.designatorDropdown    = DesignatorDropdownGroupDefOf.Bridge_DeepWater;
                currentBridgeType.researchPrerequisites = new List <ResearchProjectDef>
                {
                    DefDatabase <ResearchProjectDef> .GetNamedSilentFail(
                        "DeepWaterBridges")
                };
            }
            else
            {
                currentBridgeType.uiIconPath = "Terrain/Surfaces/HeavyBridge_MenuIcon";
                currentBridgeType.terrainAffordanceNeeded = TerrainAffordanceDefOf.Bridgeable;
                currentBridgeType.statBases.Add(new StatModifier {
                    stat = StatDefOf.WorkToBuild, value = 2200
                });
                currentBridgeType.designatorDropdown    = DesignatorDropdownGroupDefOf.Bridge_Heavy;
                currentBridgeType.researchPrerequisites = new List <ResearchProjectDef>
                {
                    DefDatabase <ResearchProjectDef> .GetNamedSilentFail(
                        "HeavyBridges")
                };
            }

            if (alternateTexture != "Concrete")
            {
                currentBridgeType.color = material.stuffProps.color;
            }

            float hitPoints;

            if (material.stuffProps.categories.Contains(StuffCategoryDefOf.Metallic))
            {
                hitPoints = 300f;
                if (string.IsNullOrEmpty(alternateTexture))
                {
                    currentBridgeType.texturePath = "Terrain/Surfaces/DeepWaterBridgeMetal";
                    if (LoadedModManager.GetMod <SimplyMoreBridgesMod>().GetSettings <SimplyMoreBridgesSettings>()
                        .AddVisuals)
                    {
                        currentBridgeType.label += " (FloorTile)";
                    }
                }
                else
                {
                    currentBridgeType.texturePath = $"Terrain/Surfaces/Bridge{alternateTexture}";
                    currentBridgeType.label      += $" ({alternateTexture})";
                }

                currentBridgeType.researchPrerequisites.Add(
                    DefDatabase <ResearchProjectDef> .GetNamedSilentFail("Smithing"));
                if (deep)
                {
                    if (material.defName == "Steel")
                    {
                        if (currentBridgeType.label.Contains("FloorTile"))
                        {
                            currentBridgeType.texturePath = "Terrain/Surfaces/BridgeMetal";
                            currentBridgeType.color       = DefDatabase <TerrainDef> .GetNamedSilentFail("MetalTile").color;
                        }

                        currentBridgeType.costList = new List <ThingDefCountClass>
                        {
                            new ThingDefCountClass
                            {
                                thingDef = ThingDefOf.Steel,
                                count    = GetCustomCost(20)
                            }
                        };
                    }
                    else
                    {
                        var baseCost = 15;
                        if (material.smallVolume)
                        {
                            currentBridgeType.texturePath = "Terrain/Surfaces/BridgeMetal";
                            switch (material.defName)
                            {
                            case "Silver":
                                currentBridgeType.color =
                                    DefDatabase <TerrainDef> .GetNamedSilentFail("SilverTile").color;

                                break;

                            case "Gold":
                                currentBridgeType.color =
                                    DefDatabase <TerrainDef> .GetNamedSilentFail("GoldTile").color;

                                break;
                            }

                            baseCost *= 10;
                        }

                        currentBridgeType.costList = new List <ThingDefCountClass>
                        {
                            new ThingDefCountClass
                            {
                                thingDef = ThingDefOf.Steel,
                                count    = GetCustomCost(5)
                            },
                            new ThingDefCountClass
                            {
                                thingDef = material,
                                count    = GetCustomCost(baseCost)
                            }
                        };
                    }
                }
                else
                {
                    if (material.defName == "Steel")
                    {
                        currentBridgeType.texturePath = "Terrain/Surfaces/BridgeMetal";
                        currentBridgeType.color       = DefDatabase <TerrainDef> .GetNamedSilentFail("MetalTile").color;

                        currentBridgeType.costList = new List <ThingDefCountClass>
                        {
                            new ThingDefCountClass
                            {
                                thingDef = ThingDefOf.Steel,
                                count    = GetCustomCost(12)
                            }
                        };
                    }
                    else
                    {
                        var baseCost = 9;
                        if (material.smallVolume)
                        {
                            currentBridgeType.texturePath = "Terrain/Surfaces/BridgeMetal";
                            switch (material.defName)
                            {
                            case "Silver":
                                currentBridgeType.color =
                                    DefDatabase <TerrainDef> .GetNamedSilentFail("SilverTile").color;

                                break;

                            case "Gold":
                                currentBridgeType.color =
                                    DefDatabase <TerrainDef> .GetNamedSilentFail("GoldTile").color;

                                break;
                            }

                            baseCost *= 10;
                        }

                        currentBridgeType.costList = new List <ThingDefCountClass>
                        {
                            new ThingDefCountClass
                            {
                                thingDef = ThingDefOf.Steel,
                                count    = GetCustomCost(3)
                            },
                            new ThingDefCountClass
                            {
                                thingDef = material,
                                count    = GetCustomCost(baseCost)
                            }
                        };
                    }
                }
            }
            else
            {
                hitPoints = 200f;
                if (string.IsNullOrEmpty(alternateTexture))
                {
                    currentBridgeType.texturePath = "Terrain/Surfaces/HeavyBridgeStone";
                    if (LoadedModManager.GetMod <SimplyMoreBridgesMod>().GetSettings <SimplyMoreBridgesSettings>()
                        .AddVisuals)
                    {
                        currentBridgeType.label += " (StoneTile)";
                    }
                }
                else
                {
                    currentBridgeType.texturePath = $"Terrain/Surfaces/Bridge{alternateTexture}";
                    currentBridgeType.label      += $" ({alternateTexture})";
                }

                if (deep)
                {
                    var baseCost = 17;
                    if (material.smallVolume)
                    {
                        baseCost *= 10;
                    }

                    currentBridgeType.costList = new List <ThingDefCountClass>
                    {
                        new ThingDefCountClass
                        {
                            thingDef = ThingDefOf.Steel, count = GetCustomCost(5)
                        },
                        new ThingDefCountClass {
                            thingDef = material, count = GetCustomCost(baseCost)
                        }
                    };
                }
                else
                {
                    var baseCost = 10;
                    if (material.smallVolume)
                    {
                        baseCost *= 10;
                    }

                    currentBridgeType.costList = new List <ThingDefCountClass>
                    {
                        new ThingDefCountClass
                        {
                            thingDef = ThingDefOf.Steel, count = GetCustomCost(3)
                        },
                        new ThingDefCountClass {
                            thingDef = material, count = GetCustomCost(baseCost)
                        }
                    };
                }
            }

            if (material.statBases.StatListContains(StatDefOf.StuffPower_Armor_Sharp))
            {
                var sharpValue = material.GetStatValueAbstract(StatDefOf.StuffPower_Armor_Sharp);
                hitPoints = (float)Math.Round(500f * sharpValue);
            }

            currentBridgeType.statBases.Add(new StatModifier {
                stat = StatDefOf.MaxHitPoints, value = hitPoints
            });

            currentBridgeType.tags = new List <string>();

            if (alternateTexture != "Flagstone")
            {
                currentBridgeType.tags.Add("Floor");
            }

            if (material.stuffProps.statOffsets?.Any(
                    modifier => modifier.stat == StatDefOf.Beauty && modifier.value > 5) == true)
            {
                currentBridgeType.tags.Add("FineFloor");
            }

            if (alternateTexture != "Sterile")
            {
                return(currentBridgeType);
            }

            currentBridgeType.statBases.Add(new StatModifier {
                stat = StatDefOf.Cleanliness, value = 0.6f
            });
            currentBridgeType.color = DefDatabase <TerrainDef> .GetNamedSilentFail("SterileTile").color;

            currentBridgeType.researchPrerequisites.Add(
                DefDatabase <ResearchProjectDef> .GetNamedSilentFail("SterileMaterials"));
            return(currentBridgeType);
        }
示例#10
0
        private static TerrainDef GenerateBridgeDef(ThingDef material, bool deep)
        {
            var currentBridgeType = new TerrainDef
            {
                edgeType         = TerrainDef.TerrainEdgeType.Hard,
                renderPrecedence = 400,
                layerable        = true,
                affordances      = new List <TerrainAffordanceDef> {
                    RimWorld.TerrainAffordanceDefOf.Light, RimWorld.TerrainAffordanceDefOf.Medium, RimWorld.TerrainAffordanceDefOf.Heavy
                },
                designationCategory                = DesignationCategoryDefOf.Structure,
                fertility                          = 0,
                constructEffect                    = EffecterDefOf.ConstructMetal,
                destroyBuildingsOnDestroyed        = true,
                destroyEffect                      = DefDatabase <EffecterDef> .GetNamedSilentFail("Bridge_Collapse"),
                destroyEffectWater                 = DefDatabase <EffecterDef> .GetNamedSilentFail("Bridge_CollapseWater"),
                description                        = "A flat surface of the chosen material on supportive beams which can be built over water. You can even build heavy structures on these bridges, but be careful, they are still fragile. If a bridge falls, buildings on top of it fall as well.",
                resourcesFractionWhenDeconstructed = 0,
                destroyOnBombDamageThreshold       = 40,
                statBases                          = new List <StatModifier>
                {
                    new StatModifier()
                    {
                        stat = StatDefOf.Flammability, value = 0
                    }
                }
            };

            if (deep)
            {
                currentBridgeType.uiIconPath = $"Terrain/Surfaces/DeepWaterBridge_MenuIcon";
                currentBridgeType.terrainAffordanceNeeded = TerrainAffordanceDefOf.BridgeableDeep;
                currentBridgeType.statBases.Add(new StatModifier()
                {
                    stat = StatDefOf.WorkToBuild, value = 3200
                });
                currentBridgeType.designatorDropdown    = DesignatorDropdownGroupDefOf.Bridge_DeepWater;
                currentBridgeType.researchPrerequisites = new List <ResearchProjectDef> {
                    DefDatabase <ResearchProjectDef> .GetNamedSilentFail("DeepWaterBridges")
                };
                currentBridgeType.label   = $"{material.label} deep water bridge";
                currentBridgeType.defName = $"DeepWaterBridge{material.defName.Replace("Blocks", string.Empty)}";
            }
            else
            {
                currentBridgeType.uiIconPath = $"Terrain/Surfaces/HeavyBridge_MenuIcon";
                currentBridgeType.terrainAffordanceNeeded = TerrainAffordanceDefOf.Bridgeable;
                currentBridgeType.statBases.Add(new StatModifier()
                {
                    stat = StatDefOf.WorkToBuild, value = 2200
                });
                currentBridgeType.designatorDropdown    = DesignatorDropdownGroupDefOf.Bridge_Heavy;
                currentBridgeType.researchPrerequisites = new List <ResearchProjectDef> {
                    DefDatabase <ResearchProjectDef> .GetNamedSilentFail("HeavyBridges")
                };
                currentBridgeType.label   = $"{material.label} bridge";
                currentBridgeType.defName = $"HeavyBridge{material.defName.Replace("Blocks", string.Empty)}";
            }
            if (material.stuffProps.categories.Contains(StuffCategoryDefOf.Metallic))
            {
                currentBridgeType.texturePath = $"Terrain/Surfaces/DeepWaterBridgeMetal";
                currentBridgeType.researchPrerequisites.Add(DefDatabase <ResearchProjectDef> .GetNamedSilentFail("Smithing"));
                if (deep)
                {
                    if (material.defName == "Steel")
                    {
                        currentBridgeType.costList = new List <ThingDefCountClass> {
                            new ThingDefCountClass {
                                thingDef = ThingDefOf.Steel, count = 20
                            }
                        };
                    }
                    else
                    {
                        int baseCost = 15;
                        if (material.smallVolume)
                        {
                            baseCost = baseCost * 10;
                        }
                        currentBridgeType.costList = new List <ThingDefCountClass> {
                            new ThingDefCountClass {
                                thingDef = ThingDefOf.Steel, count = 5
                            }, new ThingDefCountClass {
                                thingDef = material, count = baseCost
                            }
                        };
                    }
                }
                else
                {
                    if (material.defName == "Steel")
                    {
                        currentBridgeType.costList = new List <ThingDefCountClass> {
                            new ThingDefCountClass {
                                thingDef = ThingDefOf.Steel, count = 12
                            }
                        };
                    }
                    else
                    {
                        int baseCost = 9;
                        if (material.smallVolume)
                        {
                            baseCost = baseCost * 10;
                        }
                        currentBridgeType.costList = new List <ThingDefCountClass> {
                            new ThingDefCountClass {
                                thingDef = ThingDefOf.Steel, count = 3
                            }, new ThingDefCountClass {
                                thingDef = material, count = baseCost
                            }
                        };
                    }
                }
            }
            else
            {
                currentBridgeType.texturePath = $"Terrain/Surfaces/HeavyBridgeStone";
                if (deep)
                {
                    int baseCost = 17;
                    if (material.smallVolume)
                    {
                        baseCost = baseCost * 10;
                    }
                    currentBridgeType.costList = new List <ThingDefCountClass> {
                        new ThingDefCountClass {
                            thingDef = ThingDefOf.Steel, count = 5
                        }, new ThingDefCountClass {
                            thingDef = material, count = baseCost
                        }
                    };
                }
                else
                {
                    int baseCost = 10;
                    if (material.smallVolume)
                    {
                        baseCost = baseCost * 10;
                    }
                    currentBridgeType.costList = new List <ThingDefCountClass> {
                        new ThingDefCountClass {
                            thingDef = ThingDefOf.Steel, count = 3
                        }, new ThingDefCountClass {
                            thingDef = material, count = baseCost
                        }
                    };
                }
            }
            currentBridgeType.color = material.stuffProps.color;
            return(currentBridgeType);
        }
        public CustomPawn LoadPawn(SaveRecordPawnV4 record)
        {
            PawnKindDef pawnKindDef = null;

            if (record.pawnKindDef != null)
            {
                pawnKindDef = DefDatabase <PawnKindDef> .GetNamedSilentFail(record.pawnKindDef);

                if (pawnKindDef == null)
                {
                    Log.Warning("Prepare Carefully could not find the pawn kind definition for the saved character: \"" + record.pawnKindDef + "\"");
                    return(null);
                }
            }

            ThingDef pawnThingDef = ThingDefOf.Human;

            if (record.thingDef != null)
            {
                ThingDef thingDef = DefDatabase <ThingDef> .GetNamedSilentFail(record.thingDef);

                if (thingDef != null)
                {
                    pawnThingDef = thingDef;
                }
            }

            Pawn source;

            if (pawnKindDef != null)
            {
                source = new Randomizer().GenerateKindOfColonist(pawnKindDef);
            }
            else
            {
                source = new Randomizer().GenerateColonist();
            }
            source.health.Reset();

            CustomPawn pawn = new CustomPawn(source);

            if (pawn.Id == null)
            {
                pawn.GenerateId();
            }
            else
            {
                pawn.Id = record.id;
            }

            if (record.type != null)
            {
                try {
                    pawn.Type = (CustomPawnType)Enum.Parse(typeof(CustomPawnType), record.type);
                }
                catch (Exception) {
                    pawn.Type = CustomPawnType.Colonist;
                }
            }
            else
            {
                pawn.Type = CustomPawnType.Colonist;
            }

            pawn.Gender = record.gender;
            if (record.age > 0)
            {
                pawn.ChronologicalAge = record.age;
                pawn.BiologicalAge    = record.age;
            }
            if (record.chronologicalAge > 0)
            {
                pawn.ChronologicalAge = record.chronologicalAge;
            }
            if (record.biologicalAge > 0)
            {
                pawn.BiologicalAge = record.biologicalAge;
            }

            pawn.FirstName = record.firstName;
            pawn.NickName  = record.nickName;
            pawn.LastName  = record.lastName;

            if (pawn.Type == CustomPawnType.World)
            {
                if (record.faction != null)
                {
                    if (record.faction.def != null)
                    {
                        FactionDef factionDef = DefDatabase <FactionDef> .GetNamedSilentFail(record.faction.def);

                        if (factionDef != null)
                        {
                            bool randomFaction = false;
                            if (record.faction.index != null)
                            {
                                CustomFaction customFaction = null;
                                if (!record.faction.leader)
                                {
                                    customFaction = PrepareCarefully.Instance.Providers.Factions.FindCustomFactionByIndex(factionDef, record.faction.index.Value);
                                }
                                else
                                {
                                    customFaction = PrepareCarefully.Instance.Providers.Factions.FindCustomFactionWithLeaderOptionByIndex(factionDef, record.faction.index.Value);
                                }
                                if (customFaction != null)
                                {
                                    pawn.Faction = customFaction;
                                }
                                else
                                {
                                    Log.Warning("Prepare Carefully could not place at least one preset character into a saved faction because there were not enough available factions of that type in the world");
                                    randomFaction = true;
                                }
                            }
                            else
                            {
                                randomFaction = true;
                            }
                            if (randomFaction)
                            {
                                CustomFaction customFaction = PrepareCarefully.Instance.Providers.Factions.FindRandomCustomFactionByDef(factionDef);
                                if (customFaction != null)
                                {
                                    pawn.Faction = customFaction;
                                }
                            }
                        }
                        else
                        {
                            Log.Warning("Prepare Carefully could not place at least one preset character into a saved faction because that faction is not available in the world");
                        }
                    }
                }
            }

            HairDef h = FindHairDef(record.hairDef);

            if (h != null)
            {
                pawn.HairDef = h;
            }
            else
            {
                Log.Warning("Could not load hair definition \"" + record.hairDef + "\"");
                Failed = true;
            }

            pawn.HeadGraphicPath      = record.headGraphicPath;
            pawn.Pawn.story.hairColor = record.hairColor;

            if (record.melanin >= 0.0f)
            {
                pawn.MelaninLevel = record.melanin;
            }
            else
            {
                pawn.MelaninLevel = PawnColorUtils.FindMelaninValueFromColor(record.skinColor);
            }
            // Set the skin color (only for Alien Races).
            if (pawn.AlienRace != null)
            {
                pawn.SkinColor = record.skinColor;
            }

            Backstory backstory = FindBackstory(record.childhood);

            if (backstory != null)
            {
                pawn.Childhood = backstory;
            }
            else
            {
                Log.Warning("Could not load childhood backstory definition \"" + record.childhood + "\"");
                Failed = true;
            }
            if (record.adulthood != null)
            {
                backstory = FindBackstory(record.adulthood);
                if (backstory != null)
                {
                    pawn.Adulthood = backstory;
                }
                else
                {
                    Log.Warning("Could not load adulthood backstory definition \"" + record.adulthood + "\"");
                    Failed = true;
                }
            }

            BodyTypeDef bodyType = null;

            try {
                bodyType = DefDatabase <BodyTypeDef> .GetNamedSilentFail(record.bodyType);
            }
            catch (Exception) {
            }
            if (bodyType == null)
            {
                if (pawn.Adulthood != null)
                {
                    bodyType = pawn.Adulthood.BodyTypeFor(pawn.Gender);
                }
                else
                {
                    bodyType = pawn.Childhood.BodyTypeFor(pawn.Gender);
                }
            }
            if (bodyType != null)
            {
                pawn.BodyType = bodyType;
            }

            pawn.ClearTraits();
            for (int i = 0; i < record.traitNames.Count; i++)
            {
                string traitName = record.traitNames[i];
                Trait  trait     = FindTrait(traitName, record.traitDegrees[i]);
                if (trait != null)
                {
                    pawn.AddTrait(trait);
                }
                else
                {
                    Log.Warning("Could not load trait definition \"" + traitName + "\"");
                    Failed = true;
                }
            }

            foreach (var skill in record.skills)
            {
                SkillDef def = FindSkillDef(pawn.Pawn, skill.name);
                if (def == null)
                {
                    Log.Warning("Could not load skill definition \"" + skill.name + "\" from saved preset");
                    Failed = true;
                    continue;
                }
                pawn.currentPassions[def]  = skill.passion;
                pawn.originalPassions[def] = skill.passion;
                pawn.SetOriginalSkillLevel(def, skill.value);
                pawn.SetUnmodifiedSkillLevel(def, skill.value);
            }

            foreach (var layer in PrepareCarefully.Instance.Providers.PawnLayers.GetLayersForPawn(pawn))
            {
                if (layer.Apparel)
                {
                    pawn.SetSelectedApparel(layer, null);
                    pawn.SetSelectedStuff(layer, null);
                }
            }
            List <PawnLayer> apparelLayers = PrepareCarefully.Instance.Providers.PawnLayers.GetLayersForPawn(pawn).FindAll((layer) => { return(layer.Apparel); });

            foreach (var apparelRecord in record.apparel)
            {
                // Find the pawn layer for the saved apparel record.
                PawnLayer layer = apparelLayers.FirstOrDefault((apparelLayer) => { return(apparelLayer.Name == apparelRecord.layer); });
                if (layer == null)
                {
                    Log.Warning("Could not find a matching pawn layer for the saved apparel \"" + apparelRecord.layer + "\"");
                    Failed = true;
                    continue;
                }
                if (apparelRecord.apparel.NullOrEmpty())
                {
                    Log.Warning("Saved apparel entry for layer \"" + apparelRecord.layer + "\" had an empty apparel def");
                    Failed = true;
                    continue;
                }
                // Set the defaults.
                pawn.SetSelectedApparel(layer, null);
                pawn.SetSelectedStuff(layer, null);
                pawn.SetColor(layer, Color.white);

                ThingDef def = DefDatabase <ThingDef> .GetNamedSilentFail(apparelRecord.apparel);

                if (def == null)
                {
                    Log.Warning("Could not load thing definition for apparel \"" + apparelRecord.apparel + "\"");
                    Failed = true;
                    continue;
                }
                ThingDef stuffDef = null;
                if (!string.IsNullOrEmpty(apparelRecord.stuff))
                {
                    stuffDef = DefDatabase <ThingDef> .GetNamedSilentFail(apparelRecord.stuff);

                    if (stuffDef == null)
                    {
                        Log.Warning("Could not load stuff definition \"" + apparelRecord.stuff + "\" for apparel \"" + apparelRecord.apparel + "\"");
                        Failed = true;
                        continue;
                    }
                }
                pawn.SetSelectedApparel(layer, def);
                pawn.SetSelectedStuff(layer, stuffDef);
                pawn.SetColor(layer, apparelRecord.color);
            }

            OptionsHealth healthOptions = PrepareCarefully.Instance.Providers.Health.GetOptions(pawn);

            for (int i = 0; i < record.implants.Count; i++)
            {
                SaveRecordImplantV3 implantRecord  = record.implants[i];
                UniqueBodyPart      uniqueBodyPart = healthOptions.FindBodyPartByName(implantRecord.bodyPart, implantRecord.bodyPartIndex != null ? implantRecord.bodyPartIndex.Value : 0);
                if (uniqueBodyPart == null)
                {
                    uniqueBodyPart = FindReplacementBodyPart(healthOptions, implantRecord.bodyPart);
                }
                if (uniqueBodyPart == null)
                {
                    Log.Warning("Prepare Carefully could not add the implant because it could not find the needed body part \"" + implantRecord.bodyPart + "\""
                                + (implantRecord.bodyPartIndex != null ? " with index " + implantRecord.bodyPartIndex : ""));
                    Failed = true;
                    continue;
                }
                BodyPartRecord bodyPart = uniqueBodyPart.Record;
                if (implantRecord.recipe != null)
                {
                    RecipeDef recipeDef = FindRecipeDef(implantRecord.recipe);
                    if (recipeDef == null)
                    {
                        Log.Warning("Prepare Carefully could not add the implant because it could not find the recipe definition \"" + implantRecord.recipe + "\"");
                        Failed = true;
                        continue;
                    }
                    bool found = false;
                    foreach (var p in recipeDef.appliedOnFixedBodyParts)
                    {
                        if (p.defName.Equals(bodyPart.def.defName))
                        {
                            found = true;
                            break;
                        }
                    }
                    if (!found)
                    {
                        Log.Warning("Prepare carefully could not apply the saved implant recipe \"" + implantRecord.recipe + "\" to the body part \"" + bodyPart.def.defName + "\".  Recipe does not support that part.");
                        Failed = true;
                        continue;
                    }
                    Implant implant = new Implant();
                    implant.BodyPartRecord = bodyPart;
                    implant.recipe         = recipeDef;
                    implant.label          = implant.Label;
                    pawn.AddImplant(implant);
                }
            }

            foreach (var injuryRecord in record.injuries)
            {
                HediffDef def = DefDatabase <HediffDef> .GetNamedSilentFail(injuryRecord.hediffDef);

                if (def == null)
                {
                    Log.Warning("Prepare Carefully could not add the injury because it could not find the hediff definition \"" + injuryRecord.hediffDef + "\"");
                    Failed = true;
                    continue;
                }
                InjuryOption option = healthOptions.FindInjuryOptionByHediffDef(def);
                if (option == null)
                {
                    Log.Warning("Prepare Carefully could not add the injury because it could not find a matching injury option for the saved hediff \"" + injuryRecord.hediffDef + "\"");
                    Failed = true;
                    continue;
                }
                BodyPartRecord bodyPart = null;
                if (injuryRecord.bodyPart != null)
                {
                    UniqueBodyPart uniquePart = healthOptions.FindBodyPartByName(injuryRecord.bodyPart,
                                                                                 injuryRecord.bodyPartIndex != null ? injuryRecord.bodyPartIndex.Value : 0);
                    if (uniquePart == null)
                    {
                        uniquePart = FindReplacementBodyPart(healthOptions, injuryRecord.bodyPart);
                    }
                    if (uniquePart == null)
                    {
                        Log.Warning("Prepare Carefully could not add the injury because it could not find the needed body part \"" + injuryRecord.bodyPart + "\""
                                    + (injuryRecord.bodyPartIndex != null ? " with index " + injuryRecord.bodyPartIndex : ""));
                        Failed = true;
                        continue;
                    }
                    bodyPart = uniquePart.Record;
                }
                Injury injury = new Injury();
                injury.Option         = option;
                injury.BodyPartRecord = bodyPart;
                if (injuryRecord.severity != null)
                {
                    injury.Severity = injuryRecord.Severity;
                }
                if (injuryRecord.painFactor != null)
                {
                    injury.PainFactor = injuryRecord.PainFactor;
                }
                pawn.AddInjury(injury);
            }

            pawn.CopySkillsAndPassionsToPawn();
            pawn.ClearPawnCaches();

            return(pawn);
        }
示例#12
0
        public override void DoSettingsWindowContents(Rect inRect)
        {
            base.DoSettingsWindowContents(inRect);

            Def oauth = DefDatabase <HediffDef> .GetNamedSilentFail("rimtwitch_explain_oauth");

            Def bot = DefDatabase <HediffDef> .GetNamedSilentFail("rimtwitch_explain_bot");

            Def you = DefDatabase <HediffDef> .GetNamedSilentFail("rimtwitch_explain_you");

            if (you == null || bot == null || oauth == null)
            {
                Widgets.TextArea(inRect, "Missing explain defs", true);
                _settings.Clear();
                return;
            }

            var topHalf = inRect.TopHalf();
            var fourth  = topHalf.TopHalf();
            var mySlice = fourth.TopHalf();

            if (showDetails)
            {
                Widgets.Label(mySlice.LeftHalf(), oauth.description);
                _settings.oauth = Widgets.TextArea(mySlice.RightHalf().ContractedBy(4f), _settings.oauth);

                mySlice = fourth.BottomHalf();

                Widgets.Label(mySlice.LeftHalf(), you.description);
                _settings.yourName = Widgets.TextArea(mySlice.RightHalf().ContractedBy(4f), _settings.yourName);

                fourth  = topHalf.BottomHalf();
                mySlice = fourth.TopHalf();
                Widgets.Label(mySlice.LeftHalf(), bot.description);
                _settings.botName = Widgets.TextArea(mySlice.RightHalf().ContractedBy(4f), _settings.botName);
            }
            else
            {
                showDetails = Widgets.ButtonText(mySlice, "Show configuration");
            }

            mySlice = inRect.BottomHalf().BottomHalf().BottomHalf().BottomHalf();
            if (Widgets.ButtonText(mySlice.LeftHalf().ContractedBy(2f), "Test"))
            {
                try
                {
                    Broadcast.Start(_settings.oauth, _settings.yourName, _settings.botName)
                    .SendIrcMessage("RimWorld Twitch IRC Test");

                    Broadcast.Stop();

                    Log.Message("Test : Success");
                }
                catch (Exception e)
                {
                    Log.Error("Twitch IRC Failed! " + e.StackTrace);
                }
            }

            var isStart = Broadcast.OnAir() == null;

            if (Widgets.ButtonText(mySlice.RightHalf().ContractedBy(2f), isStart?"Start":"Stop"))
            {
                try
                {
                    if (isStart)
                    {
                        Broadcast.Start(_settings.oauth, _settings.yourName, _settings.botName);

                        Log.Message("Startup Success");
                    }
                    else
                    {
                        Broadcast.Stop();
                    }
                }
                catch (Exception e)
                {
                    Log.Error("Twitch IRC Failed! " + e.StackTrace);
                }
            }

            this._settings.Write();
        }
示例#13
0
        static ArmouryMain()
        {
            collapseTex = TexButton.Collapse;
            if (collapseTex == null)
            {
                Log.Error("collapseTex == null");
            }
            expandTex = TexButton.Reveal;
            if (expandTex == null)
            {
                Log.Error("expandTex == null");
            }
            humanRecipes = DefDatabase <RecipeDef> .AllDefs.Where(x => x.AllRecipeUsers.Contains(ThingDefOf.Human));

            TechHediffRecipes = from x in DefDatabase <RecipeDef> .AllDefs
                                where TechHediffItems.Any(z => x.IsIngredient(z)) && x.targetsBodyPart
                                select x;

            TechHediffItems = from x in DefDatabase <ThingDef> .AllDefs
                              where x.isTechHediff && x.BaseMarketValue > 0
                              select x;

            ReseachImperial = DefDatabase <ResearchProjectDef> .AllDefs.Where(x => x.defName.Contains("OG_Imperial_Tech_")).ToList();

            ReseachMechanicus = DefDatabase <ResearchProjectDef> .AllDefs.Where(x => x.defName.Contains("OG_Mechanicus_Tech_")).ToList();

            ReseachChaos = DefDatabase <ResearchProjectDef> .AllDefs.Where(x => x.defName.Contains("OG_Chaos_Tech_")).ToList();

            scenariosTesting = DefDatabase <ScenarioDef> .AllDefs.Where(x => x.defName.StartsWith("OGAM_TestScenario_")).ToList();

            mechanicus = DefDatabase <ThingDef> .GetNamedSilentFail("OG_Human_Mechanicus");

            astartes = DefDatabase <ThingDef> .GetNamedSilentFail("OG_Human_Astartes");

            ogryn = DefDatabase <ThingDef> .GetNamedSilentFail("OG_Abhuman_Ogryn");

            ratlin = DefDatabase <ThingDef> .GetNamedSilentFail("OG_Abhuman_Ratling");

            beastman = DefDatabase <ThingDef> .GetNamedSilentFail("OG_Abhuman_Beastman");

            geneseedAstartes = DefDatabase <ThingDef> .GetNamedSilentFail("AstarteSpaceMarine");

            geneseedCustodes = DefDatabase <ThingDef> .GetNamedSilentFail("AdaptusCustodes");

            factionColours = DefDatabase <FactionDef> .AllDefs.Where(x => x.GetModExtensionFast <FactionDefExtension>()?.factionColor != null || x.GetModExtensionFast <FactionDefExtension>()?.factionColorTwo != null).ToList();

            if (AMAMod.Dev)
            {
                Log.Message("factions with colours: " + factionColours.Count);
            }
            IEnumerable <BackstorySettings> settings = DefDatabase <BackstorySettings> .AllDefs;

            if (!settings.EnumerableNullOrEmpty())
            {
                InsertTags();
            }

            /*
             * //    Log.Message("AppDomain.CurrentDomain.GetAssemblies():\n" + System.AppDomain.CurrentDomain.GetAssemblies().Join(delimiter: "\n"));
             * //    Log.Message("GenTypes.AllActiveAssemblies:\n" + Traverse.Create(typeof(GenTypes)).Property<IEnumerable<System.Reflection.Assembly>>("AllActiveAssemblies").Value.Join(delimiter: "\n"));
             */
            //    Log.Message("ArmouryMain ");
            if (AMAMod.Dev && !scenariosTesting.NullOrEmpty())
            {
                TestingScenarioUtility.SetUpTestScenarios(scenariosTesting);
            }
            HumanlikeRecipeUtility.AddHumanlikeRecipes();
            if (AdeptusIntergrationUtility.enabled_AlienRaces)
            {
                AlienRaceUtility.AlienRaces();
            }

            /*
             * StringBuilder Memes = new StringBuilder("MemeDef's");
             * foreach (var item in DefDatabase<MemeDef>.AllDefsListForReading)
             * {
             *  Memes.AppendLine(item.defName);
             * }
             * StringBuilder Precepts = new StringBuilder("PreceptDef's");
             * foreach (var item in DefDatabase<PreceptDef>.AllDefsListForReading)
             * {
             *  Precepts.AppendLine(item.defName);
             * }
             * //    Log.Message(Memes.ToString());
             * //    Log.Message(Precepts.ToString());
             */
        }
示例#14
0
        public override void DrawHairAndHeadGear(Vector3 hairLoc, Vector3 headgearLoc,
                                                 RotDrawMode bodyDrawType,
                                                 Quaternion headQuat,
                                                 bool renderBody,
                                                 bool portrait, Vector3 hatInFrontOfFace)
        {
            Mesh hairMesh = this.GetPawnHairMesh(portrait);
            List <ApparelGraphicRecord> apparelGraphics  = this.Graphics.apparelGraphics;
            List <ApparelGraphicRecord> headgearGraphics = null;

            if (!apparelGraphics.NullOrEmpty())
            {
                headgearGraphics = apparelGraphics
                                   .Where(x => x.sourceApparel.def.apparel.LastLayer == ApparelLayerDefOf.Overhead ||
                                          x.sourceApparel.def.apparel.LastLayer == DefDatabase <ApparelLayerDef> .GetNamedSilentFail("OnHead") ||
                                          x.sourceApparel.def.apparel.LastLayer == DefDatabase <ApparelLayerDef> .GetNamedSilentFail("StrappedHead") ||
                                          x.sourceApparel.def.apparel.LastLayer == DefDatabase <ApparelLayerDef> .GetNamedSilentFail("MiddleHead")).ToList();
            }

            CompBodyAnimator animator = this.CompAnimator;

            bool noRenderGoggles = Controller.settings.FilterHats;

            bool showRoyalHeadgear = Pawn.royalty?.MostSeniorTitle != null && Controller.settings.ShowRoyalHeadgear;
            bool noRenderRoofed    = animator != null && animator.HideHat && !showRoyalHeadgear;
            bool noRenderBed       = Controller.settings.HideHatInBed && !renderBody && !showRoyalHeadgear;

            if (!headgearGraphics.NullOrEmpty())
            {
                bool filterHeadgear = portrait && Prefs.HatsOnlyOnMap || !portrait && noRenderRoofed;

                // Draw regular hair if appparel or environment allows it (FS feature)
                if (bodyDrawType != RotDrawMode.Dessicated)
                {
                    // draw full or partial hair
                    bool apCoversFullHead =
                        headgearGraphics.Any(
                            x => x.sourceApparel.def.apparel.bodyPartGroups.Contains(BodyPartGroupDefOf
                                                                                     .FullHead) &&
                            !x.sourceApparel.def.apparel.hatRenderedFrontOfFace);

                    bool apCoversUpperHead =
                        headgearGraphics.Any(
                            x => x.sourceApparel.def.apparel.bodyPartGroups.Contains(BodyPartGroupDefOf
                                                                                     .UpperHead) &&
                            !x.sourceApparel.def.apparel.hatRenderedFrontOfFace);

                    if (this.CompFace.Props.hasOrganicHair || noRenderBed || filterHeadgear ||
                        (!apCoversFullHead && !apCoversUpperHead && noRenderGoggles))
                    {
                        Material mat = this.Graphics.HairMatAt(this.HeadFacing);
                        GenDraw.DrawMeshNowOrLater(hairMesh, hairLoc, headQuat, mat, portrait);
                    }
                    else if (Controller.settings.MergeHair) // && !apCoversFullHead)
                    {
                        // If not, display the hair cut
                        HairCutPawn hairPawn   = CutHairDB.GetHairCache(this.Pawn);
                        Material    hairCutMat = hairPawn.HairCutMatAt(this.HeadFacing);
                        if (hairCutMat != null)
                        {
                            GenDraw.DrawMeshNowOrLater(hairMesh, hairLoc, headQuat, hairCutMat, portrait);
                        }
                    }
                }
                else
                {
                    filterHeadgear = false;
                }

                if (filterHeadgear)
                {
                    // Filter the head gear to only show non-hats, show nothing while in bed
                    if (noRenderGoggles)
                    {
                        headgearGraphics = headgearGraphics
                                           .Where(
                            x =>
                            !x.sourceApparel.def.apparel.bodyPartGroups
                            .Contains(BodyPartGroupDefOf.FullHead) &&
                            !x.sourceApparel.def.apparel.bodyPartGroups.Contains(
                                BodyPartGroupDefOf
                                .UpperHead))
                                           .ToList();
                    }
                    else
                    {
                        // Clear if nothing to show
                        headgearGraphics?.Clear();
                    }
                }

                if (noRenderBed && !showRoyalHeadgear)
                {
                    headgearGraphics?.Clear();
                }

                // headgearGraphics = headgearGraphics
                // .OrderBy(x => x.sourceApparel.def.apparel.bodyPartGroups.Max(y => y.listOrder)).ToList();
                if (headgearGraphics.NullOrEmpty())
                {
                    return;
                }

                for (int index = 0; index < headgearGraphics?.Count; index++)
                {
                    ApparelGraphicRecord headgearGraphic = headgearGraphics[index];
                    Material             headGearMat     = headgearGraphic.graphic.MatAt(this.HeadFacing);
                    headGearMat = this.Graphics.flasher.GetDamagedMat(headGearMat);

                    if (headgearGraphic.sourceApparel.def.apparel.hatRenderedFrontOfFace)
                    {
                        headgearLoc = hatInFrontOfFace;
                    }

                    GenDraw.DrawMeshNowOrLater(hairMesh, headgearLoc, headQuat, headGearMat, portrait);
                    headgearLoc.y += Offsets.YOffsetInterval_Clothes;
                }
            }
            else
            {
                // Draw regular hair if no hat worn
                if (bodyDrawType != RotDrawMode.Dessicated)
                {
                    Material hairMat = this.Graphics.HairMatAt(this.HeadFacing);
                    GenDraw.DrawMeshNowOrLater(hairMesh, hairLoc, headQuat, hairMat, portrait);
                }
            }
        }
        public static bool isPsyker(Pawn pawn, out int Level, out float Mult)
        {
            bool result = false;

            Mult  = 0f;
            Level = 0;

            if (pawn.RaceProps.Humanlike)
            {
                if (pawn.health.hediffSet.hediffs.Any(x => x.GetType() == typeof(Hediff_ImplantWithLevel)))
                {
                    Level  = (pawn.health.hediffSet.hediffs.First(x => x.GetType() == typeof(Hediff_ImplantWithLevel)) as Hediff_ImplantWithLevel).level;
                    result = true;
                }
                else
                if (pawn.story.traits.HasTrait(TraitDefOf.PsychicSensitivity))
                {
                    result = pawn.story.traits.DegreeOfTrait(TraitDefOf.PsychicSensitivity) > 0;
                    Level  = pawn.story.traits.DegreeOfTrait(TraitDefOf.PsychicSensitivity);
                }
                else
                {
                    TraitDef Corruptionpsyker = DefDatabase <TraitDef> .GetNamedSilentFail("Psyker");

                    if (Corruptionpsyker != null)
                    {
                        result = true;
                        pawn.story.traits.HasTrait(Corruptionpsyker);
                        Level = pawn.story.traits.DegreeOfTrait(Corruptionpsyker);
                    }
                }
                Mult = pawn.GetStatValue(StatDefOf.PsychicSensitivity) * (pawn.needs.mood.CurInstantLevelPercentage - pawn.health.hediffSet.PainTotal);
            }

            /*
             * else
             * {
             *  ToolUserPskyerDefExtension extension = null;
             *  if (pawn.def.HasModExtension<ToolUserPskyerDefExtension>())
             *  {
             *      extension = pawn.def.GetModExtension<ToolUserPskyerDefExtension>();
             *  }
             *  else
             *  if (pawn.kindDef.HasModExtension<ToolUserPskyerDefExtension>())
             *  {
             *      extension = pawn.kindDef.GetModExtension<ToolUserPskyerDefExtension>();
             *  }
             *  if (extension != null)
             *  {
             *      result = true;
             *      Level = extension.Level;
             *  }
             *  if (pawn.needs != null && pawn.needs.mood != null)
             *  {
             *      Mult = pawn.GetStatValue(StatDefOf.PsychicSensitivity) * (pawn.needs.mood.CurInstantLevelPercentage - pawn.health.hediffSet.PainTotal);
             *  }
             *  else
             *  {
             *      Mult = pawn.GetStatValue(StatDefOf.PsychicSensitivity) * (1 - pawn.health.hediffSet.PainTotal);
             *  }
             * }
             */
            return(result);
        }
        public override void Notify_PawnDied()
        {
            IntVec3 spawnLoc = !base.Pawn.Dead ? base.parent.pawn.Position : base.parent.pawn.PositionHeld;
            Map     spawnMap = !base.Pawn.Dead ? base.parent.pawn.Map : base.parent.pawn.MapHeld;

            this.Pawn.def.race.deathActionWorkerClass = typeof(DeathActionWorker_Simple);
            bool fullterm = this.parent.CurStageIndex > this.parent.def.stages.Count - 3;

            if (!fullterm || bursted || spawnMap == null || spawnLoc == null)
            {
                return;
            }
            else
            {
                bursted = true;
                if (spawnMap == null || spawnLoc == null)
                {
                    return;
                }
                else
                {
                    if (countToSpawn == 0)
                    {
                        countToSpawn++;
                    }
                    for (int i = 0; i < countToSpawn; i++)
                    {
                        Pawn pawn = XenomorphSpawnRequest();
                        //    Log.Message(string.Format("Xenomorph to hatch: {0}", pawn.LabelShortCap));
                        pawn.ageTracker.AgeBiologicalTicks    = 0;
                        pawn.ageTracker.AgeChronologicalTicks = 0;
                        Comp_Xenomorph _Xenomorph = pawn.TryGetComp <Comp_Xenomorph>();
                        if (_Xenomorph != null)
                        {
                            _Xenomorph.host = base.parent.pawn.kindDef;
                        }
                        GenSpawn.Spawn(pawn, spawnLoc, spawnMap, 0);
                    }
                    Vector3 vector = spawnLoc.ToVector3Shifted();
                    for (int i = 0; i < 101; i++)
                    {
                        if (Rand.MTBEventOccurs(DustMoteSpawnMTB, 2f, 3.TicksToSeconds()))
                        {
                            MoteMaker.ThrowDustPuffThick(new Vector3(vector.x, 0f, vector.z)
                            {
                                y = AltitudeLayer.MoteOverhead.AltitudeFor()
                            }, spawnMap, 1.5f, HostBloodColour);
                        }
                        if (i == 100)
                        {
                        }
                        if (i % 10 == 0)
                        {
                            FilthMaker.TryMakeFilth(spawnLoc + GenAdj.AdjacentCellsAndInside.RandomElement(), this.Pawn.MapHeld, this.Pawn.RaceProps.BloodDef, this.Pawn.LabelIndefinite(), 1);
                        }
                    }
                    ThingDef motedef = DefDatabase <ThingDef> .GetNamedSilentFail("Mote_BlastExtinguisher");

                    MoteMaker.ThrowExplosionCell(spawnLoc, MyMap, motedef, HostBloodColour);
                    // GenAdj.AdjacentCellsAndInside[i];
                    for (int i2 = 0; i2 < GenAdj.AdjacentCellsAndInside.Length; i2++)
                    {
                        FilthMaker.TryMakeFilth(spawnLoc + GenAdj.AdjacentCellsAndInside[i2], this.Pawn.MapHeld, this.Pawn.RaceProps.BloodDef, this.Pawn.LabelIndefinite(), 1);
                    }
                    string text = TranslatorFormattedStringExtensions.Translate("Xeno_Chestburster_Emerge", base.parent.pawn.LabelShort, this.parent.Part.LabelShort);
                    MoteMaker.ThrowText(spawnLoc.ToVector3(), spawnMap, text, 5f);

                    if (!PlayerKnowledgeDatabase.IsComplete(XenomorphConceptDefOf.RRY_Concept_Chestbursters) && MyMap != null)
                    {
                        LessonAutoActivator.TeachOpportunity(XenomorphConceptDefOf.RRY_Concept_Chestbursters, OpportunityType.Important);
                    }
                    Pawn.health.AddHediff(DefDatabase <HediffDef> .GetNamedSilentFail("RRY_PostBurstWound"), this.parent.Part);
                    Pawn.health.RemoveHediff(this.parent);
                }
            }
        }
 static AchievementTabHelper()
 {
     MainTab = DefDatabase <AchievementTabDef> .GetNamedSilentFail("Main");
 }
示例#18
0
        public CustomPawn ConvertSaveRecordToPawn(SaveRecordPawnV5 record)
        {
            bool partialFailure = false;

            PawnKindDef pawnKindDef = null;

            if (record.pawnKindDef != null)
            {
                pawnKindDef = DefDatabase <PawnKindDef> .GetNamedSilentFail(record.pawnKindDef);

                if (pawnKindDef == null)
                {
                    Logger.Warning("Pawn kind definition for the saved character (" + record.pawnKindDef + ") not found.  Picking a random player colony pawn kind definition.");
                    pawnKindDef = PrepareCarefully.Instance.Providers.Factions.GetPawnKindsForFactionDef(FactionDefOf.PlayerColony).RandomElement();
                    if (pawnKindDef == null)
                    {
                        return(null);
                    }
                }
            }

            ThingDef pawnThingDef = ThingDefOf.Human;

            if (record.thingDef != null)
            {
                ThingDef thingDef = DefDatabase <ThingDef> .GetNamedSilentFail(record.thingDef);

                if (thingDef != null)
                {
                    pawnThingDef = thingDef;
                }
            }

            PawnGenerationRequestWrapper generationRequest = new PawnGenerationRequestWrapper()
            {
                FixedBiologicalAge    = record.biologicalAge,
                FixedChronologicalAge = record.chronologicalAge,
                FixedGender           = record.gender
            };

            if (pawnKindDef != null)
            {
                generationRequest.KindDef = pawnKindDef;
            }
            Pawn source = PawnGenerator.GeneratePawn(generationRequest.Request);

            if (source.health != null)
            {
                source.health.Reset();
            }

            CustomPawn pawn = new CustomPawn(source);

            if (record.id == null)
            {
                pawn.GenerateId();
            }
            else
            {
                pawn.Id = record.id;
            }

            if (record.type != null)
            {
                try {
                    pawn.Type = (CustomPawnType)Enum.Parse(typeof(CustomPawnType), record.type);
                }
                catch (Exception) {
                    pawn.Type = CustomPawnType.Colonist;
                }
            }
            else
            {
                pawn.Type = CustomPawnType.Colonist;
            }

            pawn.Gender = record.gender;
            if (record.age > 0)
            {
                pawn.ChronologicalAge = record.age;
                pawn.BiologicalAge    = record.age;
            }
            if (record.chronologicalAge > 0)
            {
                pawn.ChronologicalAge = record.chronologicalAge;
            }
            if (record.biologicalAge > 0)
            {
                pawn.BiologicalAge = record.biologicalAge;
            }

            pawn.FirstName = record.firstName;
            pawn.NickName  = record.nickName;
            pawn.LastName  = record.lastName;

            if (record.originalFactionDef != null)
            {
                pawn.OriginalFactionDef = DefDatabase <FactionDef> .GetNamedSilentFail(record.originalFactionDef);
            }
            pawn.OriginalKindDef = pawnKindDef;

            if (pawn.Type == CustomPawnType.World)
            {
                if (record.faction != null)
                {
                    if (record.faction.def != null)
                    {
                        FactionDef factionDef = DefDatabase <FactionDef> .GetNamedSilentFail(record.faction.def);

                        if (factionDef != null)
                        {
                            bool randomFaction = false;
                            if (record.faction.index != null)
                            {
                                CustomFaction customFaction = null;
                                if (!record.faction.leader)
                                {
                                    customFaction = PrepareCarefully.Instance.Providers.Factions.FindCustomFactionByIndex(factionDef, record.faction.index.Value);
                                }
                                else
                                {
                                    customFaction = PrepareCarefully.Instance.Providers.Factions.FindCustomFactionWithLeaderOptionByIndex(factionDef, record.faction.index.Value);
                                }
                                if (customFaction != null)
                                {
                                    pawn.Faction = customFaction;
                                }
                                else
                                {
                                    Logger.Warning("Could not place at least one preset character into a saved faction because there were not enough available factions of that type in the world");
                                    randomFaction = true;
                                }
                            }
                            else
                            {
                                randomFaction = true;
                            }
                            if (randomFaction)
                            {
                                CustomFaction customFaction = PrepareCarefully.Instance.Providers.Factions.FindRandomCustomFactionByDef(factionDef);
                                if (customFaction != null)
                                {
                                    pawn.Faction = customFaction;
                                }
                            }
                        }
                        else
                        {
                            Logger.Warning("Could not place at least one preset character into a saved faction because that faction is not available in the world");
                        }
                    }
                }
            }

            HairDef h = DefDatabase <HairDef> .GetNamedSilentFail(record.hairDef);

            if (h != null)
            {
                pawn.HairDef = h;
            }
            else
            {
                Logger.Warning("Could not load hair definition \"" + record.hairDef + "\"");
                partialFailure = true;
            }

            pawn.HeadGraphicPath = record.headGraphicPath;
            if (pawn.Pawn.story != null)
            {
                pawn.Pawn.story.hairColor = record.hairColor;
            }

            if (record.melanin >= 0.0f)
            {
                pawn.MelaninLevel = record.melanin;
            }
            else
            {
                pawn.MelaninLevel = PawnColorUtils.FindMelaninValueFromColor(record.skinColor);
            }

            Backstory backstory = FindBackstory(record.childhood);

            if (backstory != null)
            {
                pawn.Childhood = backstory;
            }
            else
            {
                Log.Warning("Could not load childhood backstory definition \"" + record.childhood + "\"");
                partialFailure = true;
            }
            if (record.adulthood != null)
            {
                backstory = FindBackstory(record.adulthood);
                if (backstory != null)
                {
                    pawn.Adulthood = backstory;
                }
                else
                {
                    Log.Warning("Could not load adulthood backstory definition \"" + record.adulthood + "\"");
                    partialFailure = true;
                }
            }

            BodyTypeDef bodyType = null;

            try {
                bodyType = DefDatabase <BodyTypeDef> .GetNamedSilentFail(record.bodyType);
            }
            catch (Exception) {
            }
            if (bodyType == null)
            {
                if (pawn.Adulthood != null)
                {
                    bodyType = pawn.Adulthood.BodyTypeFor(pawn.Gender);
                }
                else
                {
                    bodyType = pawn.Childhood.BodyTypeFor(pawn.Gender);
                }
            }
            if (bodyType != null)
            {
                pawn.BodyType = bodyType;
            }

            // Load pawn comps
            //Logger.Debug("pre-copy comps xml: " + record.compsXml);
            String compsXml = "<saveable Class=\"" + typeof(PawnCompsLoader).FullName + "\">" + record.compsXml + "</saveable>";
            PawnCompInclusionRules rules = new PawnCompInclusionRules();

            rules.IncludeComps(record.savedComps);
            UtilityCopy.DeserializeExposable <PawnCompsLoader>(compsXml, new object[] { pawn.Pawn, rules });
            Dictionary <string, ThingComp> compLookup = new Dictionary <string, ThingComp>();

            foreach (var c in pawn.Pawn.AllComps)
            {
                if (!compLookup.ContainsKey(c.GetType().FullName))
                {
                    //Logger.Debug("Added comp to comp lookup with key: " + c.GetType().FullName);
                    compLookup.Add(c.GetType().FullName, c);
                }
            }
            HashSet <string> savedComps = record.savedComps != null ? new HashSet <string>(record.savedComps) : new HashSet <string>();

            DefaultPawnCompRules.PostLoadModifiers.Apply(pawn.Pawn, compLookup, savedComps);

            pawn.ClearTraits();
            if (record.traits != null)
            {
                for (int i = 0; i < record.traits.Count; i++)
                {
                    string traitName = record.traits[i].def;
                    Trait  trait     = FindTrait(traitName, record.traits[i].degree);
                    if (trait != null)
                    {
                        pawn.AddTrait(trait);
                    }
                    else
                    {
                        Logger.Warning("Could not load trait definition \"" + traitName + "\"");
                        partialFailure = true;
                    }
                }
            }
            else if (record.traitNames != null && record.traitDegrees != null && record.traitNames.Count == record.traitDegrees.Count)
            {
                for (int i = 0; i < record.traitNames.Count; i++)
                {
                    string traitName = record.traitNames[i];
                    Trait  trait     = FindTrait(traitName, record.traitDegrees[i]);
                    if (trait != null)
                    {
                        pawn.AddTrait(trait);
                    }
                    else
                    {
                        Logger.Warning("Could not load trait definition \"" + traitName + "\"");
                        partialFailure = true;
                    }
                }
            }

            foreach (var skill in record.skills)
            {
                SkillDef def = FindSkillDef(pawn.Pawn, skill.name);
                if (def == null)
                {
                    Logger.Warning("Could not load skill definition \"" + skill.name + "\" from saved preset");
                    partialFailure = true;
                    continue;
                }
                pawn.currentPassions[def]  = skill.passion;
                pawn.originalPassions[def] = skill.passion;
                pawn.SetOriginalSkillLevel(def, skill.value);
                pawn.SetUnmodifiedSkillLevel(def, skill.value);
            }

            foreach (var layer in PrepareCarefully.Instance.Providers.PawnLayers.GetLayersForPawn(pawn))
            {
                if (layer.Apparel)
                {
                    pawn.SetSelectedApparel(layer, null);
                    pawn.SetSelectedStuff(layer, null);
                }
            }
            List <PawnLayer> apparelLayers = PrepareCarefully.Instance.Providers.PawnLayers.GetLayersForPawn(pawn).FindAll((layer) => { return(layer.Apparel); });

            foreach (var apparelRecord in record.apparel)
            {
                // Find the pawn layer for the saved apparel record.
                PawnLayer layer = apparelLayers.FirstOrDefault((apparelLayer) => { return(apparelLayer.Name == apparelRecord.layer); });
                if (layer == null)
                {
                    Logger.Warning("Could not find a matching pawn layer for the saved apparel \"" + apparelRecord.layer + "\"");
                    partialFailure = true;
                    continue;
                }
                if (apparelRecord.apparel.NullOrEmpty())
                {
                    Logger.Warning("Saved apparel entry for layer \"" + apparelRecord.layer + "\" had an empty apparel def");
                    partialFailure = true;
                    continue;
                }
                // Set the defaults.
                pawn.SetSelectedApparel(layer, null);
                pawn.SetSelectedStuff(layer, null);
                pawn.SetColor(layer, Color.white);

                ThingDef def = DefDatabase <ThingDef> .GetNamedSilentFail(apparelRecord.apparel);

                if (def == null)
                {
                    Logger.Warning("Could not load thing definition for apparel \"" + apparelRecord.apparel + "\"");
                    partialFailure = true;
                    continue;
                }
                ThingDef stuffDef = null;
                if (!string.IsNullOrEmpty(apparelRecord.stuff))
                {
                    stuffDef = DefDatabase <ThingDef> .GetNamedSilentFail(apparelRecord.stuff);

                    if (stuffDef == null)
                    {
                        Logger.Warning("Could not load stuff definition \"" + apparelRecord.stuff + "\" for apparel \"" + apparelRecord.apparel + "\"");
                        partialFailure = true;
                        continue;
                    }
                }
                pawn.SetSelectedApparel(layer, def);
                pawn.SetSelectedStuff(layer, stuffDef);
                pawn.SetColor(layer, apparelRecord.color);
            }

            OptionsHealth healthOptions = PrepareCarefully.Instance.Providers.Health.GetOptions(pawn);

            for (int i = 0; i < record.implants.Count; i++)
            {
                SaveRecordImplantV3 implantRecord  = record.implants[i];
                UniqueBodyPart      uniqueBodyPart = healthOptions.FindBodyPartByName(implantRecord.bodyPart, implantRecord.bodyPartIndex != null ? implantRecord.bodyPartIndex.Value : 0);
                if (uniqueBodyPart == null)
                {
                    uniqueBodyPart = FindReplacementBodyPart(healthOptions, implantRecord.bodyPart);
                }
                if (uniqueBodyPart == null)
                {
                    Logger.Warning("Could not add the implant because it could not find the needed body part \"" + implantRecord.bodyPart + "\""
                                   + (implantRecord.bodyPartIndex != null ? " with index " + implantRecord.bodyPartIndex : ""));
                    partialFailure = true;
                    continue;
                }
                BodyPartRecord bodyPart = uniqueBodyPart.Record;
                if (implantRecord.recipe != null)
                {
                    RecipeDef recipeDef = FindRecipeDef(implantRecord.recipe);
                    if (recipeDef == null)
                    {
                        Logger.Warning("Could not add the implant because it could not find the recipe definition \"" + implantRecord.recipe + "\"");
                        partialFailure = true;
                        continue;
                    }
                    bool found = false;
                    foreach (var p in recipeDef.appliedOnFixedBodyParts)
                    {
                        if (p.defName.Equals(bodyPart.def.defName))
                        {
                            found = true;
                            break;
                        }
                    }
                    if (!found)
                    {
                        Logger.Warning("Could not apply the saved implant recipe \"" + implantRecord.recipe + "\" to the body part \"" + bodyPart.def.defName + "\".  Recipe does not support that part.");
                        partialFailure = true;
                        continue;
                    }
                    Implant implant = new Implant();
                    implant.BodyPartRecord = bodyPart;
                    implant.recipe         = recipeDef;
                    implant.label          = implant.Label;
                    pawn.AddImplant(implant);
                }
            }

            foreach (var injuryRecord in record.injuries)
            {
                HediffDef def = DefDatabase <HediffDef> .GetNamedSilentFail(injuryRecord.hediffDef);

                if (def == null)
                {
                    Logger.Warning("Could not add the injury because it could not find the hediff definition \"" + injuryRecord.hediffDef + "\"");
                    partialFailure = true;
                    continue;
                }
                InjuryOption option = healthOptions.FindInjuryOptionByHediffDef(def);
                if (option == null)
                {
                    Logger.Warning("Could not add the injury because it could not find a matching injury option for the saved hediff \"" + injuryRecord.hediffDef + "\"");
                    partialFailure = true;
                    continue;
                }
                BodyPartRecord bodyPart = null;
                if (injuryRecord.bodyPart != null)
                {
                    UniqueBodyPart uniquePart = healthOptions.FindBodyPartByName(injuryRecord.bodyPart,
                                                                                 injuryRecord.bodyPartIndex != null ? injuryRecord.bodyPartIndex.Value : 0);
                    if (uniquePart == null)
                    {
                        uniquePart = FindReplacementBodyPart(healthOptions, injuryRecord.bodyPart);
                    }
                    if (uniquePart == null)
                    {
                        Logger.Warning("Could not add the injury because it could not find the needed body part \"" + injuryRecord.bodyPart + "\""
                                       + (injuryRecord.bodyPartIndex != null ? " with index " + injuryRecord.bodyPartIndex : ""));
                        partialFailure = true;
                        continue;
                    }
                    bodyPart = uniquePart.Record;
                }
                Injury injury = new Injury();
                injury.Option         = option;
                injury.BodyPartRecord = bodyPart;
                if (injuryRecord.severity != null)
                {
                    injury.Severity = injuryRecord.Severity;
                }
                if (injuryRecord.painFactor != null)
                {
                    injury.PainFactor = injuryRecord.PainFactor;
                }
                pawn.AddInjury(injury);
            }

            pawn.CopySkillsAndPassionsToPawn();
            pawn.ClearPawnCaches();

            return(pawn);
        }
示例#19
0
		public static List<Thing> generateThing(double valueBase, string resourceOfThing)
		{
			regen:
			List<Thing> things = new List<Thing>();
			ThingSetMaker thingSetMaker = new ThingSetMaker_MarketValue();
			ThingSetMakerParams param = new ThingSetMakerParams();
			param.totalMarketValueRange = new FloatRange((float)(valueBase-300),(float)(valueBase+300));
			param.filter = new ThingFilter();
			param.techLevel = FactionColonies.getPlayerColonyFaction().def.techLevel;

			switch (resourceOfThing)
			{
				case "food": //food
					param.filter.SetAllow(ThingCategoryDefOf.FoodMeals, true);
					param.countRange = new IntRange(1, 1);
					break;
				case "weapons": //weapons
					param.filter.SetAllow(ThingCategoryDefOf.Weapons, true);
					param.qualityGenerator = QualityGenerator.Gift;
					param.totalMarketValueRange = new FloatRange((float)(valueBase - valueBase*.5), (float)(valueBase * 2));
					param.countRange = new IntRange(1, 1);
					break;
				case "apparel": //apparel
					param.filter.SetAllow(ThingCategoryDefOf.Apparel, true);
					param.qualityGenerator = QualityGenerator.Gift;
					param.totalMarketValueRange = new FloatRange((float)(valueBase - valueBase * .5), (float)(valueBase * 2));
					param.countRange = new IntRange(1, 1);
					break;
				case "armor": //armor
					param.qualityGenerator = QualityGenerator.Gift;
					param.filter.SetAllow(DefDatabase<ThingCategoryDef>.GetNamed("ApparelArmor"), true);
					param.filter.SetAllow(ThingCategoryDefOf.Apparel, true);
					param.countRange = new IntRange(1, 1);
					param.totalMarketValueRange = new FloatRange((float)(valueBase - valueBase * .5), (float)(valueBase*2));
					break;
				case "animals": //animals
					thingSetMaker = new ThingSetMaker_Animal();
					param.techLevel = TechLevel.Undefined;
					param.totalMarketValueRange = new FloatRange((float)(valueBase - valueBase * .5), (float)(valueBase * 1.5));
					//param.countRange = new IntRange(1,4);
					break;
				case "logging": //Logging
					param.filter.SetAllow(ThingDefOf.WoodLog, true);
					param.countRange = new IntRange(1, 10);
					break;
				case "mining": //Mining
					param.filter.SetAllow(StuffCategoryDefOf.Metallic, true);
					param.filter.SetAllow(ThingDefOf.Silver, false);
					//Android shit?
					param.filter.SetAllow(DefDatabase<ThingDef>.GetNamedSilentFail("Teachmat"), false);
					//Remove RimBees Beeswax
					param.filter.SetAllow(DefDatabase<StuffCategoryDef>.GetNamedSilentFail("RB_Waxy"), false);
					//Remove Alpha Animals skysteel
					param.filter.SetAllow(DefDatabase<ThingDef>.GetNamedSilentFail("AA_SkySteel"), false);
					param.countRange = new IntRange(1, 10);
					break;
				case "drugs": //drugs
					param.filter.SetAllow(ThingCategoryDefOf.Drugs, true);
					param.countRange = new IntRange(1, 2);
					break;
				default: //log error
					Log.Message("This is an error. Report this to the dev. generateThing - nonexistent case");
					Log.Message(resourceOfThing);
					break;
			}

			//Log.Message(resourceID.ToString());


			//thingSetMaker.root
			things = thingSetMaker.Generate(param);
			if(PaymentUtil.returnValueOfTithe(things) < param.totalMarketValueRange.Value.min)
			{
				goto regen;
			}

			return things;
		}
示例#20
0
        public override void DoWindowContents(Rect rect)
        {
            float x = 0f;

            Text.Font = GameFont.Small;

            // row count:
            Rect thingCount = new Rect(3f, 40f, 200f, 30f);

            Widgets.Label(thingCount, "koisama.Numbers.Count".Translate() + ": " + Pawns.Count());

            //pawn selector
            Rect sourceButton = new Rect(x, 0f, buttonWidth, buttonHeight);

            DoButton(PawnTableDef.label, optionsMaker.PawnSelector(), ref x);
            TooltipHandler.TipRegion(sourceButton, new TipSignal("koisama.Numbers.ClickToToggle".Translate(), sourceButton.GetHashCode()));

            //stats
            DoButton("TabStats".Translate(), optionsMaker.OptionsMakerForGenericDef(StatDefs), ref x);

            //worktypes
            if (PawnTableDef == NumbersDefOf.Numbers_MainTable)
            {
                DoButton(workTabName, optionsMaker.FloatMenuOptionsFor(DefDatabase <PawnColumnDef> .AllDefsListForReading.Where(pcd => pcd.workType != null).Reverse()), ref x);
            }

            //skills
            if (new[] { NumbersDefOf.Numbers_Enemies, NumbersDefOf.Numbers_Prisoners, NumbersDefOf.Numbers_MainTable }.Contains(PawnTableDef))
            {
                DoButton("Skills".Translate(), optionsMaker.OptionsMakerForGenericDef(DefDatabase <SkillDef> .AllDefsListForReading), ref x);
            }

            //needs btn (for living things)
            if (!new[] { NumbersDefOf.Numbers_AnimalCorpses, NumbersDefOf.Numbers_Corpses }.Contains(PawnTableDef))
            {
                DoButton("TabNeeds".Translate(), optionsMaker.OptionsMakerForGenericDef(NeedDefs), ref x);
            }

            //cap btn (for living things)
            if (!new[] { NumbersDefOf.Numbers_AnimalCorpses, NumbersDefOf.Numbers_Corpses }.Contains(PawnTableDef))
            {
                List <PawnColumnDef> optionalList = new List <PawnColumnDef>();

                if (new[] { NumbersDefOf.Numbers_MainTable, NumbersDefOf.Numbers_Prisoners, NumbersDefOf.Numbers_Animals }.Contains(PawnTableDef))
                {
                    optionalList.Add(DefDatabase <PawnColumnDef> .GetNamedSilentFail("MedicalCare"));
                    optionalList.Add(DefDatabase <PawnColumnDef> .GetNamedSilentFail("Numbers_Operations"));

                    if (PawnTableDef == NumbersDefOf.Numbers_MainTable)
                    {
                        optionalList.Add(DefDatabase <PawnColumnDef> .GetNamedSilentFail("Numbers_SelfTend"));
                    }
                }

                optionalList.AddRange(HealthStats);

                var tmp = optionsMaker.OptionsMakerForGenericDef(DefDatabase <PawnCapacityDef> .AllDefsListForReading)
                          .Concat(optionsMaker.FloatMenuOptionsFor(optionalList));

                DoButton("TabHealth".Translate(), tmp.ToList(), ref x);
            }

            //abilities btn
            if (ModLister.RoyaltyInstalled)
            {
                DoButton("Abilities".Translate(), optionsMaker.OptionsMakerForGenericDef(DefDatabase <AbilityDef> .AllDefsListForReading.OrderBy(y => y.label)), ref x);
            }

            //records btn
            DoButton("TabRecords".Translate(), optionsMaker.OptionsMakerForGenericDef(DefDatabase <RecordDef> .AllDefsListForReading), ref x);

            //other btn
            DoButton("MiscRecordsCategory".Translate(), optionsMaker.OtherOptionsMaker(), ref x);

            //presets button
            float startPositionOfPresetsButton = Mathf.Max(rect.xMax - buttonWidth - Margin, x);
            Rect  addPresetBtn = new Rect(startPositionOfPresetsButton, 0f, buttonWidth, buttonHeight);

            if (Widgets.ButtonText(addPresetBtn, "koisama.Numbers.SetPresetLabel".Translate()))
            {
                Find.WindowStack.Add(new FloatMenu(optionsMaker.PresetOptionsMaker()));
            }

            base.DoWindowContents(rect);
        }
示例#21
0
        public bool Load(PrepareCarefully loadout, string presetName)
        {
            List <SaveRecordPawnV3>             pawns              = new List <SaveRecordPawnV3>();
            List <SaveRecordPawnV3>             hiddenPawns        = new List <SaveRecordPawnV3>();
            List <SaveRecordRelationshipV3>     savedRelationships = new List <SaveRecordRelationshipV3>();
            List <SaveRecordParentChildGroupV3> parentChildGroups  = new List <SaveRecordParentChildGroupV3>();

            Failed = false;
            int  startingPoints = 0;
            bool usePoints      = false;

            try {
                Scribe.loader.InitLoading(PresetFiles.FilePathForSavedPreset(presetName));

                Scribe_Values.Look <bool>(ref usePoints, "usePoints", true, false);
                Scribe_Values.Look <int>(ref startingPoints, "startingPoints", 0, false);
                Scribe_Values.Look <string>(ref ModString, "mods", "", false);

                try {
                    Scribe_Collections.Look <SaveRecordPawnV3>(ref pawns, "colonists", LookMode.Deep, null);
                }
                catch (Exception e) {
                    Messages.Message("EdB.PC.Dialog.Preset.Error.Failed".Translate(), MessageTypeDefOf.ThreatBig);
                    Logger.Warning("Error while loading preset", e);
                    Logger.Warning("Preset was created with the following mods: " + ModString);
                    return(false);
                }

                try {
                    Scribe_Collections.Look <SaveRecordPawnV3>(ref hiddenPawns, "hiddenPawns", LookMode.Deep, null);
                }
                catch (Exception e) {
                    Messages.Message("EdB.PC.Dialog.Preset.Error.Failed".Translate(), MessageTypeDefOf.ThreatBig);
                    Logger.Warning("Error while loading preset", e);
                    Logger.Warning("Preset was created with the following mods: " + ModString);
                    return(false);
                }

                try {
                    Scribe_Collections.Look <SaveRecordRelationshipV3>(ref savedRelationships, "relationships", LookMode.Deep, null);
                }
                catch (Exception e) {
                    Messages.Message("EdB.PC.Dialog.Preset.Error.Failed".Translate(), MessageTypeDefOf.ThreatBig);
                    Logger.Warning("Error while loading preset", e);
                    Logger.Warning("Preset was created with the following mods: " + ModString);
                    return(false);
                }

                try {
                    Scribe_Collections.Look <SaveRecordParentChildGroupV3>(ref parentChildGroups, "parentChildGroups", LookMode.Deep, null);
                }
                catch (Exception e) {
                    Messages.Message("EdB.PC.Dialog.Preset.Error.Failed".Translate(), MessageTypeDefOf.ThreatBig);
                    Logger.Warning("Error while loading preset", e);
                    Logger.Warning("Preset was created with the following mods: " + ModString);
                    return(false);
                }

                List <SaveRecordEquipmentV3> tempEquipment = new List <SaveRecordEquipmentV3>();
                Scribe_Collections.Look <SaveRecordEquipmentV3>(ref tempEquipment, "equipment", LookMode.Deep, null);
                loadout.Equipment.Clear();
                if (tempEquipment != null)
                {
                    List <EquipmentSelection> equipment = new List <EquipmentSelection>(tempEquipment.Count);
                    foreach (var e in tempEquipment)
                    {
                        ThingDef thingDef = DefDatabase <ThingDef> .GetNamedSilentFail(e.def);

                        if (thingDef == null)
                        {
                            string replacementDefName;
                            if (thingDefReplacements.TryGetValue(e.def, out replacementDefName))
                            {
                                thingDef = DefDatabase <ThingDef> .GetNamedSilentFail(replacementDefName);
                            }
                        }
                        ThingDef stuffDef = null;
                        Gender   gender   = Gender.None;
                        if (!string.IsNullOrEmpty(e.stuffDef))
                        {
                            stuffDef = DefDatabase <ThingDef> .GetNamedSilentFail(e.stuffDef);
                        }
                        if (!string.IsNullOrEmpty(e.gender))
                        {
                            try {
                                gender = (Gender)Enum.Parse(typeof(Gender), e.gender);
                            }
                            catch (Exception) {
                                Logger.Warning("Failed to load gender value for animal.");
                                Failed = true;
                                continue;
                            }
                        }
                        if (thingDef != null)
                        {
                            if (string.IsNullOrEmpty(e.stuffDef))
                            {
                                EquipmentKey    key    = new EquipmentKey(thingDef, null, gender);
                                EquipmentRecord record = PrepareCarefully.Instance.EquipmentDatabase.LookupEquipmentRecord(key);
                                if (record != null)
                                {
                                    equipment.Add(new EquipmentSelection(record, e.count));
                                }
                                else
                                {
                                    Logger.Warning("Could not find equipment in equipment database: " + key);
                                    Failed = true;
                                    continue;
                                }
                            }
                            else
                            {
                                if (stuffDef != null)
                                {
                                    EquipmentKey    key    = new EquipmentKey(thingDef, stuffDef, gender);
                                    EquipmentRecord record = PrepareCarefully.Instance.EquipmentDatabase.LookupEquipmentRecord(key);
                                    if (record == null)
                                    {
                                        string thing = thingDef != null ? thingDef.defName : "null";
                                        string stuff = stuffDef != null ? stuffDef.defName : "null";
                                        Logger.Warning(string.Format("Could not load equipment/resource from the preset.  This may be caused by an invalid thing/stuff combination: " + key));
                                        Failed = true;
                                        continue;
                                    }
                                    else
                                    {
                                        equipment.Add(new EquipmentSelection(record, e.count));
                                    }
                                }
                                else
                                {
                                    Logger.Warning("Could not load stuff definition \"" + e.stuffDef + "\" for item \"" + e.def + "\"");
                                    Failed = true;
                                }
                            }
                        }
                        else
                        {
                            Logger.Warning("Could not load thing definition \"" + e.def + "\"");
                            Failed = true;
                        }
                    }
                    loadout.Equipment.Clear();
                    foreach (var e in equipment)
                    {
                        loadout.Equipment.Add(e);
                    }
                }
                else
                {
                    Messages.Message("EdB.PC.Dialog.Preset.Error.EquipmentFailed".Translate(), MessageTypeDefOf.ThreatBig);
                    Logger.Warning("Failed to load equipment from preset");
                    Failed = true;
                }

                //PrepareCarefully.Instance.Config.pointsEnabled = usePoints;
            }
            catch (Exception e) {
                Logger.Error("Failed to load preset file");
                throw e;
            }
            finally {
                PresetLoader.ClearSaveablesAndCrossRefs();
            }

            List <CustomPawn> allPawns            = new List <CustomPawn>();
            List <CustomPawn> colonistCustomPawns = new List <CustomPawn>();

            try {
                foreach (SaveRecordPawnV3 p in pawns)
                {
                    CustomPawn pawn = LoadPawn(p);
                    if (pawn != null)
                    {
                        allPawns.Add(pawn);
                        colonistCustomPawns.Add(pawn);
                    }
                    else
                    {
                        Messages.Message("EdB.PC.Dialog.Preset.Error.NoCharacter".Translate(), MessageTypeDefOf.ThreatBig);
                        Logger.Warning("Preset was created with the following mods: " + ModString);
                    }
                }
            }
            catch (Exception e) {
                Messages.Message("EdB.PC.Dialog.Preset.Error.Failed".Translate(), MessageTypeDefOf.ThreatBig);
                Logger.Warning("Error while loading preset", e);
                Logger.Warning("Preset was created with the following mods: " + ModString);
                return(false);
            }

            List <CustomPawn> hiddenCustomPawns = new List <CustomPawn>();

            try {
                if (hiddenPawns != null)
                {
                    foreach (SaveRecordPawnV3 p in hiddenPawns)
                    {
                        CustomPawn pawn = LoadPawn(p);
                        if (pawn != null)
                        {
                            allPawns.Add(pawn);
                            hiddenCustomPawns.Add(pawn);
                        }
                        else
                        {
                            Logger.Warning("Failed to load a hidden character from the preset");
                        }
                    }
                }
            }
            catch (Exception e) {
                Messages.Message("EdB.PC.Dialog.Preset.Error.Failed".Translate(), MessageTypeDefOf.ThreatBig);
                Logger.Warning("Error while loading preset", e);
                Logger.Warning("Preset was created with the following mods: " + ModString);
                return(false);
            }

            loadout.ClearPawns();
            foreach (CustomPawn p in colonistCustomPawns)
            {
                loadout.AddPawn(p);
            }
            loadout.RelationshipManager.Clear();
            loadout.RelationshipManager.InitializeWithCustomPawns(colonistCustomPawns.AsEnumerable().Concat(hiddenCustomPawns));

            bool atLeastOneRelationshipFailed          = false;
            List <CustomRelationship> allRelationships = new List <CustomRelationship>();

            if (savedRelationships != null)
            {
                try {
                    foreach (SaveRecordRelationshipV3 r in savedRelationships)
                    {
                        if (string.IsNullOrEmpty(r.source) || string.IsNullOrEmpty(r.target) || string.IsNullOrEmpty(r.relation))
                        {
                            atLeastOneRelationshipFailed = true;
                            Logger.Warning("Failed to load a custom relationship from the preset: " + r);
                            continue;
                        }
                        CustomRelationship relationship = LoadRelationship(r, allPawns);
                        if (relationship == null)
                        {
                            atLeastOneRelationshipFailed = true;
                            Logger.Warning("Failed to load a custom relationship from the preset: " + r);
                        }
                        else
                        {
                            allRelationships.Add(relationship);
                        }
                    }
                }
                catch (Exception e) {
                    Messages.Message("EdB.PC.Dialog.Preset.Error.RelationshipFailed".Translate(), MessageTypeDefOf.ThreatBig);
                    Logger.Warning("Error while loading preset", e);
                    Logger.Warning("Preset was created with the following mods: " + ModString);
                    return(false);
                }
                if (atLeastOneRelationshipFailed)
                {
                    Messages.Message("EdB.PC.Dialog.Preset.Error.RelationshipFailed".Translate(), MessageTypeDefOf.ThreatBig);
                }
            }
            loadout.RelationshipManager.AddRelationships(allRelationships);

            if (parentChildGroups != null)
            {
                foreach (var groupRecord in parentChildGroups)
                {
                    ParentChildGroup group = new ParentChildGroup();
                    if (groupRecord.parents != null)
                    {
                        foreach (var id in groupRecord.parents)
                        {
                            CustomPawn parent = FindPawnById(id, colonistCustomPawns, hiddenCustomPawns);
                            if (parent != null)
                            {
                                var pawn = parent;
                                if (pawn != null)
                                {
                                    group.Parents.Add(pawn);
                                }
                                else
                                {
                                    Logger.Warning("Could not load a custom parent relationship because it could not find a matching pawn in the relationship manager.");
                                }
                            }
                            else
                            {
                                Logger.Warning("Could not load a custom parent relationship because it could not find a pawn with the saved identifer.");
                            }
                        }
                    }
                    if (groupRecord.children != null)
                    {
                        foreach (var id in groupRecord.children)
                        {
                            CustomPawn child = FindPawnById(id, colonistCustomPawns, hiddenCustomPawns);
                            if (child != null)
                            {
                                var pawn = child;
                                if (pawn != null)
                                {
                                    group.Children.Add(pawn);
                                }
                                else
                                {
                                    Logger.Warning("Could not load a custom child relationship because it could not find a matching pawn in the relationship manager.");
                                }
                            }
                            else
                            {
                                Logger.Warning("Could not load a custom child relationship because it could not find a pawn with the saved identifer.");
                            }
                        }
                    }
                    loadout.RelationshipManager.ParentChildGroups.Add(group);
                }
            }
            loadout.RelationshipManager.ReassignHiddenPawnIndices();

            if (Failed)
            {
                Messages.Message(ModString, MessageTypeDefOf.SilentInput);
                Messages.Message("EdB.PC.Dialog.Preset.Error.ThingDefFailed".Translate(), MessageTypeDefOf.ThreatBig);
                Logger.Warning("Preset was created with the following mods: " + ModString);
                return(false);
            }

            return(true);
        }
        // Fill the cell
        private void TrySetCellAs(IntVec3 c, Map map, ThingDef thingDef, Rot4 thingRot, ThingDef stuffDef = null, TerrainDef terrainDef = null,
                                  PawnKindDef pawnKindDef = null, ThingDef itemDef = null, MapGeneratorBlueprintDef blueprint = null)
        {
            //Note: Here is no functionality to clear the cell by design, because it is possible to place items that are larger than 1x1

            // Check the cell information
            if (c == null || !c.InBounds(map))
            {
                Log.Warning("GenStep_CreateBlueprint: Invalid Target-Cell: cell is null or out of bounds.");
                return;
            }

            // only continue to do work if here isn't anything indestructable
            List <Thing> thingList = c.GetThingList(map);

            for (int i = 0; i < thingList.Count; i++)
            {
                if (!thingList[i].def.destroyable)
                {
                    return;
                }
            }

            // 1st step - work with the Terrain
            if (terrainDef != null)
            {
                map.terrainGrid.SetTerrain(c, terrainDef);
            }
            else if (terrainDef == null && thingDef != null && stuffDef != null)
            {
                map.terrainGrid.SetTerrain(c, this.CorrespondingTileDef(stuffDef));
            }

            // 2nd step - work with the Thing (Buildings)
            if (thingDef != null)
            {
                ThingDef stuffDef1 = stuffDef;

                if (!thingDef.MadeFromStuff)
                {
                    stuffDef1 = null;
                }

                Thing newThing = ThingMaker.MakeThing(thingDef, stuffDef1);
                if (thingRot == null || thingRot == Rot4.Invalid)
                {
                    GenSpawn.Spawn(newThing, c, map);
                }
                else
                {
                    GenSpawn.Spawn(newThing, c, map, thingRot);
                }

                CompGatherSpot compGathering = newThing.TryGetComp <CompGatherSpot>();
                if (compGathering != null)
                {
                    compGathering.Active = false;
                }
            }

            // The following needs blueprint data to work
            if (blueprint == null)
            {
                return;
            }

            // 3rd step - work with the Item
            //if (itemDef != null) // && blueprint.itemSpawnChance / 100 > Rand.Value)
            if (itemDef != null && blueprint.itemSpawnChance / 100 > Rand.Value)
            {
                ThingDef stuffDef2;
                if (itemDef.IsApparel)
                {
                    if (!DefDatabase <ThingDef> .AllDefs.Where <ThingDef>(t => t.IsStuff &&
                                                                          t.stuffProps != null && t.stuffProps.categories != null && t.stuffProps.categories.Contains(StuffCategoryDefOf.Fabric))
                        .TryRandomElement(out stuffDef2))
                    {
                        stuffDef2 = DefDatabase <ThingDef> .GetNamedSilentFail("Synthread");
                    }
                }
                else
                {
                    List <string> stuffPossibles = new List <string>()
                    {
                        "Steel", "Steel", "Steel", "Steel", "Silver", "Gold", "Jade", "Plasteel"
                    };
                    stuffDef2 = DefDatabase <ThingDef> .GetNamedSilentFail(stuffPossibles.RandomElement());
                }

                if (!itemDef.MadeFromStuff)
                {
                    stuffDef2 = null;
                }

                Thing newItem = TryGetTreasure(itemDef, stuffDef2);
                newItem = GenSpawn.Spawn(newItem, c, map);
                // don't forget to forbid the item!
                newItem.SetForbidden(true, false);
            }


            // 4th step - work with the Pawn
            if (pawnKindDef != null && blueprint.pawnSpawnChance / 100 > Rand.Value)
            {
                if (this.faction == null)
                {
                    this.faction = Find.FactionManager.FirstFactionOfDef(blueprint.factionDef);
                }

                float pointsForRaid = map.IncidentPointsRandomFactorRange.RandomInRange;

                // still null - find a valid faction.
                if (this.faction == null)
                {
                    switch (blueprint.factionSelection)
                    {
                    case FactionSelection.friendly:
                        faction = (from fac in Find.FactionManager.AllFactions
                                   where !fac.HostileTo(Faction.OfPlayer) && fac.PlayerGoodwill > 0 && !(fac == Faction.OfPlayer)
                                   select fac)
                                  .RandomElementByWeight((Faction fac) => 101 - fac.def.RaidCommonalityFromPoints(pointsForRaid));

                        if (faction == null)
                        {
                            faction = Find.FactionManager.AllFactions.RandomElementByWeight((Faction fac) => fac.def.RaidCommonalityFromPoints(pointsForRaid));
                        }

                        break;

                    case FactionSelection.hostile:
                        faction = (from fac in Find.FactionManager.AllFactions
                                   where fac.HostileTo(Faction.OfPlayer)
                                   select fac)
                                  .RandomElementByWeight((Faction fac) => 101 - fac.def.RaidCommonalityFromPoints(pointsForRaid));

                        if (faction == null)
                        {
                            faction = Faction.OfMechanoids;
                        }

                        break;

                    case FactionSelection.none:
                        faction = Find.FactionManager.AllFactions
                                  .RandomElementByWeight((Faction fac) => fac.def.RaidCommonalityFromPoints(pointsForRaid));

                        if (faction == null)
                        {
                            faction = Faction.OfMechanoids;
                        }

                        break;
                    }
                }

                Pawn pawn = PawnGenerator.GeneratePawn(pawnKindDef, faction);
                pawn.mindState.Active = false;
                pawn = GenSpawn.Spawn(pawn, c, map) as Pawn;

                if (pawn != null)
                {
                    if (allSpawnedPawns == null)
                    {
                        allSpawnedPawns = new List <Pawn>();
                    }

                    allSpawnedPawns.Add(pawn);
                }
            }
        }
示例#23
0
        private void FoundAnomaly()
        {
            int tile;

            if (!TryFindNewAnomalyTile(out tile))
            {
                return;
            }

            Site site;
            bool spacerUsable = false;

            if (Rand.Chance(Props.chanceForNoSitePart))
            {
                site         = SiteMaker.TryMakeSite(GetRandomSiteCoreDef(), null, false, null);
                spacerUsable = true;
            }
            else
            {
                site = SiteMaker.TryMakeSite(GetRandomSiteCoreDef(), GetRandomSitePartDefs, true, null);
            }

            // if spacerUsable -> 35% chance that the faction is spacer
            if (site != null && spacerUsable && Rand.Chance(0.35f))
            {
                Faction spacerFaction = null;
                if ((from x in Find.FactionManager.AllFactionsListForReading
                     where x.def == FactionDefOf.Spacer || x.def == FactionDefOf.SpacerHostile
                     select x).TryRandomElement(out spacerFaction))
                {
                    site.SetFaction(spacerFaction);
                }
            }

            if (site != null)
            {
                // Try to add a railgun :)
                Thing    railgun    = null;
                ThingDef railgunDef = DefDatabase <ThingDef> .GetNamedSilentFail(railgunDefName);

                if (railgunDef != null &&
                    site.Faction != null && site.Faction.def.techLevel >= TechLevel.Industrial &&
                    Rand.Value < 0.10)
                {
                    railgun = ThingMaker.MakeThing(railgunDef);
                }


                List <Thing> items = null;
                // Improved Sensors -> Add Items
                if (HasImprovedSensors)
                {
                    ItemStashContentsComp itemStash = site.GetComponent <ItemStashContentsComp>();
                    if (itemStash != null && site.core.defName == defName_ItemStash)
                    {
                        items = GenerateItems(site.Faction);
                        itemStash.contents.TryAddRangeOrTransfer(items);

                        if (railgun != null)
                        {
                            itemStash.contents.TryAdd(railgun);
                        }
                    }
                }


                site.Tile = tile;
                Find.WorldObjects.Add(site);
                Find.LetterStack.ReceiveLetter("TacticalComputer_LetterLabel_AnomalyFound".Translate(), "TacticalComputer_Message_AnomalyFound".Translate(), LetterDefOf.PositiveEvent, site);

                // Add a site timeout ???
                site.GetComponent <TimeoutComp>().StartTimeout(Rand.RangeInclusive(15, 60) * 60000);
            }
        }
示例#24
0
        private static void MoveRecipesToSmithy()
        {
            movedDefs = 0;
            foreach (var td in DefDatabase <ThingDef> .AllDefs.Where(t =>
                                                                     (t?.recipeMaker?.recipeUsers?.Contains(ThingDef.Named("FueledSmithy")) ?? false) ||
                                                                     (t?.recipeMaker?.recipeUsers?.Contains(ThingDef.Named("TableMachining")) ?? false)))
            {
                //td.recipeMaker.recipeUsers.RemoveAll(x => x.defName == "TableMachining" ||
                //                                          x.defName == "FueledSmithy");
                td.recipeMaker.recipeUsers.Add(ThingDef.Named("LotR_TableSmithy"));
                movedDefs++;
            }

            foreach (var rd in DefDatabase <RecipeDef> .AllDefs.Where(d =>
                                                                      (d.recipeUsers?.Contains(ThingDef.Named("TableMachining")) ?? false) ||
                                                                      (d.recipeUsers?.Contains(ThingDef.Named("FueledSmithy")) ?? false)))
            {
                //rd.recipeUsers.RemoveAll(x => x.defName == "TableMachining" ||
                //                                          x.defName == "FueledSmithy");
                rd.recipeUsers.Add(ThingDef.Named("LotR_TableSmithy"));
                movedDefs++;
            }

            Log.Message("Moved " + movedDefs + " from Machining Table to Smithy.");

            if (!ModStuff.Settings.LimitTechnology ||
                ModLister.GetActiveModWithIdentifier("CETeam.CombatExtended".ToLower()) == null)
            {
                return;
            }

            var ammoRecipiesToAdd = new List <string>
            {
                "MakeAmmo_LotRE_Arrow_Galadhrim",
                "MakeAmmo_LotRE_Arrow_Mirkwood",
                "MakeAmmo_LotRE_Arrow_Rivendell",
                "MakeAmmo_LotRD_Bolt"
            };

            foreach (var recipieDefName in ammoRecipiesToAdd)
            {
                var recipieDef = DefDatabase <RecipeDef> .GetNamedSilentFail(recipieDefName);

                recipieDef?.recipeUsers.Add(ThingDef.Named("ElectricSmithy"));
            }

            var things = from thing in DefDatabase <ThingDef> .AllDefs where thing.tradeTags != null select thing;

            foreach (var thing in things)
            {
                var tags = thing.tradeTags.ToArray();
                foreach (var tag in tags)
                {
                    if (tag.StartsWith("CE_AutoEnableCrafting_"))
                    {
                        thing.tradeTags.Remove(tag);
                    }
                }
            }

            var enumerable = new List <Def> {
                DefDatabase <ResearchTabDef> .GetNamed("CE_Turrets")
            };
            var rm = Traverse.Create(typeof(DefDatabase <ResearchTabDef>)).Method("Remove", enumerable.First());

            foreach (var def in enumerable)
            {
                rm.GetValue(def);
            }
        }
        private static void CreateSubCategories()
        {
            Logger.Debug("Creating subcategories");
            foreach (DesignationSubCategoryDef category in DefDatabase <DesignationSubCategoryDef> .AllDefsListForReading
                     )
            {
                if (category.debug)
                {
                    Logger.Message("Creating subcategory {0} in category {1}", category.LabelCap,
                                   category.designationCategory);
                }

                // cop out if main cat not found
                if (category.designationCategory == null)
                {
                    Logger.Warning("Category {0} not found! Skipping.", category.designationCategory);
                    continue;
                }

                // set up sub category
                var designators = new List <Designator_Build>();

                // keep track of best position for the subcategory - it will replace the first subitem in the original category.
                int firstDesignatorIndex = -1;

                // get list of current designators in the category
                List <Designator> resolvedDesignators = category.designationCategory.AllResolvedDesignators;

                // start adding designators to the subcategory
                if (category.defNames != null)
                {
                    foreach (string defName in category.defNames)
                    {
                        BuildableDef bdef = DefDatabase <ThingDef> .GetNamedSilentFail(defName) ??
                                            (BuildableDef)DefDatabase <TerrainDef> .GetNamedSilentFail(defName);

                        // do some common error checking
                        // buildable def exists
                        if (bdef == null)
                        {
                            if (category.debug)
                            {
                                Logger.Warning("ThingDef {0} not found! Skipping.", defName);
                            }
                            continue;
                        }

                        // find the designator for this buildabledef
                        DesignationCategoryDef designatorCategory;
                        var bdefDesignator = FindDesignator(bdef, out designatorCategory);
                        if (category.debug && bdefDesignator == null)
                        {
                            Log.Warning("No designator found with matching entity def! Skipping.");
                        }

                        // if not null, add designator to the subcategory, and remove from main category
                        if (bdefDesignator != null)
                        {
                            // if taken designator was in the same category as the new subcategory, find index and update FirstDesignatorIndex
                            if (designatorCategory == category.designationCategory)
                            {
                                int index = resolvedDesignators.IndexOf(bdefDesignator);
                                if (firstDesignatorIndex < 0 || index < firstDesignatorIndex)
                                {
                                    firstDesignatorIndex = index;
                                }
                            }

                            designators.Add(bdefDesignator);
                            HideDesignator(bdefDesignator);

                            if (category.debug)
                            {
                                Logger.Message("ThingDef {0} passed checks and was added to subcategory.", defName);
                            }
                        }
                        // done with this designator
                    }
                }

                // check if any designators were added to subdesignator
                if (!designators.NullOrEmpty())
                {
                    // create subcategory
                    var subCategory = new Designator_SubCategory(category, designators);

                    // insert to replace first designator removed, or just add at the end if taken from different categories
                    if (firstDesignatorIndex >= 0)
                    {
                        resolvedDesignators.Insert(firstDesignatorIndex, subCategory);
                    }
                    else
                    {
                        resolvedDesignators.Add(subCategory);
                    }

                    if (category.debug)
                    {
                        Logger.Message("Subcategory {0} created.", subCategory.LabelCap);
                    }
                }
                else if (category.debug)
                {
                    Logger.Warning("Subcategory {0} did not have any (resolved) contents! Skipping.", category.LabelCap);
                }
            }
        }
示例#26
0
        public PanelAppearance()
        {
            // Organize stuff by its category
            Dictionary <StuffCategoryDef, HashSet <ThingDef> > stuffByCategory = new Dictionary <StuffCategoryDef, HashSet <ThingDef> >();

            foreach (ThingDef thingDef in DefDatabase <ThingDef> .AllDefs)
            {
                if (thingDef.IsStuff && thingDef.stuffProps != null)
                {
                    foreach (StuffCategoryDef cat in thingDef.stuffProps.categories)
                    {
                        HashSet <ThingDef> thingDefs = null;
                        if (!stuffByCategory.TryGetValue(cat, out thingDefs))
                        {
                            thingDefs = new HashSet <ThingDef>();
                            stuffByCategory.Add(cat, thingDefs);
                        }
                        thingDefs.Add(thingDef);
                    }
                }
            }

            // Get material definitions so that we can use them for sorting later.
            ThingDef synthreadDef = DefDatabase <ThingDef> .GetNamedSilentFail("Synthread");

            ThingDef devilstrandDef = DefDatabase <ThingDef> .GetNamedSilentFail("DevilstrandCloth");

            ThingDef hyperweaveDef = DefDatabase <ThingDef> .GetNamedSilentFail("Hyperweave");

            // For each apparel def, get the list of all materials that can be used to make it.
            foreach (ThingDef thingDef in DefDatabase <ThingDef> .AllDefs)
            {
                if (thingDef.apparel != null && thingDef.MadeFromStuff)
                {
                    if (thingDef.stuffCategories != null)
                    {
                        List <ThingDef> stuffList = new List <ThingDef>();
                        foreach (var cat in thingDef.stuffCategories)
                        {
                            HashSet <ThingDef> thingDefs;
                            if (stuffByCategory.TryGetValue(cat, out thingDefs))
                            {
                                foreach (ThingDef stuffDef in thingDefs)
                                {
                                    stuffList.Add(stuffDef);
                                }
                            }
                        }
                        stuffList.Sort((ThingDef a, ThingDef b) => {
                            if (a != b)
                            {
                                if (a == synthreadDef)
                                {
                                    return(-1);
                                }
                                else if (b == synthreadDef)
                                {
                                    return(1);
                                }
                                else if (a == ThingDefOf.Cloth)
                                {
                                    return(-1);
                                }
                                else if (b == ThingDefOf.Cloth)
                                {
                                    return(1);
                                }
                                else if (a == devilstrandDef)
                                {
                                    return(-1);
                                }
                                else if (b == devilstrandDef)
                                {
                                    return(1);
                                }
                                else if (a == hyperweaveDef)
                                {
                                    return(-1);
                                }
                                else if (b == hyperweaveDef)
                                {
                                    return(1);
                                }
                                else
                                {
                                    return(a.LabelCap.Resolve().CompareTo(b.LabelCap.Resolve()));
                                }
                            }
                            else
                            {
                                return(0);
                            }
                        });
                        apparelStuffLookup[thingDef] = stuffList;
                    }
                }
            }

            // Set up default skin colors
            foreach (Color color in PawnColorUtils.Colors)
            {
                skinColors.Add(color);
            }

            this.ChangePawnLayer(null);
        }
        public static void Postfix(ref Apparel apparel, BodyTypeDef bodyType, ref ApparelGraphicRecord rec)
        {
            /*
             * bool Pauldron = apparel.TryGetCompFast<CompPauldronDrawer>() != null;
             * if (Pauldron)
             * {
             * //	Log.Message("Updating pad graphics for "+apparel.LabelShortCap);
             *      for (int i = 0; i < apparel.GetComps<CompPauldronDrawer>().Count(); i++)
             *      {
             *      //	Log.Message("Pauldron drawer "+(i+1));
             *              CompPauldronDrawer comp = apparel.GetComps<CompPauldronDrawer>().ElementAt(i);
             *              if (!comp.activeEntries.NullOrEmpty())
             *              {
             *                      for (int i2 = 0; i2 < comp.activeEntries.Count; i2++)
             *                      {
             *                      //	Log.Message("Entry drawer " + (i2 + 1));
             *                              comp.activeEntries[i2].UpdatePadGraphic();
             *                      }
             *              }
             *      }
             * }
             */
            string mskVariant = "";

            if (apparel is ApparelComposite composite)
            {
                if (!composite.AltGraphics.NullOrEmpty() && composite.ActiveAltGraphic != null)
                {
                    rec.graphic = composite.ActiveAltGraphic.GetGraphic(rec.graphic, true);
                    Graphic graphic = GraphicDatabase.Get <Graphic_Multi>(composite.WornGraphicPath, apparel.def.apparel.useWornGraphicMask ? ShaderDatabase.CutoutComplex : ShaderDatabase.Cutout, apparel.def.graphicData.drawSize, composite.DrawColor, composite.DrawColorTwo);
                    if (!composite.ActiveAltGraphic.maskKey.NullOrEmpty())
                    {
                        mskVariant = "_" + composite.ActiveAltGraphic.maskKey;
                    }
                    rec = new ApparelGraphicRecord(graphic, apparel);
                }
            }
            CompColorableTwo compColorable = apparel.TryGetCompFast <CompColorableTwo>();

            if (compColorable != null)
            {
                //	Log.Message("CompColorableTwo "+ apparel);
                string comptype   = compColorable.GetType().Name;
                string msg        = string.Empty;
                string mskFaction = string.Empty;
                CompColorableTwoFaction factionColors = compColorable as CompColorableTwoFaction;
                Color colorOne = compColorable.Color;
                Color colorTwo = compColorable.ColorTwo;

                if (factionColors != null)
                {
                    if (apparel.Wearer.Faction != null)
                    {
                        if (apparel.Wearer.Faction != Faction.OfPlayer)
                        {
                            factionColors.FactionDef = apparel.Wearer.Faction?.def;
                            msg += " entry for Non Player Pawn using FactionDef " + factionColors.FactionDef;
                        }
                        else
                        {
                            if (factionColors.FactionDef != null)
                            {
                                msg += " entry for Player Pawn using FactionDef " + factionColors.FactionDef;
                            }
                            else
                            {
                                /*
                                 * CompPauldronDrawer pauldrons = apparel.TryGetCompFast<CompPauldronDrawer>();
                                 * if (pauldrons != null)
                                 * {
                                 *      for (int i = 0; i < pauldrons.activeEntries.Count; i++)
                                 *      {
                                 *              ShoulderPadEntry entry = pauldrons.activeEntries[i];
                                 *              if (entry.faction != null && entry.UseFactionTextures || entry.UseFactionColors)
                                 *              {
                                 *                      factionColors.FactionDef = entry.faction;
                                 *                      msg += " entry for Player Pawn using FactionDef " + factionColors.FactionDef;
                                 *                      break;
                                 *              }
                                 *
                                 *      }
                                 * }
                                 * else
                                 * {
                                 *      //	Log.Message("CompFactionColorableTwo Player Pawn no CompPauldronDrawer");
                                 * }
                                 */
                            }
                        }
                    }
                    if (factionColors.Active)
                    {
                        //	Log.Message("factionColors.Active");
                        colorOne = factionColors.Color;
                        apparel.SetColorOne(colorOne);
                    }
                    if (factionColors.ActiveTwo)
                    {
                        //	Log.Message("factionColors.ActiveTwo");
                        colorTwo = factionColors.ColorTwo;
                        apparel.SetColorTwo(colorTwo);
                    }
                    if (factionColors.Extension != null)
                    {
                        //	Log.Message("factionColors.Extension != null");
                        if (factionColors.ActiveTwo || factionColors.Active)
                        {
                            if (!factionColors.Extension.factionMaskTag.NullOrEmpty())
                            {
                                //	Log.Message("factionColors.factionMaskTag");
                                mskFaction = "_" + factionColors.Extension.factionMaskTag;
                                //	Log.Message("factionMaskTag: "+msk);
                            }
                        }
                    }
                    // msg
                    if (factionColors.ActiveFaction)
                    {
                        comptype += "FactionActive: " + factionColors.FactionActive + ", FactionActiveTwo: " + factionColors.FactionActiveTwo;
                    }
                    else
                    {
                        comptype += "Active: " + factionColors.Active + ", ActiveTwo: " + factionColors.ActiveTwo;
                    }
                }
                else
                {
                    comptype += "Active: " + compColorable.Active + ", ActiveTwo: " + compColorable.ActiveTwo;
                }

                //	Log.Message(comptype + msg + " present on " + apparel.Wearer +"'s "+ apparel + " colorOne: " + colorOne + ", colorTwo: " + colorTwo);
                //	Log.Message("New graphic for "+rec.sourceApparel.LabelCap+" worn by "+rec.sourceApparel.Wearer.NameShortColored+ " colorOne: "+colorOne+", colorTwo"+ colorTwo);
                if (rec.graphic != null)
                {
                    Graphic newgraphic = rec.graphic.GetColoredVersion(rec.graphic.Shader, colorOne, colorTwo);
                    bool    replaced   = false;
                    if (!apparel.def.apparel.wornGraphicPath.NullOrEmpty())
                    {
                        Graphic replace = AdeptusApparelUtility.ApplyMask(newgraphic, apparel, colorOne, colorTwo, mskVariant, mskFaction);
                        replaced = replace != null;
                        if (replaced)
                        {
                            newgraphic = replace;
                            rec        = new ApparelGraphicRecord(newgraphic, apparel);
                        }
                    }
                    if (!rec.graphic.path.NullOrEmpty())
                    {
                        Texture texture = ContentFinder <Texture2D> .Get(rec.graphic.path + mskFaction, false);

                        if (texture != null)
                        {
                            newgraphic.MatSingle.SetTexture(ShaderPropertyIDs.MaskTex, texture);
                        }
                        newgraphic.MatEast.SetColor(ShaderPropertyIDs.ColorTwo, colorTwo);
                    }
                }
                //	Log.Message(comptype + msg + " present on " + apparel.Wearer +"'s "+ apparel + " colorOne: " + colorOne + ", colorTwo: " + colorTwo);
            }
            if (!apparel.def.apparel.wornGraphicPath.NullOrEmpty())
            {
                if (apparel.def.GetModExtensionFast <ApparelRestrictionDefExtension>() is ApparelRestrictionDefExtension apparelExt)
                {
                    if (!apparelExt.raceSpecifics.NullOrEmpty())
                    {
                        foreach (var item in apparelExt.raceSpecifics)
                        {
                            ThingDef RaceDef = DefDatabase <ThingDef> .GetNamedSilentFail(item.raceDef);

                            if (RaceDef == null)
                            {
                                continue;
                            }
                            if (RaceDef == apparel.Wearer.def)
                            {
                                if (!item.texPath.NullOrEmpty())
                                {
                                    string path;
                                    if (apparel.def.apparel.LastLayer == ApparelLayerDefOf.Overhead || PawnRenderer.RenderAsPack(apparel) || apparel.def.apparel.wornGraphicPath == BaseContent.PlaceholderImagePath)
                                    {
                                        path = apparel.def.apparel.wornGraphicPath + "_" + item.texPath;
                                    }
                                    else
                                    {
                                        path = apparel.def.apparel.wornGraphicPath + "_" + item.texPath + "_" + bodyType.defName;
                                    }
                                    Graphic graphic = GraphicDatabase.Get <Graphic_Multi>(path, apparel.def.apparel.useWornGraphicMask ? ShaderDatabase.CutoutComplex : ShaderDatabase.Cutout, apparel.def.graphicData.drawSize, rec.graphic.color, rec.graphic.colorTwo);
                                    rec = new ApparelGraphicRecord(graphic, apparel);
                                }
                                break;
                            }
                        }
                    }
                }
            }

            /*
             * for (int i = 0; i < apparel.AllComps.Count; i++)
             * {
             *      CompPauldronDrawer drawer = apparel.AllComps[i] as CompPauldronDrawer;
             * if (drawer != null)
             * {
             *              drawer.
             * }
             *
             * }
             */
            apparel.BroadcastCompSignal(CompPauldronDrawer.UpdateString);
        }
        public static void FSCompat_DrawBackHairLayer(object __instance,
                                                      ref Vector3 hairLoc,
                                                      RotDrawMode bodyDrawType,
                                                      Quaternion headQuat,
                                                      ref bool renderBody,
                                                      ref bool portrait)
        //FacialStuff.HumanHeadDrawer __instance
        {
            Type t_HumanHeadDrawer = GenTypes.GetTypeInAnyAssembly("FacialStuff.HumanHeadDrawer");

            try
            {
                if (t_HumanHeadDrawer != null)
                {
                    FacialStuff.HumanHeadDrawer this_HumanHeadDrawer = (FacialStuff.HumanHeadDrawer)__instance;
                    //-------------------------REPLICATED FACIAL STUFF CODE-------------------------
                    PawnGraphicSet curGraphics = Traverse.Create(this_HumanHeadDrawer).Field("Graphics").GetValue <PawnGraphicSet>();
                    if (!curGraphics.AllResolved)
                    {
                        curGraphics.ResolveAllGraphics();
                    }

                    Graphic_Multi_BHair hairGraphicExtended = curGraphics.hairGraphic as Graphic_Multi_BHair;
                    if (hairGraphicExtended != null)
                    {
                        Mesh     hairMesh      = this_HumanHeadDrawer.GetPawnHairMesh(portrait);
                        Rot4     curHeadFacing = Traverse.Create(this_HumanHeadDrawer).Field("HeadFacing").GetValue <Rot4>();
                        Material hairMat       = hairGraphicExtended.BackMatAt(curHeadFacing);

                        if (hairMat != null)
                        {
                            List <ApparelGraphicRecord> apparelGraphics  = curGraphics.apparelGraphics;
                            List <ApparelGraphicRecord> headgearGraphics = null;
                            if (!apparelGraphics.NullOrEmpty())
                            {
                                headgearGraphics = apparelGraphics
                                                   .Where(x => x.sourceApparel.def.apparel.LastLayer == ApparelLayerDefOf.Overhead ||
                                                          x.sourceApparel.def.apparel.LastLayer == DefDatabase <ApparelLayerDef> .GetNamedSilentFail("OnHead") ||
                                                          x.sourceApparel.def.apparel.LastLayer == DefDatabase <ApparelLayerDef> .GetNamedSilentFail("StrappedHead") ||
                                                          x.sourceApparel.def.apparel.LastLayer == DefDatabase <ApparelLayerDef> .GetNamedSilentFail("MiddleHead")).ToList();
                            }

                            FacialStuff.CompBodyAnimator animator = this_HumanHeadDrawer.CompAnimator;

                            bool noRenderGoggles = FacialStuff.Controller.settings.FilterHats;

                            bool showRoyalHeadgear = this_HumanHeadDrawer.Pawn.royalty?.MostSeniorTitle != null && FacialStuff.Controller.settings.ShowRoyalHeadgear;
                            bool noRenderRoofed    = animator != null && animator.HideHat && !showRoyalHeadgear;
                            bool noRenderBed       = FacialStuff.Controller.settings.HideHatInBed && !renderBody && !showRoyalHeadgear;
                            //-------------------------REPLICATED FACIAL STUFF CODE-------------------------



                            hairLoc.y        = tempBaseDrawLocY;
                            tempBaseDrawLocY = 0;



                            if (!headgearGraphics.NullOrEmpty())
                            {
                                //-------------------------REPLICATED FACIAL STUFF CODE-------------------------
                                bool filterHeadgear = portrait && Prefs.HatsOnlyOnMap || !portrait && noRenderRoofed;

                                // Draw regular hair if appparel or environment allows it (FS feature)
                                if (bodyDrawType != RotDrawMode.Dessicated)
                                {
                                    // draw full or partial hair
                                    bool apCoversFullHead =
                                        headgearGraphics.Any(
                                            x => x.sourceApparel.def.apparel.bodyPartGroups.Contains(BodyPartGroupDefOf
                                                                                                     .FullHead) &&
                                            !x.sourceApparel.def.apparel.hatRenderedFrontOfFace);

                                    bool apCoversUpperHead =
                                        headgearGraphics.Any(
                                            x => x.sourceApparel.def.apparel.bodyPartGroups.Contains(BodyPartGroupDefOf
                                                                                                     .UpperHead) &&
                                            !x.sourceApparel.def.apparel.hatRenderedFrontOfFace);
                                    //-------------------------REPLICATED FACIAL STUFF CODE-------------------------

                                    if (this_HumanHeadDrawer.CompFace.Props.hasOrganicHair || noRenderBed || filterHeadgear ||
                                        (!apCoversFullHead && !apCoversUpperHead && noRenderGoggles))
                                    {
                                        GenDraw.DrawMeshNowOrLater(hairMesh, hairLoc, headQuat, hairMat, portrait);
                                    }

                                    /*
                                     * else if (FacialStuff.Controller.settings.MergeHair) // && !apCoversFullHead)
                                     * {
                                     *  // If not, display the hair cut
                                     *  FacialStuff.HairCut.HairCutPawn hairPawn = FacialStuff.HairCut.CutHairDB.GetHairCache(this_HumanHeadDrawer.Pawn);
                                     *  Material hairCutMat = hairPawn.HairCutMatAt(curHeadFacing);
                                     *  if (hairCutMat != null)
                                     *  {
                                     *      GenDraw.DrawMeshNowOrLater(hairMesh, hairLoc, headQuat, hairCutMat, portrait);
                                     *  }
                                     * }
                                     */
                                }
                            }
                            else
                            {
                                // Draw regular hair if no hat worn
                                if (bodyDrawType != RotDrawMode.Dessicated)
                                {
                                    GenDraw.DrawMeshNowOrLater(hairMesh, hairLoc, headQuat, hairMat, portrait);
                                }
                            }
                        }
                    }
                }
            }
            catch (TypeLoadException) { }
        }
示例#29
0
        private void ScatterBlueprintAt(IntVec3 loc, Map map, MapGeneratorBlueprintDef blueprint, ref ThingDef wallStuff, HashSet <IntVec3> listOfUsedCells)
        {
            CellRect mapRect = new CellRect(loc.x, loc.z, blueprint.size.x, blueprint.size.z);
            CellRect mapRectCheck4Neighbor = mapRect.ExpandedBy(1);

            mapRect.ClipInsideMap(map);

            // if mapRect was clipped -> the blueprint doesn't fit inside the map...
            if (mapRect.Width != blueprint.size.x || mapRect.Height != blueprint.size.z)
            {
                return;
            }

            // Check if we will build on a usedCell
            bool usedCellFound = false;

            foreach (IntVec3 cell in mapRectCheck4Neighbor.Cells) //mapRect.Cells)
            {
                if (listOfUsedCells != null && listOfUsedCells.Contains(cell))
                {
                    usedCellFound = true;
                    break;
                }
            }
            if (usedCellFound)
            {
                return;
            }

            // Don't do anything, if there is an cryosleep casket at the building site
            foreach (IntVec3 current in mapRect.Cells)
            {
                List <Thing> list = map.thingGrid.ThingsListAt(current);
                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i].def == ThingDefOf.AncientCryptosleepCasket)
                    {
                        return;
                    }
                }
                // Don't do anything if there is a pawn (mechanoid? insect?) here
                foreach (Pawn pawn in map.mapPawns.AllPawnsSpawned)
                {
                    if (pawn != null && pawn.Spawned && pawn.Position == current)
                    {
                        return;
                    }
                }
                usedSpots.Add(current); // prevent the base scatterer to use this spot
                usedCells.Add(current);
                usedCells_lastChange = DateTime.UtcNow;
            }

            // Remove this blueprints map cells from the unfogging list
            List <IntVec3> rootsToUnfog = Verse.MapGenerator.rootsToUnfog;

            foreach (IntVec3 cell in mapRect.Cells)
            {
                if (rootsToUnfog != null && rootsToUnfog.Contains(cell))
                {
                    rootsToUnfog.Remove(cell);
                }
            }

            // If a building material is defined, use this
            if (blueprint.buildingMaterial != null && blueprint.buildingMaterial != "")
            {
                wallStuff = DefDatabase <ThingDef> .GetNamedSilentFail(blueprint.buildingMaterial);
            }

            int w = 0;

            while (true)
            {
                w++;
                if (w > 1000)
                {
                    break;
                }

                // Make all buildings from the same random stuff -- In BaseGen use faction, in MapGen use null!
                if (wallStuff == null)
                {
                    wallStuff = BaseGenUtility.RandomCheapWallStuff(null, true); // BaseGenUtility.RandomCheapWallStuff(faction, true);
                }
                //If not specified, don't use wood or leather
                if (blueprint.buildingMaterial != null || (!wallStuff.defName.ToLower().Contains("wood") && !wallStuff.defName.ToLower().Contains("leather")))
                {
                    break;
                }
            }

            MakeBlueprintRoom(mapRect, map, blueprint, wallStuff);

            if (blueprint.createTrigger)
            {
                int    nextSignalTagID = Find.UniqueIDsManager.GetNextSignalTagID();
                string signalTag       = "unfogTriggerSignal-" + nextSignalTagID;
                SignalAction_Letter signalAction_Letter = (SignalAction_Letter)ThingMaker.MakeThing(ThingDefOf.SignalAction_Letter, null);
                signalAction_Letter.signalTag = signalTag;

                if (blueprint.TriggerLetterMessageText != null)
                {
                    if (blueprint.TriggerLetterLabel != null)
                    {
                        signalAction_Letter.letter = LetterMaker.MakeLetter(blueprint.TriggerLetterLabel.Translate(), blueprint.TriggerLetterMessageText.Translate(), blueprint.TriggerLetterDef, new GlobalTargetInfo(mapRect.CenterCell, map, false));
                    }
                    else
                    {
                        signalAction_Letter.letter = LetterMaker.MakeLetter("", blueprint.TriggerLetterMessageText.Translate(), blueprint.TriggerLetterDef, new GlobalTargetInfo(mapRect.CenterCell, map));
                    }

                    GenSpawn.Spawn(signalAction_Letter, mapRect.CenterCell, map);
                }

                RectTrigger_UnfogArea rectTrigger = (RectTrigger_UnfogArea)ThingMaker.MakeThing(ThingDef.Named("RectTrigger_UnfogArea"), null);
                rectTrigger.signalTag         = signalTag;
                rectTrigger.destroyIfUnfogged = true;
                rectTrigger.Rect = mapRect;

                GenSpawn.Spawn(rectTrigger, mapRect.CenterCell, map);
            }
        }
        private Pawn MakePawnWithRawXml(string xml)
        {
            try {
                XmlDocument document = new XmlDocument();
                document.LoadXml(xml);
                //Debug.Message("Pawn xml: {0}", xml);
                XmlNode root = document.FirstChild;

                string      pawnKind = root.SelectSingleNode("kind").InnerText;
                PawnKindDef kindDef  = PawnKindDef.Named(pawnKind);
                if (kindDef == null)
                {
                    kindDef = PawnKindDefOf.AncientSoldier;
                }

                Pawn p = PawnGenerator.GeneratePawn(kindDef, rp.faction);

                // ==== NAME AND AGE ====
                Name name      = null;
                var  nameNode  = root.SelectSingleNode("name");
                var  attrFirst = nameNode.Attributes.GetNamedItem("first");
                var  attrLast  = nameNode.Attributes.GetNamedItem("last");
                var  attrNick  = nameNode.Attributes.GetNamedItem("nick");
                if (attrFirst != null && attrLast != null)
                {
                    name = new NameTriple(attrFirst.Value, attrNick?.Value ?? "", attrLast.Value);
                }
                else
                {
                    name = new NameSingle(attrFirst?.Value ?? "Unknown");
                }
                p.Name = name;
                //Debug.Message("got name");

                string gender = root.SelectSingleNode("gender")?.InnerText;
                if (gender == "Male")
                {
                    p.gender = Gender.Male;
                }
                else if (gender == "Female")
                {
                    p.gender = Gender.Female;
                }

                string bioAgeString    = root.SelectSingleNode("biologicalAge")?.InnerText;
                string chronoAgeString = root.SelectSingleNode("chronologicalAge")?.InnerText;
                if (bioAgeString != null && chronoAgeString != null)
                {
                    long result = 0;
                    Int64.TryParse(bioAgeString, out result);
                    p.ageTracker.AgeBiologicalTicks = result;
                    Int64.TryParse(chronoAgeString, out result);
                    p.ageTracker.AgeChronologicalTicks = result + 3600000 * (-blueprint.dateShift); //+dateShift for dates, -dateShift for ages
                }
                //Debug.Message("got age");


                // ==== STORY AND APPEARANCE ====
                var storyNode = root.SelectSingleNode("saveable[@Class='Pawn_StoryTracker']");
                if (storyNode != null)
                {
                    Backstory bs           = null;
                    string    childhoodDef = storyNode.SelectSingleNode("childhood")?.InnerText;
                    if (BackstoryDatabase.TryGetWithIdentifier(childhoodDef, out bs))
                    {
                        p.story.childhood = bs;
                    }
                    string adulthoodDef = storyNode.SelectSingleNode("adulthood")?.InnerText;
                    if (BackstoryDatabase.TryGetWithIdentifier(adulthoodDef, out bs))
                    {
                        p.story.adulthood = bs;
                    }

                    string bodyTypeDefName = storyNode.SelectSingleNode("bodyType")?.InnerText;
                    if (bodyTypeDefName != null)
                    {
                        BodyTypeDef def = DefDatabase <BodyTypeDef> .GetNamedSilentFail(bodyTypeDefName);

                        if (def != null)
                        {
                            p.story.bodyType = def;
                        }

                        try {
                            string crownTypeName = storyNode.SelectSingleNode("crownType")?.InnerText;
                            p.story.crownType = (CrownType)Enum.Parse(typeof(CrownType), crownTypeName);
                        } catch (Exception) { }

                        string  hairDefName = storyNode.SelectSingleNode("hairDef")?.InnerText;
                        HairDef hairDef     = DefDatabase <HairDef> .GetNamedSilentFail(hairDefName);

                        if (hairDef != null)
                        {
                            p.story.hairDef = hairDef;
                        }

                        float melanin = 0;
                        if (float.TryParse(storyNode.SelectSingleNode("melanin")?.InnerText, out melanin))
                        {
                            p.story.melanin = melanin;
                        }

                        string hairColorString = storyNode.SelectSingleNode("hairColor")?.InnerText;
                        Color  hairColor       = (Color)ParseHelper.FromString(hairColorString, typeof(Color));
                        if (hairColor != null)
                        {
                            p.story.hairColor = hairColor;
                        }
                    }
                    XmlNodeList traitsList = storyNode.SelectNodes("traits/allTraits/li");
                    if (traitsList != null)
                    {
                        p.story.traits.allTraits.RemoveAll(_ => true);
                        foreach (XmlNode traitNode in traitsList)
                        {
                            string traitDefName = traitNode.SelectSingleNode("def")?.InnerText;
                            int    traitDegree  = 0;
                            int.TryParse(traitNode.SelectSingleNode("degree")?.InnerText, out traitDegree);

                            TraitDef traitDef = DefDatabase <TraitDef> .GetNamedSilentFail(traitDefName);

                            if (traitDef == null)
                            {
                                continue;
                            }

                            Trait t = new Trait(traitDef, traitDegree);
                            if (t == null)
                            {
                                continue;
                            }

                            p.story.traits.allTraits.Add(t);
                        }
                    }
                }

                // ==== SKILLS ====
                var skills = root.SelectSingleNode("saveable[@Class='Pawn_SkillTracker']");
                if (skills != null)
                {
                    XmlNodeList skillsList = storyNode.SelectNodes("skills/li");

                    foreach (XmlNode skillNode in skillsList)
                    {
                        string skillDefName = skillNode.SelectSingleNode("def")?.InnerText;
                        int    level        = 0;
                        int.TryParse(skillNode.SelectSingleNode("level")?.InnerText, out level);

                        float xp = 0;
                        float.TryParse(skillNode.SelectSingleNode("xpSinceLastLevel")?.InnerText, out xp);

                        SkillDef skillDef = DefDatabase <SkillDef> .GetNamedSilentFail(skillDefName);

                        if (skillDef == null)
                        {
                            continue;
                        }

                        SkillRecord skillRecord = p.skills.GetSkill(skillDef);
                        if (skillRecord == null)
                        {
                            skillRecord = new SkillRecord(p, skillDef);
                        }

                        skillRecord.Level            = level;
                        skillRecord.xpSinceLastLevel = xp;

                        try {
                            string passionTypeName = skillNode.SelectSingleNode("passion")?.InnerText;
                            if (passionTypeName != null)
                            {
                                skillRecord.passion = (Passion)Enum.Parse(typeof(Passion), passionTypeName);
                            }
                        } catch (Exception) { }
                    }
                }
                //Debug.Message("got traits and skills");

                // ==== HEALTH ====
                var healthNode = root.SelectSingleNode("saveable[@Class='Pawn_HealthTracker']");
                if (healthNode != null)
                {
                    XmlNode healthState = healthNode.SelectSingleNode("healthState");
                    if (healthState?.InnerText == "Dead")
                    {
                        p.health.SetDead();
                    }

                    XmlNodeList hediffsList = healthNode.SelectNodes("hediffSet/hediffs/li");
                    if (hediffsList != null)
                    {
                        Scribe.mode = LoadSaveMode.LoadingVars;
                        p.health?.hediffSet?.hediffs?.RemoveAll(_ => true);
                        //probably should pre-analyze hediffs prior to instantiating
                        foreach (XmlNode hediffNode in hediffsList)
                        {
                            var sourceNode = hediffNode.SelectSingleNode("source");
                            var source     = sourceNode?.InnerText;
                            //Debug.Message("Source is {0} in hediff {1}", source, hediffNode.OuterXml);
                            if (source != null)
                            {
                                ThingDef sourceThingDef = DefDatabase <ThingDef> .GetNamedSilentFail(source);

                                //Debug.Message("Found non-null source node: {0}. Def: {1}", sourceNode.OuterXml, sourceThingDef);
                                if (sourceThingDef == null)
                                {
                                    hediffNode.RemoveChild(sourceNode);
                                    //Debug.Message("def not found, removing node, result: {0}", hediffNode.OuterXml);
                                    //continue; //skip hediffs with unknown source
                                    //} else {
                                    //Debug.Message("def found: {0}", sourceThingDef);
                                }
                            }
                            try {
                                Hediff hediff = ScribeExtractor.SaveableFromNode <Hediff>(hediffNode, null);
                                if (hediff != null)
                                {
                                    if (hediff.source != null && hediff.Part != null)
                                    {
                                        p.health.AddHediff(hediff);
                                    }
                                }
                            } catch (Exception) {
                            }
                        }
                        Scribe.mode = LoadSaveMode.Inactive;
                    }
                }
                //Debug.Message("got health");

                // ==== APPAREL ====
                var apparelNode = root.SelectSingleNode("apparel");
                if (apparelNode != null)
                {
                    XmlNodeList apparelList = apparelNode.SelectNodes("item");
                    foreach (XmlNode item in apparelList)
                    {
                        string defName      = item.Attributes?.GetNamedItem("def")?.Value;
                        string stuffDefName = item.Attributes?.GetNamedItem("stuffDef")?.Value;

                        ThingDef stuffDef = null;
                        ThingDef thingDef = DefDatabase <ThingDef> .GetNamedSilentFail(defName);

                        if (stuffDefName != null)
                        {
                            stuffDef = DefDatabase <ThingDef> .GetNamedSilentFail(stuffDefName);
                        }

                        if (thingDef != null)
                        {
                            Apparel apparel = (Apparel)ThingMaker.MakeThing(thingDef, stuffDef);
                            apparel.HitPoints = Rand.Range(1, (int)(apparel.MaxHitPoints * 0.6));
                            if (apparel is Apparel)
                            {
                                p.apparel.Wear(apparel, false);
                            }
                        }
                    }
                }
                return(p);
            } catch (Exception e) {
                //Debug.Message("Exception while creating pawn: {0}", e);
                return(PawnGenerator.GeneratePawn(PawnKindDefOf.AncientSoldier, rp.faction));
            }
        }