Beispiel #1
0
        public static SalvageDef CreateComponent(SimGameConstants sc, Contract c, MechComponentDef mc)
        {
            SalvageDef salvageDef = new SalvageDef();

            if (mc.ComponentType == ComponentType.Weapon)
            {
                WeaponDef weaponDef = mc as WeaponDef;
                salvageDef.MechComponentDef = weaponDef;

                salvageDef.Description   = new DescriptionDef(weaponDef.Description);
                salvageDef.RewardID      = c.GenerateRewardUID();
                salvageDef.Type          = SalvageDef.SalvageType.COMPONENT;
                salvageDef.ComponentType = weaponDef.ComponentType;
                salvageDef.Damaged       = false;
                salvageDef.Weight        = sc.Salvage.DefaultWeaponWeight;
                salvageDef.Count         = 1;

                return(salvageDef);
            }
            else
            {
                salvageDef.MechComponentDef = mc;

                salvageDef.Description   = new DescriptionDef(mc.Description);
                salvageDef.RewardID      = c.GenerateRewardUID();
                salvageDef.Type          = SalvageDef.SalvageType.COMPONENT;
                salvageDef.ComponentType = mc.ComponentType;
                salvageDef.Damaged       = false;
                salvageDef.Weight        = sc.Salvage.DefaultComponentWeight;
                salvageDef.Count         = 1;

                return(salvageDef);
            }
        }
Beispiel #2
0
        public static bool Prefix(Contract __instance, SimGameConstants sc, MechComponentDef def)
        {
            if (def.ComponentTags.Contains("BLACKLISTED"))
            {
                return(false);
            }

            SalvageDef salvageDef = new SalvageDef();

            salvageDef.MechComponentDef = def;
            salvageDef.Description      = new DescriptionDef(def.Description);
            salvageDef.RewardID         = __instance.GenerateRewardUID();
            salvageDef.Type             = SalvageDef.SalvageType.COMPONENT;
            salvageDef.ComponentType    = def.ComponentType;
            salvageDef.Damaged          = false;
            salvageDef.Weight           = sc.Salvage.DefaultComponentWeight;
            salvageDef.Count            = 1;
            if (def.Description.Rarity < sc.Salvage.ItemAutoCullLevel)
            {
                if ((bool)Traverse.Create(__instance).Method("IsSalvageInContent", new Type[] { typeof(SalvageDef) }).GetValue(salvageDef))
                {
                    var foo = (List <SalvageDef>)Traverse.Create(__instance).Field("finalPotentialSalvage").GetValue();
                    foo.Add(salvageDef);
                    return(false);
                }
            }
            else
            {
                Logger.Log(string.Format("CULLED ILLEGAL MECH COMPONENT ({0}) of RARITY ({1}). From Random Upgrade? {2}.", def.Description.Id, def.Description.Rarity, false));
            }
            return(false);
        }
