Exemplo n.º 1
0
        public void RandomizeBackstories()
        {
            CustomPawn  currentPawn = state.CurrentPawn;
            PawnKindDef kindDef     = currentPawn.Pawn.kindDef;
            FactionDef  factionDef  = kindDef.defaultFactionType;

            if (factionDef == null)
            {
                factionDef = Faction.OfPlayer.def;
            }
            List <BackstoryCategoryFilter> backstoryCategoryFiltersFor = Reflection.PawnBioAndNameGenerator.GetBackstoryCategoryFiltersFor(currentPawn.Pawn, factionDef);

            // Generate a bio from which to get the backstories
            if (!Reflection.PawnBioAndNameGenerator.TryGetRandomUnusedSolidBioFor(backstoryCategoryFiltersFor, kindDef, currentPawn.Gender, null, out PawnBio pawnBio))
            {
                // Other mods are patching the vanilla method in ways that cause it to return false.  If that happens,
                // we use our duplicate implementation instead.
                if (!PawnBioGenerator.TryGetRandomUnusedSolidBioFor(backstoryCategoryFiltersFor, kindDef, currentPawn.Gender, null, out pawnBio))
                {
                    // If we still can't get a bio with our duplicate implementation, we pick backstories completely at random.
                    currentPawn.Childhood = PrepareCarefully.Instance.Providers.Backstories.GetChildhoodBackstoriesForPawn(currentPawn).RandomElement();
                    if (currentPawn.BiologicalAge >= 20)
                    {
                        currentPawn.Adulthood = PrepareCarefully.Instance.Providers.Backstories.GetAdulthoodBackstoriesForPawn(currentPawn).RandomElement();
                    }
                    return;
                }
            }
            currentPawn.Childhood = pawnBio.childhood;
            // TODO: Can we remove the hard-coded adult age and get the value from a provider instead?
            // Probably not in vanilla, but maybe if other mods somehow override the "20" that's hard-coded in the vanilla code.
            if (currentPawn.BiologicalAge >= 20)
            {
                currentPawn.Adulthood = pawnBio.adulthood;
            }
        }
Exemplo n.º 2
0
 public void AddPawn(CustomPawn customPawn)
 {
     pawns.Add(customPawn);
 }
Exemplo n.º 3
0
 public static Backstory RandomAdulthood(CustomPawn customPawn)
 {
     return(PrepareCarefully.Instance.Providers.Backstories.GetAdulthoodBackstoriesForPawn(customPawn).RandomElement());
 }
Exemplo n.º 4
0
 public Pawn GenerateSameKindAndGenderOfPawn(CustomPawn customPawn)
 {
     return(GenerateKindAndGenderOfPawn(customPawn.Pawn.kindDef, customPawn.Gender));
 }
Exemplo n.º 5
0
 public void DeleteAllPawnRelationships(CustomPawn pawn)
 {
     PrepareCarefully.Instance.RelationshipManager.DeletePawn(pawn);
 }
Exemplo n.º 6
0
 public bool Contains(PawnRelationDef def, CustomPawn source, CustomPawn target)
 {
     return(Find(def, source, target) != null);
 }
 public List <HairDef> GetHairs(CustomPawn pawn)
 {
     return(GetHairs(pawn.Pawn.def, pawn.Gender));
 }
        public CustomPawn LoadPawn(SaveRecordPawnV3 record)
        {
            PawnKindDef pawnKindDef = null;

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

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

            ThingDef pawnThingDef = ThingDefOf.Human;

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

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

            Pawn source;

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

            CustomPawn pawn = new CustomPawn(source);

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

            pawn.Type = CustomPawnType.Colonist;

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

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

            HairDef h = FindHairDef(record.hairDef);

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

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

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

            Backstory backstory = FindBackstory(record.childhood);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            return(pawn);
        }
