Exemplo n.º 1
0
        public override void BeforePatch()
        {
            IGConsole.RegisterCommand <CommandRate>(this);

            ModInput.RegisterBinding(this, "RateIncrement", KeyCode.KeypadPlus).ListenKeyDown(Increment);
            ModInput.RegisterBinding(this, "RateDecrement", KeyCode.KeypadMinus).ListenKeyDown(Decrement);
        }
Exemplo n.º 2
0
        public static IEnumerable <Mod> SearchForCircularReferences(IEnumerable <Mod> mods)
        {
            Dictionary <string, Mod>        modsByPackage = mods.ToDictionary(o => o.PackageName);
            List <KeyValuePair <Mod, Mod> > warned        = new List <KeyValuePair <Mod, Mod> >();

            foreach (var item in mods)
            {
                var match = item.RequiredModPackages.SingleOrDefault(o => modsByPackage.TryGetValue(o, out var m) && m.RequiredModPackages.Contains(item.PackageName));

                if (match != null)
                {
                    var second = modsByPackage[match];

                    if (!warned.Any(o =>
                                    (o.Key.PackageName == item.PackageName && o.Value.PackageName == second.PackageName) ||
                                    (o.Key.PackageName == second.PackageName && o.Value.PackageName == item.PackageName)))
                    {
                        warned.Add(new KeyValuePair <Mod, Mod>(item, second));

                        IGConsole.Error($"Circular reference found between <b>{item.Name}</b> and <b>{second.Name}</b>, neither were loaded.");
                    }
                }
                else
                {
                    yield return(item);
                }
            }
        }
Exemplo n.º 3
0
        private static GameObject MakePlayerModel()
        {
            if (PlayerModelPrefab == null)
            {
                //Load model on Unity's main thread
                MulTUNG.SynchronizationContext.Send(_ => BuildPlayerPrefab(), null);

                //Check if the prefab is still null
                if (PlayerModelPrefab == null)
                {
                    IGConsole.Error("Couldn't load player model!");
                    return(null);
                }
            }

            //Create a new parent object that will contain the model
            GameObject player   = new GameObject("Remote Player");
            GameObject newModel = GameObject.Instantiate(PlayerModelPrefab, player.transform);

            newModel.SetActive(true);

            //Offset its local position by half of the model height
            newModel.transform.localPosition = new Vector3(0, -1.65f / 2, 0);

            return(player);
        }
Exemplo n.º 4
0
            static bool Prefix()
            {
                watch = new Stopwatch();
                watch.Start();
                if (legacySave)
                {
                    return(true);
                }
                if (!File.Exists(GetVanillaSave()))
                {
                    return(true);
                }
                PlayerPosition player = GetPlayerPosition();

                Datum[]         data      = GetDatumsToSave();
                FileStream      fs        = new FileStream(GetSavePath(), FileMode.Create);
                BinaryFormatter formatter = new BinaryFormatter();

                try
                {
                    formatter.Serialize(fs, player);
                    formatter.Serialize(fs, data);
                }
                catch (Exception e)
                {
                    IGConsole.Error($"Saving failed with {e.ToString()}");
                }
                finally
                {
                    fs.Close();
                }
                return(false);
            }
Exemplo n.º 5
0
        public static IEnumerable <Mod> Order(IEnumerable <Mod> mods)
        {
            mods = SearchForCircularReferences(mods).ToList();

            Dictionary <string, Mod> modsByPackage = mods.ToDictionary(o => o.PackageName);
            List <Mod> ret = new List <Mod>();

            foreach (var item in mods)
            {
                Push(item);
            }

            ret.AddRange(mods.Where(o => !ret.Contains(o)));

            return(ret);

            void Push(Mod mod)
            {
                bool exit = true;

                foreach (var item in mod.RequiredModPackages)
                {
                    if (!modsByPackage.TryGetValue(item, out var req))
                    {
                        IGConsole.Error($"Mod {mod.Name} requires mod {item}");
                        exit = true;
                    }

                    if (req != null && !exit && !ret.Contains(req))
                    {
                        ret.Add(req);
                    }
                }
            }
        }
