public static Hediff GetReplacingPart(IEnumerable <Hediff> diffs, BodyPartRecord part)
        {
            var replacingPart = diffs.Where(x => x is Hediff_AddedPart).FirstOrDefault();

            if (replacingPart != null)
            {
                return(replacingPart);
            }

            foreach (var diff in diffs)
            {
                if (diff.GetType().ToString() == "Pawnmorph.Hediff_AddedMutation")
                {
                    Def def = diff.def;

                    //var traverse = Traverse.Create(diff);
                    var property_IsCoreMutation = Traverse.Create(diff).Property("IsCoreMutation");
                    if (property_IsCoreMutation.PropertyExists())
                    {
                        if (property_IsCoreMutation.GetValue <bool>())
                        {
                            return(diff);
                        }
                    }
                    else
                    {
                        List <BodyPartDef> parts = Traverse.Create(def)?.Field <List <BodyPartDef> >("parts")?.Value;
                        //TODO: Remove this when Pawnmorpher updates
                        if (parts != null && parts.Count == 1 && parts[0] == part.def)                         //making an assumption here...
                        {
                            return(diff);
                        }
                    }
                }
            }

            return(null);
        }
Example #2
0
        public static bool Start(UILobbyMainWndCtrl __instance)
        {
            PeSteamFriendMgr.Instance.Init(__instance.mTopLeftAuthor.transform, __instance.mUICenter.transform, __instance.mUICamera);

            if (GameClientLobby.Self == null)
            {
                return(false);
            }

            Traverse.Create(__instance).Field("mRoleInfo").SetValue(GameClientLobby.role);

            __instance.GetType().GetMethod("SetRoleInfo", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).Invoke(__instance, new object[] { });

            var mRecentRoom_M = new RecentRoomDataManager(Traverse.Create(__instance).Field("mRoleInfo").Field("name").GetValue <string>());

            Traverse.Create(__instance).Field("mRecentRoom_M").SetValue(mRecentRoom_M);
            mRecentRoom_M.LoadFromFile();

            __instance.StartCoroutine((IEnumerator)__instance.GetType().GetMethod("UpdatePlayerInfo", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).Invoke(__instance, new object[] { }));
            __instance.StartCoroutine((IEnumerator)__instance.GetType().GetMethod("UpdateRoomInfo", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).Invoke(__instance, new object[] { }));

            SteamServerHandler.currentLanRequest =
                SteamMatchmakingServers.RequestLANServerList(new AppId_t(237870u),
                                                             new ISteamMatchmakingServerListResponse(SteamServerHandler.ServerResponded, SteamServerHandler.ServerFailedToRespond, SteamServerHandler.RefreshComplete));
            SteamServerHandler.currentInternetRequest =
                SteamMatchmakingServers.RequestInternetServerList(new AppId_t(237870u), new MatchMakingKeyValuePair_t[] { new MatchMakingKeyValuePair_t()
                                                                                                                          {
                                                                                                                              m_szKey = "gametagsand", m_szValue = "public"
                                                                                                                          } }, 1,
                                                                  new ISteamMatchmakingServerListResponse(SteamServerHandler.ServerResponded, SteamServerHandler.ServerFailedToRespond, SteamServerHandler.RefreshComplete));
            SteamServerHandler.lastUpdate = true;


            __instance.GetType().GetMethod("InitRoomListSort", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).Invoke(__instance, new object[] { });


            return(false);
        }
Example #3
0
        internal FilteredDestroyTool()
        {
            Color color;

            modes = new List <DestroyFilter>(12)
            {
                new DestroyFilter("Elements", SandboxToolsStrings.DESTROY_ELEMENTS,
                                  DestroyElement),
                new DestroyFilter("Items", SandboxToolsStrings.DESTROY_ITEMS, DestroyItems),
                new DestroyFilter("Creatures", SandboxToolsStrings.DESTROY_CREATURES,
                                  DestroyCreatures),
                new DestroyFilter("Plants", SandboxToolsStrings.DESTROY_PLANTS,
                                  DestroyPlants),
                new DestroyFilter("Buildings", SandboxToolsStrings.DESTROY_BUILDINGS),
                new DestroyFilter("BackWall", SandboxToolsStrings.DESTROY_DRYWALL),
                new DestroyFilter("LiquidPipes", SandboxToolsStrings.DESTROY_LPIPES),
                new DestroyFilter("GasPipes", SandboxToolsStrings.DESTROY_GPIPES),
                new DestroyFilter("Wires", SandboxToolsStrings.DESTROY_POWER),
                new DestroyFilter("Logic", SandboxToolsStrings.DESTROY_AUTO),
                new DestroyFilter("SolidConduits", SandboxToolsStrings.DESTROY_SHIPPING)
            };
            // "All" checkbox to destroy everything
            if (!SandboxToolsPatches.AdvancedFilterEnabled)
            {
                modes.Insert(0, new DestroyFilter("All", SandboxToolsStrings.DESTROY_ALL,
                                                  DestroyAll));
            }
            pendingCells = new HashSet <int>();
            try {
                // Take from stock tool if possible
                color = Traverse.Create(SandboxDestroyerTool.instance).GetField <Color>(
                    "recentlyAffectedCellColor");
            } catch (Exception) {
                // Use default
                color = new Color(1f, 1f, 1f, 0.1f);
            }
            pendingHighlightColor = color;
        }
