public static bool Prefix(LanceOverride __instance, Contract contract, LanceDef lanceDef)
        {
            if (contract != null)
            {
                if (LanceOverride_RunMadLibs.teamOverrides.ContainsKey(__instance.GetHashCode()))
                {
                    // Setup CurrentTeam before running the madlibs
                    TeamOverride teamOverride = LanceOverride_RunMadLibs.teamOverrides[__instance.GetHashCode()];
                    IRBT14MadlibsFix.Logger.Log($"LO:RMLOLD using teamOverride:[{teamOverride.GetHashCode()}] for lanceOverride:[{__instance?.GetHashCode()}]");
                    contract.GameContext.SetObject(GameContextObjectTagEnum.CurrentTeam, teamOverride);
                }
                else
                {
                    IRBT14MadlibsFix.Logger.Log($"LO:RMLOLD COULD NOT LOAD teamOverride using lanceOverride:[{__instance.GetHashCode()}]! MadLibs may break!");
                }

                contract.RunMadLib(lanceDef.LanceTags);

                foreach (LanceDef.Unit unit in lanceDef.LanceUnits)
                {
                    Traverse ensureTagSetsT = Traverse.Create(unit).Method("EnsureTagSets");
                    ensureTagSetsT.GetValue();

                    IRBT14MadlibsFix.Logger.Log($"LO:RMLOLD BEFORE madlibs lanceTagSet is:[{unit.unitTagSet}]");
                    contract.RunMadLib(unit.unitTagSet);
                    IRBT14MadlibsFix.Logger.Log($"LO:RMLOLD AFTER madlibs lanceTagSet is:[{unit.unitTagSet}]");

                    contract.RunMadLib(unit.excludedUnitTagSet);
                    contract.RunMadLib(unit.pilotTagSet);
                    contract.RunMadLib(unit.excludedPilotTagSet);
                }
            }

            return(false);
        }
        public static void Postfix(Panel_Map __instance, String sceneName)
        {
            if (sceneName != SceneManager.GetActiveScene().name)
            {
                // not the current region -> don't add the current location to the map
                return;
            }

            Traverse panel_Map = Traverse.Create(__instance);
            Traverse worldPositionToMapPosition = panel_Map.Method("WorldPositionToMapPosition", new Type[] { typeof(String), typeof(Vector3) });
            Vector3  mapPosition = worldPositionToMapPosition.GetValue <Vector3>(new object[] { sceneName, GameManager.GetPlayerTransform().localPosition });

            MapElementSaveData mapElementSaveData = new MapElementSaveData();

            mapElementSaveData.m_LocationNameLocID     = "GAMEPLAY_Location";
            mapElementSaveData.m_SpriteName            = "ico_X";
            mapElementSaveData.m_BigSprite             = false;
            mapElementSaveData.m_IsDetail              = true;
            mapElementSaveData.m_NameIsKnown           = true;
            mapElementSaveData.m_PositionOnMap         = (Vector2)mapPosition;
            mapElementSaveData.m_ActiveMissionLocIDs   = new List <string>();
            mapElementSaveData.m_ActiveMissionTimerIDs = new List <string>();
            mapElementSaveData.m_ActiveMissionIDs      = new List <string>();

            Transform child = __instance.m_BigSpritePoolParent.GetChild(0);

            child.GetComponent <MapIcon>().DoSetup(mapElementSaveData, __instance.m_BigSpriteActiveObjects, 1000, MapIcon.MapIconType.TopIcon);

            Dictionary <Transform, MapElementSaveData> m_TransformToMapData = panel_Map.Field("m_TransformToMapData").GetValue <Dictionary <Transform, MapElementSaveData> >();

            m_TransformToMapData.Add(child, mapElementSaveData);
        }
            private static bool Prefix(TurnDirector __instance)
            {
                Mod.Log.Info($"TD:OTAAC invoked");

                if (__instance.IsMissionOver)
                {
                    return(false);
                }

                Mod.Log.Info($"TD isInterleaved: {__instance.Combat.TurnDirector.IsInterleaved}  isInterleavePending: {__instance.Combat.TurnDirector.IsInterleavePending}" +
                             $"  isNonInterleavePending: {__instance.Combat.TurnDirector.IsNonInterleavePending}");

                int numUnusedUnitsForCurrentPhase = __instance.TurnActors[__instance.ActiveTurnActorIndex].GetNumUnusedUnitsForCurrentPhase();

                Mod.Log.Info($"There are {numUnusedUnitsForCurrentPhase} unusedUnits in the current phase)");

                if (!__instance.IsInterleavePending && !__instance.IsInterleaved && numUnusedUnitsForCurrentPhase > 0)
                {
                    Mod.Log.Info("Sending TurnActorActivateMessage");
                    Traverse staamT = Traverse.Create(__instance).Method("SendTurnActorActivateMessage", new object[] { __instance.ActiveTurnActorIndex });
                    staamT.GetValue();
                }
                else
                {
                    Mod.Log.Info("Incrementing ActiveTurnActor");
                    Traverse iataT = Traverse.Create(__instance).Method("IncrementActiveTurnActor");
                    iataT.GetValue();
                }

                return(false);
            }
