Beispiel #1
0
        public static void ApplyCustomSongs()
        {
            var removeMethod = typeof(DefDatabase <ProgramDef>).GetMethod("Remove", BindingFlags.Static | BindingFlags.NonPublic);

            object[] args = new object[1];
            foreach (var item in addedDefs)
            {
                args[0] = item;
                removeMethod.Invoke(null, args);
            }
            addedDefs.Clear();

            foreach (var item in GenerateValidDefs())
            {
                DefDatabase <ProgramDef> .Add(item);

                addedDefs.Add(item);
            }
            Core.Log($"Registered {addedDefs.Count} custom songs");
            if (addedDefs.Count > 0)
            {
                Messages.Message("DSC.RegisteredSongs".Translate(addedDefs.Count), MessageTypeDefOf.SilentInput);
            }
        }
Beispiel #2
0
        public override void PostExposeData()
        {
            //이미 존재하는 개체
            base.PostExposeData();
            if (Scribe.mode == LoadSaveMode.ResolvingCrossRefs)
            {
                if (JukeBoxCore.orignalSongList.Count > 0)
                {
                    DefDatabase <SongDef> .Clear();

                    DefDatabase <SongDef> .Add(JukeBoxCore.orignalSongList);
                }
                JukeBoxCore.jukeBoxList.Clear();
            }
            if (Scribe.mode == LoadSaveMode.PostLoadInit)
            {
                compPowerTrader = parent.GetComp <CompPowerTrader>();
                if (compPowerTrader.PowerOn)
                {
                    JukeBoxCore.AddJukeBox(this);
                }
                currentState = false;
            }
        }
Beispiel #3
0
        public static void Postfix()
        {
            var moveLabelDown = false;
            DynamicPawnTableDef medicalTable = DynamicPawnTableDefOf.Medical;

            foreach (PawnCapacityDef capacity in DefDatabase <PawnCapacityDef> .AllDefsListForReading)
            {
                var column = new PawnColumnDef_Capacity();
                column.defName       = "PawnColumnDef_" + capacity.defName;
                column.capacity      = capacity;
                column.description   = capacity.description;
                column.label         = capacity.label;
                column.moveLabelDown = moveLabelDown;
                column.sortable      = true;
                column.workerClass   = typeof(PawnColumnWorker_Capacity);

                column.PostLoad();
                DefDatabase <PawnColumnDef> .Add(column);

                medicalTable.columns.Insert(medicalTable.columns.Count - 1, column);

                moveLabelDown = !moveLabelDown;
            }
        }
		public static void CanDoNext_Prefix() {
			if (PokemonConfig.startWith) {
				DefDatabase<PawnKindDef>.Clear ();
				var hashSet = new HashSet<string>();
				foreach (ModContentPack modContentPack in (from m in LoadedModManager.RunningMods orderby m.OverwritePriority select m).ThenBy((ModContentPack x) => LoadedModManager.RunningModsListForReading.IndexOf(x))){
					
					hashSet.Clear();
					foreach (PawnKindDef t in GenDefDatabase.DefsToGoInDatabase<PawnKindDef>(modContentPack)){

						if (!modContentPack.IsCoreMod) {

							if (hashSet.Contains (t.defName)) {
								
								Log.Error (string.Concat (new object[] {
									"Mod ",
									modContentPack,
									" has multiple ",
									typeof(PawnKindDef),
									"s named ",
									t.defName,
									". Skipping."
								}));

							} else {
								
								if (t.defName == "UnnamedDef") {
									
									var text = "Unnamed" + nameof(PawnKindDef) + Rand.Range (1, 100000).ToString () + "A";
									Log.Error (string.Concat(new [] {
										nameof(PawnKindDef),
										" in ",
										modContentPack.ToString (),
										" with label ",
										t.label,
										" lacks a defName. Giving name ",
										text
									}));
									t.defName = text;
								}

								/*PawnKindDef def;
								if (DefDatabase<PawnKindDef>.defsByName.TryGetValue(t.defName, out def)){
										DefDatabase<PawnKindDef>.Remove(def);
								}*/

								DefDatabase<PawnKindDef>.Add (t);
							}
						}
					}
				}
			} else {
				DefDatabase<PawnKindDef>.Clear ();
				var hashSet = new HashSet<string>();
				foreach (ModContentPack modContentPack in (from m in LoadedModManager.RunningMods orderby m.OverwritePriority select m).ThenBy((ModContentPack x) => LoadedModManager.RunningModsListForReading.IndexOf(x))){

				    hashSet.Clear();
				    foreach (PawnKindDef t in GenDefDatabase.DefsToGoInDatabase<PawnKindDef>(modContentPack)){

						if (hashSet.Contains (t.defName)) {

							Log.Error (string.Concat (new object[] {
								"Mod ",
								modContentPack,
								" has multiple ",
								typeof(PawnKindDef),
								"s named ",
								t.defName,
								". Skipping."
							}));

						} else {

							if (t.defName == "UnnamedDef") {

								var text = "Unnamed" + typeof(PawnKindDef).Name + Rand.Range (1, 100000).ToString () + "A";
								Log.Error (string.Concat (new string[] {
									typeof(PawnKindDef).Name,
									" in ",
									modContentPack.ToString (),
									" with label ",
									t.label,
									" lacks a defName. Giving name ",
									text
								}));
								t.defName = text;
							}

							/*PawnKindDef def;
							if (DefDatabase<PawnKindDef>.defsByName.TryGetValue(t.defName, out def)){
									DefDatabase<PawnKindDef>.Remove(def);
							}*/

							DefDatabase<PawnKindDef>.Add (t);
						}
					}
				}
			}
		}
            static void Postfix()
            {
                List <RecipeDef>    list  = DefDatabase <RecipeDef> .AllDefsListForReading;
                List <WorkGiverDef> gList = DefDatabase <WorkGiverDef> .AllDefsListForReading;

                foreach (var rec in list.Where(x => x.AllRecipeUsers.FirstOrDefault(y => y is BuildableDef) != null && x.ingredients.Count() == 1 && x.ingredients[0].filter.AnyAllowedDef.stackLimit < 2))
                {
                    foreach (var rUser in rec.AllRecipeUsers.Where(y => y is BuildableDef))
                    {
                        WorkGiverDef wGiverDef = gList.Where(x => !x.fixedBillGiverDefs.NullOrEmpty() &&
                                                             x.fixedBillGiverDefs.Contains(rUser) &&
                                                             (x.giverClass == typeof(WorkGiver_DoBill) /* || x.giverClass.IsSubclassOf(typeof(WorkGiver_DoBill))*/)).FirstOrDefault();

                        if (wGiverDef == null)
                        {
                            continue;
                        }

                        DesignationDef dDef = DefDatabase <DesignationDef> .AllDefsListForReading.FirstOrDefault(x => x.defName == rec.defName + "Designation");

                        if (dDef == null)
                        {
                            dDef = new DesignationDef()
                            {
                                defName     = rec.defName + "Designation",
                                texturePath = "Designations/Uninstall",
                                iconMat     = MaterialPool.MatFrom("Designations/Uninstall", ShaderDatabase.MetaOverlay),
                                targetType  = TargetType.Thing
                            };
                            DefDatabase <DesignationDef> .Add(dDef);
                        }
                        //Log.Message($"rDef={rec},bDef={rUser},dDef={dDef}");

                        foreach (var def in rec.fixedIngredientFilter.AllowedThingDefs)
                        {
                            def.comps.Add(new CompProperties_ApplicableDesignation()
                            {
                                designationDef = dDef
                            });
                        }

                        string       wgname = $"{wGiverDef.defName}_{rec.defName}_DesignationWorkGiver";
                        WorkGiverDef wgDef  = gList.Where(x => x.defName == wgname).FirstOrDefault();
                        if (wgDef == null)
                        {
                            wgDef = new MicroWorkGiverDef()
                            {
                                recipeDef          = rec,
                                designationDef     = dDef,
                                defName            = wgname,
                                label              = wGiverDef.label,
                                giverClass         = typeof(WorkGiver_MicroRecipe),
                                workType           = wGiverDef.workType,
                                priorityInType     = wGiverDef.priorityInType - 5,
                                verb               = wGiverDef.verb,
                                gerund             = wGiverDef.verb,//wGiverDef.gerund,
                                requiredCapacities = new List <PawnCapacityDef>(wGiverDef.requiredCapacities),
                                prioritizeSustains = wGiverDef.prioritizeSustains
                            };
                            DefDatabase <WorkGiverDef> .Add(wgDef);

                            wgDef.workType.workGiversByPriority.Add(wgDef);
                        }
                    }
                }
            }