Exemplo n.º 6
0
            public override bool Execute(IEnumerable <string> arguments)
            {
                if (arguments.Count() != 1)
                {
                    IGConsole.Error("Usage: find component_name");
                    return(false);
                }
                Assembly asm           = typeof(UnityEngine.Object).Assembly;
                Type     componentType = asm.GetType($"UnityEngine.{arguments.ElementAt(0)}");

                if (componentType == null)
                {
                    IGConsole.Error($"{arguments.ElementAt(0)} is not a type");
                    return(false);
                }
                if (!componentType.IsSubclassOf(typeof(Component)))
                {
                    IGConsole.Error($"{arguments.ElementAt(0)} is not a Component");
                    return(false);
                }
                Component[] matches = (Component[])GameObject.FindObjectsOfType(componentType);
                foreach (Component component in matches)
                {
                    IGConsole.Log($"\"{component.name}\" is at {component.transform.position}");
                }
                return(true);
            }
Exemplo n.º 7
0
        public override bool Execute(IEnumerable <string> arguments)
        {
            if (MyMod.SetUpdateRate == null)
            {
                IGConsole.Error("This command can only be used while in-game!");
                return(true);
            }

            if (!arguments.Any())
            {
                IGConsole.Log($"<b>Current update rate:</b> {MyMod.CurrentUpdateRate} tps");
                return(true);
            }

            string arg = arguments.First();

            if (float.TryParse(arg, out float num))
            {
                MyMod.SetUpdateRate(num);
                return(true);
            }
            else
            {
                IGConsole.Error("tps must be a decimal number");
            }

            return(false);
        }
Exemplo n.º 8
0
        static void Prefix()
        {
            if (ModUtilities.IsOnMainMenu && !IGConsole.Shown)
            {
                var    ver = new Version(PiTUNG.FrameworkVersion.Major, PiTUNG.FrameworkVersion.Minor, PiTUNG.FrameworkVersion.Build);
                string str = $"<b>PiTUNG v{ver} enabled!</b>\nLoaded mods: " + Bootstrapper.ModCount;

                if (UpdateChecker.IsUpdateAvailable)
                {
                    ModUtilities.Graphics.DrawText("<b>Update available</b>", new Vector2(6, 36), Color.black);
                    ModUtilities.Graphics.DrawText("<b><color=#00ff00>Update available</color></b>", new Vector2(5, 35), Color.white);
                }

                ModUtilities.Graphics.DrawText(str, new Vector2(5, 5), Color.white, true);

                ModsScreen.Instance.Draw();
            }

            HologramManager.Draw();

            foreach (var item in ElementsToBeDrawn)
            {
                item.Draw();
            }
            ElementsToBeDrawn.Clear();

            Mod.CallOnAllMods(o => o.OnGUI());

            Components.CustomMenu.Instance.Draw();
            ConfigMenu.Instance.Render();
            IGConsole.Draw(); // Drawn last so that it stays on top
        }
Exemplo n.º 9
0
        private void PatchThread(IEnumerable <Mod> mods, bool hotload)
        {
            foreach (var mod in mods.Where(o => o.MultiThreadedLoad))
            {
                LoadMod(mod, hotload);
            }
            CurrentlyLoading = null;

            MDebug.WriteLine("----------Done patching!----------");

            if (hotload)
            {
                return;
            }

            UpdateChecker.UpdateStatus += (a, v) =>
            {
                if (a)
                {
                    IGConsole.Log($"<color=#00ff00>PiTUNG version {v} available!</color> Run Installer.exe or type 'update' into the console to update.");
                }
            };
            ModUtilities.DummyComponent?.StartCoroutine(UpdateChecker.CheckUpdates());

            foreach (var item in Mods.Concat(CheckUpdatesBeforeLoading))
            {
                ModUtilities.DummyComponent?.StartCoroutine(ModUpdater.CheckUpdatesForMod(item, true));
            }
        }