Beispiel #4
0
        private static int MechAssemblyRemoveParts(SimGameState s, MechDef d, int required, int min)
        {
            int curr     = s.GetItemCount(d.Description.Id, "MECHPART", SimGameState.ItemCountType.UNDAMAGED_ONLY);
            int removing = required;

            if (curr < required)
            {
                removing = curr;
            }
            if ((curr - removing) < min)
            {
                removing -= min - (curr - removing);
            }
            if (removing < 0)
            {
                removing = 0;
            }
            // the string variant of removeitem is private...
            //string stat = string.Format("{0}.{1}.{2}", "Item", "MECHPART", d.Description.Id);
            object[] args   = new object[] { d.Description.Id, "MECHPART", false };
            Traverse method = Traverse.Create(s).Method("RemoveItemStat", args);

            for (int i = 0; i < removing; i++)
            {
                //s.CompanyStats.ModifyStat("SimGameState", 0, stat, StatCollection.StatOperation.Int_Subtract, 1, -1, true);
                method.GetValue(args);
            }
            Log.LogDebug("using parts " + d.Description.Id + " " + removing);
            return(removing);
        }
 public void ResolveUpgrade()
 {
     upgraded = true;
     if (parent.def.useHitPoints)
     {
         parent.HitPoints = parent.MaxHitPoints;
     }
     if (parent is Building_TurretGun turretWGun)
     {
         ((TurretTop)(Traverse.Create(turretWGun).Field("top").GetValue())).DrawTurret();
         if (Props.turretGunDef != null)
         {
             turretWGun.gun = ThingMaker.MakeThing(Props.turretGunDef);
             AccessTools.Method(typeof(Building_TurretGun), "UpdateGunVerbs").Invoke(turretWGun, null);
         }
     }
     if (parent.TryGetComp <CompRefuelable>() is CompRefuelable refuelableComp)
     {
         Traverse fuel = Traverse.Create(refuelableComp).Field("fuel");
         fuel.SetValue((float)fuel.GetValue() * Props.barrelDurabilityFactor * Props.effectiveBarrelDurabilityFactor);
     }
     if (parent.TryGetComp <CompPowerTrader>() is CompPowerTrader powerComp)
     {
         powerComp.SetUpPowerVars();
     }
 }
        static void Postfix(WeaponRangeIndicators __instance, AbstractActor selectedActor, Vector3 position, Quaternion rotation, bool isPositionLocked,
                            ICombatant targetedActor, bool useMultiFire, List <ICombatant> lockedTargets, bool isMelee)
        {
            if (targetedActor != null && !useMultiFire && targetedActor is BattleTech.Building targetedBuilding)
            {
                Mod.Log.Trace?.Write("Drawing line for building-as-target.");
                // Replicate WeaponRangeIndicators.ShowLineToTarget, because it only supports AbstractActors
                Traverse drawLineT = Traverse.Create(__instance).Method("DrawLine", new object[] { position, rotation, true, selectedActor, targetedActor, false, false, isMelee });
                drawLineT.GetValue();

                targetedActor.GameRep.IsTargeted = true;

                //this.HUD.InWorldMgr.ShowAttackDirection(this.HUD.SelectedActor, targetedActor, this.HUD.Combat.HitLocation.GetAttackDirection(position, targetedActor), 0f,
                //    isMelee ? MeleeAttackType.Punch : MeleeAttackType.NotSet, this.HUD.InWorldMgr.NumWeaponsTargeting(targetedActor));

                Traverse hideLinesT = Traverse.Create(__instance).Method("hideLines", new object[] { 1 });
                hideLinesT.GetValue();

                Traverse             setEnemyTargetableT = Traverse.Create(__instance).Method("SetEnemyTargetable", new Type[] { typeof(ICombatant), typeof(bool) });
                List <AbstractActor> allEnemies          = selectedActor.Combat.AllEnemies;
                for (int i = 0; i < allEnemies.Count; i++)
                {
                    if (allEnemies[i] != targetedActor)
                    {
                        setEnemyTargetableT.GetValue(new object[] { allEnemies[i], false });
                    }
                }
            }
        }