Beispiel #6
0
            static AnimalGeneticsAssemblyLoader()
            {
                var h = new Harmony("AnimalGenetics");

                h.PatchAll();

                DefDatabase <StatDef> .Add(AnimalGenetics.Damage);

                DefDatabase <StatDef> .Add(AnimalGenetics.Health);

                DefDatabase <StatDef> .Add(AnimalGenetics.GatherYield);

                var affectedStats = Constants.affectedStatsToInsert;

                foreach (var stat in affectedStats)
                {
                    try
                    {
                        if (stat.parts != null)
                        {
                            stat.parts.Insert(0, new StatPart(stat));
                        }
                    }
                    catch
                    {
                        Log.Error(stat.ToString() + " is broken");
                    }
                }

                gatherableTypes = new List <Type>()
                {
                    typeof(CompShearable),
                    typeof(CompMilkable)
                };

                // Compatibility patches
                try
                {
                    if (LoadedModManager.RunningModsListForReading.Any(x => x.PackageId == "sarg.alphaanimals" || x.Name == "Alpha Animals"))
                    {
                        Log.Message("Animal Genetics : Alpha Animals is loaded - Patching");
                        h.Patch(AccessTools.Method(AccessTools.TypeByName("AlphaBehavioursAndEvents.CompAnimalProduct"), "get_ResourceAmount"),
                                postfix: new HarmonyMethod(typeof(CompatibilityPatches), nameof(CompatibilityPatches.AlphaAnimals_get_ResourceAmount_Patch)));
                        gatherableTypes.Add(AccessTools.TypeByName("AlphaBehavioursAndEvents.CompAnimalProduct"));
                    }
                    if (LoadedModManager.RunningModsListForReading.Any(x => x.PackageId == "CETeam.CombatExtended" || x.Name == "Combat Extended"))
                    {
                        //gatherableTypes.Append(AccessTools.TypeByName("CombatExtended.CompMilkableRenameable")); //they all use shearable
                        gatherableTypes.Add(AccessTools.TypeByName("CombatExtended.CompShearableRenameable"));
                    }
                }
                catch { }

                _DefaultAnimalsPawnTableDefColumns  = new List <PawnColumnDef>(PawnTableDefOf.Animals.columns);
                _DefaultWildlifePawnTableDefColumns = new List <PawnColumnDef>(PawnTableDefOf.Wildlife.columns);

                var placeholderPosition = MainTabWindow_AnimalGenetics.PawnTableDefs.Genetics.columns.FindIndex((PawnColumnDef def) => def.defName == "AnimalGenetics_Placeholder");

                MainTabWindow_AnimalGenetics.PawnTableDefs.Genetics.columns.RemoveAt(placeholderPosition);
                MainTabWindow_AnimalGenetics.PawnTableDefs.Genetics.columns.InsertRange(placeholderPosition, PawnTableColumnsDefOf.Genetics.columns);

                PatchUI();
            }
        public static void Populate()
        {
            List <RecipeDef>    list  = DefDatabase <RecipeDef> .AllDefsListForReading;
            List <WorkGiverDef> gList = DefDatabase <WorkGiverDef> .AllDefsListForReading;

            UnityEngine.Material mat = DesignationDefOf.Uninstall.iconMat;

            foreach (var rec in list.Where(x => x.AllRecipeUsers?.OfType <BuildableDef>().Any() == true &&
                                           x.ingredients?.Count() == 1 &&
                                           x.ingredients[0]?.filter?.AnyAllowedDef?.stackLimit < 2 &&
                                           x.fixedIngredientFilter?.AllowedThingDefs != null))
            {
                foreach (var rUser in rec.AllRecipeUsers.Where(y => y is BuildableDef))
                {
                    IEnumerable <WorkGiverDef> gListSel = gList.Where(x => x.fixedBillGiverDefs?.Contains(rUser) == true &&
                                                                      (x.giverClass == typeof(WorkGiver_DoBill) || x.giverClass.IsSubclassOf(typeof(WorkGiver_DoBill))));

                    if (gListSel == null)
                    {
                        continue;
                    }

                    WorkGiverDef wGiverDef = gListSel.FirstOrDefault();

                    if (wGiverDef == null)
                    {
                        continue;
                    }

                    DesignationDef dDef = DefDatabase <DesignationDef> .AllDefsListForReading.FirstOrDefault(x => x.defName == rec.defName + "Designation");

                    if (dDef == null)
                    {
                        dDef = new DesignationDef()
                        {
                            defName    = rec.defName + "Designation",
                            iconMat    = MaterialPool.MatFrom("Designations/General", ShaderDatabase.MetaOverlay),
                            targetType = TargetType.Thing
                        };

                        DefDatabase <DesignationDef> .Add(dDef);
                    }

                    foreach (var def in rec.fixedIngredientFilter.AllowedThingDefs)
                    {
                        if (def.comps != null)
                        {
                            def.comps.Add(new CompProperties_ApplicableDesignation()
                            {
                                designationDef = dDef
                            });
                        }
                    }

                    string wgname = $"{wGiverDef.defName}_{rec.defName}_DesignationWorkGiver";

                    WorkGiverDef wgDef = null;
                    gListSel = gList.Where(x => x.defName == wgname);

                    if (gListSel != null)
                    {
                        wgDef = gListSel.FirstOrDefault();
                    }

                    if (wgDef == null && wGiverDef.workType != null && wGiverDef.requiredCapacities != null)
                    {
                        JobDef jDef = JobDefOf.DoBill;

                        if (wGiverDef.giverClass != typeof(WorkGiver_DoBill))
                        {
                            RecipeJobDef rj = DefDatabase <RecipeJobDef> .AllDefsListForReading.FirstOrDefault(x => x.defName == rec.defName);

                            if (rj == null)
                            {
                                rj = DefDatabase <RecipeJobDef> .AllDefsListForReading.FirstOrDefault(x => x.workerClass == rec.workerClass);
                            }

                            if (rj == null)
                            {
                                Log.Message($"Couldn't find a proper RecipeJobDef for redefined DoBill task {wGiverDef.defName}");
                                continue;
                            }

                            jDef = DefDatabase <JobDef> .AllDefsListForReading.FirstOrDefault(x => x.defName == rj.jobName);

                            if (jDef == null)
                            {
                                Log.Message($"Couldn't find a JobDef({rj.jobName}) for RecipeJobDef({rj.defName})");
                                continue;
                            }
                        }
                        wgDef = new MicroWorkGiverDef()
                        {
                            workGiverDef       = wGiverDef,
                            recipeDef          = rec,
                            designationDef     = dDef,
                            defName            = wgname,
                            label              = wGiverDef.label,
                            giverClass         = typeof(WorkGiver_MicroRecipe),
                            jobDef             = jDef,
                            workType           = wGiverDef.workType,
                            priorityInType     = wGiverDef.priorityInType - 5,
                            verb               = wGiverDef.verb,
                            gerund             = wGiverDef.verb,
                            requiredCapacities = new List <PawnCapacityDef>(wGiverDef.requiredCapacities),
                            prioritizeSustains = wGiverDef.prioritizeSustains
                        };
                        DefDatabase <WorkGiverDef> .Add(wgDef);

                        wgDef.workType.workGiversByPriority.Add(wgDef);
                    }
                }
            }
        }
        static StaticConstructorClass()
        {
            var recipes = new List <RecipeDef>();

            // Go through each minifiable building's def that is buildable by the player, requires materials, doesn't already have a recipeMaker
            foreach (ThingDef buildingDef in DefDatabase <ThingDef> .AllDefs.Where(d => d.IsBuildingArtificial && d.Minifiable && d.BuildableByPlayer && (d.MadeFromStuff || !d.costList.NullOrEmpty()) && d.recipeMaker == null))
            {
                // Create the new Recipe Def
                var newRecipe = new RecipeDef()
                {
                    defName            = $"{GeneratedRecipeDefPrefix}_{buildingDef.defName}",
                    modContentPack     = CT_RecipeDefOf.BaseCarpentersTableRecipe.modContentPack,
                    label              = $"[{buildingDef.designationCategory.label.ToUpper()}] - {"RecipeMake".Translate(buildingDef.label).CapitalizeFirst()}",
                    jobString          = "RecipeMakeJobString".Translate(buildingDef.label),
                    workSpeedStat      = StatDefOf.ConstructionSpeed,
                    workSkill          = SkillDefOf.Construction,
                    unfinishedThingDef = CT_ThingDefOf.UnfinishedBuilding,
                    recipeUsers        = new List <ThingDef>()
                    {
                        CT_ThingDefOf.TableCarpenter
                    },
                    defaultIngredientFilter = CT_RecipeDefOf.BaseCarpentersTableRecipe.defaultIngredientFilter,
                    effectWorking           = EffecterDefOf.ConstructMetal,
                    soundWorking            = SoundDefOf.Building_Complete,
                    factionPrerequisiteTags = DetermineRecipeFactionPrerequisiteTags(buildingDef.minTechLevelToBuild, buildingDef.maxTechLevelToBuild)
                };

                // Add construction skill requirement if there is any
                if (buildingDef.constructionSkillPrerequisite > 0)
                {
                    var constructionRequirement = new SkillRequirement();
                    constructionRequirement.skill    = SkillDefOf.Construction;
                    constructionRequirement.minLevel = buildingDef.constructionSkillPrerequisite;
                    newRecipe.skillRequirements      = new List <SkillRequirement>()
                    {
                        constructionRequirement
                    };
                }

                // Add ingredient count for building's stuff if applicable
                if (buildingDef.MadeFromStuff)
                {
                    var stuffIngredientCount = new IngredientCount();
                    stuffIngredientCount.SetBaseCount(buildingDef.costStuffCount);
                    stuffIngredientCount.filter.SetAllowAllWhoCanMake(buildingDef);
                    newRecipe.ingredients.Add(stuffIngredientCount);
                    newRecipe.fixedIngredientFilter.SetAllowAllWhoCanMake(buildingDef);
                    newRecipe.productHasIngredientStuff = true;
                }

                // Add ingredient counts for other required materials if applicable
                if (!buildingDef.costList.NullOrEmpty())
                {
                    foreach (ThingDefCountClass normalMaterialCost in buildingDef.costList)
                    {
                        var materialIngredientCount = new IngredientCount();
                        materialIngredientCount.SetBaseCount(normalMaterialCost.count * normalMaterialCost.thingDef.VolumePerUnit);
                        materialIngredientCount.filter.SetAllow(normalMaterialCost.thingDef, true);
                        newRecipe.ingredients.Add(materialIngredientCount);
                    }
                }

                // Add building as the recipe def's product
                newRecipe.products.Add(new ThingDefCountClass(buildingDef, 1));

                // Add the new recipe def to the list of recipes
                recipes.Add(newRecipe);
            }

            // Sort the list of recipes alphabetically and add to the database
            recipes.Sort((d1, d2) => d1.label.CompareTo(d2.label));
            DefDatabase <RecipeDef> .Add(recipes);
        }
Beispiel #9
0
        private static void CreateGuestBedDefs(ThingDef[] bedDefs, CompProperties_Facility[] facilities)
        {
            var sb     = new StringBuilder("Created guest beds for the following beds: ");
            var fields = typeof(ThingDef).GetFields(BindingFlags.Public | BindingFlags.Instance);

            foreach (var bedDef in bedDefs)
            {
                if (bedDef.comps == null || !bedDef.comps.Any(c => c.compClass == typeof(CompAssignableToPawn_Bed)))
                {
                    string mod = bedDef.modContentPack != null ? bedDef.modContentPack.Name : "an unknown mod";
                    Log.Warning($"Not creating guest beds for {bedDef.label} from {mod}. It does not have a CompAssignableToPawn_Bed.");
                    continue;
                }
                var guestBedDef = new ThingDef();

                // Copy fields
                foreach (var field in fields)
                {
                    field.SetValue(guestBedDef, field.GetValue(bedDef));
                }

                CopyComps(guestBedDef, bedDef);

                // Other properties
                guestBedDef.defName            += "Guest";
                guestBedDef.label               = "GuestBedFormat".Translate(guestBedDef.label);
                guestBedDef.thingClass          = typeof(Building_GuestBed);
                guestBedDef.shortHash           = 0;
                guestBedDef.minifiedDef         = bedDef.minifiedDef;
                guestBedDef.tradeability        = Tradeability.None;
                guestBedDef.scatterableOnMapGen = false;
                guestBedDef.tickerType          = TickerType.Long;
                guestBedDef.modContentPack      = GuestUtility.relaxDef.modContentPack;

                typeof(ShortHashGiver).GetMethod("GiveShortHash", BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, new object[] { guestBedDef, typeof(ThingDef) });
                DefDatabase <ThingDef> .Add(guestBedDef);

                sb.Append(bedDef.defName + ", ");

                foreach (var facility in facilities)
                {
                    facility.linkableBuildings.Add(guestBedDef);
                }

                // Royalty
                var titles = DefDatabase <RoyalTitleDef> .AllDefs;
                foreach (var title in titles)
                {
                    if (title.bedroomRequirements == null)
                    {
                        continue;
                    }
                    foreach (var thingAnyOf in title.bedroomRequirements.OfType <RoomRequirement_ThingAnyOf>())
                    {
                        if (thingAnyOf.things.Contains(bedDef))
                        {
                            thingAnyOf.things.Add(guestBedDef);
                        }
                    }
                }
            }
            Log.Message(sb.ToString().TrimEnd(' ', ','));
        }