Beispiel #3
0
        // SETUP
        internal static void Setup()
        {
            if (IsSetup)
            {
                return;
            }

            constants   = SimGameConstants.GetInstance(LazySingletonBehavior <UnityGameInstance> .Instance.Game);
            dataManager = LazySingletonBehavior <UnityGameInstance> .Instance.Game.DataManager;

            // make sure that datamanager has gotten all of the abilities
            var loadRequest = dataManager.CreateLoadRequest(x =>
            {
                HBSLog.Log("AbilityDefs Loaded");

                if (!Settings.DumpFixedPilotDefMerges)
                {
                    return;
                }

                HBSLog.Log("PilotDefs loaded");
                DumpFixedPilotDefMerges();
            });

            loadRequest.AddAllOfTypeBlindLoadRequest(BattleTechResourceType.AbilityDef);

            // if dumping pilotDefs, request them
            if (Settings.DumpFixedPilotDefMerges)
            {
                loadRequest.AddAllOfTypeBlindLoadRequest(BattleTechResourceType.PilotDef);
            }

            loadRequest.ProcessRequests();

            progressionAbilities = new List <string>();

            // read in progression tables
            var progressionTables = new List <string[][]>
            {
                constants.Progression.GunnerySkills, constants.Progression.PilotingSkills,
                constants.Progression.GutsSkills, constants.Progression.TacticsSkills
            };

            foreach (var progressionTable in progressionTables)
            {
                foreach (var abilityTable in progressionTable)
                {
                    foreach (var abilityName in abilityTable)
                    {
                        progressionAbilities.Add(abilityName);
                    }
                }
            }

            IsSetup = true;
        }
        public static SalvageDef CreateMechPart(Contract contract, SimGameConstants sc, MechDef m)
        {
            SalvageDef salvageDef = new SalvageDef();

            salvageDef.Type          = SalvageDef.SalvageType.MECH_PART;
            salvageDef.ComponentType = ComponentType.MechPart;
            salvageDef.Count         = 1;
            salvageDef.Weight        = sc.Salvage.DefaultMechPartWeight;
            DescriptionDef description  = m.Description;
            DescriptionDef description2 = new DescriptionDef(description.Id, string.Format("{0} {1}", description.Name, sc.Story.DefaultMechPartName), description.Details, description.Icon, description.Cost, description.Rarity, description.Purchasable, description.Manufacturer, description.Model, description.UIName);

            salvageDef.Description = description2;
            salvageDef.RewardID    = contract.GenerateRewardUID();
            return(salvageDef);
        }
        public void TestInitialize()
        {
            // SGS tries to invoke a LazyInitialize for the queue, which will throw a security error. Work around this.
            SimGameState = (SimGameState)FormatterServices.GetUninitializedObject(typeof(SimGameState));

            // Init story constants
            StoryConstantsDef storyConstantsDef = new StoryConstantsDef();

            storyConstantsDef.MRBRepCap = new float[] { 50f, 200f, 500f, 700f, 900f };
            SimGameConstants constants = new SimGameConstants(null, null, null, null, null, null, null, storyConstantsDef, null, null, null, null, null);

            Traverse constantsT = Traverse.Create(SimGameState).Property("Constants");

            constantsT.SetValue(constants);

            // Init the MRB faction
            FactionValue mrbFactionValue   = new FactionValue();
            Traverse     factionValueNameT = Traverse.Create(mrbFactionValue).Property("Name");

            factionValueNameT.SetValue(FactionName);

            Dictionary <int, FactionValue> factionValuesDict = new Dictionary <int, FactionValue>
            {
                [12] = mrbFactionValue
            };

            FactionEnumeration factionEnum      = FactionEnumeration.Instance;
            Traverse           initFactionDictT = Traverse.Create(factionEnum).Field("intFactionDict");

            initFactionDictT.SetValue(factionValuesDict);

            // Add the company stat manually (since constructor did not run)
            StatCollection companyStats  = new StatCollection();
            Traverse       companyStatsT = Traverse.Create(SimGameState).Field("companyStats");

            companyStatsT.SetValue(companyStats);
            SimGameState.CompanyStats.AddStatistic <int>($"Reputation.{FactionName}", 0);
        }