Example #4
0
        public static void Initialize(GameWindow window)
        {
            if (initialized)
            {
                throw new InvalidOperationException("KeyboardInput.Initialize can only be called once!");
            }

            hookProcDelegate = new WndProc(HookProc);
            //set Wnd long before Init IME
            SetWindowLong(window.Handle, GWL_WNDPROC, (int)Marshal.GetFunctionPointerForDelegate(hookProcDelegate));

            ImmReleaseContext(window.Handle, (IntPtr)Traverse.Create(typeof(KeyboardInput)).Field("hIMC").GetValue());

            if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)
            {
                //Init IME
                iMEControl = ImeSharp.ImeSharp.GetDefaultControl();
                //iMEControl = ImeSharp.ImeSharp.Get_IMM32Control();
                iMEControl.Initialize(window.Handle);
                iMEControl.GetCompExtEvent  += IMEControl_GetCompExtEvent;
                iMEControl.CompositionEvent += IMEControl_CompositionEvent;
            }
            else
            {
                ModEntry.notifyHelper.Notify(Resources.WARN_MTA, NotifyPlace.Monitor, NotifyMoment.GameLaunched, LogLevel.Warn);
                ModEntry.notifyHelper.Notify(Resources.WARN_UseSTALauncher, NotifyPlace.Monitor, NotifyMoment.GameLaunched, LogLevel.Warn);
                ModEntry.notifyHelper.Notify(Resources.WARN_MTA, NotifyPlace.GameHUD, NotifyMoment.SaveLoaded);
                ModEntry.notifyHelper.Notify(Resources.WARN_UseSTALauncher, NotifyPlace.GameHUD, NotifyMoment.SaveLoaded);
            }

            prevWndProc = (IntPtr)Traverse.Create(typeof(KeyboardInput)).Field("prevWndProc").GetValue();

            CharEntered += KeyboardInput__CharEntered;
            KeyDown     += KeyboardInput__KeyDown;

            ModEntry._helper.Events.Display.RenderedActiveMenu += Display_RenderedActiveMenu;
            initialized = true;
        }
        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);
        }
Example #6
0
 public static bool Prefix(ref CampaignSave __result, string campaignID)
 {
     if (!(VTOLAPI.currentScene == VTOLScenes.VehicleConfiguration) || AEAT.trueSave == null)
     {
         //Debug.Log("Not spoofing this save.");
         return(true);
     }
     Debug.Log(AEAT.trueSave.campaignID + " will be used as a campaign save.");
     __result = AEAT.trueSave;
     if (!AEAT.buttonMade)
     {
         Debug.Log(AEAT.path + " is AEAT.path");
         VTOLAPI.GetPlayersVehicleGameObject().GetComponentInChildren <WeaponManager>().resourcePath = "hpequips/" + AEAT.path;
         LoadoutConfigurator config = Resources.FindObjectsOfTypeAll <LoadoutConfigurator>()[0];
         config.wm.resourcePath = VTOLAPI.GetPlayersVehicleGameObject().GetComponentInChildren <WeaponManager>().resourcePath;
         PilotSaveManager.currentVehicle.equipsResourcePath = "hpequips/" + AEAT.path;
         List <string> marsh      = new List <string>();
         List <GameObject> ketkev = new List <GameObject>();
         foreach (var gameobject in Resources.LoadAll <GameObject>("hpequips/" + AEAT.path))
         {
             if (!AllowedEquips.allowedEquips.Contains(gameobject.name))
             {
                 //Debug.Log("Unauthorized gameobject " + gameobject.name);
                 continue;
             }
             marsh.Add(gameobject.name);
             ketkev.Add(gameobject);
         }
         Traverse.Create(config).Field("unlockedWeaponPrefabs").SetValue(new Dictionary <string, EqInfo>());
         Traverse.Create(config).Field("allWeaponPrefabs").SetValue(new Dictionary <string, EqInfo>());
         config.lockedHardpoints = new List <int>();
         VTResources.GetScenario(PilotSaveManager.currentScenario.scenarioID, PilotSaveManager.currentCampaign).allowedEquips = marsh;
         __result.availableWeapons = marsh;
         Debug.Log("Set allowedEquips.");
         PilotSaveManager.currentVehicle.allEquipPrefabs = ketkev; // Don't need to reinit the config because this is prefixing the init statement
     }
     return(false);
 }
Example #7
0
        // TODO: Dangerous PREFIX false here!
        public static bool Prefix(CombatHUDTargetingComputer __instance, CombatHUD ___HUD)
        {
            //Mod.Log.Trace?.Write("CHUDTC:U:pre - entered.");

            CombatGameState Combat = ___HUD?.Combat;

            UIModule_Update(__instance);
            if (__instance.ActorInfo != null)
            {
                __instance.ActorInfo.DisplayedCombatant = __instance.ActivelyShownCombatant;
            }

            if (__instance.ActivelyShownCombatant == null ||
                (__instance.ActivelyShownCombatant.team != Combat.LocalPlayerTeam &&
                 !Combat.HostilityMatrix.IsFriendly(__instance.ActivelyShownCombatant.team.GUID, Combat.LocalPlayerTeamGuid) &&
                 Combat.LocalPlayerTeam.VisibilityToTarget(__instance.ActivelyShownCombatant) < VisibilityLevel.Blip0Minimum)
                )
            {
                if (__instance.Visible)
                {
                    __instance.Visible = false;
                }
            }
            else
            {
                if (!__instance.Visible)
                {
                    __instance.Visible = true;
                }
                if (__instance.ActivelyShownCombatant != null)
                {
                    Traverse method = Traverse.Create(__instance).Method("UpdateStructureAndArmor", new Type[] { });
                    method.GetValue();
                }
            }

            return(false);
        }
        //It may be "FinelyTunedMachine" now, but it will always be "TuneUpForWhat in my heart.
        public static List <string> TuneUpForWhatFormatter(ColonyAchievementStatus cas)
        {
            List <string> outStrings = new List <string>();

            TuneUpGenerator __instance = (TuneUpGenerator)cas.Requirements.Find(s => s is TuneUpGenerator);

            var priv = Traverse.Create(__instance);
            //Sic. This *is* the name of the field. If they fix the typo, it'll need to be fixed here as well.
            float numChores = (float)priv.Field("numChoreseToComplete").GetValue();

            float num = 0.0f;

            ReportManager.ReportEntry entry = ReportManager.Instance.TodaysReport.GetEntry(ReportManager.ReportType.ChoreStatus);
            for (int index = 0; index < entry.contextEntries.Count; ++index)
            {
                ReportManager.ReportEntry contextEntry = entry.contextEntries[index];
                if (contextEntry.context == Db.Get().ChoreTypes.PowerTinker.Name)
                {
                    num += contextEntry.Negative;
                }
            }
            for (int index1 = 0; index1 < ReportManager.Instance.reports.Count; ++index1)
            {
                for (int index2 = 0; index2 < ReportManager.Instance.reports[index1].GetEntry(ReportManager.ReportType.ChoreStatus).contextEntries.Count; ++index2)
                {
                    ReportManager.ReportEntry contextEntry = ReportManager.Instance.reports[index1].GetEntry(ReportManager.ReportType.ChoreStatus).contextEntries[index2];
                    if (contextEntry.context == Db.Get().ChoreTypes.PowerTinker.Name)
                    {
                        num += contextEntry.Negative;
                    }
                }
            }

            string output = string.Format("Tune Ups: {0} / {1}", (double)Math.Abs(num), (double)numChores);

            outStrings.Add(output);
            return(outStrings);
        }