Beispiel #10
0
        public void Inject()
        {
            Type bed = typeof(Building_Bed);
            Dictionary <string, ThingDef> bedDefs = DefDatabase <ThingDef> .AllDefsListForReading
                                                    .Where(d => !d.defName.StartsWith("Ogre_NanoTech") && bed.IsAssignableFrom(d.thingClass))
                                                    .ToDictionary(x => x.defName, y => y);

            HashSet <string> modSupport = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            List <ThingDef> linkableBuildings         = ThingDef.Named("Ogre_NanoTech_Bed").GetCompProperties <CompProperties_AffectedByFacilities>().linkableFacilities;
            List <CompProperties_Facility> facilities = linkableBuildings
                                                        .Select(x => x.GetCompProperties <CompProperties_Facility>())
                                                        .Where(x => x != null)
                                                        .ToList();

            List <ThingDef> linkableHospitalOnly = ThingDef.Named("Ogre_NanoTech_HospitalBed").GetCompProperties <CompProperties_AffectedByFacilities>().linkableFacilities;
            List <CompProperties_Facility> hospitalOnlyFacilities = linkableHospitalOnly
                                                                    .Select(x => x.GetCompProperties <CompProperties_Facility>())
                                                                    .Where(x => x != null)
                                                                    .ToList();

            ThingCategoryDef buildingCategory = DefDatabase <ThingCategoryDef> .AllDefsListForReading.Find(x => x.defName == "BuildingsFurniture");

            List <MemeDef> memesRef = new List <MemeDef>();

            Dictionary <string, List <MemeDef> > designatorViaMeme = new Dictionary <string, List <MemeDef> >();

            if (ModsConfig.IdeologyActive)
            {
                // build a lookup of all memes
                // that have unlockable buildables
                // ex pain in virtue ( slab beds )
                List <MemeDef> memes = new List <MemeDef>(DefDatabase <MemeDef> .AllDefsListForReading);
                foreach (MemeDef m in memes)
                {
                    if (m.addDesignators != null)
                    {
                        foreach (BuildableDef d in m.addDesignators)
                        {
                            if (d != null && !string.IsNullOrWhiteSpace(d.defName))
                            {
                                List <MemeDef> o;
                                if (!designatorViaMeme.TryGetValue(d.defName, out o))
                                {
                                    o = new List <MemeDef>();
                                    designatorViaMeme.Add(d.defName, o);
                                }
                                o.Add(m);
                            }
                        }
                    }
                }
            }

            foreach (SupportedBed b in _BEDS_TO_SUPPORT)
            {
                if (bedDefs.ContainsKey(b.DefName))
                {
                    ThingDef nanoBed = NanoUtil.CreateNanoBedDefFromSupportedBed(
                        bed: bedDefs[b.DefName],
                        fnAdditionalProcessing: b.FnPostProcess,
                        linkableBuildings: b.UseHospitalLinkablesOnly ? linkableHospitalOnly : linkableBuildings,
                        facilities: b.UseHospitalLinkablesOnly ? hospitalOnlyFacilities : facilities
                        );

                    DefDatabase <ThingDef> .Add(nanoBed);

                    buildingCategory.childThingDefs.Add(nanoBed);                     // so beds are in stockpile filters
                    modSupport.Add(b.ModName);

                    if (ModsConfig.IdeologyActive)
                    {
                        // check if this bed is listed as an
                        // unlockable building via a memedef
                        if (!nanoBed.canGenerateDefaultDesignator)
                        {
                            if (designatorViaMeme.ContainsKey(b.DefName))
                            {
                                foreach (MemeDef m in designatorViaMeme[b.DefName])
                                {
                                    m.addDesignators.Add(nanoBed);
                                }
                            }
                        }
                    }
                }
            }

            Verse.Log.Message("Nano Repair Tech Added Support: [ " + string.Join(", ", modSupport.OrderBy(x => x).ToArray()) + " ]");

            // defs show up where they are
            // supposed to in the game menus?
            DefDatabase <DesignationCategoryDef> .AllDefsListForReading.Find(x => x.defName == "Ogre_NanoRepairTech_DesignationCategory").ResolveReferences();

            // pawns will not auto seek out
            // the beds unless the
            // RestUtilty is reset
            RestUtility.Reset();
        }
Beispiel #11
0
        private static void GenRecipes()
        {
            var allRecipes = DefDatabase <RecipeDef> .AllDefsListForReading;
            var srcs       = new List <RecipeDef>();

            foreach (var recipe in allRecipes)
            {
                if (recipe.products.Count != 1)
                {
                    continue;
                }

                if (recipe.ingredients.Count == 0)
                {
                    continue;
                }

                if (recipe.WorkAmountTotal(null) > thresholdLimit * 60)
                {
                    continue;
                }

                srcs.Add(recipe);
                //Log.Message(recipe.label + "\t" + recipe.defName + "\t" + recipe.WorkAmountTotal(null)/60);
            }

            var RecipesUsers = new List <ThingDef>();

            foreach (var recipe in srcs)
            {
                var lastOne = false;
                foreach (var factor in mulFactors)
                {
                    if (factor * recipe.WorkAmountTotal(null) > thresholdLimit * 60)
                    {
                        lastOne = true;
                    }

                    var newRecipe = MkNewRecipe(recipe, factor);
                    if (newRecipe == null)
                    {
                        Log.Warning(
                            $"BulkRecipeGenerator: newRecipe == null  on {recipe.label}, this should not happen normally");
                        continue;
                    }


                    newRecipe.ResolveReferences();

                    DefDatabase <RecipeDef> .Add(newRecipe);

                    RememberNewRecipe(recipe, newRecipe);

                    foreach (var ru in recipe.AllRecipeUsers)
                    {
                        if (!RecipesUsers.Contains(ru))
                        {
                            RecipesUsers.Add(ru);
                        }

                        if (newRecipe.recipeUsers == null)
                        {
                            ru.recipes.Add(newRecipe);
                        }
                    }

                    if (lastOne)
                    {
                        break;
                    }
                }
            }

            foreach (var ru in RecipesUsers)
            {
                Traverse.Create(ru).Field("allRecipesCached").SetValue(null);
            }
        }
