Example #1
0
 public void SetSelectedStuff(int layer, ThingDef stuffDef)
 {
     if (layer < 0)
     {
         return;
     }
     this.selectedStuff[layer] = stuffDef;
     if (stuffDef != null)
     {
         ThingDef apparelDef = this.GetSelectedApparel(layer);
         if (apparelDef != null)
         {
             EquipmentKey pair = new EquipmentKey(apparelDef, stuffDef);
             Color        color;
             if (colorCache.TryGetValue(pair, out color))
             {
                 colors[layer] = color;
             }
             else
             {
                 if (stuffDef.stuffProps.allowColorGenerators)
                 {
                     colors[layer] = stuffDef.stuffProps.color;
                 }
                 else
                 {
                     colors[layer] = Color.white;
                 }
             }
         }
     }
 }
 protected bool AddRecordIfNotThereAlready(EquipmentKey key, EquipmentRecord record)
 {
     if (entries.TryGetValue(key, out EquipmentRecord value))
     {
         return(false);
     }
     else
     {
         entries[key] = record;
         return(true);
     }
 }
 protected void AddThingDef(ThingDef def, EquipmentType type)
 {
     if (def.MadeFromStuff)
     {
         foreach (var s in stuff)
         {
             if (s.stuffProps.CanMake(def))
             {
                 EquipmentKey    key   = new EquipmentKey(def, s);
                 EquipmentRecord entry = CreateEquipmentEntry(def, s, type);
                 if (entry != null)
                 {
                     entries[key] = entry;
                 }
             }
         }
     }
     else if (def.race != null && def.race.Animal)
     {
         if (def.race.hasGenders)
         {
             EquipmentRecord femaleEntry = CreateEquipmentEntry(def, Gender.Female, type);
             if (femaleEntry != null)
             {
                 entries[new EquipmentKey(def, Gender.Female)] = femaleEntry;
             }
             EquipmentRecord maleEntry = CreateEquipmentEntry(def, Gender.Male, type);
             if (maleEntry != null)
             {
                 entries[new EquipmentKey(def, Gender.Male)] = maleEntry;
             }
         }
         else
         {
             EquipmentKey    key   = new EquipmentKey(def, Gender.None);
             EquipmentRecord entry = CreateEquipmentEntry(def, Gender.None, type);
             if (entry != null)
             {
                 entries[key] = entry;
             }
         }
     }
     else
     {
         EquipmentKey    key   = new EquipmentKey(def, null);
         EquipmentRecord entry = CreateEquipmentEntry(def, null, Gender.None, type);
         if (entry != null)
         {
             entries[key] = entry;
         }
     }
 }
