Пример #1
0
 // Deep-copies modded properties from a source pawn to a target pawn.  Kept separate from the Copy() method to provide a
 // clear place for modders to add patches/detours for their mods.
 private static void CopyModdedProperties(Pawn source, Pawn target)
 {
     // Copy fields from Psychology mod.
     object[] constructorArgs = new object[] { target };
     UtilityCopy.CopyExposableViaReflection("psyche", source, target, constructorArgs);
     UtilityCopy.CopyExposableViaReflection("sexuality", source, target, constructorArgs);
 }
Пример #2
0
        // It would be nice if we could just do this to deep copy a pawn, but there are references to world objects in a saved pawn that can cause
        // problems, i.e. relationship references to other pawns.  So we follow the more explicit technique below to copy the pawn.
        // Leaving this here to remind us to not bother trying to do this again.
        //public static Pawn IdealCopy(this Pawn source) {
        //    try {
        //        Pawn copy = UtilityCopy.CopyExposable<Pawn>(source);
        //        copy.ClearCaches();
        //        return copy;
        //    }
        //    catch (Exception e) {
        //        Logger.Warning("Failed to copy pawn with preferred method.  Using backup method instead.\n" + e);
        //        return CopyBackup(source);
        //    }
        //}

        public static Pawn Copy(this Pawn source)
        {
            PawnHealthState savedHealthState = source.health.State;

            Pawn result = (Pawn)ThingMaker.MakeThing(source.kindDef.race, null);

            result.kindDef = source.kindDef;
            result.SetFactionDirect(source.Faction);
            PawnComponentsUtility.CreateInitialComponents(result);

            // Copy gender.
            result.gender = source.gender;

            // Copy name;
            NameTriple nameTriple = source.Name as NameTriple;
            NameSingle nameSingle = source.Name as NameSingle;

            if (nameTriple != null)
            {
                result.Name = new NameTriple(nameTriple.First, nameTriple.Nick, nameTriple.Last);
            }
            else if (nameSingle != null)
            {
                result.Name = new NameSingle(nameSingle.Name, nameSingle.Numerical);
            }

            // Copy trackers.
            object[] constructorArgs = new object[] { result };
            result.ageTracker = UtilityCopy.CopyExposable(source.ageTracker, constructorArgs);
            result.story      = UtilityCopy.CopyExposable(source.story, constructorArgs);
            result.skills     = UtilityCopy.CopyExposable(source.skills, constructorArgs);
            result.health     = UtilityCopy.CopyExposable(source.health, constructorArgs);
            result.apparel    = UtilityCopy.CopyExposable(source.apparel, constructorArgs);

            // Copy comps
            //List<ThingComp> validComps = new List<ThingComp>();
            //foreach (var c in source.AllComps) {
            //    PawnCompsSaver saver = new PawnCompsSaver(new List<ThingComp>() { c }, null);
            //    string xml = UtilityCopy.SerializeExposableToString(saver);
            //    XmlDocument doc = new XmlDocument();
            //    doc.LoadXml(xml);
            //    if (doc.DocumentElement.HasChildNodes) {
            //        validComps.Add(c);
            //        Logger.Debug(c.GetType().FullName + ": \n  " + xml);
            //    }
            //    else {
            //        Logger.Debug(c.GetType().FullName + " is empty");
            //    }
            //}

            CopyPawnComps(source, result);

            // Clear all of the pawn caches.
            source.ClearCaches();
            result.ClearCaches();

            return(result);
        }
Пример #3
0
        public static Pawn Copy(this Pawn source)
        {
            PawnHealthState savedHealthState = source.health.State;

            Pawn result = (Pawn)ThingMaker.MakeThing(source.kindDef.race, null);

            result.kindDef = source.kindDef;
            result.SetFactionDirect(source.Faction);
            PawnComponentsUtility.CreateInitialComponents(result);

            // Copy gender.
            result.gender = source.gender;

            // Copy name;
            NameTriple nameTriple = source.Name as NameTriple;
            NameSingle nameSingle = source.Name as NameSingle;

            if (nameTriple != null)
            {
                result.Name = new NameTriple(nameTriple.First, nameTriple.Nick, nameTriple.Last);
            }
            else if (nameSingle != null)
            {
                result.Name = new NameSingle(nameSingle.Name, nameSingle.Numerical);
            }

            // Copy trackers.
            object[] constructorArgs = new object[] { result };
            result.ageTracker = UtilityCopy.CopyExposable(source.ageTracker, constructorArgs);
            result.story      = UtilityCopy.CopyExposable(source.story, constructorArgs);
            result.skills     = UtilityCopy.CopyExposable(source.skills, constructorArgs);
            result.health     = UtilityCopy.CopyExposable(source.health, constructorArgs);
            result.apparel    = UtilityCopy.CopyExposable(source.apparel, constructorArgs);

            // Copy properties added to pawns by mods.
            CopyModdedProperties(source, result);

            // Verify the pawn health state.
            if (result.health.State != savedHealthState)
            {
                Log.Warning("Mismatched health state on copied pawn: " + savedHealthState + " != " + result.health.State + ";  Resetting value to match.");
                result.SetHealthState(savedHealthState);
            }

            // Clear all of the pawn caches.
            source.ClearCaches();

            return(result);
        }