Beispiel #6
0
        static bool Prefix(Contract __instance, List <UnitResult> enemyMechs, List <VehicleDef> enemyVehicles, List <UnitResult> lostUnits, bool logResults = false)
        {
            try {
                Settings settings = Helper.LoadSettings();
                if (__instance.BattleTechGame.Simulation == null)
                {
                    return(false);
                }
                ReflectionHelper.SetPrivateField(__instance, "finalPotentialSalvage", new List <SalvageDef>());
                ReflectionHelper.InvokePrivateMethode(__instance, "set_SalvagedChassis", new object[] { new List <SalvageDef>() });
                ReflectionHelper.InvokePrivateMethode(__instance, "set_LostMechs", new object[] { new List <MechDef>() });
                ReflectionHelper.InvokePrivateMethode(__instance, "set_SalvageResults", new object[] { new List <SalvageDef>() });
                SimGameState     simulation = __instance.BattleTechGame.Simulation;
                SimGameConstants constants  = simulation.Constants;
                for (int i = 0; i < lostUnits.Count; i++)
                {
                    MechDef mech  = lostUnits[i].mech;
                    Pilot   pilot = lostUnits[i].pilot;
                    float   num   = simulation.NetworkRandom.Float(0f, 1f);
                    float   ejectRecoveryBonus         = 0;
                    float   incapacitatedRecoveryBonus = 0;
                    bool    notDestroyed = !mech.IsLocationDestroyed(ChassisLocations.CenterTorso) && !mech.IsLocationDestroyed(ChassisLocations.Head) &&
                                           (!mech.IsLocationDestroyed(ChassisLocations.LeftLeg) && !mech.IsLocationDestroyed(ChassisLocations.RightLeg));
                    if (pilot.HasEjected)
                    {
                        ejectRecoveryBonus = settings.ejectRecoveryBonus;
                    }
                    else if (mech.IsLocationDestroyed(ChassisLocations.Head) || (pilot.IsIncapacitated && notDestroyed))
                    {
                        incapacitatedRecoveryBonus = settings.incapacitatedRecoveryBonus;
                    }
                    bool flag = num <= constants.Salvage.DestroyedMechRecoveryChance + ejectRecoveryBonus + incapacitatedRecoveryBonus;

                    // keep mech if the roll is good enough, or if CT + head + legs are intact and the pilot isn't incapacitated
                    if (flag || (notDestroyed && !pilot.IsIncapacitated))
                    {
                        lostUnits[i].mechLost = false;
                    }
                    else
                    {
                        lostUnits[i].mechLost = true;

                        float mechparts = simulation.Constants.Story.DefaultMechPartMax;
                        if (mech.IsLocationDestroyed(ChassisLocations.CenterTorso))
                        {
                            mechparts = settings.centerTorsoSalvageValue;
                        }
                        else
                        {
                            if (mech.IsLocationDestroyed(ChassisLocations.LeftArm))
                            {
                                mechparts -= (simulation.Constants.Story.DefaultMechPartMax / 5);
                            }
                            if (mech.IsLocationDestroyed(ChassisLocations.RightArm))
                            {
                                mechparts -= (simulation.Constants.Story.DefaultMechPartMax / 5);
                            }
                            if (mech.IsLocationDestroyed(ChassisLocations.LeftLeg))
                            {
                                mechparts -= (simulation.Constants.Story.DefaultMechPartMax / 5);
                            }
                            if (mech.IsLocationDestroyed(ChassisLocations.RightLeg))
                            {
                                mechparts -= (simulation.Constants.Story.DefaultMechPartMax / 5);
                            }
                        }


                        SalvageDef def = (SalvageDef)ReflectionHelper.InvokePrivateMethode(__instance, "CreateMechPart", new object[] { constants, mech });
                        if (settings.ownMechsForFree)
                        {
                            for (int s = 0; s < Mathf.RoundToInt(mechparts); s++)
                            {
                                __instance.SalvageResults.Add(def);
                            }
                        }
                        else
                        {
                            List <SalvageDef> finalPotentialSalvage = (List <SalvageDef>)ReflectionHelper.GetPrivateField(__instance, "finalPotentialSalvage");
                            ReflectionHelper.InvokePrivateMethode(__instance, "CreateAndAddMechPart", new object[] { constants, mech, Mathf.RoundToInt(mechparts), finalPotentialSalvage });
                        }
                        if (settings.ownMechsForFree)
                        {
                            foreach (MechComponentRef mechComponentRef in mech.Inventory)
                            {
                                if (!mech.IsLocationDestroyed(mechComponentRef.MountedLocation) && mechComponentRef.DamageLevel != ComponentDamageLevel.Destroyed)
                                {
                                    ReflectionHelper.InvokePrivateMethode(__instance, "AddToFinalSalvage", new object[] { new SalvageDef {
                                                                                                                              MechComponentDef = mechComponentRef.Def,
                                                                                                                              Description      = new DescriptionDef(mechComponentRef.Def.Description),
                                                                                                                              RewardID         = __instance.GenerateRewardUID(),
                                                                                                                              Type             = SalvageDef.SalvageType.COMPONENT,
                                                                                                                              ComponentType    = mechComponentRef.Def.ComponentType,
                                                                                                                              Damaged          = false,
                                                                                                                              Count            = 1
                                                                                                                          } });
                                }
                            }
                        }
                        else
                        {
                            foreach (MechComponentRef mechComponentRef in mech.Inventory)
                            {
                                if (!mech.IsLocationDestroyed(mechComponentRef.MountedLocation) && mechComponentRef.DamageLevel != ComponentDamageLevel.Destroyed)
                                {
                                    List <SalvageDef> finalPotentialSalvage = (List <SalvageDef>)ReflectionHelper.GetPrivateField(__instance, "finalPotentialSalvage");
                                    ReflectionHelper.InvokePrivateMethode(__instance, "AddMechComponentToSalvage", new object[] { finalPotentialSalvage, mechComponentRef.Def, ComponentDamageLevel.Functional, false, constants, simulation.NetworkRandom, true });
                                }
                            }
                        }
                    }
                }
                int k = 0;
                while (k < enemyMechs.Count)
                {
                    MechDef           mech2                 = enemyMechs[k].mech;
                    Pilot             pilot                 = enemyMechs[k].pilot;
                    SalvageDef        salvageDef            = null;
                    bool              flag2                 = false;
                    bool              flag3                 = false;
                    List <SalvageDef> finalPotentialSalvage = (List <SalvageDef>)ReflectionHelper.GetPrivateField(__instance, "finalPotentialSalvage");

                    if (pilot.IsIncapacitated || mech2.IsDestroyed || mech2.Inventory.Any(cref => cref.Def != null && cref.Def.CriticalComponent && cref.DamageLevel == ComponentDamageLevel.Destroyed))
                    {
                        float mechparts = simulation.Constants.Story.DefaultMechPartMax;
                        if (mech2.IsLocationDestroyed(ChassisLocations.CenterTorso))
                        {
                            mechparts = settings.centerTorsoSalvageValue;
                        }
                        else
                        {
                            if (mech2.IsLocationDestroyed(ChassisLocations.LeftArm))
                            {
                                mechparts -= (simulation.Constants.Story.DefaultMechPartMax / 5);
                            }
                            if (mech2.IsLocationDestroyed(ChassisLocations.RightArm))
                            {
                                mechparts -= (simulation.Constants.Story.DefaultMechPartMax / 5);
                            }
                            if (mech2.IsLocationDestroyed(ChassisLocations.LeftLeg))
                            {
                                mechparts -= (simulation.Constants.Story.DefaultMechPartMax / 5);
                            }
                            if (mech2.IsLocationDestroyed(ChassisLocations.RightLeg))
                            {
                                mechparts -= (simulation.Constants.Story.DefaultMechPartMax / 5);
                            }
                        }

                        ReflectionHelper.InvokePrivateMethode(__instance, "CreateAndAddMechPart", new object[] { constants, mech2, Mathf.RoundToInt(mechparts), finalPotentialSalvage });
                        goto IL_2E4;
                    }
IL_4AB:
                    k++;
                    continue;
IL_2E4:
                    foreach (MechComponentRef mechComponentRef2 in mech2.Inventory)
                    {
                        if (!mech2.IsLocationDestroyed(mechComponentRef2.MountedLocation) && mechComponentRef2.DamageLevel != ComponentDamageLevel.Destroyed)
                        {
                            ReflectionHelper.InvokePrivateMethode(__instance, "AddMechComponentToSalvage", new object[] { finalPotentialSalvage, mechComponentRef2.Def, ComponentDamageLevel.Functional, false, constants, simulation.NetworkRandom, true });
                        }
                    }
                    if (flag3)
                    {
                        salvageDef             = new SalvageDef();
                        salvageDef.Type        = SalvageDef.SalvageType.CHASSIS;
                        salvageDef.Description = new DescriptionDef(mech2.Chassis.Description);
                        salvageDef.Count       = 1;
                        IEnumerator enumerator = Enum.GetValues(typeof(ChassisLocations)).GetEnumerator();
                        try {
                            while (enumerator.MoveNext())
                            {
                                object           obj = enumerator.Current;
                                ChassisLocations chassisLocations = (ChassisLocations)obj;
                                if (chassisLocations != ChassisLocations.None && chassisLocations != ChassisLocations.All && chassisLocations != ChassisLocations.Arms && chassisLocations != ChassisLocations.Legs && chassisLocations != ChassisLocations.Torso && chassisLocations != ChassisLocations.MainBody)
                                {
                                    salvageDef.ChassisLocations.Add(chassisLocations);
                                    salvageDef.ChassisStructure.Add(mech2.GetLocationLoadoutDef(chassisLocations).CurrentInternalStructure);
                                }
                            }
                        }
                        finally {
                            IDisposable disposable;
                            if ((disposable = (enumerator as IDisposable)) != null)
                            {
                                disposable.Dispose();
                            }
                        }
                        if (flag2)
                        {
                            for (int m = 0; m < salvageDef.ChassisLocations.Count; m++)
                            {
                                List <float> chassisStructure;
                                int          index;
                                (chassisStructure = salvageDef.ChassisStructure)[index = m] = chassisStructure[index] / 2f;
                            }
                        }
                        salvageDef.Weight = constants.Salvage.DefaultChassisWeight;
                        __instance.SalvagedChassis.Add(salvageDef);
                        goto IL_4AB;
                    }
                    goto IL_4AB;
                }
                for (int n = 0; n < enemyVehicles.Count; n++)
                {
                    VehicleDef        vehicleDef            = enemyVehicles[n];
                    List <SalvageDef> finalPotentialSalvage = (List <SalvageDef>)ReflectionHelper.GetPrivateField(__instance, "finalPotentialSalvage");
                    foreach (VehicleComponentRef vehicleComponentRef in vehicleDef.Inventory)
                    {
                        ReflectionHelper.InvokePrivateMethode(__instance, "AddMechComponentToSalvage", new object[] { finalPotentialSalvage, vehicleComponentRef.Def, ComponentDamageLevel.Functional, false, constants, simulation.NetworkRandom, true });
                    }
                }
                int   num2 = __instance.SalvagePotential;
                float num3 = constants.Salvage.VictorySalvageChance;
                float num4 = constants.Salvage.VictorySalvageLostPerMechDestroyed;
                if (__instance.State == Contract.ContractState.Failed)
                {
                    num3 = constants.Salvage.DefeatSalvageChance;
                    num4 = constants.Salvage.DefeatSalvageLostPerMechDestroyed;
                }
                else if (__instance.State == Contract.ContractState.Retreated)
                {
                    num3 = constants.Salvage.RetreatSalvageChance;
                    num4 = constants.Salvage.RetreatSalvageLostPerMechDestroyed;
                }
                float num5 = num3;
                float num6 = (float)num2 * __instance.PercentageContractSalvage;
                if (num2 > 0)
                {
                    num6 += (float)constants.Finances.ContractFloorSalvageBonus;
                }
                num3 = Mathf.Max(0f, num5 - num4 * (float)lostUnits.Count);
                int num7 = Mathf.FloorToInt(num6 * num3);
                if (num2 > 0)
                {
                    num2 += constants.Finances.ContractFloorSalvageBonus;
                }
                ReflectionHelper.InvokePrivateMethode(__instance, "set_FinalSalvageCount", new object[] { num7 });
                ReflectionHelper.InvokePrivateMethode(__instance, "set_FinalPrioritySalvageCount", new object[] { Mathf.FloorToInt((float)num7 * constants.Salvage.PrioritySalvageModifier) });

                return(false);
            }
            catch (Exception e) {
                Logger.LogError(e);
                return(false);
            }
        }
        static void Postfix(Contract __instance, List <UnitResult> enemyMechs, List <VehicleDef> enemyVehicles, List <UnitResult> lostUnits, bool logResults = false)
        {
            Logger.LogLine("Postfix Start");
            Settings settings = CompanyMechSalvage.LoadSettings();

            Logger.LogLine("Settings Loaded");
            SimGameState     simulation = __instance.BattleTechGame.Simulation;
            SimGameConstants constants  = simulation.Constants;
            float            roll       = simulation.NetworkRandom.Float(0f, 1f);

            Logger.LogLine("Rolled: " + roll);
            bool recovered = roll <= settings.RecoveryChance;

            if (!recovered)
            {
                Logger.LogLine("Mech not recovered");
                for (int i = 0; i < lostUnits.Count; i++)
                {
                    MechDef mech = lostUnits[i].mech;
                    if (mech.IsLocationDestroyed(ChassisLocations.CenterTorso))
                    {
                        Logger.LogLine("CT destroyed");
                        lostUnits[i].mechLost = true;
                        SalvageDef def = CompanyMechSalvage.CreateMechPart(__instance, constants, mech);
                        __instance.SalvageResults.Add(def);

                        foreach (MechComponentRef mechComponentRef in mech.Inventory)
                        {
                            if (!mech.IsLocationDestroyed(mechComponentRef.MountedLocation) && mechComponentRef.DamageLevel != ComponentDamageLevel.Destroyed)
                            {
                                __instance.SalvageResults.Add(new SalvageDef
                                {
                                    MechComponentDef = mechComponentRef.Def,
                                    Description      = new DescriptionDef(mechComponentRef.Def.Description),
                                    RewardID         = __instance.GenerateRewardUID(),
                                    Type             = SalvageDef.SalvageType.COMPONENT,
                                    ComponentType    = mechComponentRef.Def.ComponentType,
                                    Damaged          = false,
                                    Count            = 1
                                });
                            }
                        }
                    }
                    else if ((mech.IsLocationDestroyed(ChassisLocations.LeftLeg) && mech.IsLocationDestroyed(ChassisLocations.RightLeg)) || (mech.IsLocationDestroyed(ChassisLocations.Head) && settings.DestroyedWithHead))
                    {
                        Logger.LogLine("Legs or Head destroyed");
                        lostUnits[i].mechLost = true;
                        SalvageDef def = CompanyMechSalvage.CreateMechPart(__instance, constants, mech);
                        __instance.SalvageResults.Add(def);
                        __instance.SalvageResults.Add(def);
                        foreach (MechComponentRef mechComponentRef in mech.Inventory)
                        {
                            if (!mech.IsLocationDestroyed(mechComponentRef.MountedLocation) && mechComponentRef.DamageLevel != ComponentDamageLevel.Destroyed)
                            {
                                __instance.SalvageResults.Add(new SalvageDef
                                {
                                    MechComponentDef = mechComponentRef.Def,
                                    Description      = new DescriptionDef(mechComponentRef.Def.Description),
                                    RewardID         = __instance.GenerateRewardUID(),
                                    Type             = SalvageDef.SalvageType.COMPONENT,
                                    ComponentType    = mechComponentRef.Def.ComponentType,
                                    Damaged          = false,
                                    Count            = 1
                                });
                            }
                        }
                    }
                    Logger.LogLine("Salvage created");
                }
            }
        }
        private static void AddMechToSalvage(MechDef mech, ContractHelper contract, SimGameState simgame, SimGameConstants constants, bool can_upgrade)
        {
            Control.LogDebug($"-- Salvaging {mech.Name}");

            int numparts = Control.GetNumParts(mech);

            try
            {
                Control.LogDebug($"--- Adding {numparts} parts");
                contract.AddMechPartsToPotentialSalvage(constants, mech, numparts);
            }
            catch (Exception e)
            {
                Control.LogError("Error in adding parts", e);
            }

            try
            {
                foreach (var component in mech.Inventory.Where(item =>
                                                               !mech.IsLocationDestroyed(item.MountedLocation) &&
                                                               item.DamageLevel != ComponentDamageLevel.Destroyed))
                {
                    contract.AddComponentToPotentialSalvage(component.Def, ComponentDamageLevel.Functional, can_upgrade);
                }
            }
            catch (Exception e)
            {
                Control.LogError("Error in adding component", e);
            }
        }
 public static void AddMechComponentToSalvage(this Contract c, List <SalvageDef> l, MechComponentDef d, ComponentDamageLevel dl, bool b, SimGameConstants co, NetworkRandom r, bool b2)
 {
     throw new NotImplementedException();
 }
 public static void CreateAndAddMechPart(this Contract c, SimGameConstants co, MechDef d, int num, List <SalvageDef> l)
 {
     throw new NotImplementedException();
 }
        private static void AddMechToSalvage(MechDef mech, ContractHelper contract, SimGameState simgame, SimGameConstants constants, List <SalvageDef> salvage)
        {
            Control.LogDebug(DType.SalvageProccess, $"-- Salvaging {mech.Name}");

            int numparts = 0;

            if (Control.Settings.OverrideMechPartCalculation)
            {
                if (mech.IsLocationDestroyed(ChassisLocations.CenterTorso))
                {
                    numparts = Control.Settings.CenterTorsoDestroyedParts;
                }
                else
                {
                    float total = Control.Settings.SalvageArmWeight * 2 + Control.Settings.SalvageHeadWeight +
                                  Control.Settings.SalvageLegWeight * 2 + Control.Settings.SalvageTorsoWeight * 2 + 1;

                    float val = total;

                    val -= mech.IsLocationDestroyed(ChassisLocations.Head) ? Control.Settings.SalvageHeadWeight : 0;

                    val -= mech.IsLocationDestroyed(ChassisLocations.LeftTorso)
                        ? Control.Settings.SalvageTorsoWeight
                        : 0;
                    val -= mech.IsLocationDestroyed(ChassisLocations.RightTorso)
                        ? Control.Settings.SalvageTorsoWeight
                        : 0;

                    val -= mech.IsLocationDestroyed(ChassisLocations.LeftLeg) ? Control.Settings.SalvageLegWeight : 0;
                    val -= mech.IsLocationDestroyed(ChassisLocations.RightLeg) ? Control.Settings.SalvageLegWeight : 0;

                    val -= mech.IsLocationDestroyed(ChassisLocations.LeftArm) ? Control.Settings.SalvageArmWeight : 0;
                    val -= mech.IsLocationDestroyed(ChassisLocations.LeftLeg) ? Control.Settings.SalvageArmWeight : 0;

                    numparts = (int)(constants.Story.DefaultMechPartMax * val / total + 0.5f);
                    if (numparts <= 0)
                    {
                        numparts = 1;
                    }
                    if (numparts > constants.Story.DefaultMechPartMax)
                    {
                        numparts = constants.Story.DefaultMechPartMax;
                    }
                }
            }
            else
            {
                numparts = 3;
                if (mech.IsLocationDestroyed(ChassisLocations.CenterTorso))
                {
                    numparts = 1;
                }
                else if (mech.IsLocationDestroyed(ChassisLocations.LeftLeg) &&
                         mech.IsLocationDestroyed(ChassisLocations.RightLeg))
                {
                    numparts = 2;
                }
            }

            try
            {
                Control.LogDebug(DType.SalvageProccess, $"--- Adding {numparts} parts");
                contract.CreateAndAddMechPart(constants, mech, numparts, salvage);
            }
            catch (Exception e)
            {
                Control.LogError("Error in adding parts", e);
            }

            try
            {
                if (Control.Settings.NoLootCTDestroyed && mech.IsLocationDestroyed(ChassisLocations.CenterTorso))
                {
                    Control.LogDebug(DType.SalvageProccess, $"--- CT Destroyed - no component loot");
                }
                else
                {
                    foreach (var component in mech.Inventory.Where(item =>
                                                                   !mech.IsLocationDestroyed(item.MountedLocation) &&
                                                                   item.DamageLevel != ComponentDamageLevel.Destroyed))
                    {
                        Control.LogDebug(DType.SalvageProccess, $"--- Adding {component.ComponentDefID}");
                        contract.AddMechComponentToSalvage(salvage, component.Def, ComponentDamageLevel.Functional, false,
                                                           constants, simgame.NetworkRandom, true);
                    }
                }
            }
            catch (Exception e)
            {
                Control.LogError("Error in adding component", e);
            }
        }