Example #4
0
 public void SetSelectedApparel(int layer, ThingDef def)
 {
     if (layer < 0)
     {
         return;
     }
     this.selectedApparel[layer] = def;
     if (def != null)
     {
         ThingDef stuffDef = this.GetSelectedStuff(layer);
         this.graphics[layer] = GraphicsCache.Instance.GetApparel(def, BodyType);
         EquipmentKey pair = new EquipmentKey(def, stuffDef);
         if (colorCache.ContainsKey(pair))
         {
             this.colors[layer] = colorCache[pair];
         }
         else
         {
             if (stuffDef == null)
             {
                 if (def.colorGenerator != null)
                 {
                     if (!ColorValidator.Validate(def.colorGenerator, this.colors[layer]))
                     {
                         this.colors[layer] = def.colorGenerator.NewRandomizedColor();
                     }
                 }
                 else
                 {
                     this.colors[layer] = Color.white;
                 }
             }
             else
             {
                 if (stuffDef.stuffProps.allowColorGenerators)
                 {
                     this.colors[layer] = stuffDef.stuffProps.color;
                 }
                 else
                 {
                     this.colors[layer] = Color.white;
                 }
             }
         }
     }
     else
     {
         this.graphics[layer] = null;
     }
     this.acceptedApparel[layer] = def;
     ApparelAcceptanceTest();
 }
 protected void AddThingDef(ThingDef def, EquipmentType type)
 {
     if (def.MadeFromStuff)
     {
         foreach (var s in stuff)
         {
             if (s.stuffProps.CanMake(def))
             {
                 EquipmentKey    key   = new EquipmentKey(def, s);
                 EquipmentRecord entry = CreateEquipmentRecord(def, s, type);
                 if (entry != null)
                 {
                     AddRecordIfNotThereAlready(key, entry);
                 }
             }
         }
     }
     else if (def.race != null && def.race.Animal)
     {
         if (def.race.hasGenders)
         {
             EquipmentRecord femaleEntry = CreateAnimalEquipmentRecord(def, Gender.Female);
             if (femaleEntry != null)
             {
                 AddRecordIfNotThereAlready(new EquipmentKey(def, Gender.Female), femaleEntry);
             }
             EquipmentRecord maleEntry = CreateAnimalEquipmentRecord(def, Gender.Male);
             if (maleEntry != null)
             {
                 AddRecordIfNotThereAlready(new EquipmentKey(def, Gender.Male), maleEntry);
             }
         }
         else
         {
             EquipmentKey    key   = new EquipmentKey(def, Gender.None);
             EquipmentRecord entry = CreateAnimalEquipmentRecord(def, Gender.None);
             if (entry != null)
             {
                 AddRecordIfNotThereAlready(key, entry);
             }
         }
     }
     else
     {
         EquipmentKey    key   = new EquipmentKey(def, null);
         EquipmentRecord entry = CreateEquipmentRecord(def, null, type);
         if (entry != null)
         {
             AddRecordIfNotThereAlready(key, entry);
         }
     }
 }
 public EquipmentRecord this[EquipmentKey key] {
     get {
         EquipmentRecord result;
         if (entries.TryGetValue(key, out result))
         {
             return(result);
         }
         else
         {
             return(null);
         }
     }
 }
 public EquipmentDatabaseEntry this[EquipmentKey key] {
     get {
         EquipmentDatabaseEntry result;
         if (entries.TryGetValue(key, out result))
         {
             return(result);
         }
         else
         {
             return(null);
         }
     }
 }
        public EquipmentRecord Find(EquipmentKey key)
        {
            EquipmentRecord result;

            if (entries.TryGetValue(key, out result))
            {
                return(result);
            }
            else
            {
                return(null);
            }
        }
        public override bool Equals(System.Object o)
        {
            if (o == null)
            {
                return(false);
            }
            if (!(o is EquipmentKey))
            {
                return(false);
            }
            EquipmentKey pair = (EquipmentKey)o;

            return(thingDef == pair.thingDef && stuffDef == pair.stuffDef);
        }
        public EquipmentRecord AddThingDefWithStuff(ThingDef def, ThingDef stuff, EquipmentType type)
        {
            if (type == null)
            {
                Logger.Warning("Could not add unclassified equipment: " + def);
                return(null);
            }
            EquipmentKey    key   = new EquipmentKey(def, stuff);
            EquipmentRecord entry = CreateEquipmentRecord(def, stuff, type);

            if (entry != null)
            {
                AddRecordIfNotThereAlready(key, entry);
            }
            return(entry);
        }
        public EquipmentRecord AddThingDefWithStuff(ThingDef def, ThingDef stuff, EquipmentType type)
        {
            if (type == null)
            {
                Log.Warning("Prepare Carefully could not add unclassified equipment: " + def);
                return(null);
            }
            EquipmentKey    key   = new EquipmentKey(def, stuff);
            EquipmentRecord entry = CreateEquipmentEntry(def, stuff, type);

            if (entry != null)
            {
                entries[key] = entry;
            }
            return(entry);
        }
        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);
        }