Exemplo n.º 9
0
        public void AddFactionPawn(PawnKindDef kindDef, bool startingPawn)
        {
            FactionDef factionDef = kindDef.defaultFactionType;
            Faction    faction    = PrepareCarefully.Instance.Providers.Factions.GetFaction(factionDef);

            // Workaround to force pawn generation to skip adding weapons to the pawn.
            // Might be a slightly risky hack, but the finally block should guarantee that
            // the weapons money range always gets set back to its original value.
            // TODO: Try to remove this at a later date.  It would be nice if the pawn generation
            // request gave you an option to skip weapon and equipment generation.
            FloatRange savedWeaponsMoney = kindDef.weaponMoney;

            kindDef.weaponMoney = new FloatRange(0, 0);
            Pawn pawn = null;

            try {
                pawn = randomizer.GeneratePawn(new PawnGenerationRequestWrapper()
                {
                    Faction = faction,
                    KindDef = kindDef,
                    Context = PawnGenerationContext.NonPlayer,
                    WorldPawnFactionDoesntMatter = true
                }.Request);
                if (pawn.equipment != null)
                {
                    pawn.equipment.DestroyAllEquipment(DestroyMode.Vanish);
                }
                if (pawn.inventory != null)
                {
                    pawn.inventory.DestroyAll(DestroyMode.Vanish);
                }
            }
            catch (Exception e) {
                Log.Warning("Failed to create faction pawn of kind " + kindDef.defName);
                Log.Message(e.Message);
                Log.Message(e.StackTrace);
                if (pawn != null)
                {
                    pawn.Destroy();
                }
                state.AddError("EdB.PC.Panel.PawnList.Error.FactionPawnFailed".Translate());
                return;
            }
            finally {
                kindDef.weaponMoney = savedWeaponsMoney;
            }
            // Reset the quality and damage of all apparel.
            foreach (var a in pawn.apparel.WornApparel)
            {
                a.SetQuality(QualityCategory.Normal);
                a.HitPoints = a.MaxHitPoints;
            }

            CustomPawn customPawn = new CustomPawn(pawn);

            customPawn.Type = startingPawn ? CustomPawnType.Colonist : CustomPawnType.World;
            if (!startingPawn)
            {
                CustomFaction customFaction = PrepareCarefully.Instance.Providers.Factions.FindRandomCustomFactionByDef(factionDef);
                if (customFaction != null)
                {
                    customPawn.Faction = customFaction;
                }
            }

            PrepareCarefully.Instance.AddPawn(customPawn);
            state.CurrentPawn = customPawn;
            PawnAdded(customPawn);
        }
Exemplo n.º 10
0
 // Pawn-related actions.
 public void SelectPawn(CustomPawn pawn)
 {
     state.CurrentPawn = pawn;
 }
Exemplo n.º 11
0
        public SaveRecordPawnV4(CustomPawn pawn)
        {
            this.id       = pawn.Id;
            this.thingDef = pawn.Pawn.def.defName;
            this.type     = pawn.Type.ToString();
            if (pawn.Type == CustomPawnType.World && pawn.Faction != null)
            {
                this.faction        = new SaveRecordFactionV4();
                this.faction.def    = pawn.Faction.Def != null ? pawn.Faction.Def.defName : null;
                this.faction.index  = pawn.Faction.Index;
                this.faction.leader = pawn.Faction.Leader;
            }
            this.pawnKindDef        = pawn.OriginalKindDef != null ? pawn.OriginalKindDef.defName : pawn.Pawn.kindDef.defName;
            this.originalFactionDef = pawn.OriginalFactionDef != null ? pawn.OriginalFactionDef.defName : null;
            this.gender             = pawn.Gender;
            if (pawn.Adulthood != null)
            {
                this.adulthood = pawn.Adulthood.identifier;
            }
            else
            {
                this.adulthood = pawn.LastSelectedAdulthoodBackstory?.identifier;
            }
            this.childhood        = pawn.Childhood.identifier;
            this.skinColor        = pawn.Pawn.story.SkinColor;
            this.melanin          = pawn.Pawn.story.melanin;
            this.hairDef          = pawn.HairDef.defName;
            this.hairColor        = pawn.Pawn.story.hairColor;
            this.headGraphicPath  = pawn.HeadGraphicPath;
            this.bodyType         = pawn.BodyType.defName;
            this.firstName        = pawn.FirstName;
            this.nickName         = pawn.NickName;
            this.lastName         = pawn.LastName;
            this.age              = 0;
            this.biologicalAge    = pawn.BiologicalAge;
            this.chronologicalAge = pawn.ChronologicalAge;
            foreach (var trait in pawn.Traits)
            {
                if (trait != null)
                {
                    this.traitNames.Add(trait.def.defName);
                    this.traitDegrees.Add(trait.Degree);
                }
            }
            foreach (var skill in pawn.Pawn.skills.skills)
            {
                SaveRecordSkillV4 skillRecord = new SaveRecordSkillV4();
                skillRecord.name    = skill.def.defName;
                skillRecord.value   = pawn.GetUnmodifiedSkillLevel(skill.def);
                skillRecord.passion = pawn.currentPassions[skill.def];
                this.skills.Add(skillRecord);
            }
            foreach (var layer in PrepareCarefully.Instance.Providers.PawnLayers.GetLayersForPawn(pawn))
            {
                if (layer.Apparel)
                {
                    ThingDef apparelThingDef = pawn.GetAcceptedApparel(layer);
                    Color    color           = pawn.GetColor(layer);
                    if (apparelThingDef != null)
                    {
                        ThingDef            apparelStuffDef = pawn.GetSelectedStuff(layer);
                        SaveRecordApparelV4 apparelRecord   = new SaveRecordApparelV4();
                        apparelRecord.layer   = layer.Name;
                        apparelRecord.apparel = apparelThingDef.defName;
                        apparelRecord.stuff   = apparelStuffDef != null ? apparelStuffDef.defName : "";
                        apparelRecord.color   = color;
                        this.apparel.Add(apparelRecord);
                    }
                }
            }
            OptionsHealth healthOptions = PrepareCarefully.Instance.Providers.Health.GetOptions(pawn);

            foreach (Implant implant in pawn.Implants)
            {
                var saveRecord = new SaveRecordImplantV3(implant);
                if (implant.BodyPartRecord != null)
                {
                    UniqueBodyPart part = healthOptions.FindBodyPartsForRecord(implant.BodyPartRecord);
                    if (part != null && part.Index > 0)
                    {
                        saveRecord.bodyPartIndex = part.Index;
                    }
                }
                this.implants.Add(saveRecord);
            }
            foreach (Injury injury in pawn.Injuries)
            {
                var saveRecord = new SaveRecordInjuryV3(injury);
                if (injury.BodyPartRecord != null)
                {
                    UniqueBodyPart part = healthOptions.FindBodyPartsForRecord(injury.BodyPartRecord);
                    if (part != null && part.Index > 0)
                    {
                        saveRecord.bodyPartIndex = part.Index;
                    }
                }
                this.injuries.Add(saveRecord);
            }

            ThingComp alienComp = ProviderAlienRaces.FindAlienCompForPawn(pawn.Pawn);

            if (alienComp != null)
            {
                alien                 = new SaveRecordAlienV4();
                alien.crownType       = ProviderAlienRaces.GetCrownTypeFromComp(alienComp);
                alien.skinColor       = ProviderAlienRaces.GetSkinColorFromComp(alienComp);
                alien.skinColorSecond = ProviderAlienRaces.GetSkinColorSecondFromComp(alienComp);
                alien.hairColorSecond = ProviderAlienRaces.GetHairColorSecondFromComp(alienComp);
            }
        }