Example #9
0
        /// <summary>
        /// Reimplements the operations pertaining to the drawing of the Farmhouse, Greenhouse, Mailbox, and
        /// the note on the grandpa shrine to accomidate for repositioning based on the information provided by
        /// the custom farm's content pack.
        /// </summary>
        /// <param name="__instance">The instance of the Farm</param>
        /// <param name="b">From original method. The spritebatch used to draw.</param>
        public static void Postfix(Farm __instance, SpriteBatch b)
        {
            int x;

            if (__instance.Name != "Farm")
            {
                return;
            }
            NetRectangle house      = (NetRectangle)Traverse.Create(__instance).Field("houseSource").GetValue();
            NetRectangle greenhouse = (NetRectangle)Traverse.Create(__instance).Field("greenhouseSource").GetValue();

            //Farmhouse & Farmhouse Shadows
            b.Draw(Game1.mouseCursors, Game1.GlobalToLocal(Game1.viewport, customManager.FarmHouseCoords(64f, 568f)), new Rectangle?(Building.leftShadow), Color.White, 0f, Vector2.Zero, 4f, SpriteEffects.None, 1E-05f);
            for (x = 2; x < 9; x++)
            {
                b.Draw(Game1.mouseCursors, Game1.GlobalToLocal(Game1.viewport, customManager.FarmHouseCoords(x * 64f, 568f)), new Rectangle?(Building.middleShadow), Color.White, 0f, Vector2.Zero, 4f, SpriteEffects.None, 1E-05f);
            }
            b.Draw(Game1.mouseCursors, Game1.GlobalToLocal(Game1.viewport, customManager.FarmHouseCoords(x * 64, 568f)), new Rectangle?(Building.rightShadow), Color.White, 0f, Vector2.Zero, 4f, SpriteEffects.None, 1E-05f);
            b.Draw(Farm.houseTextures, Game1.GlobalToLocal(Game1.viewport, customManager.FarmHouseCoords()), new Rectangle?(house), Color.White, 0.0f, Vector2.Zero, 4f, SpriteEffects.None, customManager.FarmHouseLayerDepth());

            //Green House
            b.Draw(Farm.houseTextures, Game1.GlobalToLocal(Game1.viewport, customManager.GreenHouseCoords()), new Rectangle?(greenhouse), Color.White, 0.0f, Vector2.Zero, 4f, SpriteEffects.None, customManager.GreenHouseLayerDepth());

            //Mailbox Notification ("!" symbol when new mail arrives).
            if (Game1.mailbox.Count > 0)
            {
                float yOffset = 4f * (float)Math.Round(Math.Sin(DateTime.Now.TimeOfDay.TotalMilliseconds / 250.0), 2);
                b.Draw(Game1.mouseCursors, Game1.GlobalToLocal(Game1.viewport, customManager.MailboxNotification(0f, (2.25f * -64f) + yOffset, false)), new Rectangle?(new Rectangle(141, 465, 20, 24)), Color.White * 0.75f, 0f, Vector2.Zero, 4f, SpriteEffects.None, customManager.MailBoxNotifyLayerDepth(false));
                b.Draw(Game1.mouseCursors, Game1.GlobalToLocal(Game1.viewport, customManager.MailboxNotification(0.5626f * 64f, (1.5f * -64f) + yOffset, true)), new Rectangle?(new Rectangle(189, 423, 15, 13)), Color.White, 0f, new Vector2(7f, 6f), 4f, SpriteEffects.None, customManager.MailBoxNotifyLayerDepth(true));
            }

            //Shrine note
            if (!__instance.hasSeenGrandpaNote)
            {
                b.Draw(Game1.mouseCursors, Game1.GlobalToLocal(Game1.viewport, customManager.GrandpaShrineCoords()), new Rectangle?(new Rectangle(575, 1972, 11, 8)), Color.White, 0f, Vector2.Zero, 4f, SpriteEffects.None, 0.0448009968f);
            }
            return;
        }
        public static bool Prefix(AVPVideoPlayer __instance, string video, Strings.Culture culture, Action <string> onComplete = null)
        {
            var videoEntry = ModTek.CustomResources["Video"].Values.LastOrDefault(entry =>
                                                                                  entry.Id == video || entry.Id == Path.GetFileNameWithoutExtension(video));

            if (videoEntry == null)
            {
                return(true);
            }

            // THIS CODE IS REWRITTEN FROM DECOMPILED HBS CODE
            // AND IS NOT SUBJECT TO MODTEK LICENSE

            var instance       = Traverse.Create(__instance);
            var AVPMediaPlayer = instance.Field("AVPMediaPlayer").GetValue <MediaPlayer>();

            if (AVPMediaPlayer.Control == null)
            {
                instance.Method("ConfigureMediaPlayer").GetValue();
            }
            AVPMediaPlayer.OpenVideoFromFile(MediaPlayer.FileLocation.AbsolutePathOrURL, videoEntry.FilePath, false);
            if (ActiveOrDefaultSettings.CloudSettings.subtitles)
            {
                instance.Method("LoadSubtitle", video, Strings.GetCultureNameEnglish(culture));
            }
            else
            {
                AVPMediaPlayer.DisableSubtitles();
            }
            BTPostProcess.SetUIPostprocessing(false);

            instance.Field("OnPlayerComplete").SetValue(onComplete);
            instance.Method("Initialize").GetValue();

            // END REWRITTEN DECOMPILED HBS CODE

            return(false);
        }