Beispiel #7
0
        public static bool ActiveProbeSequence_CompleteOrders_Prefix(ActiveProbeSequence __instance, AbstractActor ___owningActor, ParticleSystem ___probeParticles)
        {
            Mod.Log.Trace?.Write("SLS:CO entered, aborting invocation");
            //Mod.Log.Trace?.Write($"  oa:{___owningActor.DisplayName}_{___owningActor.GetPilot().Name} hasFired:{___owningActor.HasFiredThisRound} hasMoved:{___owningActor.HasMovedThisRound} hasActivated:{___owningActor.HasActivatedThisRound}");

            // Force the ability to be on cooldown
            if (ActorHasFreeSensorLock(___owningActor))
            {
                CombatGameState ___Combat = Traverse.Create(__instance).Property("Combat").GetValue <CombatGameState>();
                if (___probeParticles != null)
                {
                    ___probeParticles.Stop(true);
                    ___Combat.DataManager.PoolGameObject(___Combat.Constants.VFXNames.active_probe_effect, ___probeParticles.gameObject);
                }
                WwiseManager.PostEvent(AudioEventList_activeProbe.activeProbe_stop, WwiseManager.GlobalAudioObject, null, null);

                Mod.Log.Debug?.Write($"  Clearing all sequences");

                if (ModState.SelectionStateActiveProbe != null)
                {
                    Mod.Log.Debug?.Write($"  Calling clearTargetedActor");
                    Traverse traverse = Traverse.Create(ModState.SelectionStateActiveProbe).Method("RefreshPossibleTargets");
                    traverse.GetValue();

                    //State.SelectionStateSensorLock.BackOut();

                    ModState.SelectionStateActiveProbe = null;
                }
                return(false);
            }

            return(true);
        }
        private static void Postfix(CombatHUDWeaponSlot __instance, ICombatant target, Weapon ___displayedWeapon, CombatHUD ___HUD)
        {
            if (__instance == null || ___displayedWeapon == null || ___HUD.SelectedActor == null || target == null)
            {
                return;
            }

            Mod.Log.Trace?.Write("CHUDWS:SHC - entered.");

            Traverse AddToolTipDetailMethod = Traverse.Create(__instance).Method("AddToolTipDetail",
                                                                                 new Type[] { typeof(string), typeof(int) });

            AbstractActor attacker  = __instance.DisplayedWeapon.parent;
            string        cacheKey  = StraightTonnageCalculator.CacheKey(attacker, target);
            bool          keyExists = ModState.CachedComparisonMods.TryGetValue(cacheKey, out int modifier);

            if (!keyExists)
            {
                modifier = StraightTonnageCalculator.Modifier(attacker, target);
                ModState.CachedComparisonMods.Add(cacheKey, modifier);
            }

            string localText = new Localize.Text(Mod.LocalizedText.Label[ModText.LT_AttackModSizeDelta]).ToString();

            AddToolTipDetailMethod.GetValue(new object[] { localText, modifier });
        }
Beispiel #9
0
        public static void CalculateMimeticPips(CombatHUDStealthBarPips stealthDisplay, AbstractActor actor, float distanceMoved)
        {
            EWState actorState = new EWState(actor);

            Mod.Log.Trace?.Write($"Calculating mimeticPips for Actor: {CombatantUtils.Label(actor)}");

            int stepsMoved = (int)Math.Ceiling(distanceMoved / 30f);

            Mod.Log.Trace?.Write($"  stepsMoved: {stepsMoved} = distanceMoved: {distanceMoved} / 30");

            // Update # of pips
            int maxPips     = actorState.MaxMimeticPips();
            int currentPips = actorState.CurrentMimeticPips(distanceMoved);

            stealthDisplay.ShowNewActorStealth(currentPips, maxPips);

            // Change colors to reflect maxmimums
            Traverse       pipsT = Traverse.Create(stealthDisplay).Property("Pips");
            List <Graphic> pips  = pipsT.GetValue <List <Graphic> >();

            for (int i = 0; i < pips.Count; i++)
            {
                Graphic g = pips[i];
                if (g.isActiveAndEnabled)
                {
                    //Color pipColor = Color.white;
                    Color pipColor = new Color(50f, 206f, 230f);
                    UIHelpers.SetImageColor(g, pipColor);
                }
            }
        }
Beispiel #10
0
        static void Postfix(CombatHUDWeaponSlot __instance, ICombatant target, Weapon ___displayedWeapon, CombatHUD ___HUD)
        {
            if (__instance == null || ___displayedWeapon == null || ___HUD.SelectedActor == null || target == null)
            {
                return;
            }

            Mod.Log.Trace?.Write("CHUDWS:SHC entered");

            if (___HUD.SelectionHandler.ActiveState.SelectionType == SelectionType.FireMorale)
            {
                int calledShotMod = ActorHelper.CalledShotModifier(___HUD.SelectedActor);
                if (calledShotMod != 0)
                {
                    Traverse addToolTipDetailT = Traverse.Create(__instance)
                                                 .Method("AddToolTipDetail", new Type[] { typeof(string), typeof(int) });

                    string localText = new Text(Mod.LocalizedText.Modifiers[ModText.Mod_CalledShot]).ToString();
                    addToolTipDetailT.GetValue(new object[] { localText, calledShotMod });
                    Mod.Log.Debug?.Write($"Adding calledShot tooltip with text: {localText} and mod: {calledShotMod}");
                }
                Mod.Log.Debug?.Write($"Updated TooltipsForFiring for actor: {___HUD.SelectedActor} with mod: {calledShotMod}");
            }
            else
            {
                Mod.Log.Debug?.Write("Not FireMorale, skipping!");
            }
        }