Beispiel #12
0
 public static void Postfix(SimGameConstants __instance, string json)
 {
     RLog.M.TWL(0, "SimGameConstants.FromJSON");
     RLog.M.WL(1, json);
 }
Beispiel #13
0
        public static void Postfix(Contract __instance, List <UnitResult> enemyMechs, ref List <SalvageDef> ___finalPotentialSalvage, DataManager ___dataManager)
        {
            try
            {
                // Only for opportunity contracts
                if (__instance.IsOpportunityMission())
                {
                    Logger.Debug($"[Contract_GenerateSalvage_POSTFIX] Checking BLACKLISTED overrides for contract {__instance.Override.ID}");

                    SimGameState     simGameState     = __instance.BattleTechGame.Simulation;
                    SimGameConstants simGameConstants = simGameState.Constants;

                    foreach (UnitResult unitResult in enemyMechs)
                    {
                        MechDef mech  = unitResult.mech;
                        Pilot   pilot = unitResult.pilot;



                        // Component handling needs to be before evaluating MechParts as there the MechDef is probably normalized
                        if (mech.MechTags.Contains("WHITELIST_COMPONENTS"))
                        {
                            Logger.Debug($"[Contract_GenerateSalvage_POSTFIX] MechDef of {mech.Name} has WHITELIST_COMPONENTS tag. Manually adding blacklisted components to salvage.");

                            foreach (MechComponentRef mechComponentRef in mech.Inventory)
                            {
                                // Skip if destroyed or in a destroyed location
                                if (mech.IsLocationDestroyed(mechComponentRef.MountedLocation) || mechComponentRef.DamageLevel == ComponentDamageLevel.Destroyed)
                                {
                                    continue;
                                }

                                if (mechComponentRef.Def.ComponentTags.Contains("BLACKLISTED"))
                                {
                                    Logger.Debug($"[Contract_GenerateSalvage_PREFIX] mechComponentRef.Def {mechComponentRef.Def.Description.Id} has BLACKLISTED tag. Adding to salvage.");

                                    SalvageDef salvageDef = Utilities.CreateComponent(simGameConstants, __instance, mechComponentRef.Def);
                                    ___finalPotentialSalvage.Add(salvageDef);
                                }
                            }
                        }



                        // MechParts
                        if (mech.MechTags.Contains("BLACKLISTED") || mech.Chassis.ChassisTags.Contains("BLACKLISTED"))
                        {
                            Logger.Debug($"[Contract_GenerateSalvage_POSTFIX] MechDef or ChassisDef of {mech.Name} has BLACKLISTED tag. Checking for override flags.");

                            if (mech.MechTags.Contains("WHITELIST_PARTS"))
                            {
                                Logger.Debug($"[Contract_GenerateSalvage_POSTFIX] MechDef of {mech.Name} has WHITELIST_PARTS tag. Manually adding MechParts to salvage.");

                                // Needs to work on original MechDef so has to be called before a possible normalization
                                int numberOfParts = Utilities.GetMechPartCountForSalvage(mech, pilot);

                                // Normalize MechDef
                                string stockMechDefId = mech.ChassisID.Replace("chassisdef", "mechdef");
                                if (mech.Description.Id != stockMechDefId)
                                {
                                    Logger.Debug($"[Contract_GenerateSalvage_POSTFIX] Normalizing {mech.Description.Id} to {stockMechDefId}");
                                    mech = ___dataManager.MechDefs.Get(stockMechDefId);
                                }

                                // Add MechParts to Salvage
                                for (int i = 0; i < numberOfParts; i++)
                                {
                                    SalvageDef salvageDef = Utilities.CreateMechPart(simGameConstants, __instance, mech);
                                    ___finalPotentialSalvage.Add(salvageDef);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Error(e);
            }
        }
Beispiel #14
0
        public static bool Prefix(Contract __instance, ref MechComponentDef def, DataManager ___dataManager)
        {
            try
            {
                Logger.Debug("----------------------------------------------------------------------------------------------------");
                Logger.Debug("[Contract_AddMechComponentToSalvage_PREFIX] Handling def: " + def.Description.Id + "(ComponentType: " + def.ComponentType + ")");

                // If rare upgrades are found, just cancel original method completely -> Skip adding anything to salvage for this component
                // Rare upgrades will still be added to salvage by Vanillas Replacement-RNG on anything non-weapon
                if (def.ComponentType == ComponentType.Upgrade)
                {
                    Logger.Debug("[Contract_AddMechComponentToSalvage_PREFIX] Component is an upgrade, skipping original method");
                    return(false);
                }
                // Ignore blacklisted components
                if (def.ComponentTags.Contains("BLACKLISTED"))
                {
                    return(true);
                }
                // Only touch weapons for now
                if (def.ComponentType != ComponentType.Weapon)
                {
                    return(true);
                }
                // Don't touch stock weapons either
                if (def.Description.Rarity <= 0)
                {
                    return(true);
                }

                // At this point only RARE WEAPONS should be left to handle
                // Adding in a random chance to keep exactly the item that will be passed into the original method.
                // Default behaviour is to replace any rare weapon with its stock version and let vanillas algorithms decide if some of them will be replaced by rare counterparts
                // Note that even if the current component is rare and it passes the test to be kept, the original method will still probably replace it with *another* rare component.
                SimGameState     simGameState     = __instance.BattleTechGame.Simulation;
                SimGameConstants simGameConstants = simGameState.Constants;
                int contractDifficulty            = __instance.Override.finalDifficulty;
                int globalDifficulty = Utilities.GetNormalizedGlobalDifficulty(simGameState);
                Logger.Info($"[Contract_AddMechComponentToSalvage_PREFIX] contractDifficulty: {contractDifficulty}, globalDifficulty: {globalDifficulty}");


                // Respect difficulty setting "No Rare Salvage" in here too...
                //Logger.Info($"[Contract_AddMechComponentToSalvage_PREFIX] simGameConstants.Salvage.RareWeaponChance: {simGameConstants.Salvage.RareWeaponChance}");
                //Logger.Info($"[Contract_AddMechComponentToSalvage_PREFIX] simGameConstants.Salvage.VeryRareWeaponChance: {simGameConstants.Salvage.VeryRareWeaponChance}");
                bool rareSalvageEnabled = simGameConstants.Salvage.RareWeaponChance > -10f;
                Logger.Debug($"[Contract_AddMechComponentToSalvage_PREFIX] rareSalvageEnabled: {rareSalvageEnabled}");

                if (rareSalvageEnabled)
                {
                    // Minimum chance to keep this rare weapon by settings + (contract difficulty OR global difficulty (whatever is higher) multiplied by mod-difficulty), max 80%
                    int   bonus  = Math.Max(contractDifficulty, globalDifficulty) * EvenTheOdds.Settings.Difficulty;
                    float chance = Math.Min(EvenTheOdds.Settings.SalvageHighQualityWeaponsBaseChancePercent + bonus, 80) / 100f;
                    float roll   = simGameState.NetworkRandom.Float(0f, 1f);
                    bool  keep   = roll < chance;
                    Logger.Info($"[Contract_AddMechComponentToSalvage_PREFIX] ({def.Description.Id}) chance({chance}) against roll({roll}) to keep: {keep}");

                    // Currently handled rare weapons should pass into original method as is
                    if (keep)
                    {
                        Logger.Debug("[Contract_AddMechComponentToSalvage_PREFIX] (" + def.Description.Id + ") passes into original method");
                        return(true);
                    }
                }


                // Resetting rare weapon to its stock version if above checks to potentially keep it fails
                WeaponDef weaponDef        = def as WeaponDef;
                string    weaponOriginalId = def.Description.Id;

                // Note that the "Heavy Metal" weapons don't follow this scheme. But as they're all blacklisted they should never end up down here
                string weaponStockId = def.ComponentType.ToString() + "_" + weaponDef.Type.ToString() + "_" + weaponDef.WeaponSubType.ToString() + "_0-STOCK";

                // Set to stock
                def = ___dataManager.WeaponDefs.Get(weaponStockId);
                Logger.Debug("[Contract_AddMechComponentToSalvage_PREFIX] (" + weaponOriginalId + ") was replaced with stock version (" + def.Description.Id + ")");

                return(true);
            }
            catch (Exception e)
            {
                Logger.Error(e);
                return(true);
            }
        }