Example #11
0
        private static NewExpression BuildNewExpression(ParameterExpression rootParameter, IReadOnlyDictionary <PropertyPath, ODataSelectColumnExpression> mapping)
        {
            // all paths longer than length 1 get grouped together and mapped to their own expression (this lets us support an arbitrary number of selected columns)
            var nestedProperties = mapping.Where(kvp => kvp.Key.Count > 1).ToArray();
            var nestedExpression = nestedProperties.Length > 0
                ? BuildNewExpression(rootParameter, nestedProperties.ToDictionary(kvp => kvp.Key.Skip(1).ToArray().As <PropertyPath>(), kvp => kvp.Value, PathComparer))
                : Expression.Constant(false).As <Expression>();

            // gather all argument expressions which will be used to initialize the type
            var arguments = ProjectionTypeProperties.Take(ProjectionTypeProperties.Count - 1)
                            .Select(prop =>
            {
                ODataSelectColumnExpression selectColumn;
                if (!mapping.TryGetValue(new[] { prop }, out selectColumn))
                {
                    return(Expression.Constant(false));
                }

                var selectColumnPropertyPath = Traverse.Along(selectColumn.Expression, c => c.Expression)
                                               .Select(m => m.Member)
                                               .Reverse();
                var expression = selectColumnPropertyPath.Aggregate(rootParameter.As <Expression>(), (acc, pi) => Expression.MakeMemberAccess(acc, pi));
                return(expression);
            })
                            .ToList();

            arguments.Add(nestedExpression);

            // build the new expression
            var parameterizedType = ProjectionType.MakeGenericType(arguments.Select(a => a.Type).ToArray());
            var newExpression     = Expression.New(
                parameterizedType.GetConstructors().Single(),
                arguments,
                members: parameterizedType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                );

            return(newExpression);
        }
        static void Postfix(Pawn_HealthTracker __instance, ref bool __result)
        {
            Pawn pawn = Traverse.Create(__instance).Field("pawn").GetValue <Pawn>();

            if (!pawn.RaceProps.IsMechanoid)
            {
                return;
            }
            if (pawn.Faction != Faction.OfPlayer && !pawn.Faction.HostileTo(Faction.OfPlayer))//make sure allied mechs always die to prevent issues with relation penalties when the player hacks their mechs.
            {
                return;
            }

            if (__result == true)
            {
                if (__instance.hediffSet.HasHediff(WTH_DefOf.WTH_HeavilyDamaged))
                {
                    __result = false;
                    return;
                }
                if (Rand.Chance(Base.downedOnDeathThresholdChance.Value / 100f))//Chance mech goes down instead of dying when lethal threshold is achieved.
                {
                    __instance.AddHediff(WTH_DefOf.WTH_HeavilyDamaged);
                    if (pawn.mindState == null)
                    {
                        pawn.mindState = new Pawn_MindState(pawn);
                    }
                    __result = false;
                }
            }
            else
            {
                if (__instance.hediffSet.HasHediff(WTH_DefOf.WTH_HeavilyDamaged))
                {
                    __instance.RemoveHediff(__instance.hediffSet.GetFirstHediffOfDef(WTH_DefOf.WTH_HeavilyDamaged));
                }
            }
        }
        static bool Prefix(ShieldBelt __instance)
        {
            bool             ShouldDisplay = Traverse.Create(__instance).Property("ShouldDisplay").GetValue <bool>();
            ExtendedPawnData pawnData      = Base.Instance.GetExtendedDataStorage().GetExtendedDataFor(__instance.Wearer);
            Pawn             mount         = pawnData.mount;

            if (mount == null)
            {
                return(true);
            }

            if (__instance.ShieldState == ShieldState.Active && ShouldDisplay)
            {
                float    energy = Traverse.Create(__instance).Field("energy").GetValue <float>();
                int      lastAbsorbDamageTick = Traverse.Create(__instance).Field("lastAbsorbDamageTick").GetValue <int>();
                Vector3  impactAngleVect      = Traverse.Create(__instance).Field("impactAngleVect").GetValue <Vector3>();
                Material BubbleMat            = MaterialPool.MatFrom("Other/ShieldBubble", ShaderDatabase.Transparent);
                ;

                float   num    = Mathf.Lerp(1.2f, 1.55f, energy);
                Vector3 vector = __instance.Wearer.Drawer.DrawPos;
                vector.z += pawnData.drawOffset;
                vector.y  = Altitudes.AltitudeFor(AltitudeLayer.MoteOverhead);
                int num2 = Find.TickManager.TicksGame - lastAbsorbDamageTick;
                if (num2 < 8)
                {
                    float num3 = (float)(8 - num2) / 8f * 0.05f;
                    vector += impactAngleVect * num3;
                    num    -= num3;
                }
                float     angle  = (float)Rand.Range(0, 360);
                Vector3   s      = new Vector3(num, 1f, num);
                Matrix4x4 matrix = default(Matrix4x4);
                matrix.SetTRS(vector, Quaternion.AngleAxis(angle, Vector3.up), s);
                Graphics.DrawMesh(MeshPool.plane10, matrix, BubbleMat, 0);
            }
            return(false);
        }