Example #13
0
        protected void InitializeDefaultEquipment()
        {
            // Go through all of the scenario steps that scatter resources near the player starting location and add
            // them to the resource/equipment list.
            foreach (ScenPart part in Verse.Find.Scenario.AllParts)
            {
                ScenPart_ScatterThingsNearPlayerStart nearPlayerStart = part as ScenPart_ScatterThingsNearPlayerStart;
                if (nearPlayerStart != null)
                {
                    FieldInfo              thingDefField = typeof(ScenPart_ScatterThingsNearPlayerStart).GetField("thingDef", BindingFlags.Instance | BindingFlags.NonPublic);
                    FieldInfo              stuffDefField = typeof(ScenPart_ScatterThingsNearPlayerStart).GetField("stuff", BindingFlags.Instance | BindingFlags.NonPublic);
                    FieldInfo              countField    = typeof(ScenPart_ScatterThingsNearPlayerStart).GetField("count", BindingFlags.Instance | BindingFlags.NonPublic);
                    ThingDef               thingDef      = (ThingDef)thingDefField.GetValue(nearPlayerStart);
                    ThingDef               stuffDef      = (ThingDef)stuffDefField.GetValue(nearPlayerStart);
                    int                    count         = (int)countField.GetValue(nearPlayerStart);
                    EquipmentKey           key           = new EquipmentKey(thingDef, stuffDef);
                    EquipmentDatabaseEntry entry         = equipmentDatabase[key];
                    if (entry == null)
                    {
                        entry = AddNonStandardScenarioEquipmentEntry(key);
                    }
                    if (entry != null)
                    {
                        AddEquipment(entry, count);
                    }
                }

                // Go through all of the scenario steps that place starting equipment with the colonists and
                // add them to the resource/equipment list.
                ScenPart_StartingThing_Defined startingThing = part as ScenPart_StartingThing_Defined;
                if (startingThing != null)
                {
                    FieldInfo              thingDefField = typeof(ScenPart_StartingThing_Defined).GetField("thingDef", BindingFlags.Instance | BindingFlags.NonPublic);
                    FieldInfo              stuffDefField = typeof(ScenPart_StartingThing_Defined).GetField("stuff", BindingFlags.Instance | BindingFlags.NonPublic);
                    FieldInfo              countField    = typeof(ScenPart_StartingThing_Defined).GetField("count", BindingFlags.Instance | BindingFlags.NonPublic);
                    ThingDef               thingDef      = (ThingDef)thingDefField.GetValue(startingThing);
                    ThingDef               stuffDef      = (ThingDef)stuffDefField.GetValue(startingThing);
                    int                    count         = (int)countField.GetValue(startingThing);
                    EquipmentKey           key           = new EquipmentKey(thingDef, stuffDef);
                    EquipmentDatabaseEntry entry         = equipmentDatabase[key];
                    if (entry == null)
                    {
                        entry = AddNonStandardScenarioEquipmentEntry(key);
                    }
                    if (entry != null)
                    {
                        AddEquipment(entry, count);
                    }
                }

                // Go through all of the scenario steps that spawn a pet and add the pet to the equipment/resource
                // list.
                ScenPart_StartingAnimal animal = part as ScenPart_StartingAnimal;
                if (animal != null)
                {
                    FieldInfo animalCountField = typeof(ScenPart_StartingAnimal).GetField("count", BindingFlags.Instance | BindingFlags.NonPublic);
                    int       count            = (int)animalCountField.GetValue(animal);
                    for (int i = 0; i < count; i++)
                    {
                        AddEquipment(RandomPet(animal));
                    }
                }
            }
        }
Example #14
0
        // TODO: Alpha 14
        // Think about whether or not this is the best approach.  Might need to do a bug report for the vanilla game?
        // The tribal scenario adds a weapon with an invalid thing/stuff combination (jade knife).  The
        // knife ThingDef should allow the jade material, but it does not.  We need this workaround to
        // add the normally disallowed equipment to our equipment database.
        protected EquipmentDatabaseEntry AddNonStandardScenarioEquipmentEntry(EquipmentKey key)
        {
            int type = equipmentDatabase.ClassifyThingDef(key.thingDef);

            return(equipmentDatabase.AddThingDefWithStuff(key.thingDef, key.stuffDef, type));
        }