Beispiel #12
0
        protected override void FillTab()
        {
            if (this.pawn != this.SelPawn)
            {
                this.pawn = this.SelPawn;
            }

            bool horizontal = this.pawn.Rotation.IsHorizontal;

            if (!this.SelPawn.GetCompFace(out CompFace compFace))
            {
                return;
            }

            Rect rect = new Rect(10f, 10f, 330f, 530f);

            Listing_Standard listing = new Listing_Standard();

            listing.Begin(rect);


            this.SelPawn.GetCompAnim(out CompBodyAnimator _);


            listing.CheckboxLabeled("Ignore renderer", ref compFace.IgnoreRenderer);
            if (GUI.changed)
            {
                IgnoreRenderer = compFace.IgnoreRenderer;
            }

            ThingWithComps primary = this.SelPawn.equipment?.Primary;

            if (primary == null)
            {
                return;
            }

            weaponExtensions = primary?.def.GetCompProperties <CompProperties_WeaponExtensions>();

            if (weaponExtensions == null)
            {
                weaponExtensions = new CompProperties_WeaponExtensions
                {
                    compClass = typeof(CompWeaponExtensions)
                };

                primary.def.comps?.Add(weaponExtensions);
            }

            if (this.SelPawn.Drafted)
            {
                listing.Label(this.pawn.equipment.Primary.def.defName);

                Vector3 weaponOffset = weaponExtensions.WeaponPositionOffset;

                listing.Label("Offset: " +
                              (weaponOffset.x).ToString("N2") + " / " +
                              (weaponOffset.y).ToString("N2") + " / " +
                              (weaponOffset.z).ToString("N2"));
                if (horizontal)
                {
                    weaponOffset.y = listing.Slider(weaponOffset.y, -1f, 1f, label: "Horizontal x");
                }
                else
                {
                    weaponOffset.x = listing.Slider(weaponOffset.x, -1f, 1f, label: "Vertical x");
                }
                weaponOffset.z = listing.Slider(weaponOffset.z, -1f, 1f, label: "z");

                Vector3 aimedOffset = weaponExtensions.AimedWeaponPositionOffset;
                listing.Label("OffsetAiming: " +
                              (aimedOffset.x).ToString("N2") + " / " +
                              (aimedOffset.y).ToString("N2") + " / " +
                              (aimedOffset.z).ToString("N2"));
                if (horizontal)
                {
                    aimedOffset.y = listing.Slider(aimedOffset.y, -1f, 1f, label: "Horizontal x");
                }
                else
                {
                    aimedOffset.x = listing.Slider(aimedOffset.x, -1f, 1f, label: "Vertical x");
                }
                aimedOffset.z = listing.Slider(aimedOffset.z, -1f, 1f, label: "z");

                Vector3 rightHandPosition = weaponExtensions.RightHandPosition;
                listing.Label("RH: " +
                              (rightHandPosition.x).ToString("N2") + " / " +
                              (rightHandPosition.z).ToString("N2"));

                listing.Gap();
                rightHandPosition.y =
                    listing.Slider(rightHandPosition.y, -YOffset_HandsFeet, YOffset_HandsFeet, leftAlignedLabel: "behind",
                                   rightAlignedLabel: "front", roundTo: YOffset_HandsFeet);

                rightHandPosition.x = listing.Slider(rightHandPosition.x, -1f, 1f);
                rightHandPosition.z = listing.Slider(rightHandPosition.z, -1f, 1f);

                Vector3 leftHandPosition = weaponExtensions.LeftHandPosition;
                listing.Label("LH: " +
                              (leftHandPosition.x).ToString("N2") + " / " +
                              (leftHandPosition.z).ToString("N2"));

                listing.Gap();
                leftHandPosition.y =
                    listing.Slider(leftHandPosition.y, -YOffset_HandsFeet,
                                   YOffset_HandsFeet, leftAlignedLabel: "behind",
                                   rightAlignedLabel: "front", roundTo: YOffset_HandsFeet);

                leftHandPosition.x = listing.Slider(leftHandPosition.x, -1f, 1f);
                leftHandPosition.z = listing.Slider(leftHandPosition.z, -1f, 1f);

                if (leftHandPosition != Vector3.zero)
                {
                    if (listing.ButtonText("Remove left hand position"))
                    {
                        leftHandPosition = Vector3.zero;
                    }
                }

                listing.Gap();

                if (listing.ButtonText("Export WeaponExtensionDef"))
                {
                    string defName = "WeaponExtensionDef_" + primary?.def.defName;

                    WeaponExtensionDef wepDef;
                    if (!DefDatabase <WeaponExtensionDef> .AllDefsListForReading.Any(x => x.defName == defName))
                    {
                        wepDef = new WeaponExtensionDef
                        {
                            defName = defName,
                            label   = defName,
                            weapon  = primary.def.defName
                        };
                        DefDatabase <WeaponExtensionDef> .Add(wepDef);
                    }
                    else
                    {
                        wepDef = DefDatabase <WeaponExtensionDef> .GetNamed(defName);
                    }

                    wepDef.weaponPositionOffset      = weaponOffset;
                    wepDef.aimedWeaponPositionOffset = aimedOffset;
                    wepDef.firstHandPosition         = rightHandPosition;
                    wepDef.secondHandPosition        = leftHandPosition;

                    string configFolder = MainTabWindow_BaseAnimator.DefPath;
                    string path         = configFolder + "/WeaponExtensionDefs/" + wepDef.defName + ".xml";


                    Find.WindowStack.Add(
                        Dialog_MessageBox.CreateConfirmation(
                            "Confirm overwriting: " + path,
                            delegate
                    {
                        ExportWeaponExtensionDefs.Defs cycle =
                            new ExportWeaponExtensionDefs.Defs(wepDef);

                        DirectXmlSaver.SaveDataObject(
                            cycle,
                            path);
                    },
                            true));
                }

                if (GUI.changed)
                {
                    weaponExtensions.WeaponPositionOffset      = weaponOffset;
                    weaponExtensions.AimedWeaponPositionOffset = aimedOffset;
                    weaponExtensions.LeftHandPosition          = leftHandPosition;
                    weaponExtensions.RightHandPosition         = rightHandPosition;
                }
            }


            listing.End();
            // NeedsCardUtility.DoNeedsMoodAndThoughts(new Rect(0f, 0f, this.size.x, this.size.y), base.SelPawn, ref this.thoughtScrollPosition);
        }
 static void GetClutterStructureDefPostfix(ThingDef Wallzie)
 {
     DefDatabase <BuildableDef> .Add(Wallzie);
 }
        static HarmonyPatchesFS()
        {
            HarmonyLib.Harmony harmony = new HarmonyLib.Harmony("rimworld.facialstuff.mod");
            // HarmonyLib.Harmony.DEBUG = true;
            harmony.PatchAll(Assembly.GetExecutingAssembly());


            harmony.Patch(
                AccessTools.Method(typeof(Page_ConfigureStartingPawns), "DrawPortraitArea"),
                null,
                new HarmonyMethod(typeof(HarmonyPatchesFS), nameof(AddFaceEditButton)));

            harmony.Patch(
                AccessTools.Method(typeof(PawnGraphicSet), nameof(PawnGraphicSet.ResolveAllGraphics)),
                null,
                new HarmonyMethod(typeof(HarmonyPatchesFS), nameof(ResolveAllGraphics_Postfix)));

            harmony.Patch(
                AccessTools.Method(typeof(PawnGraphicSet), nameof(PawnGraphicSet.ResolveApparelGraphics)),
                null,
                new HarmonyMethod(typeof(HarmonyPatchesFS), nameof(ResolveApparelGraphics_Postfix)));

            harmony.Patch(
                AccessTools.Method(typeof(PawnRenderer), nameof(PawnRenderer.DrawEquipmentAiming)),
                new HarmonyMethod(typeof(HarmonyPatchesFS), nameof(DrawEquipmentAiming_Prefix)),
                null,
                new HarmonyMethod(typeof(HarmonyPatchesFS),
                                  nameof(DrawEquipmentAiming_Transpiler)));

            harmony.Patch(
                AccessTools.Method(typeof(PawnRenderer), nameof(PawnRenderer.RenderPawnAt),
                                   new[] { typeof(Vector3), typeof(RotDrawMode), typeof(bool), typeof(bool) }),

                // new HarmonyMethod(typeof(HarmonyPatchesFS), nameof(HarmonyPatchesFS.RenderPawnAt)),
                null,
                null,
                new HarmonyMethod(typeof(HarmonyPatchesFS), nameof(RenderPawnAt_Transpiler))
                );

            harmony.Patch(
                AccessTools.Method(typeof(HediffSet), nameof(HediffSet.DirtyCache)),
                null,
                new HarmonyMethod(typeof(HarmonyPatchesFS), nameof(DirtyCache_Postfix)));

            harmony.Patch(
                AccessTools.Method(typeof(GraphicDatabaseHeadRecords),
                                   nameof(GraphicDatabaseHeadRecords.Reset)),
                null,
                new HarmonyMethod(
                    typeof(GraphicDatabaseHeadRecordsModded),
                    nameof(GraphicDatabaseHeadRecordsModded.Reset)));

            harmony.Patch(
                AccessTools.Method(typeof(PawnHairChooser), nameof(PawnHairChooser.RandomHairDefFor)),
                new HarmonyMethod(typeof(HarmonyPatchesFS), nameof(RandomHairDefFor_PreFix)),
                null);

            harmony.Patch(
                AccessTools.Method(typeof(PawnSkinColors), "GetSkinDataIndexOfMelanin"),
                new HarmonyMethod(
                    typeof(PawnSkinColors_FS),
                    nameof(PawnSkinColors_FS.GetSkinDataIndexOfMelanin_Prefix)),
                null);

            harmony.Patch(
                AccessTools.Method(typeof(PawnSkinColors), nameof(PawnSkinColors.GetSkinColor)),
                new HarmonyMethod(typeof(PawnSkinColors_FS), nameof(PawnSkinColors_FS.GetSkinColor_Prefix)),
                null);

            harmony.Patch(
                AccessTools.Method(typeof(PawnSkinColors), nameof(PawnSkinColors.RandomMelanin)),
                new HarmonyMethod(typeof(PawnSkinColors_FS), nameof(PawnSkinColors_FS.RandomMelanin_Prefix)),
                null);

            harmony.Patch(
                AccessTools.Method(typeof(PawnSkinColors),
                                   nameof(PawnSkinColors.GetMelaninCommonalityFactor)),
                new HarmonyMethod(
                    typeof(PawnSkinColors_FS),
                    nameof(PawnSkinColors_FS.GetMelaninCommonalityFactor_Prefix)),
                null);

            harmony.Patch(
                AccessTools.Method(typeof(Pawn_InteractionsTracker),
                                   nameof(Pawn_InteractionsTracker.TryInteractWith)),
                null,
                new HarmonyMethod(typeof(HarmonyPatchesFS), nameof(TryInteractWith_Postfix)));


            Log.Message(
                "Facial Stuff successfully completed " + harmony.GetPatchedMethods().Count()
                + " patches with harmony.");

            foreach (ThingDef def in DefDatabase <ThingDef> .AllDefsListForReading.Where(
                         td => td.category ==
                         ThingCategory.Pawn &&
                         td.race.Humanlike))
            {
                if (def.inspectorTabs == null || def.inspectorTabs.Count == 0)
                {
                    def.inspectorTabs         = new List <Type>();
                    def.inspectorTabsResolved = new List <InspectTabBase>();
                }

                if (def.inspectorTabs.Contains(typeof(ITab_Pawn_Weapons)))
                {
                    return;
                }

                def.inspectorTabs.Add(typeof(ITab_Pawn_Weapons));
                def.inspectorTabsResolved.Add(InspectTabManager.GetSharedInstance(typeof(ITab_Pawn_Weapons)));

                def.inspectorTabs.Add(typeof(ITab_Pawn_Face));
                def.inspectorTabsResolved.Add(InspectTabManager.GetSharedInstance(typeof(ITab_Pawn_Face)));
            }

            List <HairDef> beardyHairList =
                DefDatabase <HairDef> .AllDefsListForReading.Where(x => x.IsBeardNotHair()).ToList();

            for (int i = 0; i < beardyHairList.Count(); i++)
            {
                HairDef beardy = beardyHairList[i];
                if (beardy.label.Contains("shaven"))
                {
                    continue;
                }
                BeardDef beardDef = new BeardDef
                {
                    defName    = beardy.defName,
                    label      = "_VHE_" + beardy.label,
                    hairGender = beardy.hairGender,
                    texPath    = beardy.texPath.Replace("Things/Pawn/Humanlike/Beards/", ""),
                    hairTags   = beardy.hairTags,
                    beardType  = BeardType.FullBeard
                };
                if (beardDef.label.Contains("stubble") || beardDef.label.Contains("goatee") || beardDef.label.Contains("lincoln"))
                {
                    beardDef.drawMouth = true;
                }
                DefDatabase <BeardDef> .Add(beardDef);
            }
            Dialog_FaceStyling.FullBeardDefs = DefDatabase <BeardDef> .AllDefsListForReading.Where(x => x.beardType == BeardType.FullBeard)
                                               .ToList();

            Dialog_FaceStyling.LowerBeardDefs = DefDatabase <BeardDef> .AllDefsListForReading.Where(x => x.beardType != BeardType.FullBeard)
                                                .ToList();

            Dialog_FaceStyling.MoustacheDefs = DefDatabase <MoustacheDef> .AllDefsListForReading;

            CheckAllInjected();
        }
 static void GenerateBridgeDefPostfix(TerrainDef __result)
 {
     DefDatabase <BuildableDef> .Add(__result);
 }