Example #14
0
        public static void DoHotReload(GameInstance game)
        {
            Main.HBSLog?.Log("HotReload!");

            Main.ReloadResources();

            // reload behavior variables by forcing a new scope manager
            // TODO: THIS CAUSES A GAME FREEZE IF HOT RELOAD DURING AI PAUSE
            // this is because of scope manager taking a little bit to get info
            // from dataManager, temp solution is to skip if paused
            if (!AIPause.IsPaused)
            {
                Traverse.Create(game).Property("BehaviorVariableScopeManager")
                .SetValue(new BehaviorVariableScopeManager(game));
            }

            var aiActors = game.Combat.AllActors.Where(unit => unit.team is AITeam);

            foreach (var unit in aiActors)
            {
                Main.ResetUnitAI(unit);
                Main.TryOverrideUnitAI(unit);
            }

            var aiTeams = game.Combat.Teams.Where(team => team is AITeam).Cast <AITeam>();

            foreach (var team in aiTeams)
            {
                Main.ResetTeamAI(team);
                Main.TryOverrideTeamAI(team);
            }

            if (AIPause.IsPaused)
            {
                AIPause.Reset();
                TurnOrderOverride.TryRecalculateCurrentUnit(AIPause.CurrentAITeam);
            }
        }
Example #15
0
        // reimplementation of MBObjectManager.LoadXML(string id, Type typeOfGameMenusCallbacks = null, bool skipXmlFilterForEditor = false)
        // reimplemented to avoid unwanted callbacks and constructors,
        // just want a small slice of info, not for the game to reload the information.
        XmlDocument LoadXmls(IEnumerable <MbObjectXmlInformation> xmlFiles)
        {
            var xmlDocuments = new List <(string xmlPath, string xsdPath, string xsltPath)>();

            foreach (var xmlFile in xmlFiles)
            {
                var xmlPath = ModuleInfo.GetXmlPath(xmlFile.ModuleName, xmlFile.Name);
                if (File.Exists(xmlPath))
                {
                    var xsdPath  = ModuleInfo.GetXsdPath(xmlFile.ModuleName, xmlFile.Id);
                    var xsltPath = ModuleInfo.GetXsltPath(xmlFile.ModuleName, xmlFile.Id);
                    xmlDocuments.Add((xmlPath, xsdPath, xsltPath));
                }
            }

            if (xmlDocuments.Count == 0)
            {
                return(null);
            }

            var id = xmlFiles.First().Id;

            XmlDocument loadDocument(string xmlPath, string xsdPath) =>
            Traverse.Create(MBObjectManager.Instance).Method("CreateDocumentFromXmlFile", xmlPath, xsdPath, false).GetValue() as XmlDocument;

            var document = loadDocument(xmlDocuments[0].xmlPath, xmlDocuments[0].xsdPath);

            foreach (var(xmlPath, xsdPath, xsltPath) in xmlDocuments.Skip(1))
            {
                if (File.Exists(xsltPath))
                {
                    document = Traverse.Create(MBObjectManager.Instance).Method("ApplyXslt", xsltPath, document).GetValue() as XmlDocument;
                }
                var newDocument = loadDocument(xmlPath, xsdPath);
                document = Traverse.Create(MBObjectManager.Instance).Method("MergeTwoXmls", document, newDocument, id).GetValue() as XmlDocument;
            }
            return(document);
        }