Пример #4
0
        // Given a field name, deep-copies an instance of an IExposable class from a source object to a target object via reflection.
        // Creates a deep copy by serializing and then deserializing the IExposable instance.  The class must be constructable
        // with no arguments.
        public static void CopyExposableViaReflection(string fieldName, object source, object target, object[] constructorArgs)
        {
            FieldInfo sourceField = source.GetType().GetField(fieldName);
            FieldInfo targetField = target.GetType().GetField(fieldName);

            if (sourceField != null && targetField != null)
            {
                object value = sourceField.GetValue(source);
                if (typeof(IExposable).IsAssignableFrom(value.GetType()))
                {
                    IExposable e    = (IExposable)value;
                    IExposable copy = UtilityCopy.CopyExposable(e, constructorArgs);
                    targetField.SetValue(target, copy);
                }
            }
        }
Пример #5
0
        public static void CopyPawnComps(Pawn source, Pawn target)
        {
            PawnCompsSaver saver = new PawnCompsSaver(source, DefaultPawnCompRules.RulesForCopying);
            string         xml   = UtilityCopy.SerializeExposableToString(saver);
            //Logger.Debug("Serialized comps to string\n" + xml);
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(xml);
            foreach (var fieldPath in DefaultPawnCompRules.RulesForCopying.ExcludedFields)
            {
                XmlNode node = doc.DocumentElement.SelectSingleNode(fieldPath);
                if (node != null)
                {
                    //Logger.Debug("Removing " + node.Name + " element");
                    doc.DocumentElement.RemoveChild(node);
                }
            }
            xml = "<saveable Class=\"" + typeof(PawnCompsLoader).FullName + "\">" + doc.DocumentElement.InnerXml + "</saveable>";
            //Logger.Debug("Post node-exclusions\n" + xml);
            UtilityCopy.DeserializeExposable <PawnCompsLoader>(xml, new object[] { target, DefaultPawnCompRules.RulesForCopying });
        }
Пример #6
0
        public void PrepareGame()
        {
            PrepareColonists();
            PrepareWorldPawns();
            PrepareRelatedPawns();

            // This needs some explaining.  We need custom scenario parts to handle animal spawning
            // and scattered things.  However, we don't want the scenario that gets saved with a game
            // to include any Prepare Carefully-specific parts (because the save would become bound to
            // the mod).  We work around this by creating two copies of the actual scenario.  The first
            // copy includes the customized scenario parts needed to do the spawning.  The second contains
            // vanilla versions of those parts that can safely be saved without forcing a dependency on
            // the mod.  The GenStep_RemovePrepareCarefullyScenario class is responsible for switching out
            // the actual scenario with the vanilla-friendly version at the end of the map generation process.
            Scenario actualScenario          = UtilityCopy.CopyExposable(Find.Scenario);
            Scenario vanillaFriendlyScenario = UtilityCopy.CopyExposable(Find.Scenario);

            Current.Game.Scenario             = actualScenario;
            PrepareCarefully.OriginalScenario = vanillaFriendlyScenario;

            // Remove equipment scenario parts.
            ReplaceScenarioParts(actualScenario, vanillaFriendlyScenario);
        }
Пример #7
0
        public CustomPawn ConvertSaveRecordToPawn(SaveRecordPawnV5 record)
        {
            bool partialFailure = false;

            PawnKindDef pawnKindDef = null;

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

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

            ThingDef pawnThingDef = ThingDefOf.Human;

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

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

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

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

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

            CustomPawn pawn = new CustomPawn(source);

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

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

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

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

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

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

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

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

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

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

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

            Backstory backstory = FindBackstory(record.childhood);

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

            BodyTypeDef bodyType = null;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            return(pawn);
        }