Exemplo n.º 10
0
        public static IEnumerator CheckUpdatesForMod(Mod mod, bool update)
        {
            if (mod.UpdateUrl == null)
            {
                yield break;
            }

            yield return(GetModInfo(mod));

            if (ModInfos.TryGetValue(mod, out var modInfo))
            {
                mod.HasAvailableUpdate = modInfo.Version > mod.ModVersion;
            }

            if (mod.HasAvailableUpdate)
            {
                Bootstrapper.Instance.ModUpdatesAvailable = true;

                if (update)
                {
                    yield return(UpdateMod(mod));
                }

                IGConsole.Log($"<color=lime>Downloaded update for {mod.FullName}!</color> Restart TUNG to install.");
            }
        }
Exemplo n.º 11
0
        private static IEnumerator GetModInfo(Mod mod)
        {
            Manifest man = null;

            var down = new WWW(mod.UpdateUrl);

            yield return(down);

            try
            {
                man = ManifestParser.ParseManifest(down.text.Split('\n'));
            }
            catch (Exception ex)
            {
                MDebug.WriteLine("Exception occurred while parsing update manifest for " + mod.FullName);
                MDebug.WriteLine("Details: " + ex);

                IGConsole.Log("Error occurred while updating " + mod.FullName);
            }

            if (man == null || man.Mods == null || man.Mods.Length == 0)
            {
                yield break;
            }

            var modInfo = man.Mods.SingleOrDefault(o => o.Name.Equals(mod.PackageName));

            if (modInfo != null)
            {
                ModInfos[mod] = modInfo;
            }
        }
Exemplo n.º 12
0
 public static bool isButtonActive(string button)
 {
     if (!activeKeys_button.ContainsKey(button))
     {
         IGConsole.Log(new KeyNotFoundException($"'{button}'" + " is not contained in activeKeys_button dictionary! To register another key, call registerButton(string button) first!"));
     }
     return(activeKeys_button[button]);
 }
Exemplo n.º 13
0
 public static bool isActive(KeyCode key)
 {
     if (!activeKeys_kc.ContainsKey(key))
     {
         IGConsole.Log(new KeyNotFoundException($"'KeyCode.{key.ToString()}'" + " is not contained in activeKeys_kc dictionary! To register another key, call registerKey(KeyCode key) first!"));
     }
     return(activeKeys_kc[key]);
 }
Exemplo n.º 14
0
 public static bool isActive(string key)
 {
     if (!activeKeys.ContainsKey(key))
     {
         IGConsole.Log(new KeyNotFoundException($"'{key}'" + " is not contained in activeKeys dictionary! To register another key, call registerKey(string key) first!"));                throw new KeyNotFoundException(key + " is not contained in activeKeys dictionary! To register another key, call registerKey(string key) first!");
     }
     return(activeKeys[key]);
 }
Exemplo n.º 15
0
 public void Init()
 {
     client = new Client();
     placer = new Placer();
     IGConsole.RegisterCommand(new Command_find());
     IGConsole.RegisterCommand(new Command_findobj());
     IGConsole.Log($"Polyglot v{ModVersion.ToString()} initialized");
 }