Example #16
0
        /// <summary>
        /// Adjusts trait strings.
        /// </summary>
        private static void InitStrings()
        {
            // Maximum HP description is in a different category than the embark screen looks
            Strings.Add("STRINGS.DUPLICANTS.ATTRIBUTES.HITPOINTSMAX.NAME", STRINGS.DUPLICANTS.
                        STATS.HITPOINTS.NAME);
            Strings.Add("STRINGS.DUPLICANTS.ATTRIBUTES.HITPOINTSMAX.TOOLTIP", STRINGS.
                        DUPLICANTS.STATS.HITPOINTS.TOOLTIP);
            // Short descriptions
            AddShortDesc("CantCook", TraitStrings.CANTCOOK_SHORTDESC, TraitStrings.
                         NOFOOD_SHORTTOOLTIP);
            AddShortDesc("Narcolepsy", TraitStrings.NARCOLEPSY_SHORTDESC, TraitStrings.
                         NARCOLEPSY_TOOLTIP);
            AddShortDesc("ScaredyCat", TraitStrings.SCAREDYCAT_SHORTDESC, TraitStrings.
                         NOFOOD_SHORTTOOLTIP);
            // Trait description updates, only public fields desired anyways
            var traitsClass = typeof(STRINGS.DUPLICANTS.TRAITS);

            foreach (var field in typeof(TraitStrings.TraitDescriptions).GetFields())
            {
                if (field.FieldType == typeof(LocString))
                {
                    string name = field.Name;
                    // This is done before TRAITS tuning class is initialized
                    var traitClass = traitsClass.GetNestedType(name);
                    try {
                        if (traitClass != null && (field.GetValue(null) is LocString initValue))
                        {
                            Traverse.Create(traitClass).SetField("DESC", initValue);
                        }
                    } catch (FieldAccessException e) {
                        // Should be unreachable, only public fields
                        PUtil.LogExcWarn(e);
                    } catch (TargetException e) {
                        PUtil.LogExcWarn(e);
                    }
                }
            }
        }
        public static bool DetermineLowVelocity(
            float speedWanted,
            float turningRatio,
            ref Vector3 vel,
            ref bool fly,
            ref PlayerNavigation __instance
            )
        {
            var getPlayer  = Traverse.Create(__instance).Method("get_player").GetValue <Player>();
            var realRadius = getPlayer.planetData.realRadius;

            Debug.Log("realRadius" + realRadius);
            var vector3_1 = getPlayer.position.normalized * realRadius;

            Debug.Log("vector3_1" + vector3_1);
            Vector3 vector3_2 = __instance.naviTarget.normalized * realRadius;

            Debug.Log("vector3_2" + vector3_2);
            var normalized1 = vector3_1.normalized;

            Debug.Log("normalized1" + normalized1);
            var rhs = vector3_2 - vector3_1;

            Debug.Log("rhs" + rhs);
            var magnitude = rhs.magnitude;

            Debug.Log("magnitude" + magnitude);
            var normalized2 = Vector3.Cross(Vector3.Cross(normalized1, rhs).normalized, normalized1).normalized;

            Debug.Log("normalized2" + normalized2);
            vel = Vector3.Slerp(vel, normalized2 * speedWanted, turningRatio);
            if (!__instance.useFlyFinally || magnitude <= 20.0)
            {
                return(false);
            }
            fly = true;
            return(false);
        }
        private void RegisterIndyArmyTimer()
        {
            if (Hero.MainHero.PartyBelongedTo == null)
            {
                return;
            }
            Army army = Hero.MainHero.PartyBelongedTo.Army;

            if (army?.LeaderParty == null || army.LeaderParty != Hero.MainHero.PartyBelongedTo || army.Kingdom != null)
            {
                return;
            }
            Traverse traverse = Traverse.Create((object)army).Method("OnAfterLoad");

            if (traverse.MethodExists())
            {
                traverse.GetValue();
            }
            else
            {
                int num = (int)MessageBox.Show("Party AI Overhaul and Commands: Cannot find method Army.OnAfterLoad, needs update.");
            }
        }
Example #19
0
            public static bool Prefix(Pawn member, ref bool free)
            {
                if (member.Faction == Faction.OfPlayer)
                {
                    return(true);
                }
                if (PawnUtility.IsTravelingInTransportPodWorldObject(member))
                {
                    return(false);                                                          // Fired in pod? Don't trigger
                }
                var compGuest = member.CompGuest();

                if (compGuest == null || !compGuest.rescued || member.guest == null || PawnUtility.IsTravelingInTransportPodWorldObject(member))
                {
                    return(true);
                }

                free = true;
                Traverse.Create(member.guest).Field("hostFactionInt").SetValue(Faction.OfPlayer); // Settings this makes the reward work
                compGuest.rescued = false;                                                        // Turn back off

                return(true);
            }
 public static bool Prefix(TransportPodsArrivalAction_LandInSpecificCell __instance, List <ActiveDropPodInfo> pods, int tile)
 {
     //    Log.Message(string.Format("pods: {0}", pods.Count));
     foreach (ActiveDropPodInfo info in pods)
     {
         if (info.innerContainer.Contains(USCMDefOf.RRY_USCM_DropshipUD4L))
         {
             //    Log.Message(string.Format("pods: {0}", info.innerContainer.ContentsString));
             Thing    lookTarget = TransportPodsArrivalActionUtility.GetLookTarget(pods);
             Traverse tv         = Traverse.Create(__instance);
             IntVec3  c          = tv.Field("cell").GetValue <IntVec3>();
             Map      map        = tv.Field("mapParent").GetValue <MapParent>().Map;
             TransportPodsArrivalActionUtility.RemovePawnsFromWorldPawns(pods);
             for (int i = 0; i < pods.Count; i++)
             {
                 DropPodUtility.MakeDropPodAt(c, map, pods[i]);
             }
             Messages.Message("USCM_Dropship_MessageArrived".Translate(), lookTarget, MessageTypeDefOf.TaskCompletion, true);
             return(false);
         }
     }
     return(true);
 }
Example #21
0
        public void Render(PawnRenderer renderer, Vector3 drawLoc, RotDrawMode bodyDrawType)
        {
            if (!renderer.graphics.AllResolved)
            {
                renderer.graphics.ResolveAllGraphics();
            }

            drawLoc.x = (int)(drawLoc.x) + 0.5f;

            var progress = rubbleCounter / (float)Constants.RUBBLE_AMOUNT;

            if (progress >= Constants.EMERGE_DELAY)
            {
                var bodyRot    = GenMath.LerpDouble(Constants.EMERGE_DELAY, 1, 90, 0, progress);
                var bodyOffset = GenMath.LerpDouble(Constants.EMERGE_DELAY, 1, -0.45f, 0, progress);

                Traverse.Create(renderer)
                .Method("RenderPawnInternal", RenderPawnInternalParameterTypes)
                .GetValue(drawLoc + new Vector3(0, 0, bodyOffset), Quaternion.Euler(bodyRot, 0, 0), true, Rot4.North, Rot4.North, bodyDrawType, false, false);
            }

            RenderRubble(drawLoc);
        }