Example #15
0
        protected void InitializeDefaultEquipment()
        {
            // Go through all of the scenario steps that scatter resources near the player starting location and add
            // them to the resource/equipment list.
            foreach (ScenPart part in Verse.Find.Scenario.AllParts)
            {
                ScenPart_ScatterThingsNearPlayerStart nearPlayerStart = part as ScenPart_ScatterThingsNearPlayerStart;
                if (nearPlayerStart != null)
                {
                    FieldInfo thingDefField = typeof(ScenPart_ScatterThingsNearPlayerStart).GetField("thingDef", BindingFlags.Instance | BindingFlags.NonPublic);
                    FieldInfo stuffDefField = typeof(ScenPart_ScatterThingsNearPlayerStart).GetField("stuff", BindingFlags.Instance | BindingFlags.NonPublic);
                    FieldInfo countField    = typeof(ScenPart_ScatterThingsNearPlayerStart).GetField("count", BindingFlags.Instance | BindingFlags.NonPublic);
                    ThingDef  thingDef      = (ThingDef)thingDefField.GetValue(nearPlayerStart);
                    ThingDef  stuffDef      = (ThingDef)stuffDefField.GetValue(nearPlayerStart);
                    equipmentDatabase.PreloadDefinition(stuffDef);
                    equipmentDatabase.PreloadDefinition(thingDef);
                    int             count  = (int)countField.GetValue(nearPlayerStart);
                    EquipmentKey    key    = new EquipmentKey(thingDef, stuffDef);
                    EquipmentRecord record = equipmentDatabase.LookupEquipmentRecord(key);
                    if (record == null)
                    {
                        Logger.Warning("Couldn't initialize all scenario equipment.  Didn't find an equipment entry for " + thingDef.defName);
                        record = AddNonStandardScenarioEquipmentEntry(key);
                    }
                    if (record != null)
                    {
                        AddEquipment(record, count);
                    }
                }

                // Go through all of the scenario steps that place starting equipment with the colonists and
                // add them to the resource/equipment list.
                ScenPart_StartingThing_Defined startingThing = part as ScenPart_StartingThing_Defined;
                if (startingThing != null)
                {
                    FieldInfo thingDefField = typeof(ScenPart_StartingThing_Defined).GetField("thingDef", BindingFlags.Instance | BindingFlags.NonPublic);
                    FieldInfo stuffDefField = typeof(ScenPart_StartingThing_Defined).GetField("stuff", BindingFlags.Instance | BindingFlags.NonPublic);
                    FieldInfo countField    = typeof(ScenPart_StartingThing_Defined).GetField("count", BindingFlags.Instance | BindingFlags.NonPublic);
                    ThingDef  thingDef      = (ThingDef)thingDefField.GetValue(startingThing);
                    ThingDef  stuffDef      = (ThingDef)stuffDefField.GetValue(startingThing);
                    equipmentDatabase.PreloadDefinition(stuffDef);
                    equipmentDatabase.PreloadDefinition(thingDef);
                    int             count = (int)countField.GetValue(startingThing);
                    EquipmentKey    key   = new EquipmentKey(thingDef, stuffDef);
                    EquipmentRecord entry = equipmentDatabase.LookupEquipmentRecord(key);
                    if (entry == null)
                    {
                        Logger.Warning("Couldn't initialize all scenario equipment.  Didn't find an equipment entry for " + thingDef.defName);
                        entry = AddNonStandardScenarioEquipmentEntry(key);
                    }
                    if (entry != null)
                    {
                        AddEquipment(entry, count);
                    }
                }

                // Go through all of the scenario steps that spawn a pet and add the pet to the equipment/resource
                // list.
                ScenPart_StartingAnimal animal = part as ScenPart_StartingAnimal;
                if (animal != null)
                {
                    FieldInfo animalCountField = typeof(ScenPart_StartingAnimal).GetField("count", BindingFlags.Instance | BindingFlags.NonPublic);
                    int       count            = (int)animalCountField.GetValue(animal);
                    for (int i = 0; i < count; i++)
                    {
                        PawnKindDef animalKindDef = RandomPet(animal);
                        equipmentDatabase.PreloadDefinition(animalKindDef.race);

                        List <EquipmentRecord> entries = PrepareCarefully.Instance.EquipmentDatabase.Animals.FindAll((EquipmentRecord e) => {
                            return(e.def == animalKindDef.race);
                        });
                        EquipmentRecord entry = null;
                        if (entries.Count > 0)
                        {
                            entry = entries.RandomElement();
                        }
                        if (entry != null)
                        {
                            AddEquipment(entry);
                        }
                        else
                        {
                            Logger.Warning("Failed to add the expected scenario animal to list of selected equipment");
                        }
                    }
                }
            }
        }
        // TODO:
        // Think about whether or not this is the best approach.  Might need to do a bug report for the vanilla game?
        // The tribal scenario adds a weapon with an invalid thing/stuff combination (jade knife).  The
        // knife ThingDef should allow the jade material, but it does not.  We need this workaround to
        // add the normally disallowed equipment to our equipment database.
        protected EquipmentRecord AddNonStandardScenarioEquipmentEntry(EquipmentKey key)
        {
            EquipmentType type = equipmentDatabase.ClassifyThingDef(key.ThingDef);

            return(equipmentDatabase.AddThingDefWithStuff(key.ThingDef, key.StuffDef, type));
        }