Beispiel #11
0
            public static void Postfix(ref Spellbook __instance, ref int ___m_CasterLevelInternal, List <BlueprintSpellList> ___m_SpecialLists)
            {
                int maxSpellLevel = __instance.MaxSpellLevel;

                ___m_CasterLevelInternal += settings.addCasterLevel;
                int maxSpellLevel2 = __instance.MaxSpellLevel;

                if (__instance.Blueprint.AllSpellsKnown)
                {
                    Traverse addSpecialMethod = Traverse.Create(__instance).Method("AddSpecial", new Type[] { typeof(int), typeof(BlueprintAbility) });
                    for (int i = maxSpellLevel + 1; i <= maxSpellLevel2; i++)
                    {
                        foreach (BlueprintAbility spell in __instance.Blueprint.SpellList.GetSpells(i))
                        {
                            __instance.AddKnown(i, spell);
                        }
                        foreach (BlueprintSpellList specialList in ___m_SpecialLists)
                        {
                            foreach (BlueprintAbility spell2 in specialList.GetSpells(i))
                            {
                                addSpecialMethod.GetValue(i, spell2);
                            }
                        }
                    }
                }
            }
Beispiel #12
0
            public static void Postfix(CombatHUDWeaponSlot __instance, CombatGameState ___Combat, ICombatant target)
            {
                try
                {
                    if (DemandingJumps.Settings.ToHitSelfJumpedSpareAI && !___Combat.LocalPlayerTeam.IsActive)
                    {
                        return;
                    }
                    Logger.Info("[CombatHUDWeaponSlot_SetHitChance_POSTFIX] CombatGameState.LocalPlayerTeam.IsActive: " + ___Combat.LocalPlayerTeam.IsActive);



                    AbstractActor attacker = __instance.DisplayedWeapon.parent;
                    bool          AttackerJumpedThisRound = attacker.HasMovedThisRound && attacker.JumpedLastRound;
                    Logger.Info("[CombatHUDWeaponSlot_SetHitChance_POSTFIX] Fields.JumpPreview: " + Fields.JumpPreview);
                    Logger.Info("[CombatHUDWeaponSlot_SetHitChance_POSTFIX] AttackerJumpedThisRound: " + AttackerJumpedThisRound);

                    if (AttackerJumpedThisRound)
                    {
                        int      ToHitSelfJumpedModifier = Utilities.GetAttackerJumpedAccuracyModifier(attacker);
                        Traverse AddToolTipDetail        = Traverse.Create(__instance).Method("AddToolTipDetail", "SELF JUMPED", ToHitSelfJumpedModifier);
                        Logger.Info($"[CombatHUDWeaponSlot_SetHitChance_POSTFIX] Invoking AddToolTipDetail for ToHitSelfJumped: {ToHitSelfJumpedModifier}");
                        AddToolTipDetail.GetValue();
                    }
                }
                catch (Exception e)
                {
                    Logger.Error(e);
                }
            }
        public static void Postfix(CombatHUDStatusPanel __instance, List <CombatHUDStatusIndicator> ___Buffs, List <CombatHUDStatusIndicator> ___Debuffs)
        {
            Mod.Log.Trace?.Write("CHUDSP:RDC - entered.");
            if (__instance != null && __instance.DisplayedCombatant != null)
            {
                AbstractActor target = __instance.DisplayedCombatant as AbstractActor;
                // We can receive a building here, so
                if (target != null)
                {
                    if (target.Combat.HostilityMatrix.IsLocalPlayerEnemy(target.team))
                    {
                        SensorScanType scanType = SensorLockHelper.CalculateSharedLock(target, ModState.LastPlayerActorActivated);

                        // Hide the buffs and debuffs if the current scanType is less than allInfo
                        if (scanType < SensorScanType.AllInformation)
                        {
                            //// Hide the buffs and debuffs
                            ___Buffs.ForEach(si => si.gameObject.SetActive(false));
                            ___Debuffs.ForEach(si => si.gameObject.SetActive(false));
                        }
                    }

                    // Calculate stealth pips
                    Traverse stealthDisplayT = Traverse.Create(__instance).Field("stealthDisplay");
                    CombatHUDStealthBarPips stealthDisplay = stealthDisplayT.GetValue <CombatHUDStealthBarPips>();
                    VfxHelper.CalculateMimeticPips(stealthDisplay, target);
                }
            }
        }
        private static void Prefix(Team __instance, List <IStackSequence> __result)
        {
            Mod.Log.Debug?.Write($"T:DWAAA invoked");
            if (!__instance.IsLocalPlayer)
            {
                return;
            }

            if (__instance.Combat.TurnDirector.IsInterleavePending)
            {
                if (__result == null)
                {
                    Mod.Log.Debug?.Write("Result was null, adding a new list.");
                    __result = new List <IStackSequence>();
                }

                int numUnitsEndingActivation = 0;
                foreach (AbstractActor unit in __instance.units)
                {
                    Mod.Log.Debug?.Write($"Processing unit: {unit.DisplayName}_{unit.GetPilot().Name}");
                    if (!unit.IsCompletingActivation && !unit.IsDead && !unit.IsFlaggedForDeath)
                    {
                        Mod.Log.Info?.Write($"  Ending activation for unit {CombatantUtils.Label(unit)}");
                        IStackSequence item = unit.DoneWithActor();
                        numUnitsEndingActivation++;
                        __result.Add(item);
                    }
                }

                Traverse numUnitsEndingActivationT = Traverse.Create(__instance).Field("numUnitsEndingActivation");
                int      currentValue = numUnitsEndingActivationT.GetValue <int>();
                numUnitsEndingActivationT.SetValue(currentValue + numUnitsEndingActivation);
            }
        }