Example #22
0
        internal static void Prefix(Panel_Map __instance, ref int opts)
        {
            if (GameManager.IsStoryMode())
            {
                return;
            }

            string mapName     = Traverse.Create(__instance).Method("GetMapNameOfCurrentScene").GetValue <string>();
            bool   canBeMapped = SceneCanBeMapped(mapName);

            if (!canBeMapped)
            {
                return;
            }

            int currentIndex  = Traverse.Create(__instance).Method("GetIndexOfCurrentScene").GetValue <int>();
            int selectedIndex = Traverse.Create(__instance).Field("m_RegionSelectedIndex").GetValue <int>();

            if (currentIndex == selectedIndex)
            {
                opts |= 4;
            }
        }
        public static bool Prefix(Dialog_LoadTransporters __instance)
        {
            Traverse tv = Traverse.Create(__instance);
            List <CompTransporter> lp = tv.Field("transporters").GetValue <List <CompTransporter> >();

            foreach (CompTransporter lpc in lp)
            {
                if (lpc.parent.TryGetComp <CompUSCMDropship>() != null)
                {
                    Map         map  = tv.Field("map").GetValue <Map>();
                    List <Pawn> list = CaravanFormingUtility.AllSendablePawns(map, true, true, true, true);
                    for (int i = 0; i < list.Count; i++)
                    {
                        Type       typ   = __instance.GetType();
                        MethodInfo minfo = typ.GetMethod("AddToTransferables", BindingFlags.NonPublic | BindingFlags.Instance);
                        minfo.Invoke(__instance, new object[] { list[i] });
                        // __instance.AddToTransferables(list[i]);
                    }
                    return(false);
                }
            }
            return(true);
        }
Example #24
0
            public static void Prefix(ZNet __instance, ZRpc rpc)
            {
                ZNetPeer peer = Traverse.Create(__instance).Method("GetPeer", new object[] { rpc }).GetValue <ZNetPeer>();

                Dbgl("Server Handshake");

                if (peer == null)
                {
                    Dbgl("peer is null");
                    return;
                }

                var steamID = (peer.m_socket as ZSteamSocket).GetPeerID();

                Dbgl($"Peer connected, steam ID: {steamID}");

                /*
                 * peer.m_rpc.Invoke("SendServerRewardsJSON", new object[]
                 * {
                 *  "{ command:\"SendID\", data:\""+SteamUser.GetSteamID().GetAccountID().m_AccountID+"\" }"
                 * });
                 */
            }
Example #25
0
        protected override void OnPrefabInit()
        {
            base.OnPrefabInit();

            visualizer = Util.KInstantiate(Traverse.Create(DeconstructTool.Instance).Field("visualizer").GetValue <GameObject>());

            visualizer.SetActive(false);
            visualizer.transform.SetParent(transform);

            FieldInfo areaVisualizerField = AccessTools.Field(typeof(DragTool), "areaVisualizer");
            FieldInfo areaVisualizerSpriteRendererField = AccessTools.Field(typeof(DragTool), "areaVisualizerSpriteRenderer");

            GameObject areaVisualizer = Util.KInstantiate(Traverse.Create(DeconstructTool.Instance).Field("areaVisualizer").GetValue <GameObject>());

            areaVisualizer.SetActive(false);

            areaVisualizer.name = "AdvancedFilterMenuDecontructToolAreaVisualizer";
            areaVisualizerSpriteRendererField.SetValue(this, areaVisualizer.GetComponent <SpriteRenderer>());
            areaVisualizer.transform.SetParent(transform);

            areaVisualizerField.SetValue(this, areaVisualizer);
            gameObject.AddComponent <CancelToolHoverTextCard>();
        }
            public static void Postfix(ResourceCategoryScreen __instance)
            {
                // Create Favorites tag
                Tag favoritesTag = TagManager.Create("Favorites", "Favorites");

                // Create Favorites Header
                var createTagSetHeaders = Traverse.Create(__instance).Method("CreateTagSetHeaders", new[] { typeof(IEnumerable <Tag>), typeof(GameUtil.MeasureUnit) });

                createTagSetHeaders.GetValue(new TagSet {
                    favoritesTag
                }, GameUtil.MeasureUnit.mass);

                // reset DisplayedCategories, so Favorites is displayed
                var displayedCategoryKeys = Traverse.Create(__instance).Field("DisplayedCategoryKeys");

                displayedCategoryKeys.SetValue(__instance.DisplayedCategories.Keys.ToArray <Tag>());

                // keep our instance of favoritesCategoryHeader saved
                __instance.DisplayedCategories.TryGetValue(favoritesTag, out favoritesCategoryHeader);

                // move Favorites to the top of the list
                favoritesCategoryHeader.transform.SetAsFirstSibling();
            }
Example #27
0
        public void TestMimetic_Visibility_NoDecay_ProbeCarrier()
        {
            Mech attacker = TestHelper.BuildTestMech();
            Mech target   = TestHelper.BuildTestMech();

            target.CurrentPosition = new Vector3(0f, 0, 0);
            Traverse previousPositionT = Traverse.Create(target).Field("previousPosition");

            previousPositionT.SetValue(new Vector3(0f, 0f, 0f));

            attacker.StatCollection.AddStatistic <float>("SpotterDistanceMultiplier", 1f);
            attacker.StatCollection.AddStatistic <float>("SpotterDistanceAbsolute", 0f);
            attacker.StatCollection.Set(ModStats.ProbeCarrier, 3);

            target.StatCollection.AddStatistic <float>("SpottingVisibilityMultiplier", 1f);
            target.StatCollection.AddStatistic <float>("SpottingVisibilityAbsolute", 0f);
            target.StatCollection.Set(ModStats.MimeticEffect, "4_0.10_1_2");

            EWState attackerState = new EWState(attacker);
            EWState targetState   = new EWState(target);

            Assert.AreEqual(0.9f, VisualLockHelper.GetTargetVisibility(target, attackerState), 0.001);
        }