Beispiel #16
0
        public static bool LoadUserShow(UserShowDef userShow, bool addToDefDatabase = true)
        {
            // Get images in path
            IEnumerable <string> filePaths = Enumerable.Empty <string>();

            if (!Directory.Exists(userShow.path))
            {
                Log.Message($"RimFlix {userShow.defName} : {userShow.label}: Path <{userShow.path}> does not exist.");
                return(false);
            }
            try
            {
                DirectoryInfo dirInfo = new DirectoryInfo(userShow.path);
                filePaths = from file in dirInfo.GetFiles()
                            where file.Name.ToLower().EndsWith(".jpg") || file.Name.ToLower().EndsWith(".png")
                            where (file.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden
                            select file.FullName;
            }
            catch
            {
                Log.Message($"RimFlix {userShow.defName} : {userShow.label}: Error trying to load files from <{userShow.path}>.");
                return(false);
            }
            if (!filePaths.Any())
            {
                Log.Message($"RimFlix {userShow.defName} : {userShow.label}: No images found in <{userShow.path}>.");
                // User may want to keep a show with an empty directory for future use.
                //return false;
            }

            // Load textures for images
            userShow.frames = new List <GraphicData>();
            foreach (string filePath in filePaths)
            {
                // RimWorld sets internalPath to filePath without extension
                // This causes problems with files that have same name but different extension (file.jpg, file.png)
                string internalPath = filePath.Replace('\\', '/');
                if (!RimFlixContent.contentList.ContainsKey(internalPath))
                {
                    string      path        = Path.GetDirectoryName(filePath);
                    string      file        = Path.GetFileName(filePath);
                    VirtualFile virtualFile = AbstractFilesystem.GetDirectory(path).GetFile(file);
                    LoadedContentItem <Texture2D> loadedContentItem = ModContentLoader <Texture2D> .LoadItem(virtualFile);

                    RimFlixContent.contentList.Add(internalPath, loadedContentItem.contentItem);
                }
                userShow.frames.Add(new GraphicData
                {
                    texPath      = internalPath,
                    graphicClass = typeof(Graphic_Single)
                });
            }

            // Create televisionDefs list
            userShow.televisionDefs = new List <ThingDef>();
            foreach (string televisionDefString in userShow.televisionDefStrings)
            {
                userShow.televisionDefs.Add(ThingDef.Named(televisionDefString));
            }

            // Add user show to def database
            if (!DefDatabase <ShowDef> .AllDefs.Contains(userShow))
            {
                DefDatabase <ShowDef> .Add(userShow);
            }
            return(true);
        }
Beispiel #17
0
        private static void CreateNewPawnKind(PawnKindDef pkOld, string label, string defname)
        {
            // if it already exists then don't recreate it
            if (DefDatabase <PawnKindDef> .GetNamedSilentFail(defname) != null)
            {
                return;
            }
            PawnKindDef pk = new PawnKindDef
            {
                defName = defname,
                label   = pkOld.label + " (" + label.ToLower() + ")",

                allowRoyalApparelRequirements = pkOld.allowRoyalApparelRequirements,
                allowRoyalRoomRequirements    = pkOld.allowRoyalRoomRequirements,
                alternateGraphicChance        = pkOld.alternateGraphicChance,
                alternateGraphics             = pkOld.alternateGraphics.ListFullCopyOrNull <AlternateGraphic>(),
                apparelRequired                 = pkOld.apparelRequired.ListFullCopyOrNull <ThingDef>(),
                apparelDisallowTags             = pkOld.apparelDisallowTags.ListFullCopyOrNull <string>(),
                apparelTags                     = pkOld.apparelTags.ListFullCopyOrNull <string>(),
                apparelAllowHeadgearChance      = pkOld.apparelAllowHeadgearChance,
                aiAvoidCover                    = pkOld.aiAvoidCover,
                apparelColor                    = pkOld.apparelColor,
                apparelIgnoreSeasons            = pkOld.apparelIgnoreSeasons,
                apparelMoney                    = new FloatRange(min: pkOld.apparelMoney.min, max: pkOld.apparelMoney.max),
                backstoryCategories             = pkOld.backstoryCategories.ListFullCopyOrNull <string>(),
                backstoryFilters                = pkOld.backstoryFilters.ListFullCopyOrNull <BackstoryCategoryFilter>(),
                backstoryFiltersOverride        = pkOld.backstoryFiltersOverride.ListFullCopyOrNull <BackstoryCategoryFilter>(),
                backstoryCryptosleepCommonality = pkOld.backstoryCryptosleepCommonality,
                baseRecruitDifficulty           = pkOld.baseRecruitDifficulty,
                biocodeWeaponChance             = pkOld.biocodeWeaponChance,
                canArriveManhunter              = pkOld.canArriveManhunter,
                canBeSapper                     = pkOld.canBeSapper,
                chemicalAddictionChance         = pkOld.chemicalAddictionChance,
                combatEnhancingDrugsChance      = pkOld.combatEnhancingDrugsChance,
                combatEnhancingDrugsCount       = pkOld.combatEnhancingDrugsCount,
                combatPower                     = pkOld.combatPower,
                defaultFactionType              = pkOld.defaultFactionType,
                description                     = pkOld.description,
                defendPointRadius               = pkOld.defendPointRadius,
                destroyGearOnDrop               = pkOld.destroyGearOnDrop,
                disallowedTraits                = pkOld.disallowedTraits.ListFullCopyOrNull <TraitDef>(),
                ecoSystemWeight                 = pkOld.ecoSystemWeight,
                factionLeader                   = pkOld.factionLeader,
                fixedInventory                  = pkOld.fixedInventory.ListFullCopyOrNull <ThingDefCountClass>(),
                fleeHealthThresholdRange        = new FloatRange(min: pkOld.fleeHealthThresholdRange.min, max: pkOld.fleeHealthThresholdRange.max),
                forceNormalGearQuality          = pkOld.forceNormalGearQuality,
                gearHealthRange                 = new FloatRange(min: pkOld.gearHealthRange.min, max: pkOld.gearHealthRange.max),
                generated         = pkOld.generated,
                inventoryOptions  = pkOld.inventoryOptions,
                invFoodDef        = pkOld.invFoodDef,
                invNutrition      = pkOld.invNutrition,
                isFighter         = pkOld.isFighter,
                itemQuality       = pkOld.itemQuality,
                labelMale         = pkOld.labelMale,
                labelMalePlural   = pkOld.labelMalePlural,
                labelFemale       = pkOld.labelFemale,
                labelFemalePlural = pkOld.labelFemalePlural,
                labelPlural       = pkOld.labelPlural,
                lifeStages        = pkOld.lifeStages.ListFullCopyOrNull <PawnKindLifeStage>(),
                maxGenerationAge  = pkOld.maxGenerationAge,
                minGenerationAge  = pkOld.minGenerationAge,
                modContentPack    = pkOld.modContentPack,
                modExtensions     = pkOld.modExtensions,
                royalTitleChance  = pkOld.royalTitleChance,
                skills            = pkOld.skills.ListFullCopyOrNull <SkillRange>()
            };

            pk.specificApparelRequirements = pkOld.specificApparelRequirements.ListFullCopyOrNull <SpecificApparelRequirement>();
            pk.trader                  = pkOld.trader;
            pk.titleSelectOne          = pkOld.titleSelectOne.ListFullCopyOrNull <RoyalTitleDef>();
            pk.techHediffsRequired     = pkOld.techHediffsRequired.ListFullCopyOrNull <ThingDef>();
            pk.techHediffsChance       = pkOld.techHediffsChance;
            pk.techHediffsMaxAmount    = pkOld.techHediffsMaxAmount;
            pk.techHediffsMoney        = new FloatRange(min: pkOld.techHediffsMoney.min, max: pkOld.techHediffsMoney.max);
            pk.techHediffsTags         = pkOld.techHediffsTags.ListFullCopyOrNull <string>();
            pk.techHediffsDisallowTags = pkOld.techHediffsDisallowTags.ListFullCopyOrNull <string>();
            pk.weaponMoney             = new FloatRange(min: pkOld.weaponMoney.min, max: pkOld.weaponMoney.max);
            pk.weaponTags              = pkOld.weaponTags.ListFullCopyOrNull <string>();
            pk.wildGroupSize           = pkOld.wildGroupSize;
            pk.initialResistanceRange  = pkOld.initialResistanceRange.GetValueOrDefault();
            pk.initialWillRange        = pkOld.initialWillRange.GetValueOrDefault();


            switch (label)
            {
            case "Togruta":
                ThingDef_AlienRace thisRace = DefDatabase <ThingDef_AlienRace> .GetNamed("StarWarsRaces_Togruta");

                pk.race = thisRace;
                pk.apparelAllowHeadgearChance = 0f;
                break;

            default:
                ThingDef_AlienRace newRace = DefDatabase <ThingDef_AlienRace> .GetNamed("StarWarsRaces_" + label);

                pk.race = newRace;
                break;
            }
            DefDatabase <PawnKindDef> .Add(pk);
        }
 public static void Add <D>(D d) where D : Def
 {
     DefDatabase <D> .Add(d);
 }
Beispiel #19
0
            static AnimalGeneticsAssemblyLoader()
            {
                var h = new Harmony("AnimalGenetics");

                h.PatchAll();

                DefDatabase <StatDef> .Add(AnimalGenetics.Damage);

                DefDatabase <StatDef> .Add(AnimalGenetics.Health);

                DefDatabase <StatDef> .Add(AnimalGenetics.GatherYield);

                var affectedStats = Constants.affectedStatsToInsert;

                foreach (var stat in affectedStats)
                {
                    try
                    {
                        stat.parts?.Insert(0, new StatPart(stat));
                    }
                    catch
                    {
                        Log.Error(stat + " is broken");
                    }
                }

                var category = new StatCategoryDef {
                    defName = "AnimalGenetics_Category", label = "Genetics", displayAllByDefault = true, displayOrder = 200
                };

                DefDatabase <StatCategoryDef> .Add(category);

                foreach (var stat in Constants.affectedStats)
                {
                    DefDatabase <StatDef> .Add(new StatDefWrapper { defName = "AnimalGenetics_" + stat.defName, label = Constants.GetLabel(stat), Underlying = stat, category = category, workerClass = typeof(StatWorker), toStringStyle = ToStringStyle.PercentZero });
                }

                StatDefOf.MarketValue.parts.Add(new MarketValueCalculator());

                gatherableTypes = new List <Type>()
                {
                    typeof(CompShearable),
                    typeof(CompMilkable)
                };

                // Compatibility patches
                try
                {
                    if (LoadedModManager.RunningModsListForReading.Any(x => x.PackageId == "sarg.alphaanimals" || x.Name == "Alpha Animals"))
                    {
                        Log.Message("Animal Genetics : Alpha Animals is loaded - Patching");
                        h.Patch(AccessTools.Method(AccessTools.TypeByName("AlphaBehavioursAndEvents.CompAnimalProduct"), "get_ResourceAmount"),
                                postfix: new HarmonyMethod(typeof(CompatibilityPatches), nameof(CompatibilityPatches.AlphaAnimals_get_ResourceAmount_Patch)));
                        gatherableTypes.Add(AccessTools.TypeByName("AlphaBehavioursAndEvents.CompAnimalProduct"));
                    }
                    if (LoadedModManager.RunningModsListForReading.Any(x => x.PackageId == "CETeam.CombatExtended" || x.Name == "Combat Extended"))
                    {
                        //gatherableTypes.Append(AccessTools.TypeByName("CombatExtended.CompMilkableRenameable")); //they all use shearable
                        gatherableTypes.Add(AccessTools.TypeByName("CombatExtended.CompShearableRenameable"));
                    }

                    if (LoadedModManager.RunningModsListForReading.Any(x => x.PackageId == "rim.job.world"))
                    {
                        Log.Message("Patched RJW");
                        h.Patch(AccessTools.Method(AccessTools.TypeByName("rjw.Hediff_BasePregnancy"), "GenerateBabies"),
                                prefix: new HarmonyMethod(typeof(CompatibilityPatches), nameof(CompatibilityPatches.RJW_GenerateBabies_Prefix)),
                                postfix: new HarmonyMethod(typeof(CompatibilityPatches), nameof(CompatibilityPatches.RJW_GenerateBabies_Postfix)));
                    }
                }
                catch { }

                if (ColonyManager.ModRunning && Settings.Integration.ColonyManagerIntegration)
                {
                    ColonyManager.Patch(h);
                }

                _DefaultAnimalsPawnTableDefColumns  = new List <PawnColumnDef>(PawnTableDefOf.Animals.columns);
                _DefaultWildlifePawnTableDefColumns = new List <PawnColumnDef>(PawnTableDefOf.Wildlife.columns);

                var placeholderPosition = MainTabWindow_AnimalGenetics.PawnTableDefs.Genetics.columns.FindIndex(def => def.defName == "AnimalGenetics_Placeholder");

                MainTabWindow_AnimalGenetics.PawnTableDefs.Genetics.columns.RemoveAt(placeholderPosition);
                MainTabWindow_AnimalGenetics.PawnTableDefs.Genetics.columns.InsertRange(placeholderPosition, PawnTableColumnsDefOf.Genetics.columns);

                PatchUI();
            }
Beispiel #20
0
        static MyStaticConstructor()
        {
            IEnumerable <ThingDef> workTables = DefDatabase <ThingDef> .AllDefs.Where(t => t.IsWorkTable);

            FieldInfo thingDefs        = typeof(ThingFilter).GetField("thingDefs", BindingFlags.NonPublic | BindingFlags.Instance);
            FieldInfo allRecipesCached = typeof(ThingDef).GetField("allRecipesCached", BindingFlags.NonPublic | BindingFlags.Instance);

            foreach (ThingDef workTable in workTables)
            {
                IEnumerable <RecipeDef> tableRecipes = workTable.AllRecipes.Where(r => r.ProducedThingDef?.HasSmeltProducts() ?? false);
                // If the table has no relevant recipes, no point doing anything else for it.
                if (!tableRecipes.Any())
                {
                    continue;
                }

                ThingFilter newFilter = new ThingFilter();
                thingDefs.SetValue(newFilter, tableRecipes.Select(r => r.ProducedThingDef).ToList());

                IngredientCount newCount = new IngredientCount();
                newCount.SetBaseCount(1);
                newCount.filter = newFilter;

                RecipeDef generatedRecipe = new RecipeDef
                {
                    defName         = "LuluScrapAnything_DisassembleAt" + workTable.defName,
                    label           = "LuluScrapAnything_BillLabel".Translate(),
                    description     = "LuluScrapAnything_BillDesc".Translate(),
                    jobString       = "LuluScrapAnything_BillJob".Translate(workTable.label),
                    workAmount      = 1600,
                    workSpeedStat   = MyDefOf.SmeltingSpeed,
                    effectWorking   = tableRecipes.GroupBy(r => r.effectWorking).OrderByDescending(g => g.Count()).Select(o => o.Key).First(),
                    soundWorking    = tableRecipes.GroupBy(r => r.soundWorking).OrderByDescending(g => g.Count()).Select(o => o.Key).First(),
                    specialProducts = new List <SpecialProductType> {
                        SpecialProductType.Smelted
                    },
                    recipeUsers = new List <ThingDef> {
                        workTable
                    },
                    ingredients = new List <IngredientCount> {
                        newCount
                    },
                    fixedIngredientFilter     = newFilter,
                    forceHiddenSpecialFilters = new List <SpecialThingFilterDef>
                    {
                        MyDefOf.AllowBurnableApparel,
                        MyDefOf.AllowBurnableWeapons,
                        MyDefOf.AllowNonBurnableApparel,
                        MyDefOf.AllowNonBurnableWeapons,
                        MyDefOf.AllowNonSmeltableApparel,
                        MyDefOf.AllowNonSmeltableWeapons,
                        MyDefOf.AllowSmeltable,
                        MyDefOf.AllowSmeltableApparel,
                    }
                };
                generatedRecipe.ResolveReferences();
                DefDatabase <RecipeDef> .Add(generatedRecipe);

                // Clear the recipe cache because we've added a new recipe.
                allRecipesCached.SetValue(workTable, null);
            }
        }
Beispiel #21
0
        public static void SetupWrappedDefs()
        {
            DefDatabase <ThingDef> .Add(KK_ThingDefGenerator_Bugs.ImpliedThingDefs());

            DefDatabase <PawnKindDef> .Add(KK_PawnKindGenerator_Bugs.ImpliedPawnKindDefs());
        }
        static void AddMissingSeed(ThingDef thingDef)
        {
            string name = thingDef.defName;

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

            var template = ResourceBank.ThingDefOf.Seed_Psychoid;
            var seed     = new SeedDef()
            {
                defName         = "Seed_" + name,
                label           = name.ToLower() + " seeds",
                plant           = thingDef,
                harvest         = thingDef.plant.harvestedThingDef,
                BaseMarketValue = AssignMarketValueFromHarvest(thingDef),
                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.ResolveReferences();
            thingDef.blueprintDef = seed;
            foreach (var category in seed.thingCategories)
            {
                category.childThingDefs.Add(seed);
            }
            DefDatabase <ThingDef> .Add(seed);

            DefDatabase <SeedDef> .Add(seed);

            var stringBuilder = new System.Text.StringBuilder();

            stringBuilder.Append("SeedsPlease :: ");
            stringBuilder.Append(thingDef.defName);
            stringBuilder.Append(" (");
            stringBuilder.Append(thingDef.modContentPack.IsCoreMod ? "Patched" : thingDef.modContentPack.Name);
            stringBuilder.Append(") is missing a SeedDef. Autogenerated as ");
            stringBuilder.AppendLine(seed.defName);
            stringBuilder.AppendLine();

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

            stringBuilder.AppendLine(seedXml.ToString());

            if (thingDef.plant.harvestedThingDef.IsStuff)
            {
                Log.Warning(stringBuilder.ToString());

                return;
            }

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

            ingredient.filter.SetAllow(thingDef.plant.harvestedThingDef, true);
            ingredient.SetBaseCount(yieldCount);

            var 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);

            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)));

            stringBuilder.AppendLine();
            stringBuilder.AppendLine(recipeXml.ToString());

            Log.Warning(stringBuilder.ToString());
        }
        //UNDONE This doesn't define weapons as yet and the code might not handle that well.  Want to get various things stable first RE inventory.
        //       But we can define generics for short range, assault, pistol, melee.

        /*       (ProfoundDarkness) Some issues with weapons is that they have durability, quality, and often made of stuffs.
         *                          Also could use a super-generic which fetches x clips for each weapon on the pawn (working on that for something else).
         *                          I'm thinking we could add another button (more clutter) to each loadout slot which is only displayed if the item
         *                           has key properties.  Clicking that button would show a new window which lets the user configure parameters like
         *                           a range slider for durability, range slider for quality, and a checklist for stuffs (assuming is made of stuffs).
         */

        /// <summary>
        /// This constructor gets run on startup of RimWorld and generates the various LoadoutGenericDef instance objects akin to having been loaded from xml.
        /// </summary>
        static LoadoutGenericDef()
        {
            // Used in a handful of places where all loaded ThingDefs are useful.
            IEnumerable <ThingDef> everything = DefDatabase <ThingDef> .AllDefs;

            // need to generate a list as that's how new defs are taken by DefDatabase.
            List <LoadoutGenericDef> defs = new List <LoadoutGenericDef>();


            LoadoutGenericDef generic = new LoadoutGenericDef();

            generic.defName          = "GenericMeal";
            generic.description      = "Generic Loadout for Meals.  Intended for compatibility with pawns automatically picking up a meal for themself.";
            generic.label            = "CE_Generic_Meal".Translate();
            generic.defaultCountType = LoadoutCountType.pickupDrop; // Fits with disabling of RimWorld Pawn behavior of fetching meals themselves.
            generic._lambda          = td => td.IsNutritionGivingIngestible && td.ingestible.preferability >= FoodPreferability.MealAwful && !td.IsDrug;
            generic.isBasic          = true;

            defs.Add(generic);
            //Log.Message(string.Concat("CombatExtended :: LoadoutGenericDef :: ", generic.LabelCap, " list: ", string.Join(", ", DefDatabase<ThingDef>.AllDefs.Where(t => generic.lambda(t)).Select(t => t.label).ToArray())));


            float targetNutrition = 0.85f;

            generic             = new LoadoutGenericDef();
            generic.defName     = "GenericRawFood";
            generic.description = "Generic Loadout for Raw Food.  Intended for compatibility with pawns automatically picking up raw food to train animals.";
            generic.label       = "CE_Generic_RawFood".Translate();
            // Exclude drugs and corpses.  Also exclude any food worse than RawBad as in testing the pawns would not even pick it up for training.
            generic._lambda      = td => td.IsNutritionGivingIngestible && td.ingestible.preferability <= FoodPreferability.RawTasty && td.ingestible.HumanEdible && td.plant == null && !td.IsDrug && !td.IsCorpse;
            generic.defaultCount = Convert.ToInt32(Math.Floor(targetNutrition / everything.Where(td => generic.lambda(td)).Average(td => td.ingestible.nutrition)));
            //generic.defaultCount = 1;
            generic.isBasic = false;             // doesn't need to be in loadouts by default as animal interaction talks to HoldTracker now.
            //TODO: Test pawns fetching raw food if no meal is available, if so then add a patch to have that talk to HoldTracker too.

            defs.Add(generic);
            //Log.Message(string.Concat("CombatExtended :: LoadoutGenericDef :: ", generic.LabelCap, " list: ", string.Join(", ", DefDatabase<ThingDef>.AllDefs.Where(t => generic.lambda(t)).Select(t => t.label + " B(" + t.GetStatValueAbstract(CE_StatDefOf.Bulk) + ") M(" + t.GetStatValueAbstract(StatDefOf.Mass) + ")").ToArray())));


            generic                   = new LoadoutGenericDef();
            generic.defName           = "GenericDrugs";
            generic.defaultCount      = 3;
            generic.description       = "Generic Loadout for Drugs.  Intended for compatibility with pawns automatically picking up drugs in compliance with drug policies.";
            generic.label             = "CE_Generic_Drugs".Translate();
            generic.thingRequestGroup = ThingRequestGroup.Drug;
            generic.isBasic           = true;

            defs.Add(generic);
            //Log.Message(string.Concat("CombatExtended :: LoadoutGenericDef :: ", generic.LabelCap, " list: ", string.Join(", ", DefDatabase<ThingDef>.AllDefs.Where(t => generic.lambda(t)).Select(t => t.label).ToArray())));


            generic                   = new LoadoutGenericDef();
            generic.defName           = "GenericMedicine";
            generic.defaultCount      = 5;
            generic.defaultCountType  = LoadoutCountType.pickupDrop;
            generic.description       = "Generic Loadout for Medicine.  Intended for pawns which will handle triage activities.";
            generic.label             = "CE_Generic_Medicine".Translate();
            generic.thingRequestGroup = ThingRequestGroup.Medicine;

            // now for the guns and ammo...

            // Get a list of guns that are player acquireable (not menuHidden but could also go with not dropOnDeath) which have expected comps/compProperties/verbs.
            List <ThingDef> guns = everything.Where(td => !td.menuHidden &&
                                                    td.HasComp(typeof(CompAmmoUser)) && td.GetCompProperties <CompProperties_AmmoUser>() != null &&
                                                    td.Verbs.FirstOrDefault(v => v is VerbPropertiesCE) != null).ToList();
            string       ammoLabel       = "CE_Generic_Ammo".Translate();
            const string ammoDescription = "Generic Loadout ammo for {0}. Intended for generic collection of ammo for given gun.";

            foreach (ThingDef gun in guns)
            {
                // make sure the gun has ammo defined...
                if (gun.GetCompProperties <CompProperties_AmmoUser>().ammoSet.ammoTypes.Count <= 0)
                {
                    continue;
                }
                generic                  = new LoadoutGenericDef();
                generic.defName          = "GenericAmmo-" + gun.defName;
                generic.description      = string.Format(ammoDescription, gun.LabelCap);
                generic.label            = string.Format(ammoLabel, gun.LabelCap);
                generic.defaultCount     = gun.GetCompProperties <CompProperties_AmmoUser>().magazineSize;
                generic.defaultCountType = LoadoutCountType.pickupDrop;                 // we want ammo to get picked up.
                //generic._lambda = td => td is AmmoDef && gun.GetCompProperties<CompProperties_AmmoUser>().ammoSet.ammoTypes.Contains(td);
                generic.thingRequestGroup = ThingRequestGroup.HaulableEver;
                generic._lambda           = td => td is AmmoDef && gun.GetCompProperties <CompProperties_AmmoUser>().ammoSet.ammoTypes.Any(al => al.ammo == td);
                defs.Add(generic);
                //Log.Message(string.Concat("CombatExtended :: LoadoutGenericDef :: ", generic.LabelCap, " list: ", string.Join(", ", DefDatabase<ThingDef>.AllDefs.Where(t => generic.lambda(t)).Select(t => t.label).ToArray())));
            }

            // finally we add all the defs generated to the DefDatabase.
            DefDatabase <LoadoutGenericDef> .Add(defs);
        }