Beispiel #15
0
        // Remove the BuildWeaponDirectorSequence, to prevent duplicate ammo consumption
        static bool Prefix(MechMeleeSequence __instance)
        {
            Traverse BuildMeleeDirectorSequenceT = Traverse.Create(__instance).Method("BuildMeleeDirectorSequence");

            BuildMeleeDirectorSequenceT.GetValue();

            if (__instance.OwningMech.GameRep != null)
            {
                __instance.OwningMech.GameRep.ReturnToNeutralFacing(isParellelSequence: true, 0.5f, __instance.RootSequenceGUID, __instance.SequenceGUID, null);
            }
            if (__instance.OwningMech.GameRep != null)
            {
                __instance.OwningMech.GameRep.FadeThrottleAudio(0f, 50f, 1f);
            }
            SharedState.Combat.MessageCenter.AddSubscriber(MessageCenterMessageType.OnAttackComplete, __instance.OnMeleeComplete);
            SharedState.Combat.MessageCenter.AddSubscriber(MessageCenterMessageType.OnAttackSequenceFire, __instance.OnMeleeReady);

            // Reading meleeSequence as a property doesn't seem to work, because it always returns null. I'm unsure if this
            //   is a harmony bug... so read it directly, which seems to work.
            Traverse            meleeSequenceT = Traverse.Create(__instance).Field("meleeSequence");
            AttackStackSequence meleeSequence  = meleeSequenceT.GetValue <AttackStackSequence>();

            SharedState.Combat.MessageCenter.PublishMessage(new AddParallelSequenceToStackMessage(meleeSequence));

            return(false);
        }
Beispiel #16
0
 public override void PostIngested(Pawn ingester)
 {
     base.PostIngested(ingester);
     if (ingester.health.hediffSet.HasHediff(InfectionDefOf.MuscleParasites))
     {
         HediffWithComps hediff = (HediffWithComps)ingester.health.hediffSet.GetFirstHediffOfDef(InfectionDefOf.MuscleParasites);
         hediff.comps.First(h => h is HediffComp_TendDuration).CompTended(1, 0);
     }
     if (ingester.health.hediffSet.HasHediff(InfectionDefOf.GutWorms))
     {
         HediffWithComps hediff = (HediffWithComps)ingester.health.hediffSet.GetFirstHediffOfDef(InfectionDefOf.GutWorms);
         hediff.comps.First(h => h is HediffComp_TendDuration).CompTended(1, 0);
     }
     if (ingester.health.hediffSet.HasHediff(InfectionDefOf.FibrousMechanites))
     {
         HediffWithComps hediff           = (HediffWithComps)ingester.health.hediffSet.GetFirstHediffOfDef(InfectionDefOf.FibrousMechanites);
         HediffComp      hediffComp       = hediff.comps.First(h => h is HediffComp_Disappears);
         Traverse        field            = Traverse.Create(hediffComp).Field("ticksToDisappear");
         int             ticksToDisappear = field.GetValue <int>();
         field.SetValue(ticksToDisappear - 90000);
     }
     if (ingester.health.hediffSet.HasHediff(InfectionDefOf.SensoryMechanites))
     {
         HediffWithComps hediff           = (HediffWithComps)ingester.health.hediffSet.GetFirstHediffOfDef(InfectionDefOf.SensoryMechanites);
         HediffComp      hediffComp       = hediff.comps.First(h => h is HediffComp_Disappears);
         Traverse        field            = Traverse.Create(hediffComp).Field("ticksToDisappear");
         int             ticksToDisappear = field.GetValue <int>();
         field.SetValue(ticksToDisappear - 90000);
     }
 }