Example #28
0
        public void TestMimetic_AttackMod_NoDecay_Pinged()
        {
            Mech attacker = TestHelper.BuildTestMech();
            Mech target   = TestHelper.BuildTestMech();

            target.CurrentPosition = new Vector3(0f, 0, 0);
            Traverse previousPositionT = Traverse.Create(target).Field("previousPosition");

            previousPositionT.SetValue(new Vector3(0f, 0f, 0f));

            attacker.StatCollection.AddStatistic <float>("SpotterDistanceMultiplier", 1f);
            attacker.StatCollection.AddStatistic <float>("SpotterDistanceAbsolute", 0f);

            target.StatCollection.AddStatistic <float>("SpottingVisibilityMultiplier", 1f);
            target.StatCollection.AddStatistic <float>("SpottingVisibilityAbsolute", 0f);
            target.StatCollection.Set(ModStats.MimeticEffect, "4_0.10_1_2");
            target.StatCollection.Set(ModStats.PingedByProbe, 2);

            EWState attackerState = new EWState(attacker);
            EWState targetState   = new EWState(target);

            Assert.AreEqual(2, targetState.MimeticAttackMod(attackerState));
        }
 public static bool SkipCinematic_Prefix(PlayerCinematicController __instance, Player player)
 {
     Traverse.Create(__instance).Field("player").SetValue(player);
     if (player)
     {
         Transform component  = player.GetComponent <Transform>();
         Transform component2 = MainCameraControl.main.GetComponent <Transform>();
         if (Traverse.Create(__instance).Method("UseEndTransform", new object[0]).GetValue <bool>())
         {
             player.playerController.SetEnabled(false);
             component.position  = __instance.endTransform.position;
             component.rotation  = __instance.endTransform.rotation;
             component2.rotation = component.rotation;
         }
         player.playerController.SetEnabled(true);
         player.cinematicModeActive = false;
     }
     if (__instance.informGameObject != null)
     {
         __instance.informGameObject.SendMessage("OnPlayerCinematicModeEnd", __instance, SendMessageOptions.DontRequireReceiver);
     }
     return(false);
 }
Example #30
0
        public void Traverse_Property_GetValue()
        {
            var instance = new TraverseProperties_AccessModifiers(TraverseProperties.testStrings);
            var trv      = Traverse.Create(instance);

            for (var i = 0; i < TraverseProperties.testStrings.Length; i++)
            {
                var name = TraverseProperties.propertyNames[i];
                var ptrv = trv.Property(name);
                Assert.IsNotNull(ptrv);
                if (name == "BaseProperty2")
                {
                    // BaseProperty2 is only defined in base class
                    Assert.IsNull(ptrv.GetValue());
                    Assert.IsNull(ptrv.GetValue <string>());
                }
                else
                {
                    Assert.AreEqual(TraverseProperties.testStrings[i], ptrv.GetValue());
                    Assert.AreEqual(TraverseProperties.testStrings[i], ptrv.GetValue <string>());
                }
            }
        }
Example #31
0
 private void TraverseTree(IVariableInformation root, Traverse goLeft, Traverse goRight, Traverse getValue, List<IVariableInformation> content, uint size)
 {
     uint i = 0;
     var nodes = new Stack<Node>();
     nodes.Push(new Node(root));
     while (nodes.Count > 0 && i < size)
     {
         switch (nodes.Peek().State)
         {
             case Node.ScanState.left:
                 nodes.Peek().State = Node.ScanState.value;
                 var leftVal = goLeft(nodes.Peek().Content);
                 if (leftVal != null)
                 {
                     ulong left = MICore.Debugger.ParseAddr(leftVal.Value);
                     if (left != 0)
                     {
                         nodes.Push(new Node(leftVal));
                     }
                 }
                 break;
             case Node.ScanState.value:
                 nodes.Peek().State = Node.ScanState.right;
                 IVariableInformation value = getValue(nodes.Peek().Content);
                 if (value != null)
                 {
                     content.Add(new SimpleWrapper("[" + i + "]", _process.Engine, value));
                     i++;
                 }
                 break;
             case Node.ScanState.right:
                 Node n = nodes.Pop();
                 var rightVal = goRight(n.Content);
                 if (rightVal != null)
                 {
                     ulong right = MICore.Debugger.ParseAddr(rightVal.Value);
                     if (right != 0)
                     {
                         nodes.Push(new Node(rightVal));
                     }
                 }
                 break;
         }
     }
 }
Example #32
0
 private void TraverseList(IVariableInformation root, Traverse goNext, Traverse getValue, List<IVariableInformation> content, uint size, bool noValueInRoot)
 {
     uint i = 0;
     IVariableInformation node = root;
     ulong rootAddr = MICore.Debugger.ParseAddr(node.Value);
     ulong nextAddr = rootAddr;
     while (node != null && nextAddr != 0 && i < size)
     {
         if (!noValueInRoot || nextAddr != rootAddr)
         {
             IVariableInformation value = getValue(node);
             if (value != null)
             {
                 content.Add(new SimpleWrapper("[" + i + "]", _process.Engine, value));
                 i++;
             }
         }
         if (i < size)
         {
             node = goNext(node);
         }
         nextAddr = MICore.Debugger.ParseAddr(node.Value);
         if (nextAddr == rootAddr)
         {
             // circular link, exit the loop
             break;
         }
     }
 }