Exemplo n.º 12
0
 public override void SelectColor(CustomPawn pawn, Color color)
 {
     pawn.SkinColor = color;
 }
Exemplo n.º 13
0
 public override Color GetSelectedColor(CustomPawn pawn)
 {
     return(pawn.SkinColor);
 }
Exemplo n.º 14
0
        public CustomPawn Load(PrepareCarefully loadout, string name)
        {
            SaveRecordPawnV3 pawnRecord = new SaveRecordPawnV3();
            string           modString  = "";
            string           version    = "";

            try {
                Scribe.loader.InitLoading(ColonistFiles.FilePathForSavedColonist(name));
                Scribe_Values.Look <string>(ref version, "version", "unknown", false);
                Scribe_Values.Look <string>(ref modString, "mods", "", false);

                try {
                    Scribe_Deep.Look <SaveRecordPawnV3>(ref pawnRecord, "colonist", null);
                }
                catch (Exception e) {
                    Messages.Message(modString, MessageTypeDefOf.SilentInput);
                    Messages.Message("EdB.PC.Dialog.PawnPreset.Error.Failed".Translate(), MessageTypeDefOf.RejectInput);
                    Log.Warning(e.ToString());
                    Log.Warning("Colonist was created with the following mods: " + modString);
                    return(null);
                }
            }
            catch (Exception e) {
                Log.Error("Failed to load preset file");
                throw e;
            }
            finally {
                // I don't fully understand how these cross-references and saveables are resolved, but
                // if we don't clear them out, we get null pointer exceptions.
                HashSet <IExposable> saveables = (HashSet <IExposable>)(typeof(PostLoadIniter).GetField("saveablesToPostLoad", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(Scribe.loader.initer));
                saveables.Clear();
                List <IExposable> crossReferencingExposables = (List <IExposable>)(typeof(CrossRefHandler).GetField("crossReferencingExposables", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(Scribe.loader.crossRefs));
                crossReferencingExposables.Clear();
                Scribe.loader.FinalizeLoading();
            }

            if (pawnRecord == null)
            {
                Messages.Message(modString, MessageTypeDefOf.SilentInput);
                Messages.Message("EdB.PC.Dialog.PawnPreset.Error.Failed".Translate(), MessageTypeDefOf.RejectInput);
                Log.Warning("Colonist was created with the following mods: " + modString);
                return(null);
            }

            PresetLoaderVersion3 loader     = new PresetLoaderVersion3();
            CustomPawn           loadedPawn = loader.LoadPawn(pawnRecord);

            if (loadedPawn != null)
            {
                CustomPawn idConflictPawn = PrepareCarefully.Instance.Pawns.FirstOrDefault((CustomPawn p) => {
                    return(p.Id == loadedPawn.Id);
                });
                if (idConflictPawn != null)
                {
                    loadedPawn.GenerateId();
                }
                return(loadedPawn);
            }
            else
            {
                loadout.State.AddError(loader.ModString);
                loadout.State.AddError("EdB.PC.Dialog.Preset.Error.NoCharacter".Translate());
                Log.Warning("Preset was created with the following mods: " + modString);
                return(null);
            }
        }
Exemplo n.º 15
0
 public void RemovePawn(CustomPawn customPawn)
 {
     pawns.Remove(customPawn);
 }
Exemplo n.º 16
0
        protected override void DrawPanelContent(State state)
        {
            /*
             * // Test code for adjusting the size and position of the portrait.
             * if (Event.current.type == EventType.KeyDown) {
             *  if (Event.current.shift) {
             *      if (Event.current.keyCode == KeyCode.LeftArrow) {
             *          float portraitWidth = RectPortrait.width;
             *          portraitWidth -= 1f;
             *          float portraitHeight = Mathf.Floor(portraitWidth * 1.4f);
             *          RectPortrait = new Rect(RectPortrait.x, RectPortrait.y, portraitWidth, portraitHeight);
             *          Log.Message("RectPortrait = " + RectPortrait);
             *      }
             *      else if (Event.current.keyCode == KeyCode.RightArrow) {
             *          float portraitWidth = RectPortrait.width;
             *          portraitWidth += 1f;
             *          float portraitHeight = Mathf.Floor(portraitWidth * 1.4f);
             *          RectPortrait = new Rect(RectPortrait.x, RectPortrait.y, portraitWidth, portraitHeight);
             *          Log.Message("RectPortrait = " + RectPortrait);
             *      }
             *  }
             *  else {
             *      if (Event.current.keyCode == KeyCode.LeftArrow) {
             *          RectPortrait = RectPortrait.OffsetBy(new Vector2(-1, 0));
             *          Log.Message("RectPortrait = " + RectPortrait);
             *      }
             *      else if (Event.current.keyCode == KeyCode.RightArrow) {
             *          RectPortrait = RectPortrait.OffsetBy(new Vector2(1, 0));
             *          Log.Message("RectPortrait = " + RectPortrait);
             *      }
             *      else if (Event.current.keyCode == KeyCode.UpArrow) {
             *          RectPortrait = RectPortrait.OffsetBy(new Vector2(0, -1));
             *          Log.Message("RectPortrait = " + RectPortrait);
             *      }
             *      else if (Event.current.keyCode == KeyCode.DownArrow) {
             *          RectPortrait = RectPortrait.OffsetBy(new Vector2(0, 1));
             *          Log.Message("RectPortrait = " + RectPortrait);
             *      }
             *  }
             * }
             */
            base.DrawPanelContent(state);

            CustomPawn        currentPawn  = state.CurrentPawn;
            CustomPawn        pawnToSelect = null;
            CustomPawn        pawnToSwap   = null;
            CustomPawn        pawnToDelete = null;
            List <CustomPawn> pawns        = GetPawnListFromState(state);
            int colonistCount = pawns.Count();

            if (IsMinimized(state))
            {
                // Count label.
                Text.Font = GameFont.Medium;
                float headerWidth = Text.CalcSize(PanelHeader).x;
                Rect  countRect   = new Rect(10 + headerWidth + 3, 3, 50, 27);
                GUI.color   = Style.ColorTextPanelHeader;
                Text.Font   = GameFont.Small;
                Text.Anchor = TextAnchor.LowerLeft;
                Widgets.Label(countRect, "EdB.PC.Panel.PawnList.PawnCount".Translate(colonistCount));
                GUI.color = Color.white;

                // Maximize button.
                if (RectHeader.Contains(Event.current.mousePosition))
                {
                    GUI.color = Style.ColorButtonHighlight;
                }
                else
                {
                    GUI.color = Style.ColorButton;
                }
                GUI.DrawTexture(RectMaximize, IsTopPanel() ? Textures.TextureMaximizeDown : Textures.TextureMaximizeUp);
                if (Widgets.ButtonInvisible(RectHeader, false))
                {
                    SoundDefOf.ThingSelected.PlayOneShotOnCamera();
                    Maximize();
                }
                return;
            }

            float cursor = 0;

            GUI.BeginGroup(RectScrollFrame);
            scrollView.Begin(RectScrollView);
            try {
                LabelTrimmer nameTrimmer        = scrollView.ScrollbarsVisible ? nameTrimmerWithScrollbar : nameTrimmerNoScrollbar;
                LabelTrimmer descriptionTrimmer = scrollView.ScrollbarsVisible ? descriptionTrimmerWithScrollbar : descriptionTrimmerNoScrollbar;
                foreach (var pawn in pawns)
                {
                    bool selected = pawn == currentPawn;
                    Rect rect     = RectEntry;
                    rect.y     += cursor;
                    rect.width -= (scrollView.ScrollbarsVisible ? 16 : 0);

                    GUI.color = Style.ColorPanelBackground;
                    GUI.DrawTexture(rect, BaseContent.WhiteTex);
                    GUI.color = Color.white;

                    if (selected || rect.Contains(Event.current.mousePosition))
                    {
                        if (selected)
                        {
                            GUI.color = new Color(66f / 255f, 66f / 255f, 66f / 255f);
                            Widgets.DrawBox(rect, 1);
                        }
                        GUI.color = Color.white;
                        Rect deleteRect = RectButtonDelete.OffsetBy(rect.position);
                        deleteRect.x = deleteRect.x - (scrollView.ScrollbarsVisible ? 16 : 0);
                        if (CanDeleteLastPawn || colonistCount > 1)
                        {
                            Style.SetGUIColorForButton(deleteRect);
                            GUI.DrawTexture(deleteRect, Textures.TextureButtonDelete);
                            // For some reason, this GUI.Button call is causing weirdness with text field focus (select
                            // text in one of the name fields and hover over the pawns in the pawn list to see what I mean).
                            // Replacing it with a mousedown event check fixes it for some reason.
                            //if (GUI.Button(deleteRect, string.Empty, Widgets.EmptyStyle)) {
                            if (Event.current.type == EventType.MouseDown && deleteRect.Contains(Event.current.mousePosition))
                            {
                                // Shift-click skips the confirmation dialog
                                if (Event.current.shift)
                                {
                                    // Delete after we've iterated and drawn everything
                                    pawnToDelete = pawn;
                                }
                                else
                                {
                                    CustomPawn localPawn = pawn;
                                    Find.WindowStack.Add(
                                        new Dialog_Confirm("EdB.PC.Panel.PawnList.Delete.Confirm".Translate(),
                                                           delegate {
                                        PawnDeleted(localPawn);
                                    },
                                                           true, null, true)
                                        );
                                }
                            }
                            GUI.color = Color.white;
                        }
                        if (rect.Contains(Event.current.mousePosition))
                        {
                            Rect swapRect = RectButtonSwap.OffsetBy(rect.position);
                            swapRect.x -= (scrollView.ScrollbarsVisible ? 16 : 0);
                            if (CanDeleteLastPawn || colonistCount > 1)
                            {
                                Style.SetGUIColorForButton(swapRect);
                                GUI.DrawTexture(swapRect, pawn.Type == CustomPawnType.Colonist ? Textures.TextureButtonWorldPawn : Textures.TextureButtonColonyPawn);
                                if (Event.current.type == EventType.MouseDown && swapRect.Contains(Event.current.mousePosition))
                                {
                                    pawnToSwap = pawn;
                                }
                                GUI.color = Color.white;
                            }
                        }
                    }

                    Rect pawnRect = RectPortrait.OffsetBy(rect.position);
                    GUI.color = Color.white;
                    RenderTexture pawnTexture = pawn.GetPortrait(pawnRect.size);
                    Rect          clipRect    = RectEntry.OffsetBy(rect.position);
                    try {
                        GUI.BeginClip(clipRect);
                        GUI.DrawTexture(RectPortrait, (Texture)pawnTexture);
                    }
                    finally {
                        GUI.EndClip();
                    }

                    GUI.color   = new Color(238f / 255f, 238f / 255f, 238f / 255f);
                    Text.Font   = GameFont.Small;
                    Text.Anchor = TextAnchor.LowerLeft;
                    Rect nameRect = RectName.OffsetBy(rect.position);
                    nameRect.width = nameRect.width - (scrollView.ScrollbarsVisible ? 16 : 0);
                    Vector2 nameSize = Text.CalcSize(pawn.Pawn.LabelShort);
                    Widgets.Label(nameRect, nameTrimmer.TrimLabelIfNeeded(pawn.Pawn.LabelShort));

                    Text.Font   = GameFont.Tiny;
                    Text.Anchor = TextAnchor.UpperLeft;
                    GUI.color   = new Color(184f / 255f, 184f / 255f, 184f / 255f);
                    Rect professionRect = RectDescription.OffsetBy(rect.position);
                    professionRect.width = professionRect.width - (scrollView.ScrollbarsVisible ? 16 : 0);
                    string description = null;
                    if (pawn.IsAdult)
                    {
                        if (pawn.Adulthood != null)
                        {
                            description = pawn.Adulthood.TitleShortCapFor(pawn.Gender);
                        }
                    }
                    else
                    {
                        description = pawn.Childhood.TitleShortCapFor(pawn.Gender);
                    }
                    if (!description.NullOrEmpty())
                    {
                        Widgets.Label(professionRect, descriptionTrimmer.TrimLabelIfNeeded(description));
                    }

                    if (pawn != state.CurrentPawn && Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition) && pawnToSwap == null)
                    {
                        pawnToSelect = pawn;
                    }

                    cursor += rect.height + SizeEntrySpacing;
                }
                cursor -= SizeEntrySpacing;
            }
            finally {
                scrollView.End(cursor);
                GUI.EndGroup();
            }

            GUI.color = Color.white;
            Text.Font = GameFont.Tiny;
            if (Widgets.ButtonText(RectButtonAdd, "EdB.PC.Common.Add".Translate(), true, false, true))
            {
                SoundDefOf.SelectDesignator.PlayOneShotOnCamera();
                AddingPawn(StartingPawns);
            }
            if (Widgets.ButtonText(RectButtonAdvancedAdd, "...", true, false, true))
            {
                ShowPawnKindDialog();
            }
            Text.Font   = GameFont.Small;
            Text.Anchor = TextAnchor.UpperLeft;

            if (pawnToDelete != null)
            {
                PawnDeleted(pawnToDelete);
            }
            else if (pawnToSwap != null)
            {
                PawnSwapped(pawnToSwap);
            }
            else if (pawnToSelect != null)
            {
                PawnSelected(pawnToSelect);
            }
        }
Exemplo n.º 17
0
 public void SelectPawn(CustomPawn pawn)
 {
     PawnSelected(pawn);
 }
 abstract public void AddToPawn(CustomPawn customPawn, Pawn pawn);
        public bool Load(PrepareCarefully loadout, string presetName)
        {
            List <SaveRecordPawnV3>             pawns              = new List <SaveRecordPawnV3>();
            List <SaveRecordPawnV3>             hiddenPawns        = new List <SaveRecordPawnV3>();
            List <SaveRecordRelationshipV3>     savedRelationships = new List <SaveRecordRelationshipV3>();
            List <SaveRecordParentChildGroupV3> parentChildGroups  = new List <SaveRecordParentChildGroupV3>();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            return(true);
        }
Exemplo n.º 20
0
        public IEnumerable <BodyPartRecord> AllSkinCoveredBodyParts(CustomPawn pawn)
        {
            BodyPartDictionary dictionary = GetBodyPartDictionary(pawn.Pawn.def);

            return(dictionary.AllSkinCoveredBodyParts);
        }
Exemplo n.º 21
0
 public OptionsHair GetHairsForRace(CustomPawn pawn)
 {
     return(GetHairsForRace(pawn.Pawn.def));
 }
Exemplo n.º 22
0
        public BodyPartRecord FirstBodyPartRecord(CustomPawn pawn, string bodyPartDefName)
        {
            BodyPartDictionary dictionary = GetBodyPartDictionary(pawn.Pawn.def);

            return(dictionary.FirstBodyPartRecord(bodyPartDefName));
        }
Exemplo n.º 23
0
 public void AddRelationship(PawnRelationDef def, CustomPawn source, CustomPawn target)
 {
     PrepareCarefully.Instance.RelationshipManager.AddRelationship(def, source, target);
 }
Exemplo n.º 24
0
 public BodyPartRecord FirstBodyPartRecord(CustomPawn pawn, BodyPartDef def)
 {
     return(FirstBodyPartRecord(pawn, def.defName));
 }
Exemplo n.º 25
0
 public void ReplacePawn(CustomPawn pawn)
 {
     PrepareCarefully.Instance.RelationshipManager.DeletePawn(pawn);
     PrepareCarefully.Instance.RelationshipManager.AddVisibleParentChildPawn(pawn);
 }
Exemplo n.º 26
0
        protected void Resize()
        {
            float headerSize = 0;

            headerSize = HeaderHeight;
            if (HeaderLabel != null)
            {
                headerSize = HeaderHeight;
            }

            HeaderHeight         = 32;
            RowGroupHeaderHeight = 36;
            FooterHeight         = 40f;
            WindowPadding        = 18;
            ContentMargin        = new Vector2(10f, 18f);
            WindowSize           = new Vector2(440f, 584f);
            ButtonSize           = new Vector2(140f, 40f);

            ContentSize = new Vector2(WindowSize.x - WindowPadding * 2 - ContentMargin.x * 2,
                                      WindowSize.y - WindowPadding * 2 - ContentMargin.y * 2 - FooterHeight - headerSize);

            ContentRect = new Rect(ContentMargin.x, ContentMargin.y + headerSize, ContentSize.x, ContentSize.y);

            ScrollRect = new Rect(0, 0, ContentRect.width, ContentRect.height);

            HeaderRect = new Rect(ContentMargin.x, ContentMargin.y, ContentSize.x, HeaderHeight);

            FooterRect = new Rect(ContentMargin.x, ContentRect.y + ContentSize.y + 20,
                                  ContentSize.x, FooterHeight);

            GenderSize = new Vector2(48, 48);

            SingleButtonRect = new Rect(ContentSize.x / 2 - ButtonSize.x / 2,
                                        (FooterHeight / 2) - (ButtonSize.y / 2),
                                        ButtonSize.x, ButtonSize.y);

            CancelButtonRect = new Rect(0,
                                        (FooterHeight / 2) - (ButtonSize.y / 2),
                                        ButtonSize.x, ButtonSize.y);
            ConfirmButtonRect = new Rect(ContentSize.x - ButtonSize.x,
                                         (FooterHeight / 2) - (ButtonSize.y / 2),
                                         ButtonSize.x, ButtonSize.y);

            Vector2 portraitSize      = new Vector2(70, 70);
            float   portraitOverflow  = 8;
            float   nameOffset        = 2;
            float   descriptionOffset = -2;
            float   radioWidth        = 36;
            Vector2 nameSize          = new Vector2(ContentRect.width - portraitSize.x - radioWidth, portraitSize.y * 0.5f);

            table                      = new WidgetTable <CustomParentChildPawn>();
            table.Rect                 = new Rect(Vector2.zero, ContentRect.size);
            table.RowHeight            = portraitSize.y;
            table.RowGroupHeaderHeight = RowGroupHeaderHeight;
            table.RowColor             = new Color(28f / 255f, 32f / 255f, 36f / 255f);
            table.AlternateRowColor    = new Color(0, 0, 0, 0);
            table.SelectedRowColor     = new Color(0, 0, 0, 0);
            table.SupportSelection     = true;
            table.SelectedAction       = (CustomParentChildPawn pawn) => {
                if (!DisabledPawns.Contains(pawn))
                {
                    SoundDefOf.TickTiny.PlayOneShotOnCamera();
                    Select(pawn);
                }
            };
            table.AddColumn(new WidgetTable <CustomParentChildPawn> .Column()
            {
                Name       = "Portrait",
                DrawAction = (CustomParentChildPawn pawn, Rect rect, WidgetTable <CustomParentChildPawn> .Metadata metadata) => {
                    GUI.color = Color.white;
                    if (!pawn.Hidden)
                    {
                        var texture = pawn.Pawn.GetPortrait(new Vector2(portraitSize.x, portraitSize.y + portraitOverflow * 2));
                        GUI.DrawTexture(new Rect(rect.position.x, rect.position.y - portraitOverflow, portraitSize.x, portraitSize.y + portraitOverflow * 2), texture as Texture);
                    }
                    else
                    {
                        GUI.color       = Style.ColorButton;
                        Rect genderRect = new Rect(rect.MiddleX() - GenderSize.HalfX(), rect.MiddleY() - GenderSize.HalfY(), GenderSize.x, GenderSize.y);
                        if (pawn.Pawn.Gender == Gender.Female)
                        {
                            GUI.DrawTexture(genderRect, Textures.TextureGenderFemaleLarge);
                        }
                        else if (pawn.Pawn.Gender == Gender.Male)
                        {
                            GUI.DrawTexture(genderRect, Textures.TextureGenderMaleLarge);
                        }
                        else
                        {
                            GUI.DrawTexture(genderRect, Textures.TextureGenderlessLarge);
                        }
                        GUI.color = Color.white;
                    }
                },
                Width = portraitSize.x
            });
            table.AddColumn(new WidgetTable <CustomParentChildPawn> .Column()
            {
                Name  = "Description",
                Width = nameSize.x,
                AdjustForScrollbars = true,
                DrawAction          = (CustomParentChildPawn parentChildPawn, Rect rect, WidgetTable <CustomParentChildPawn> .Metadata metadata) => {
                    CustomPawn pawn = parentChildPawn.Pawn;
                    Text.Anchor     = TextAnchor.LowerLeft;
                    Text.Font       = GameFont.Small;
                    Widgets.Label(new Rect(rect.x, rect.y + nameOffset, rect.width, nameSize.y), parentChildPawn.Name);
                    Text.Anchor = TextAnchor.UpperLeft;
                    string description;
                    if (!parentChildPawn.Hidden)
                    {
                        string age = pawn.BiologicalAge != pawn.ChronologicalAge ?
                                     "EdB.PC.Pawn.AgeWithChronological".Translate(new object[] { pawn.BiologicalAge, pawn.ChronologicalAge }) :
                                     "EdB.PC.Pawn.AgeWithoutChronological".Translate(new object[] { pawn.BiologicalAge });
                        description = pawn.Gender != Gender.None ?
                                      "EdB.PC.Pawn.PawnDescriptionWithGender".Translate(new object[] { pawn.ProfessionLabelShort, pawn.Gender.GetLabel(), age }) :
                                      "EdB.PC.Pawn.PawnDescriptionNoGender".Translate(new object[] { pawn.ProfessionLabelShort, age });
                    }
                    else
                    {
                        string profession = "EdB.PC.Pawn.HiddenPawnProfession".Translate();
                        description       = pawn.Gender != Gender.None ?
                                            "EdB.PC.Pawn.HiddenPawnDescriptionWithGender".Translate(new object[] { profession, pawn.Gender.GetLabel() }) :
                                            "EdB.PC.Pawn.HiddenPawnDescriptionNoGender".Translate(new object[] { profession });
                    }
                    Text.Font = GameFont.Tiny;
                    Widgets.Label(new Rect(rect.x, rect.y + nameSize.y + descriptionOffset, rect.width, nameSize.y), description);
                    Text.Font   = GameFont.Small;
                    Text.Anchor = TextAnchor.UpperLeft;
                }
            });
            table.AddColumn(new WidgetTable <CustomParentChildPawn> .Column()
            {
                Name       = "RadioButton",
                Width      = radioWidth,
                DrawAction = (CustomParentChildPawn pawn, Rect rect, WidgetTable <CustomParentChildPawn> .Metadata metadata) => {
                    if (DisabledPawns != null && DisabledPawns.Contains(pawn))
                    {
                        GUI.color = Style.ColorControlDisabled;
                        GUI.color = new Color(1, 1, 1, 0.28f);
                        GUI.DrawTexture(new Rect(rect.x, rect.MiddleY() - 12, 24, 24), Textures.TextureRadioButtonOff);
                        GUI.color = Color.white;
                    }
                    else
                    {
                        if (Widgets.RadioButton(new Vector2(rect.x, rect.MiddleY() - 12), this.SelectedPawn == pawn))
                        {
                            Select(pawn);
                        }
                    }
                }
            });
            resizeDirtyFlag = false;
        }
Exemplo n.º 27
0
 public Pawn GenerateSameKindOfPawn(CustomPawn customPawn)
 {
     return(GenerateKindOfPawn(customPawn.Pawn.kindDef));
 }
Exemplo n.º 28
0
        public CustomPawn CreatePawn()
        {
            // TODO: Evaluate
            //Pawn source = PawnGenerator.GeneratePawn(PawnKindDefOf.Colonist, Faction.OfColony);
            Pawn source = new Randomizer().GenerateColonist();

            source.health = new Pawn_HealthTracker(source);

            CustomPawn pawn = new CustomPawn(source);

            pawn.Gender = this.gender;
            if (age > 0)
            {
                pawn.ChronologicalAge = age;
                pawn.BiologicalAge    = age;
            }
            if (chronologicalAge > 0)
            {
                pawn.ChronologicalAge = chronologicalAge;
            }
            if (biologicalAge > 0)
            {
                pawn.BiologicalAge = biologicalAge;
            }
            pawn.FirstName = this.firstName;
            pawn.NickName  = this.nickName;
            pawn.LastName  = this.lastName;

            HairDef h = FindHairDef(this.hairDef);

            if (h != null)
            {
                pawn.HairDef = h;
            }

            pawn.HeadGraphicPath = this.headGraphicPath;
            pawn.SetColor(PawnLayers.Hair, hairColor);
            pawn.SetColor(PawnLayers.HeadType, skinColor);
            Backstory backstory = FindBackstory(childhood);

            if (backstory != null)
            {
                pawn.Childhood = backstory;
            }
            backstory = FindBackstory(adulthood);
            if (backstory != null)
            {
                pawn.Adulthood = backstory;
            }

            int traitCount = pawn.Traits.Count();

            for (int i = 0; i < traitCount; i++)
            {
                pawn.ClearTrait(i);
            }
            for (int i = 0; i < traitNames.Count; i++)
            {
                string traitName = traitNames[i];
                if (i >= traitCount)
                {
                    break;
                }
                Trait trait = FindTrait(traitName, traitDegrees[i]);
                if (trait != null)
                {
                    pawn.SetTrait(i, trait);
                }
            }

            for (int i = 0; i < this.skillNames.Count; i++)
            {
                string   name = this.skillNames[i];
                SkillDef def  = FindSkillDef(pawn.Pawn, name);
                if (def == null)
                {
                    continue;
                }
                pawn.currentPassions[def] = this.passions[i];
                pawn.SetUnmodifiedSkillLevel(def, this.skillValues[i]);
            }

            for (int i = 0; i < PawnLayers.Count; i++)
            {
                if (PawnLayers.IsApparelLayer(i))
                {
                    pawn.SetSelectedApparel(i, null);
                    pawn.SetSelectedStuff(i, null);
                }
            }
            for (int i = 0; i < this.apparelLayers.Count; i++)
            {
                int      layer = this.apparelLayers[i];
                ThingDef def   = DefDatabase <ThingDef> .GetNamedSilentFail(this.apparel[i]);

                if (def == null)
                {
                    continue;
                }
                ThingDef stuffDef = null;
                if (!string.IsNullOrEmpty(this.apparelStuff[i]))
                {
                    stuffDef = DefDatabase <ThingDef> .GetNamedSilentFail(this.apparelStuff[i]);

                    if (stuffDef == null)
                    {
                        continue;
                    }
                }
                pawn.SetSelectedApparel(layer, def);
                pawn.SetSelectedStuff(layer, stuffDef);
                pawn.SetColor(layer, this.apparelColors[i]);
            }

            return(pawn);
        }
 protected void Select(CustomPawn pawn)
 {
     this.SelectedPawn = pawn;
     SelectAction?.Invoke(pawn);
 }
Exemplo n.º 30
0
 public IEnumerable <CustomHeadType> GetHeadTypes(CustomPawn pawn)
 {
     return(GetHeadTypes(pawn.Pawn.def, pawn.Gender));
 }