Beispiel #17
0
        public static List <KeyValuePair <string, int> > GetCurrentKeys(Transform container, SimGameState sgs)
        {
            List <KeyValuePair <string, int> > currentKeys = new List <KeyValuePair <string, int> >();
            IEnumerator enumerator = container.GetEnumerator();

            try {
                while (enumerator.MoveNext())
                {
                    object         obj       = enumerator.Current;
                    Transform      transform = (Transform)obj;
                    SGKeyValueView component = transform.gameObject.GetComponent <SGKeyValueView>();

                    Mod.Log.Debug($"SGCQSS:RD - Reading key from component:{component.name}.");
                    Traverse        keyT    = Traverse.Create(component).Field("Key");
                    TextMeshProUGUI keyText = (TextMeshProUGUI)keyT.GetValue();
                    string          key     = keyText.text;
                    Mod.Log.Debug($"SGCQSS:RD - key found as: {key}");

                    Traverse        valueT    = Traverse.Create(component).Field("Value");
                    TextMeshProUGUI valueText = (TextMeshProUGUI)valueT.GetValue();
                    string          valueS    = valueText.text;
                    string          digits    = Regex.Replace(valueS, @"[^\d]", "");
                    Mod.Log.Debug($"SGCQSS:RD - rawValue:{valueS} digits:{digits}");
                    int value = Int32.Parse(digits);

                    Mod.Log.Debug($"SGCQSS:RD - found existing pair: {key} / {value}");
                    KeyValuePair <string, int> kvp = new KeyValuePair <string, int>(key, value);
                    currentKeys.Add(kvp);
                }
            } catch (Exception e) {
                Mod.Log.Info($"Failed to get key-value pairs: {e.Message}");
            }

            return(currentKeys);
        }
        static void Postfix(CombatHUDWeaponSlot __instance, Weapon ___displayedWeapon, CombatHUD ___HUD)
        {
            if (__instance == null || ___displayedWeapon == null || ___HUD.SelectedActor == null ||
                !Mod.Config.Melee.FilterCanUseInMeleeWeaponsByAttack)
            {
                return;
            }

            MeleeAttack selectedAttack = ModState.GetSelectedAttack(___HUD.SelectedActor);

            if (selectedAttack != null)
            {
                Mod.UILog.Debug?.Write($"Checking ranged weapons attacker: {___HUD.SelectedActor.DistinctId()} using selectedAttack: {selectedAttack.Label}");

                // Check if the weapon can fire according to the select melee type
                bool isAllowed = selectedAttack.IsRangedWeaponAllowed(___displayedWeapon);
                Mod.UILog.Debug?.Write($"Ranged weapon '{___displayedWeapon.UIName}' can fire in melee by type? {isAllowed}");

                if (!isAllowed)
                {
                    Mod.UILog.Debug?.Write($"Disabling weapon from selection");
                    __instance.ToggleButton.isChecked = false;
                    Traverse showDisabledHexT = Traverse.Create(__instance).Method("ShowDisabledHex");
                    showDisabledHexT.GetValue();
                }
            }
            //else
            //{
            //    // No selected attack, so revert the weapon to the state it should have
            //    __instance.ToggleButton.isChecked = ___displayedWeapon.IsEnabled && !___displayedWeapon.IsDisabled;
            //}
        }
        public static DialogueContent BuildDialogueContent(CastDef castDef, string dialogue, Color dialogueColor)
        {
            if (castDef == null || String.IsNullOrEmpty(castDef.id) || castDef.defaultEmotePortrait == null || String.IsNullOrEmpty(castDef.defaultEmotePortrait.portraitAssetPath))
            {
                Mod.Log.Warn?.Write("Was passed a castDef with an empty ID - we can't handle this!");
                return(null);
            }

            Mod.Log.Info?.Write($"Creating dialogueContent for castDef: {castDef.id}");

            DialogueContent content = new DialogueContent(dialogue, dialogueColor, castDef.id, null, null,
                                                          DialogCameraDistance.Medium, DialogCameraHeight.Default, 0);

            // ContractInitialize normally sets the castDef on the content... no need, since we have the actual ref
            Traverse castDefT = Traverse.Create(content).Field("castDef");

            castDefT.SetValue(castDef);

            // Initialize the active contract's team settings
            ApplyCastDef(content);

            // Load the default emote portrait
            Traverse dialogueSpriteCacheT = Traverse.Create(content).Field("dialogueSpriteCache");
            Dictionary <string, Sprite> dialogueSpriteCache = dialogueSpriteCacheT.GetValue <Dictionary <string, Sprite> >();

            Mod.Log.Debug?.Write($"Populating dialogueContent with sprite from path: {castDef.defaultEmotePortrait.portraitAssetPath}");
            dialogueSpriteCache[castDef.defaultEmotePortrait.portraitAssetPath] = ModState.Portraits[castDef.defaultEmotePortrait.portraitAssetPath];

            return(content);
        }