Beispiel #24
0
        internal static ThingDef CreateNanoBedDefFromSupportedBed(this ThingDef bed, Action <ThingDef> fnAdditionalProcessing, List <ThingDef> linkableBuildings, List <CompProperties_Facility> facilities)
        {
            Type typeRimworldBed = typeof(Building_Bed);
            Type bedToClone      = bed.GetType();

            if (typeRimworldBed.IsAssignableFrom(bedToClone))
            {
                throw new Exception("Type [" + bedToClone.Name + "] is not supported.");
            }

            //FieldInfo[] fieldsThingDef = typeof(ThingDef).GetFields(BindingFlags.Public | BindingFlags.Instance);

            //ThingDef nBed = new ThingDef();
            //foreach (FieldInfo field in fieldsThingDef)
            //	field.SetValue(nBed, field.GetValue(bed));

            //nBed.comps = new List<CompProperties>();
            //for (int i = 0; i < bed.comps.Count; i++)
            //{
            //	ConstructorInfo constructor = bed.comps[i].GetType().GetConstructor(Type.EmptyTypes);
            //	CompProperties comp = (CompProperties)constructor.Invoke(null);

            //	FieldInfo[] fields = comp.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
            //	foreach (FieldInfo field in fields)
            //		field.SetValue(comp, field.GetValue(bed.comps[i]));

            //	nBed.comps.Add(comp);
            //}

            ThingDef nBed = InitialCloneWithComps(bed);

            nBed.statBases.Add(new StatModifier()
            {
                stat = StatDef.Named("Ogre_NanoApparelRate"), value = 0
            });
            nBed.statBases.Add(new StatModifier()
            {
                stat = StatDef.Named("Ogre_NanoWeaponsRate"), value = 0
            });

            CompProperties_Power power = new CompProperties_Power();

            power.compClass            = typeof(CompPowerTrader);
            power.basePowerConsumption = 60f;
            power.shortCircuitInRain   = false;
            nBed.comps.Add(power);

            CompProperties_Flickable flick = new CompProperties_Flickable();

            flick.compClass = typeof(CompFlickable);
            nBed.comps.Add(flick);

            CompProperties_Refuelable fuel = new CompProperties_Refuelable();

            fuel.fuelConsumptionRate     = 0;
            fuel.fuelCapacity            = 25.0f * bed.size.x;  // same way it calculates in BedUtility
            fuel.consumeFuelOnlyWhenUsed = true;
            fuel.fuelFilter = new ThingFilter();
            fuel.fuelFilter.SetAllow(ThingDef.Named("Ogre_NanoTechFuel"), true);
            nBed.comps.Add(fuel);

            Dictionary <string, int> cost = new Dictionary <string, int>()
            {
                { "ComponentIndustrial", 1 },
                { "Steel", 5 }
            };

            if (nBed.costList == null)
            {
                nBed.costList = new List <ThingDefCountClass>();
            }

            Dictionary <string, ThingDefCountClass> current = nBed.costList.ToDictionary(x => x.thingDef.defName, y => y);


            foreach (string item in cost.Keys)
            {
                ThingDefCountClass count = null;
                if (!current.TryGetValue(item, out count))
                {
                    count = new ThingDefCountClass(ThingDef.Named(item), (cost[item] * nBed.size.x));
                    nBed.costList.Add(count);
                }
                else
                {
                    count.count += (cost[item] * nBed.size.x);
                }
            }

            bool found = false;

            nBed.researchPrerequisites = new List <ResearchProjectDef>();
            if (bed.researchPrerequisites != null && bed.researchPrerequisites.Count > 0)
            {
                foreach (ResearchProjectDef d in bed.researchPrerequisites)
                {
                    if (d.defName == "Ogre_NanoTech")
                    {
                        found = true;
                    }
                    nBed.researchPrerequisites.Add(d);
                }
            }

            if (!found)
            {
                nBed.researchPrerequisites.Add(ResearchProjectDef.Named("Ogre_NanoTech"));
            }


            nBed.defName                      += "_NanoBed";
            nBed.description                  += "\n\n" + TranslatorFormattedStringExtensions.Translate("NanoTech.Description.Short");
            nBed.label                         = TranslatorFormattedStringExtensions.Translate("NanoTech.ModName.Short") + " " + nBed.label;
            nBed.thingClass                    = typeof(NanoBed);
            nBed.tradeability                  = Tradeability.None;
            nBed.scatterableOnMapGen           = false;
            nBed.tickerType                    = TickerType.Rare;
            nBed.constructionSkillPrerequisite = bed.constructionSkillPrerequisite < 2 ? 2 : bed.constructionSkillPrerequisite;
            nBed.uiIconScale                   = 0.9f;
            nBed.techLevel                     = TechLevel.Industrial;
            nBed.shortHash                     = 0;

            nBed.statBases = new List <StatModifier>();
            foreach (StatModifier s in bed.statBases)
            {
                if (s.stat == StatDefOf.WorkToBuild)
                {
                    nBed.statBases.Add(new StatModifier()
                    {
                        stat  = StatDefOf.WorkToBuild,
                        value = s.value + 2500
                    });
                }
                else
                {
                    nBed.statBases.Add(s);
                }
            }

            ModContentPack nTechModPack = DefDatabase <ThingDef> .GetNamed("Ogre_NanoTech_Bed").modContentPack;;

            nBed.modContentPack = nTechModPack;

            // as of 1.3 without this, it wont
            // show the out of fuel icon
            nBed.drawerType = DrawerType.RealtimeOnly;

            nBed.designationCategory = DefDatabase <DesignationCategoryDef> .AllDefsListForReading.Find(x => x.defName == "Ogre_NanoRepairTech_DesignationCategory");

            //typeof(ShortHashGiver).GetMethod("GiveShortHash", BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, new object[] { nBed, typeof(ThingDef) });

            MethodInfo hashGiver = typeof(ShortHashGiver).GetMethod("GiveShortHash", BindingFlags.NonPublic | BindingFlags.Static);

            hashGiver.Invoke(null, new object[] { nBed, typeof(ThingDef) });

            // These things do not appear to work as good as
            // they did in 1.2, comment them out and do the
            // frame/blueprint defs by clone

            //MethodInfo newBluePrintDef = typeof(RimWorld.ThingDefGenerator_Buildings).GetMethod("NewBlueprintDef_Thing", BindingFlags.Static | BindingFlags.NonPublic);
            //nBed.blueprintDef = (ThingDef)newBluePrintDef.Invoke(null, new object[] { nBed, false, null });
            //nBed.installBlueprintDef = (ThingDef)newBluePrintDef.Invoke(null, new object[] { nBed, true, null });

            //MethodInfo newFrameDef = typeof(RimWorld.ThingDefGenerator_Buildings).GetMethod("NewFrameDef_Thing", BindingFlags.Static | BindingFlags.NonPublic);
            //nBed.frameDef = (ThingDef)newFrameDef.Invoke(null, new object[] { nBed });

            //ThingDef bluePrint = new ThingDef();
            //foreach (FieldInfo field in fieldsThingDef)
            //	field.SetValue(bluePrint, field.GetValue(bed.blueprintDef));

            //bluePrint.comps = new List<CompProperties>();
            //for (int i = 0; i < bed.blueprintDef.comps.Count; i++)
            //{
            //	ConstructorInfo constructor = bed.blueprintDef.comps[i].GetType().GetConstructor(Type.EmptyTypes);
            //	CompProperties comp = (CompProperties)constructor.Invoke(null);

            //	FieldInfo[] fields = comp.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
            //	foreach (FieldInfo field in fields)
            //		field.SetValue(comp, field.GetValue(bed.blueprintDef.comps[i]));

            //	bluePrint.comps.Add(comp);
            //}

            ThingDef bluePrint = InitialCloneWithComps(bed.blueprintDef);

            bluePrint.modContentPack   = nTechModPack;
            bluePrint.entityDefToBuild = nBed;
            bluePrint.defName          = nBed.defName + "_BluePrint";

            bluePrint.shortHash = 0;
            hashGiver.Invoke(null, new object[] { bluePrint, typeof(ThingDef) });

            nBed.blueprintDef = bluePrint;

            //ThingDef installBluePrint = new ThingDef();
            //foreach (FieldInfo field in fieldsThingDef)
            //	field.SetValue(installBluePrint, field.GetValue(bed.installBlueprintDef));

            //installBluePrint.comps = new List<CompProperties>();
            //for (int i = 0; i < bed.installBlueprintDef.comps.Count; i++)
            //{
            //	ConstructorInfo constructor = bed.installBlueprintDef.comps[i].GetType().GetConstructor(Type.EmptyTypes);
            //	CompProperties comp = (CompProperties)constructor.Invoke(null);

            //	FieldInfo[] fields = comp.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
            //	foreach (FieldInfo field in fields)
            //		field.SetValue(comp, field.GetValue(bed.installBlueprintDef.comps[i]));

            //	installBluePrint.comps.Add(comp);
            //}

            ThingDef installBluePrint = InitialCloneWithComps(bed.installBlueprintDef);

            installBluePrint.modContentPack   = nTechModPack;
            installBluePrint.entityDefToBuild = nBed;
            installBluePrint.defName          = nBed.defName + "_InstallBluePrint";

            installBluePrint.shortHash = 0;
            hashGiver.Invoke(null, new object[] { installBluePrint, typeof(ThingDef) });

            nBed.installBlueprintDef = installBluePrint;

            //ThingDef frameDef = new ThingDef();
            //foreach (FieldInfo field in fieldsThingDef)
            //	field.SetValue(frameDef, field.GetValue(bed.frameDef));

            //frameDef.comps = new List<CompProperties>();

            //for (int i = 0; i < bed.frameDef.comps.Count; i++)
            //{
            //	ConstructorInfo constructor = bed.frameDef.comps[i].GetType().GetConstructor(Type.EmptyTypes);
            //	CompProperties comp = (CompProperties)constructor.Invoke(null);

            //	FieldInfo[] fields = comp.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
            //	foreach (FieldInfo field in fields)
            //		field.SetValue(comp, field.GetValue(bed.frameDef.comps[i]));

            //	frameDef.comps.Add(comp);
            //}

            ThingDef frameDef = InitialCloneWithComps(bed.frameDef);

            frameDef.modContentPack   = nTechModPack;
            frameDef.entityDefToBuild = nBed;
            frameDef.defName          = nBed.defName + "_Frame";

            frameDef.shortHash = 0;
            hashGiver.Invoke(null, new object[] { frameDef, typeof(ThingDef) });

            nBed.frameDef = frameDef;

            // Breaks on save if these defs
            // are not loaded into the DefDatabase
            DefDatabase <ThingDef> .Add(bluePrint);

            DefDatabase <ThingDef> .Add(installBluePrint);

            DefDatabase <ThingDef> .Add(frameDef);

            if (bed.building.bed_humanlike)
            {
                CompProperties_AffectedByFacilities abf = nBed.GetCompProperties <CompProperties_AffectedByFacilities>();
                if (abf == null)
                {
                    abf = new CompProperties_AffectedByFacilities();
                    nBed.comps.Add(abf);
                }

                if (abf.linkableFacilities == null)
                {
                    abf.linkableFacilities = new List <ThingDef>();
                }

                abf.linkableFacilities.AddRange(linkableBuildings);

                foreach (CompProperties_Facility f in facilities)
                {
                    f.linkableBuildings.Add(nBed);
                }
            }

            if (fnAdditionalProcessing != null)
            {
                fnAdditionalProcessing.Invoke(nBed);
            }



            return(nBed);
        }
        private void processDefs()
        {
            var modsList = new List <ModContentPack>();

            // ----------- Injecting tabs -----------

            //{
            //	var caravanDef = DefDatabase<WorldObjectDef>.GetNamed("Caravan");
            //	var newTabType = typeof(UI.WITab_Caravan_Needs);
            //	var oldTabType = typeof(ITab_Pawn_Needs);
            //	if (caravanDef.inspectorTabs.Remove(oldTabType))
            //	{
            //		caravanDef.inspectorTabsResolved.Remove(InspectTabManager.GetSharedInstance(oldTabType));
            //caravanDef.inspectorTabs.Add(newTabType);
            //caravanDef.inspectorTabsResolved.Add(InspectTabManager.GetSharedInstance(newTabType));
            //	}
            //	else
            //	{
            //		//TODO: disaster error message
            //	}
            //}

            foreach (var current in DefDatabase <ThingDef> .AllDefs.Where((ThingDef arg) => arg.race != null))
            {
                current.inspectorTabs.Add(typeof(UI.ITab_Pawn_Food));
                current.inspectorTabsResolved.Add(InspectTabManager.GetSharedInstance(typeof(UI.ITab_Pawn_Food)));

                ////Tab inject
                //var newTabType = typeof(UI.ITab_Pawn_Needs);
                //var oldTabType = typeof(ITab_Pawn_Needs);

                //int index = current.inspectorTabs.IndexOf(oldTabType);

                //if (index != -1)
                //{
                //	current.inspectorTabs[index] = newTabType;

                //	int index2 = current.inspectorTabsResolved.IndexOf(InspectTabManager.GetSharedInstance(oldTabType));

                //	if (index2 != -1)
                //	{
                //		current.inspectorTabsResolved[index2] = InspectTabManager.GetSharedInstance(newTabType);
                //	}
                //}
            }

            // ----------- Processing policies and patches -----------

            foreach (CompabilityDef def in ModCore.patches)
            {
                def.TryApplyPatch();
            }

            // Hardcoded policies
            DefDatabase <Policy> .Add(Policies.Unrestricted);

            DefDatabase <Policy> .Add(Policies.Taming);

            DefDatabase <Policy> .Add(Policies.FriendlyPets);

            DefDatabase <Policy> .Add(Policies.Friendly);

            //Policies.FriendlyPets.DefsLoaded();

            foreach (MyDefClass current in Policies.AllPolicies)
            {
                current.DefsLoaded();
            }

            Policies.BuildMaskTree();

            // ----------- Processing food categories and races -----------

            foreach (ThingDef current in DefDatabaseHelper.AllDefsIngestibleNAnimals)
            {
                if (current.ingestible != null)
                {
                    current.DetermineFoodCategory(true);
                }
                else if (current.race != null && current.race.IsFlesh)
                {
                    if (current.race.meatDef != null)
                    {
                        current.race.meatDef.DetermineFoodCategory(true);
                    }

                    if (current.race.corpseDef != null)
                    {
                        current.race.corpseDef.DetermineFoodCategory(true);
                    }
                }
            }

            // ----------- Processing recipes for food cost factors -----------

            //TODO: manage intermediate recipes + handle side products
            foreach (RecipeDef recipeDef in DefDatabase <RecipeDef> .AllDefs)
            {
                if (recipeDef.products == null || recipeDef.products.Count > 1 || recipeDef.ingredients == null || !recipeDef.products.Any((obj) => obj.thingDef.ingestible != null))
                {
                    continue;
                }

                float nutritionCost = recipeDef.ingredients.Sum((arg) => arg.GetBaseCount());
                var   singleProduct = recipeDef.products.FirstOrDefault().thingDef;

                if (!recipeDef.products.All((arg) => arg.thingDef == singleProduct))
                {
                    continue;
                }

                float nutritionOutput = recipeDef.products.Sum((arg) => arg.thingDef.ingestible.nutrition * arg.count);

                if (nutritionOutput <= 0f)
                {
                    continue;
                }

                float costFactor = nutritionCost / nutritionOutput;

                FoodDefRecord record;

                if (FoodCategoryUtils.FoodRecords.TryGetValue(singleProduct, out record))
                {
                    record.costFactor = Math.Min(record.costFactor, costFactor);
                }
            }

            // Dispenser(s)
            //TODO: make more reliable
            {
                FoodDefRecord record;
                var           dispensableDef = ThingDefOf.MealNutrientPaste;
                if (FoodCategoryUtils.FoodRecords.TryGetValue(dispensableDef, out record))
                {
                    float costFactor = 0.3f / dispensableDef.ingestible.nutrition;
                    record.costFactor = Math.Min(record.costFactor, costFactor);
                }
            }


            //foreach (ThingDef dispenser in DefDatabase<ThingDef>.AllDefs.Where(arg => arg.IsFoodDispenser))

            //ThingDef meal = null;
            //float foodCost = 0;

            //if (dispenser.thingClass == typeof(Building_NutrientPasteDispenser))
            //{
            //	var dummy = new Building_NutrientPasteDispenser();
            //	meal = dummy.DispensableDef;
            //	foodCost = (dummy.def.building.foodCostPerDispense * 0.05f);
            //}

            //if (meal != null)
            //{
            //	float costFactor = foodCost / meal.ingestible.nutrition;
            //	FoodDefRecord record;
            //	if (FoodCategoryUtils.FoodRecords.TryGetValue(meal, out record))
            //	{
            //		record.costFactor = Math.Min(record.costFactor, costFactor);
            //	}
            //}
            //}

            // ----------- Reporting -----------

            var loadedPaches = patches.Where((arg) => arg.Loaded);

            Logger.Message(string.Format("Loaded - {0} food categorized - {1} pawn diets - {2} compatibility patches ({3} fixes) - {4} policies.", FoodCategoryUtils.TotalFoodPrefsCount, FoodCategoryUtils.TotalAnimalsDietsCount, loadedPaches.Count(), loadedPaches.Sum((arg) => arg.DefsCount), Policies.AllPolicies.Count()));

            if (FoodCategoryUtils.NullPrefFoodsCount > 0)
            {
                Logger.Warning(string.Format("Could not determine food category for {0} Defs. Restricted pawns will ignore them. Are you using unsupported food mods ? ({1})", FoodCategoryUtils.NullPrefFoodsCount, string.Join(" ; ", FoodCategoryUtils.NullPrefFoods.Select((ThingDef arg) => arg.defName + " (" + arg.label + ")").ToArray())));
            }
        }