Exemplo n.º 16
0
        /// <summary>
        /// Main bootstrap method. Loads and patches all mods.
        /// </summary>
        public void Patch(bool hotload = false)
        {
            if (Patched && !hotload)
            {
                return;
            }
            Patched = true;

            string tungVersion = GetTungVersion();

            MDebug.WriteLine("PiTUNG Framework version {0} on TUNG {1}", 0, new Version(PiTUNG.FrameworkVersion.Major, PiTUNG.FrameworkVersion.Minor, PiTUNG.FrameworkVersion.Build), tungVersion);
            MDebug.WriteLine("-------------Patching-------------" + (hotload ? " (reloading)" : ""));

            if (!hotload)
            {
                Configuration.LoadPitungConfig();

                _Mods.Clear();

                _Harmony = HarmonyInstance.Create("me.pipe01.pitung");

                if (!Testing)
                {
                    try
                    {
                        _Harmony.PatchAll(Assembly.GetExecutingAssembly());
                    }
                    catch (Exception ex)
                    {
                        MDebug.WriteLine("[ERROR] PiTUNG failed to load! Exception: \n" + ex);
                        return;
                    }

                    ModInput.LoadBinds();
                    IGConsole.Init();
                }

                SceneManager.activeSceneChanged += SceneManager_activeSceneChanged;
            }

            if (!Testing)
            {
                AddDummyComponent(SceneManager.GetActiveScene());
            }

            SelectionMenu.AllowModdedComponents = true;

            var mods = ModLoader.Order(ModLoader.GetMods());

            foreach (var item in mods.Where(o => !o.MultiThreadedLoad))
            {
                LoadMod(item, hotload);
            }

            CurrentlyLoading = null;

            new Thread(() => PatchThread(mods, hotload)).Start();
        }
Exemplo n.º 17
0
 public override bool Execute(IEnumerable <string> arguments)
 {
     if (SceneManager.GetActiveScene().name != "gameplay")
     {
         IGConsole.Error("Only usable on gameplay");
         return(false);
     }
     placer.Board(4, 4, new Vector3(0f, 1f, 0f), Quaternion.identity);
     return(true);
 }
Exemplo n.º 18
0
        public override bool Execute(IEnumerable <string> arguments)
        {
            IList <string> players = PlayerManager.Players.Select(o => o.Username).ToList();

            players.Insert(0, Network.Username);

            IGConsole.Log($"<color=lime>Online players</color> (<b>{players.Count}</b>): {string.Join(", ", players.ToArray())}");

            return(true);
        }
Exemplo n.º 19
0
 private void OnPlayerIDAttribution(PlayerIDAttribution packet)
 {
     if (ID.HasValue)
     {
         IGConsole.Error("Received unexpected IDAttribution");
         return;
     }
     ID = packet.ID;
     IGConsole.Log($"ID set to {ID.Value}");
     SendPacket(new IDAttibutionACK());
 }
Exemplo n.º 20
0
 private static void Prefix(BoardPlacer __instance)
 {
     if (BoardPlacer.BoardBeingPlaced == null)
     {
         IGConsole.Log("null board?");
     }
     foreach (BuildListener listener in instances)
     {
         listener.OnPlaceBoard(BoardPlacer.BoardBeingPlaced);
     }
 }
Exemplo n.º 21
0
 public override bool Execute(IEnumerable <string> arguments)
 {
     if (SceneManager.GetActiveScene().name != "gameplay")
     {
         IGConsole.Error("Not currently in a world");
         return(false);
     }
     legacySave = true;
     SaveManager.SaveAll();
     return(true);
 }
Exemplo n.º 22
0
 static void Postfix()
 {
     if (watch.IsRunning)
     {
         watch.Stop();
     }
     if (!betterSave)
     {
         IGConsole.Log($"Loaded save in {watch.Elapsed.ToString()}");
     }
 }
Exemplo n.º 23
0
        public static void WaveGoodbye(int playerId)
        {
            if (PlayersInner.TryGetValue(playerId, out var player))
            {
                IGConsole.Log($"<color=orange>Player {player.Username} disconnected</color>");

                GameObject.Destroy(player.gameObject);

                PlayersInner.Remove(playerId);
            }
        }
Exemplo n.º 24
0
 public override bool Execute(IEnumerable <string> args)
 {
     if (args.Count() == 0)
     {
         IGConsole.Log(CustomMusic.bmp.GetListOfSongs());
     }
     else
     {
         return(false);
     }
     return(true);
 }