Example #17
0
        public bool Load(PrepareCarefully loadout, string presetName)
        {
            SaveRecordPresetV4 preset = new SaveRecordPresetV4();

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

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

                        if (thingDef == null)
                        {
                            string replacementDefName;
                            if (thingDefReplacements.TryGetValue(e.def, out replacementDefName))
                            {
                                thingDef = DefDatabase <ThingDef> .GetNamedSilentFail(replacementDefName);
                            }
                        }
                        ThingDef stuffDef = null;
                        Gender   gender   = Gender.None;
                        if (!string.IsNullOrEmpty(e.stuffDef))
                        {
                            stuffDef = DefDatabase <ThingDef> .GetNamedSilentFail(e.stuffDef);
                        }
                        if (!string.IsNullOrEmpty(e.gender))
                        {
                            try {
                                gender = (Gender)Enum.Parse(typeof(Gender), e.gender);
                            }
                            catch (Exception) {
                                Log.Warning("Failed to load gender value for animal.");
                                Failed = true;
                                continue;
                            }
                        }
                        if (thingDef != null)
                        {
                            if (string.IsNullOrEmpty(e.stuffDef))
                            {
                                EquipmentKey    key    = new EquipmentKey(thingDef, null, gender);
                                EquipmentRecord record = PrepareCarefully.Instance.EquipmentDatabase.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;
                }
            }
            catch (Exception e) {
                Log.Error("Failed to load preset file");
                throw e;
            }
            finally {
                // I don't fully understand how these cross-references and saveables are resolved, but
                // if we don't clear them out, we get null pointer exceptions.
                HashSet <IExposable> saveables = (HashSet <IExposable>)(typeof(PostLoadIniter).GetField("saveablesToPostLoad", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(Scribe.loader.initer));
                if (saveables != null)
                {
                    saveables.Clear();
                }
                List <IExposable> crossReferencingExposables = (List <IExposable>)(typeof(CrossRefHandler).GetField("crossReferencingExposables", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(Scribe.loader.crossRefs));
                if (crossReferencingExposables != null)
                {
                    crossReferencingExposables.Clear();
                }
                Scribe.loader.FinalizeLoading();
            }

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

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

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

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

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

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

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

            return(true);
        }
        public void CalculatePawnCost(ColonistCostDetails cost, CustomPawn pawn)
        {
            cost.Clear();
            cost.name = pawn.NickName;

            // Start with the market value plus a bit of a mark-up.
            cost.marketValue  = pawn.Pawn.MarketValue;
            cost.marketValue += 300;

            // Calculate passion cost.  Each passion above 8 makes all passions
            // cost more.  Minor passion counts as one passion.  Major passion
            // counts as 3.
            double skillCount           = pawn.currentPassions.Keys.Count();
            double passionLevelCount    = 0;
            double passionLevelCost     = 20;
            double passionateSkillCount = 0;

            foreach (SkillDef def in pawn.currentPassions.Keys)
            {
                Passion passion = pawn.currentPassions[def];
                int     level   = pawn.GetSkillLevel(def);

                if (passion == Passion.Major)
                {
                    passionLevelCount    += 3.0;
                    passionateSkillCount += 1.0;
                }
                else if (passion == Passion.Minor)
                {
                    passionLevelCount    += 1.0;
                    passionateSkillCount += 1.0;
                }
            }
            double levelCost = passionLevelCost;

            if (passionLevelCount > 8)
            {
                double penalty = passionLevelCount - 8;
                levelCost += penalty * 0.4;
            }
            cost.marketValue += levelCost * passionLevelCount;

            // Calculate trait cost.
            if (pawn.TraitCount > Constraints.MaxVanillaTraits)
            {
                int    extraTraitCount = pawn.TraitCount - Constraints.MaxVanillaTraits;
                double extraTraitCost  = 100;
                for (int i = 0; i < extraTraitCount; i++)
                {
                    cost.marketValue += extraTraitCost;
                    extraTraitCost    = Math.Ceiling(extraTraitCost * 2.5);
                }
            }

            // Calculate cost of worn apparel.
            for (int layer = 0; layer < PawnLayers.Count; layer++)
            {
                if (PawnLayers.IsApparelLayer(layer))
                {
                    var def = pawn.GetAcceptedApparel(layer);
                    if (def == null)
                    {
                        continue;
                    }
                    EquipmentKey key = new EquipmentKey();
                    key.ThingDef = def;
                    key.StuffDef = pawn.GetSelectedStuff(layer);
                    EquipmentRecord record = PrepareCarefully.Instance.EquipmentDatabase.Find(key);
                    if (record == null)
                    {
                        continue;
                    }
                    EquipmentSelection selection = new EquipmentSelection(record, 1);
                    double             c         = CalculateEquipmentCost(selection);
                    if (def != null)
                    {
                        // TODO: Discounted materials should be based on the faction, not hard-coded.
                        // TODO: Should we continue with the discounting?
                        if (key.StuffDef != null)
                        {
                            if (key.StuffDef.defName == "Synthread")
                            {
                                if (freeApparel.Contains(key.ThingDef.defName))
                                {
                                    c = 0;
                                }
                                else if (cheapApparel.Contains(key.ThingDef.defName))
                                {
                                    c = c * 0.15d;
                                }
                            }
                        }
                    }
                    cost.apparel += c;
                }
            }

            // Calculate cost for any materials needed for implants.
            OptionsHealth healthOptions = PrepareCarefully.Instance.Providers.Health.GetOptions(pawn);

            foreach (Implant option in pawn.Implants)
            {
                // Check if there are any ancestor parts that override the selection.
                UniqueBodyPart uniquePart = healthOptions.FindBodyPartsForRecord(option.BodyPartRecord);
                if (uniquePart == null)
                {
                    Log.Warning("Prepare Carefully could not find body part record when computing the cost of an implant: " + option.BodyPartRecord.def.defName);
                    continue;
                }
                if (pawn.AtLeastOneImplantedPart(uniquePart.Ancestors.Select((UniqueBodyPart p) => { return(p.Record); })))
                {
                    continue;
                }

                //  Figure out the cost of the part replacement based on its recipe's ingredients.
                if (option.recipe != null)
                {
                    RecipeDef def = option.recipe;
                    foreach (IngredientCount amount in def.ingredients)
                    {
                        int    count     = 0;
                        double totalCost = 0;
                        bool   skip      = false;
                        foreach (ThingDef ingredientDef in amount.filter.AllowedThingDefs)
                        {
                            if (ingredientDef == ThingDefOf.Medicine)
                            {
                                skip = true;
                                break;
                            }
                            count++;
                            EquipmentRecord entry = PrepareCarefully.Instance.EquipmentDatabase[new EquipmentKey(ingredientDef, null)];
                            if (entry != null)
                            {
                                totalCost += entry.cost * (double)amount.GetBaseCount();
                            }
                        }
                        if (skip || count == 0)
                        {
                            continue;
                        }
                        cost.bionics += (int)(totalCost / (double)count);
                    }
                }
            }

            cost.apparel = Math.Ceiling(cost.apparel);
            cost.bionics = Math.Ceiling(cost.bionics);

            // Use a multiplier to balance pawn cost vs. equipment cost.
            // Disabled for now.
            cost.Multiply(1.0);

            cost.ComputeTotal();
        }