Beispiel #26
0
        public static void AddSaltedMeats()
        {
            HashSet <ThingDef> defsToAdd = new HashSet <ThingDef>();

            foreach (ThingDef td in DefDatabase <ThingDef> .AllDefs.Where(t => t.IsMeat))
            {
                ThingDef d = new ThingDef
                {
                    resourceReadoutPriority = td.resourceReadoutPriority, //ResourceCountPriority.Middle;
                    category    = td.category,                            // ThingCategory.Item;
                    thingClass  = td.thingClass,                          // typeof(ThingWithComps);
                    graphicData = new GraphicData()
                };
                d.graphicData.graphicClass = td.graphicData.graphicClass; // typeof(Graphic_Single);
                d.useHitPoints             = td.useHitPoints;             // true;
                d.selectable = td.selectable;                             // true;
                //d.SetStatBaseValue(StatDefOf.MaxHitPoints, 115f);
                d.SetStatBaseValue(StatDefOf.MaxHitPoints, td.GetStatValueAbstract(StatDefOf.MaxHitPoints) * 1.15f);
                d.altitudeLayer = td.altitudeLayer; // AltitudeLayer.Item;
                d.stackLimit    = td.stackLimit;    // 75;
                d.comps.Add(new CompProperties_Forbiddable());
                CompProperties_Rottable rotProps = new CompProperties_Rottable
                {
                    daysToRotStart = td.GetCompProperties <CompProperties_Rottable>().daysToRotStart, // 2f;
                    rotDestroys    = td.GetCompProperties <CompProperties_Rottable>().rotDestroys     // true;
                };
                d.comps.Add(rotProps);
                d.tickerType = td.tickerType;                                                                                 // TickerType.Rare;
                d.SetStatBaseValue(StatDefOf.Beauty, td.GetStatValueAbstract(StatDefOf.Beauty));                              // -20f
                d.alwaysHaulable          = td.alwaysHaulable;                                                                // true;
                d.rotatable               = td.rotatable;                                                                     // false;
                d.pathCost                = td.pathCost;                                                                      // 15;
                d.drawGUIOverlay          = td.drawGUIOverlay;                                                                // true;
                d.socialPropernessMatters = td.socialPropernessMatters;                                                       // true;

                d.modContentPack = td.modContentPack;                                                                         // +

                d.category     = td.category;                                                                                 // ThingCategory.Item;
                d.description  = td.description;
                d.useHitPoints = td.useHitPoints;                                                                             // true;
                d.SetStatBaseValue(StatDefOf.MaxHitPoints, td.GetStatValueAbstract(StatDefOf.MaxHitPoints) * 1.15f);          // 65f
                d.SetStatBaseValue(StatDefOf.DeteriorationRate, td.GetStatValueAbstract(StatDefOf.DeteriorationRate) * 0.5f); // 3f
                d.SetStatBaseValue(StatDefOf.Mass, td.GetStatValueAbstract(StatDefOf.Mass));                                  // 0.025f
                d.SetStatBaseValue(StatDefOf.Flammability, td.GetStatValueAbstract(StatDefOf.Flammability));                  // 0.5f
                d.SetStatBaseValue(StatDefOf.Nutrition, td.GetStatValueAbstract(StatDefOf.Nutrition) * 1.6f);
                //d.ingestible.nutrition = td.ingestible.nutrition + 0.03f;
                d.SetStatBaseValue(StatDefOf.FoodPoisonChanceFixedHuman, 0.02f);
                //d.comps.Add(new CompProperties_FoodPoisonable());
                d.BaseMarketValue = td.BaseMarketValue;
                if (d.thingCategories == null)
                {
                    d.thingCategories = new List <ThingCategoryDef>();
                }
                DirectXmlCrossRefLoader.RegisterListWantsCrossRef <ThingCategoryDef>(d.thingCategories, "LotR_MeatRawSalted", d);
                d.ingestible = new IngestibleProperties {
                    parent = d
                };
                d.ingestible.foodType      = td.ingestible.foodType;      // FoodTypeFlags.Meat;
                d.ingestible.preferability = td.ingestible.preferability; // FoodPreferability.RawBad;
                DirectXmlCrossRefLoader.RegisterObjectWantsCrossRef(d.ingestible, "tasteThought", ThoughtDefOf.AteRawFood.defName);
                d.ingestible.ingestEffect               = td.ingestible.ingestEffect;
                d.ingestible.ingestSound                = td.ingestible.ingestSound;
                d.ingestible.specialThoughtDirect       = td.ingestible.specialThoughtDirect;
                d.ingestible.specialThoughtAsIngredient = td.ingestible.specialThoughtAsIngredient;

                d.graphicData.texPath = td.graphicData.texPath;
                d.graphicData.color   = td.graphicData.color;
                //d.thingCategories.Add(TTADefOf.LotR_MeatRawSalted);
                d.defName = td.defName + "Salted";
                d.label   = "TTA_SaltedLabel".Translate(td.label);
                d.ingestible.sourceDef = td.ingestible.sourceDef;
                defsToAdd.Add(d);
            }
            TTADefOf.LotR_MeatRawSalted.parent = ThingCategoryDefOf.MeatRaw;
            while (defsToAdd?.Count > 0)
            {
                var thingDef = defsToAdd.FirstOrDefault();
                if (thingDef != null)
                {
                    if (!DefDatabase <ThingDef> .AllDefs.Contains(thingDef))
                    {
                        thingDef.PostLoad();
                        DefDatabase <ThingDef> .Add(thingDef);

                        if (!TTADefOf.LotR_MeatRawSalted.childThingDefs.Contains(thingDef))
                        {
                            TTADefOf.LotR_MeatRawSalted.childThingDefs.Add(thingDef);
                        }
                    }
                    defsToAdd.Remove(thingDef);
                }
                else
                {
                    break;
                }
            }

            DirectXmlCrossRefLoader.ResolveAllWantedCrossReferences(FailMode.Silent);
        }