Beispiel #20
0
        public static bool SensorLockSequence_CompleteOrders_Prefix(SensorLockSequence __instance, AbstractActor ___owningActor)
        {
            Mod.Log.Trace?.Write("SLS:CO entered, aborting invocation");
            //Mod.Log.Trace?.Write($"  oa:{___owningActor.DisplayName}_{___owningActor.GetPilot().Name} hasFired:{___owningActor.HasFiredThisRound} hasMoved:{___owningActor.HasMovedThisRound} hasActivated:{___owningActor.HasActivatedThisRound}");

            // Force the ability to be on cooldown
            if (PilotHasFreeSensorLockAbility(___owningActor))
            {
                Pilot   pilot   = ___owningActor.GetPilot();
                Ability ability = pilot.GetActiveAbility(ActiveAbilityID.SensorLock);
                Mod.Log.Debug?.Write($"  On sensor lock complete, cooldown is:{ability.CurrentCooldown}");
                if (ability.CurrentCooldown < 1)
                {
                    ability.ActivateCooldown();
                }

                Mod.Log.Debug?.Write($"  Clearing all sequences");

                if (ModState.SelectionStateSensorLock != null)
                {
                    Mod.Log.Debug?.Write($"  Calling clearTargetedActor");
                    Traverse traverse = Traverse.Create(ModState.SelectionStateSensorLock).Method("ClearTargetedActor");
                    traverse.GetValue();

                    //State.SelectionStateSensorLock.BackOut();

                    ModState.SelectionStateSensorLock = null;
                }
            }

            return(false);
        }
        public static void Prefix(MechDFASequence __instance, ref List <Weapon> ___requestedWeapons)
        {
            if (___requestedWeapons.Count < 1)
            {
                return;
            }

            AbstractActor actor       = __instance.owningActor;
            ICombatant    MeleeTarget = __instance.DFATarget;

            bool TargetIsDead            = MeleeTarget.IsDead;
            bool TargetIsFlaggedForDeath = MeleeTarget.IsFlaggedForDeath;

            Logger.Info("[MechMeleeSequence_OnMeleeComplete_PREFIX] TargetIsDead: " + TargetIsDead);
            Logger.Info("[MechMeleeSequence_OnMeleeComplete_PREFIX] TargetIsFlaggedForDeath: " + TargetIsFlaggedForDeath);

            if (TargetIsDead || TargetIsFlaggedForDeath)
            {
                ___requestedWeapons.Clear();
                actor.Combat.MessageCenter.PublishMessage(new FloatieMessage(actor.GUID, actor.GUID, "SUSPENDED SUPPORT WEAPONS", FloatieMessage.MessageNature.Neutral));
            }
            else
            {
                DontShootTheDead.BuildSupportWeaponSequence = true;
                Traverse BuildWeaponDirectorSequence = Traverse.Create(__instance).Method("BuildWeaponDirectorSequence");
                BuildWeaponDirectorSequence.GetValue();
            }
        }
Beispiel #22
0
        public static bool CombatHUDInWorldElementMgr_AddFloatieMessage_Prefix(CombatHUDInWorldElementMgr __instance, MessageCenterMessage message, CombatGameState ___combat)
        {
            Traverse       showFloatieT   = Traverse.Create(__instance).Method("ShowFloatie", new Type[] { typeof(FloatieMessage) });
            FloatieMessage floatieMessage = message as FloatieMessage;

            switch (floatieMessage.nature)
            {
            case MessageNature.ArmorDamage:
            case MessageNature.StructureDamage:
            case MessageNature.Buff:
            case MessageNature.Debuff:
                showFloatieT.GetValue(new object[] { floatieMessage });
                break;

            case MessageNature.Miss:
            case MessageNature.MeleeMiss:
            case MessageNature.Dodge:
                //__instance.ShowFloatie(floatieMessage);
                break;

            default:
                //__instance.ShowStackedFloatie(floatieMessage);
                break;
            }

            return(false);
        }
        // Display the initiative modifiers for the current unit as a buff that folks can hover over for details.
        public static void Postfix(CombatHUDStatusPanel __instance)
        {
            Mod.Log.Debug("___ CombatHUDStatusPanel:ShowActorStatuses:post - entered.");

            if (__instance.DisplayedCombatant != null)
            {
                AbstractActor actor    = __instance.DisplayedCombatant as AbstractActor;
                bool          isPlayer = actor.team == actor.Combat.LocalPlayerTeam;
                if (isPlayer)
                {
                    Type[]   iconMethodParams   = new Type[] { typeof(SVGAsset), typeof(Text), typeof(Text), typeof(Vector3), typeof(bool) };
                    Traverse showBuffIconMethod = Traverse.Create(__instance).Method("ShowBuff", iconMethodParams);

                    Type[]   stringMethodParams   = new Type[] { typeof(string), typeof(Text), typeof(Text), typeof(Vector3), typeof(bool) };
                    Traverse showBuffStringMethod = Traverse.Create(__instance).Method("ShowBuff", stringMethodParams);

                    showBuffIconMethod.GetValue(new object[] {
                        LazySingletonBehavior <UIManager> .Instance.UILookAndColorConstants.StatusSensorLockIcon,
                        new Text("INITIATIVE", new object[0]),
                        new Text(BuildTooltipText(actor)),
                        __instance.effectIconScale,
                        false
                    });
                }
            }
        }
        public static bool ProcessJobApplicant(ref JobApplicant jobApplicant, string build)
        {
            if (!Builds.ContainsKey(build))
            {
                return(false);
            }

            Traverse q = Traverse.Create(jobApplicant).Property("Qualifications");
            List <QualificationSlot> target = q.GetValue <List <QualificationSlot> >();

            target.Clear();

            if (CheckExactAction(1)) // we're speccing trainees
            {
                Traverse r    = Traverse.Create(jobApplicant).Property("Rank");
                int      rank = r.GetValue <int>();
                rank = 0;
                r.SetValue(rank);
            }
            else if (CheckMinAction(2)) // if we're set to random or max
            {
                int num = jobApplicant.MaxQualifications - 1;
                if (CheckExactAction(3))
                {
                    Traverse r    = Traverse.Create(jobApplicant).Property("Rank");
                    int      rank = r.GetValue <int>();
                    rank = 4;
                    r.SetValue(rank);

                    Traverse x  = Traverse.Create(jobApplicant).Property("Experience");
                    float    xp = x.GetValue <float>();
                    xp = 0.0f;
                    x.SetValue(xp);

                    num = jobApplicant.MaxQualifications;
                }
                else if (RandomUtils.GlobalRandomInstance.Next(0, 100) > 50)
                {
                    num++;
                }
                int i = 0;
                foreach (string job in Builds[build])
                {
                    if (++i > num)
                    {
                        break;
                    }
                    if (!qualifications.Definitions.ContainsKey(job))
                    {
                        Logger.Error($"Unable to locate qualification {job} in current level.");
                        return(false);
                    }
                    target.Add(new QualificationSlot(qualifications.Definitions[job], true));
                }
            }

            q.SetValue(target);
            return(true);
        }