Exemplo n.º 25
0
 public Placer()
 {
     IGConsole.RegisterCommand(new Command_tryplace(this));
     if (SceneManager.GetActiveScene().name == "gameplay")
     {
         Init();
     }
     else
     {
         SceneManager.activeSceneChanged += DelayedInit;
     }
 }
Exemplo n.º 26
0
        private Vector3 GetScale()
        {
            if (Physics.Raycast(FirstPersonInteraction.Ray(), out var hit))
            {
                IGConsole.Log(hit.transform.localPosition);
                IGConsole.Log(hit.transform.localScale);
                IGConsole.Log(hit.transform.localEulerAngles);

                ModUtilities.Graphics.CreateSphere(hit.point);
            }

            return(Vector3.back);
        }
Exemplo n.º 27
0
        public NetOutgoingMessage GetMessage(NetPeer peer)
        {
            var msg = peer.CreateMessage();

            try
            {
                msg.Write(this.Serialize());
            }
            catch (Exception ex)
            {
                IGConsole.Log(ex);
            }
            return(msg);
        }
Exemplo n.º 28
0
        public override void OnWorldLoaded(string worldName)
        {
            bmp = BetterMusicPlayer.CreateSelf();
            MusicPlayer[] mps = GameObject.FindObjectsOfType <MusicPlayer>();

            string musicDir = Directory.GetCurrentDirectory() + "\\music";

            if (!Directory.Exists(musicDir))
            {
                Directory.CreateDirectory(musicDir);
            }

            string[] musFiles = Directory.GetFiles(musicDir);
            foreach (string path in Directory.GetFiles(musicDir))
            {
                string[] splitPath           = path.Split('.');
                string   ext                 = splitPath[splitPath.Length - 1].ToLower();
                string[] availableExtensions = { "wav", "ogg" };
                if (!availableExtensions.Contains(ext))
                {
                    IGConsole.Log("[Custom Music] " + ext + " file type not supported! Try using .WAV or .OGG instead!");
                }
                else
                {
                    AudioType       at  = (ext == "ogg") ? AudioType.OGGVORBIS : ((ext == "mp3")?AudioType.MPEG :AudioType.WAV);
                    UnityWebRequest uwr = UnityWebRequestMultimedia.GetAudioClip("file:///" + path, at);

                    try {
                        uwr.SendWebRequest();
                        while (uwr.downloadProgress != 1.0f || !uwr.isDone)
                        {
                            //IGConsole.Log($"[Custom Music] File {path} downloaded: {100f*uwr.downloadProgress}%");
                        }
                        AudioClip ac = DownloadHandlerAudioClip.GetContent(uwr);

                        string[] splitPath2 = path.Split('/');
                        bmp.AddNewTrack(splitPath2[splitPath2.Length - 1], ac);
                    } catch (Exception e) {
                        IGConsole.Log(e);
                    }
                }
            }
            foreach (MusicPlayer mp in mps)
            {
                mp.Tracks = new AudioClip[] {}
            }
            ;
            bmp.BeginPlaylist();
        }
Exemplo n.º 29
0
 public override bool Execute(IEnumerable <string> arguments)
 {
     IGConsole.Log("Disconnecting...");
     Disconnect();
     if (SceneManager.GetActiveScene().name == "gameplay")
     {
         UIManager.UnlockMouseAndDisableFirstPersonLooking();
         SceneManager.LoadScene("main menu");
     }
     else
     {
         IGConsole.Log("Not currently connected");
         return(false);
     }
     return(true);
 }
Exemplo n.º 30
0
        public UserModel GetByID(int id)
        {
            if (!UserCache.ContainsKey(id))
            {
                var user = MakeRequest <UserModel>($"/user/{id}", HttpMethod.Get);

                if (user == null) //Error on the request, don't cache
                {
                    IGConsole.Log("Dont cache user " + id);
                    return(null);
                }

                UserCache[id] = user;
            }

            return(UserCache[id]);
        }