Beispiel #27
0
        public static void CreateStuff(this ResearchProjectDef tech, ThingFilter filter, UnlockManager unlocked)
        {
            string           name = "Tech_" + tech.defName;
            ThingCategoryDef tCat = DefDatabase <ThingCategoryDef> .GetNamed(tech.techLevel.ToString());

            string   label     = "KnowledgeLabel".Translate(tech.label);
            ThingDef techStuff = new ThingDef
            {
                thingClass      = typeof(ThingWithComps),
                defName         = name,
                label           = label,
                description     = tech.description,
                category        = ThingCategory.Item,
                thingCategories = new List <ThingCategoryDef>()
                {
                    tCat
                },
                techLevel  = tech.techLevel,
                menuHidden = true,
                stuffProps = new StuffProperties()
                {
                    categories = new List <StuffCategoryDef>()
                    {
                        TechDefOf.Technic
                    },
                    color          = ResearchTree_Assets.ColorCompleted[tech.techLevel],
                    stuffAdjective = tech.LabelCap,
                    statOffsets    = new List <StatModifier>()
                    {
                        new StatModifier
                        {
                            stat  = StatDefOf.MarketValue,
                            value = MarketValueOffset
                        }
                    },
                    statFactors = new List <StatModifier>()
                    {
                        new StatModifier
                        {
                            stat  = StatDefOf.WorkToMake,
                            value = StuffCostFactor(tech)
                        },
                        new StatModifier
                        {
                            stat  = StatDefOf.MarketValue,
                            value = StuffMarketValueFactor(tech)
                        }
                    }
                }
            };

            techStuff.ResolveReferences();
            MethodInfo GiveShortHashInfo = AccessTools.Method(typeof(ShortHashGiver), "GiveShortHash");

            GiveShortHashInfo.Invoke(tech, new object[] { techStuff, typeof(ThingDef) });
            DefDatabase <ThingDef> .Add(techStuff);

            filter.SetAllow(techStuff, true);
            unlocked.stuffByTech.Add(tech, techStuff);
            unlocked.techByStuff.Add(techStuff, tech);
        }
Beispiel #28
0
 static void GetStuffedTerrainDefPosfix(TerrainDef __result)
 {
     DefDatabase <BuildableDef> .Add(__result);
 }