Beispiel #25
0
        public static void AddCarePackage(ref Immigration immigration, string objectId, float amount, Func <bool> requirement = null)
        {
            Traverse field = Traverse.Create(immigration).Field("carePackages");
            List <CarePackageInfo> list = field.GetValue <CarePackageInfo[]>().ToList();

            list.Add(new CarePackageInfo(objectId, amount, requirement));
            field.SetValue(list.ToArray());
        }
        public static void Postfix()
        {
            // tranverses the PDAScanner static class to get its private Dictionary of TechTypes and modify them
            Traverse pdaTraverse        = Traverse.Create(typeof(PDAScanner));
            Traverse pdaMappingTraverse = pdaTraverse.Field("mapping");
            Dictionary <TechType, PDAScanner.EntryData> mapping = pdaMappingTraverse.GetValue <Dictionary <TechType, PDAScanner.EntryData> >();

            // reads in the JSON specifying the new totalFragments values
            List <string> fragmentStrs = new List <string>();

            try
            {
                string line;
                using (var reader = File.OpenText("QMods\\FragmentCountChanger\\fragments.txt"))
                {
                    while ((line = reader.ReadLine()) != null)
                    {
                        fragmentStrs.Add(line);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("[FragmentCountChanger] " + ex.ToString());
                return;
            }

            Console.WriteLine("[FragmentCountChanger] loading");

            // iterate over every fragment pairing in the txt and update the value
            try
            {
                foreach (string fragPair in fragmentStrs)
                {
                    try
                    {
                        string[] fragPairSplit = fragPair.Split(':');

                        TechType fragType = (TechType)Enum.Parse(typeof(TechType), fragPairSplit[0].Trim());

                        PDAScanner.EntryData entryData;
                        if (mapping.TryGetValue(fragType, out entryData))
                        {
                            entryData.totalFragments = Int16.Parse(fragPairSplit[1].Trim());
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("[FragmentCountChanger] " + ex.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("[FragmentCountChanger] " + ex.ToString());
            }
            Console.WriteLine("[FragmentCountChanger] done");
        }
Beispiel #27
0
        public static void Prefix()
        {
            DataManager dm = SceneSingletonBehavior <DataManagerUnityInstance> .Instance.DataManager;
            Traverse    refreshTypedEntriesT = Traverse.Create(dm.ResourceLocator).Method("RefreshTypedEntries");

            RLog.LogWrite("Forcing refresh of TypedEntities to prevent Shadowhawk DLC bug...");
            refreshTypedEntriesT.GetValue();
            RLog.LogWrite(" DONE");
        }
Beispiel #28
0
        public static void Postfix(SkirmishSettings_Beta __instance, HBS_Dropdown ___lanceBudgetDropdown)
        {
            Mod.Log.Trace?.Write("SS_B:OLC - ENTERED!");

            Traverse initLanceModuleT = Traverse.Create(__instance).Method("InitializeLanceModules", new object[] { 3 });

            initLanceModuleT.GetValue();

            Mod.Log.Info?.Write("Set battlevalue to 3");
        }
Beispiel #29
0
        public static bool TeammateCountPatchAdd(ref TeammatesController __instance, string entityId)
        {
            CharacterData component = Game.EntityManager.GetComponent <CharacterData>(entityId);

            if (component == null)
            {
                return(false);
            }
            orderedTeammates.Add(component.Character);
            teammates.SetValue(orderedTeammates.GetRange(0, orderedTeammates.Count));
            var teammatesValue = teammates.GetValue <List <ICharacter> >();

            if (teammatesValue.Count > 6)
            {
                teammatesValue.RemoveRange(6, teammatesValue.Count - 6);
            }
            __instance.UpdateView();
            return(false);
        }
Beispiel #30
0
        public BuyHelper(SG_Shop_Screen shopScreen, InventoryDataObject_SHOP selectedController, SimGameState simGameState)
        {
            this.shopScreen   = shopScreen;
            this.simGameState = simGameState;
            shopIDO           = selectedController;

            Traverse traverse = Traverse.Create(shopScreen).Field("inventoryWidget");

            inventoryWidget = (MechLabInventoryWidget_ListView)traverse.GetValue();
        }